diff --git a/apps/app/src/api/ads.rs b/apps/app/src/api/ads.rs index 5f719b52b..fd498a56d 100644 --- a/apps/app/src/api/ads.rs +++ b/apps/app/src/api/ads.rs @@ -197,15 +197,13 @@ pub async fn open_link( if url::Url::parse(&path).is_ok() && !state.malicious_origins.contains(&origin) + && let Some(last_click) = state.last_click + && last_click.elapsed() < Duration::from_millis(100) { - if let Some(last_click) = state.last_click { - if last_click.elapsed() < Duration::from_millis(100) { - let _ = app.opener().open_url(&path, None::); - state.last_click = None; + let _ = app.opener().open_url(&path, None::); + state.last_click = None; - return Ok(()); - } - } + return Ok(()); } tracing::info!("Malicious click: {path} origin {origin}"); diff --git a/apps/app/src/api/auth.rs b/apps/app/src/api/auth.rs index c18bd770e..d7bbe3a94 100644 --- a/apps/app/src/api/auth.rs +++ b/apps/app/src/api/auth.rs @@ -59,16 +59,13 @@ pub async fn login( .url()? .as_str() .starts_with("https://login.live.com/oauth20_desktop.srf") - { - if let Some((_, code)) = + && let Some((_, code)) = window.url()?.query_pairs().find(|x| x.0 == "code") - { - window.close()?; - let val = - minecraft_auth::finish_login(&code.clone(), flow).await?; + { + window.close()?; + let val = minecraft_auth::finish_login(&code.clone(), flow).await?; - return Ok(Some(val)); - } + return Ok(Some(val)); } tokio::time::sleep(std::time::Duration::from_millis(50)).await; diff --git a/apps/app/src/api/utils.rs b/apps/app/src/api/utils.rs index 0ba25fc46..8a067b7cc 100644 --- a/apps/app/src/api/utils.rs +++ b/apps/app/src/api/utils.rs @@ -63,11 +63,11 @@ pub async fn should_disable_mouseover() -> bool { // We try to match version to 12.2 or higher. If unrecognizable to pattern or lower, we default to the css with disabled mouseover for safety if let tauri_plugin_os::Version::Semantic(major, minor, _) = tauri_plugin_os::version() + && major >= 12 + && minor >= 3 { - if major >= 12 && minor >= 3 { - // Mac os version is 12.3 or higher, we allow mouseover - return false; - } + // Mac os version is 12.3 or higher, we allow mouseover + return false; } true } else { diff --git a/apps/app/src/main.rs b/apps/app/src/main.rs index b6b00ea81..09723d39f 100644 --- a/apps/app/src/main.rs +++ b/apps/app/src/main.rs @@ -233,10 +233,10 @@ fn main() { }); #[cfg(not(target_os = "linux"))] - if let Some(window) = app.get_window("main") { - if let Err(e) = window.set_shadow(true) { - tracing::warn!("Failed to set window shadow: {e}"); - } + if let Some(window) = app.get_window("main") + && let Err(e) = window.set_shadow(true) + { + tracing::warn!("Failed to set window shadow: {e}"); } Ok(()) diff --git a/apps/daedalus_client/src/forge.rs b/apps/daedalus_client/src/forge.rs index ab67ae914..c1bf60564 100644 --- a/apps/daedalus_client/src/forge.rs +++ b/apps/daedalus_client/src/forge.rs @@ -506,27 +506,25 @@ async fn fetch( return Ok(lib); } - } else if let Some(url) = &lib.url { - if !url.is_empty() { - insert_mirrored_artifact( - &lib.name, - None, - vec![ - url.clone(), - "https://libraries.minecraft.net/" - .to_string(), - "https://maven.creeperhost.net/" - .to_string(), - maven_url.to_string(), - ], - false, - mirror_artifacts, - )?; + } else if let Some(url) = &lib.url + && !url.is_empty() + { + insert_mirrored_artifact( + &lib.name, + None, + vec![ + url.clone(), + "https://libraries.minecraft.net/".to_string(), + "https://maven.creeperhost.net/".to_string(), + maven_url.to_string(), + ], + false, + mirror_artifacts, + )?; - lib.url = Some(format_url("maven/")); + lib.url = Some(format_url("maven/")); - return Ok(lib); - } + return Ok(lib); } // Other libraries are generally available in the "maven" directory of the installer. If they are diff --git a/apps/daedalus_client/src/main.rs b/apps/daedalus_client/src/main.rs index dcd610558..a09454715 100644 --- a/apps/daedalus_client/src/main.rs +++ b/apps/daedalus_client/src/main.rs @@ -93,22 +93,22 @@ async fn main() -> Result<()> { .ok() .and_then(|x| x.parse::().ok()) .unwrap_or(false) + && let Ok(token) = dotenvy::var("CLOUDFLARE_TOKEN") + && let Ok(zone_id) = dotenvy::var("CLOUDFLARE_ZONE_ID") { - if let Ok(token) = dotenvy::var("CLOUDFLARE_TOKEN") { - if let Ok(zone_id) = dotenvy::var("CLOUDFLARE_ZONE_ID") { - let cache_clears = upload_files + let cache_clears = upload_files + .into_iter() + .map(|x| format_url(&x.0)) + .chain( + mirror_artifacts .into_iter() - .map(|x| format_url(&x.0)) - .chain( - mirror_artifacts - .into_iter() - .map(|x| format_url(&format!("maven/{}", x.0))), - ) - .collect::>(); + .map(|x| format_url(&format!("maven/{}", x.0))), + ) + .collect::>(); - // Cloudflare ratelimits cache clears to 500 files per request - for chunk in cache_clears.chunks(500) { - REQWEST_CLIENT.post(format!("https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache")) + // Cloudflare ratelimits cache clears to 500 files per request + for chunk in cache_clears.chunks(500) { + REQWEST_CLIENT.post(format!("https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache")) .bearer_auth(&token) .json(&serde_json::json!({ "files": chunk @@ -128,8 +128,6 @@ async fn main() -> Result<()> { item: "cloudflare clear cache".to_string(), } })?; - } - } } } diff --git a/apps/daedalus_client/src/util.rs b/apps/daedalus_client/src/util.rs index 3f8f11e53..6d331d839 100644 --- a/apps/daedalus_client/src/util.rs +++ b/apps/daedalus_client/src/util.rs @@ -167,20 +167,18 @@ pub async fn download_file( let bytes = x.bytes().await; if let Ok(bytes) = bytes { - if let Some(sha1) = sha1 { - if &*sha1_async(bytes.clone()).await? != sha1 { - if attempt <= 3 { - continue; - } else { - return Err( - crate::ErrorKind::ChecksumFailure { - hash: sha1.to_string(), - url: url.to_string(), - tries: attempt, - } - .into(), - ); + if let Some(sha1) = sha1 + && &*sha1_async(bytes.clone()).await? != sha1 + { + if attempt <= 3 { + continue; + } else { + return Err(crate::ErrorKind::ChecksumFailure { + hash: sha1.to_string(), + url: url.to_string(), + tries: attempt, } + .into()); } } diff --git a/apps/labrinth/src/auth/checks.rs b/apps/labrinth/src/auth/checks.rs index 662a8b093..f810ca773 100644 --- a/apps/labrinth/src/auth/checks.rs +++ b/apps/labrinth/src/auth/checks.rs @@ -322,12 +322,11 @@ pub async fn is_visible_collection( } else { !collection_data.status.is_hidden() }) && !collection_data.projects.is_empty(); - if let Some(user) = &user_option { - if !authorized - && (user.role.is_mod() || user.id == collection_data.user_id.into()) - { - authorized = true; - } + if let Some(user) = &user_option + && !authorized + && (user.role.is_mod() || user.id == collection_data.user_id.into()) + { + authorized = true; } Ok(authorized) } @@ -356,10 +355,10 @@ pub async fn filter_visible_collections( for collection in check_collections { // Collections are simple- if we are the owner or a mod, we can see it - if let Some(user) = user_option { - if user.role.is_mod() || user.id == collection.user_id.into() { - return_collections.push(collection.into()); - } + if let Some(user) = user_option + && (user.role.is_mod() || user.id == collection.user_id.into()) + { + return_collections.push(collection.into()); } } diff --git a/apps/labrinth/src/database/models/flow_item.rs b/apps/labrinth/src/database/models/flow_item.rs index 53bd379c5..192823d86 100644 --- a/apps/labrinth/src/database/models/flow_item.rs +++ b/apps/labrinth/src/database/models/flow_item.rs @@ -95,10 +95,10 @@ impl DBFlow { redis: &RedisPool, ) -> Result, DatabaseError> { let flow = Self::get(id, redis).await?; - if let Some(flow) = flow.as_ref() { - if predicate(flow) { - Self::remove(id, redis).await?; - } + if let Some(flow) = flow.as_ref() + && predicate(flow) + { + Self::remove(id, redis).await?; } Ok(flow) } diff --git a/apps/labrinth/src/database/models/loader_fields.rs b/apps/labrinth/src/database/models/loader_fields.rs index da293ae6c..32f836c88 100644 --- a/apps/labrinth/src/database/models/loader_fields.rs +++ b/apps/labrinth/src/database/models/loader_fields.rs @@ -801,24 +801,24 @@ impl VersionField { }; if let Some(count) = countable { - if let Some(min) = loader_field.min_val { - if count < min { - return Err(format!( - "Provided value '{v}' for {field_name} is less than the minimum of {min}", - v = serde_json::to_string(&value).unwrap_or_default(), - field_name = loader_field.field, - )); - } + if let Some(min) = loader_field.min_val + && count < min + { + return Err(format!( + "Provided value '{v}' for {field_name} is less than the minimum of {min}", + v = serde_json::to_string(&value).unwrap_or_default(), + field_name = loader_field.field, + )); } - if let Some(max) = loader_field.max_val { - if count > max { - return Err(format!( - "Provided value '{v}' for {field_name} is greater than the maximum of {max}", - v = serde_json::to_string(&value).unwrap_or_default(), - field_name = loader_field.field, - )); - } + if let Some(max) = loader_field.max_val + && count > max + { + return Err(format!( + "Provided value '{v}' for {field_name} is greater than the maximum of {max}", + v = serde_json::to_string(&value).unwrap_or_default(), + field_name = loader_field.field, + )); } } diff --git a/apps/labrinth/src/database/models/team_item.rs b/apps/labrinth/src/database/models/team_item.rs index ec32a143b..dc3139401 100644 --- a/apps/labrinth/src/database/models/team_item.rs +++ b/apps/labrinth/src/database/models/team_item.rs @@ -483,20 +483,20 @@ impl DBTeamMember { .await?; } - if let Some(accepted) = new_accepted { - if accepted { - sqlx::query!( - " + if let Some(accepted) = new_accepted + && accepted + { + sqlx::query!( + " UPDATE team_members SET accepted = TRUE WHERE (team_id = $1 AND user_id = $2) ", - id as DBTeamId, - user_id as DBUserId, - ) - .execute(&mut **transaction) - .await?; - } + id as DBTeamId, + user_id as DBUserId, + ) + .execute(&mut **transaction) + .await?; } if let Some(payouts_split) = new_payouts_split { diff --git a/apps/labrinth/src/database/redis.rs b/apps/labrinth/src/database/redis.rs index 9d3197c48..cc01b0b20 100644 --- a/apps/labrinth/src/database/redis.rs +++ b/apps/labrinth/src/database/redis.rs @@ -353,10 +353,10 @@ impl RedisPool { }; for (idx, key) in fetch_ids.into_iter().enumerate() { - if let Some(locked) = results.get(idx) { - if locked.is_none() { - continue; - } + if let Some(locked) = results.get(idx) + && locked.is_none() + { + continue; } if let Some((key, raw_key)) = ids.remove(&key) { diff --git a/apps/labrinth/src/models/v2/projects.rs b/apps/labrinth/src/models/v2/projects.rs index 0af1e53fe..f495c7f1e 100644 --- a/apps/labrinth/src/models/v2/projects.rs +++ b/apps/labrinth/src/models/v2/projects.rs @@ -334,18 +334,14 @@ impl From for LegacyVersion { // the v2 loaders are whatever the corresponding loader fields are let mut loaders = data.loaders.into_iter().map(|l| l.0).collect::>(); - if loaders.contains(&"mrpack".to_string()) { - if let Some((_, mrpack_loaders)) = data + if loaders.contains(&"mrpack".to_string()) + && let Some((_, mrpack_loaders)) = data .fields .into_iter() .find(|(key, _)| key == "mrpack_loaders") - { - if let Ok(mrpack_loaders) = - serde_json::from_value(mrpack_loaders) - { - loaders = mrpack_loaders; - } - } + && let Ok(mrpack_loaders) = serde_json::from_value(mrpack_loaders) + { + loaders = mrpack_loaders; } let loaders = loaders.into_iter().map(Loader).collect::>(); diff --git a/apps/labrinth/src/models/v2/search.rs b/apps/labrinth/src/models/v2/search.rs index 1aabaca14..528bd9d83 100644 --- a/apps/labrinth/src/models/v2/search.rs +++ b/apps/labrinth/src/models/v2/search.rs @@ -43,35 +43,33 @@ impl LegacyResultSearchProject { pub fn from(result_search_project: ResultSearchProject) -> Self { let mut categories = result_search_project.categories; categories.extend(result_search_project.loaders.clone()); - if categories.contains(&"mrpack".to_string()) { - if let Some(mrpack_loaders) = result_search_project + if categories.contains(&"mrpack".to_string()) + && let Some(mrpack_loaders) = result_search_project .project_loader_fields .get("mrpack_loaders") - { - categories.extend( - mrpack_loaders - .iter() - .filter_map(|c| c.as_str()) - .map(String::from), - ); - categories.retain(|c| c != "mrpack"); - } + { + categories.extend( + mrpack_loaders + .iter() + .filter_map(|c| c.as_str()) + .map(String::from), + ); + categories.retain(|c| c != "mrpack"); } let mut display_categories = result_search_project.display_categories; display_categories.extend(result_search_project.loaders); - if display_categories.contains(&"mrpack".to_string()) { - if let Some(mrpack_loaders) = result_search_project + if display_categories.contains(&"mrpack".to_string()) + && let Some(mrpack_loaders) = result_search_project .project_loader_fields .get("mrpack_loaders") - { - categories.extend( - mrpack_loaders - .iter() - .filter_map(|c| c.as_str()) - .map(String::from), - ); - display_categories.retain(|c| c != "mrpack"); - } + { + categories.extend( + mrpack_loaders + .iter() + .filter_map(|c| c.as_str()) + .map(String::from), + ); + display_categories.retain(|c| c != "mrpack"); } // Sort then remove duplicates diff --git a/apps/labrinth/src/models/v3/projects.rs b/apps/labrinth/src/models/v3/projects.rs index 56d241d3b..8b212ef16 100644 --- a/apps/labrinth/src/models/v3/projects.rs +++ b/apps/labrinth/src/models/v3/projects.rs @@ -166,10 +166,10 @@ impl From for Project { Ok(spdx_expr) => { let mut vec: Vec<&str> = Vec::new(); for node in spdx_expr.iter() { - if let spdx::expression::ExprNode::Req(req) = node { - if let Some(id) = req.req.license.id() { - vec.push(id.full_name); - } + if let spdx::expression::ExprNode::Req(req) = node + && let Some(id) = req.req.license.id() + { + vec.push(id.full_name); } } // spdx crate returns AND/OR operations in postfix order diff --git a/apps/labrinth/src/models/v3/teams.rs b/apps/labrinth/src/models/v3/teams.rs index 65292c917..5f124f316 100644 --- a/apps/labrinth/src/models/v3/teams.rs +++ b/apps/labrinth/src/models/v3/teams.rs @@ -51,16 +51,16 @@ impl ProjectPermissions { return Some(ProjectPermissions::all()); } - if let Some(member) = project_team_member { - if member.accepted { - return Some(member.permissions); - } + if let Some(member) = project_team_member + && member.accepted + { + return Some(member.permissions); } - if let Some(member) = organization_team_member { - if member.accepted { - return Some(member.permissions); - } + if let Some(member) = organization_team_member + && member.accepted + { + return Some(member.permissions); } if role.is_mod() { @@ -107,10 +107,10 @@ impl OrganizationPermissions { return Some(OrganizationPermissions::all()); } - if let Some(member) = team_member { - if member.accepted { - return member.organization_permissions; - } + if let Some(member) = team_member + && member.accepted + { + return member.organization_permissions; } if role.is_mod() { return Some( diff --git a/apps/labrinth/src/queue/maxmind.rs b/apps/labrinth/src/queue/maxmind.rs index 1e65a5256..bb80fb690 100644 --- a/apps/labrinth/src/queue/maxmind.rs +++ b/apps/labrinth/src/queue/maxmind.rs @@ -45,17 +45,15 @@ impl MaxMindIndexer { if let Ok(entries) = archive.entries() { for mut file in entries.flatten() { - if let Ok(path) = file.header().path() { - if path.extension().and_then(|x| x.to_str()) == Some("mmdb") - { - let mut buf = Vec::new(); - file.read_to_end(&mut buf).unwrap(); + if let Ok(path) = file.header().path() + && path.extension().and_then(|x| x.to_str()) == Some("mmdb") + { + let mut buf = Vec::new(); + file.read_to_end(&mut buf).unwrap(); - let reader = - maxminddb::Reader::from_source(buf).unwrap(); + let reader = maxminddb::Reader::from_source(buf).unwrap(); - return Ok(Some(reader)); - } + return Ok(Some(reader)); } } } diff --git a/apps/labrinth/src/queue/moderation.rs b/apps/labrinth/src/queue/moderation.rs index c7f27be2e..87ebce31a 100644 --- a/apps/labrinth/src/queue/moderation.rs +++ b/apps/labrinth/src/queue/moderation.rs @@ -371,8 +371,8 @@ impl AutomatedModerationQueue { for file in files.iter().filter(|x| x.version_id == version.id.into()) { - if let Some(hash) = file.hashes.get("sha1") { - if let Some((index, (sha1, _, file_name, _))) = hashes + if let Some(hash) = file.hashes.get("sha1") + && let Some((index, (sha1, _, file_name, _))) = hashes .iter() .enumerate() .find(|(_, (value, _, _, _))| value == hash) @@ -382,7 +382,6 @@ impl AutomatedModerationQueue { hashes.remove(index); } - } } } @@ -420,12 +419,11 @@ impl AutomatedModerationQueue { .await?; for row in rows { - if let Some(sha1) = row.sha1 { - if let Some((index, (sha1, _, file_name, _))) = hashes.iter().enumerate().find(|(_, (value, _, _, _))| value == &sha1) { + if let Some(sha1) = row.sha1 + && let Some((index, (sha1, _, file_name, _))) = hashes.iter().enumerate().find(|(_, (value, _, _, _))| value == &sha1) { final_hashes.insert(sha1.clone(), IdentifiedFile { file_name: file_name.clone(), status: ApprovalType::from_string(&row.status).unwrap_or(ApprovalType::Unidentified) }); hashes.remove(index); } - } } if hashes.is_empty() { @@ -499,8 +497,8 @@ impl AutomatedModerationQueue { let mut insert_ids = Vec::new(); for row in rows { - if let Some((curse_index, (hash, _flame_id))) = flame_files.iter().enumerate().find(|(_, x)| Some(x.1 as i32) == row.flame_project_id) { - if let Some((index, (sha1, _, file_name, _))) = hashes.iter().enumerate().find(|(_, (value, _, _, _))| value == hash) { + if let Some((curse_index, (hash, _flame_id))) = flame_files.iter().enumerate().find(|(_, x)| Some(x.1 as i32) == row.flame_project_id) + && let Some((index, (sha1, _, file_name, _))) = hashes.iter().enumerate().find(|(_, (value, _, _, _))| value == hash) { final_hashes.insert(sha1.clone(), IdentifiedFile { file_name: file_name.clone(), status: ApprovalType::from_string(&row.status).unwrap_or(ApprovalType::Unidentified), @@ -512,7 +510,6 @@ impl AutomatedModerationQueue { hashes.remove(index); flame_files.remove(curse_index); } - } } if !insert_ids.is_empty() && !insert_hashes.is_empty() { @@ -581,8 +578,8 @@ impl AutomatedModerationQueue { for (sha1, _pack_file, file_name, _mumur2) in hashes { let flame_file = flame_files.iter().find(|x| x.0 == sha1); - if let Some((_, flame_project_id)) = flame_file { - if let Some(project) = flame_projects.iter().find(|x| &x.id == flame_project_id) { + if let Some((_, flame_project_id)) = flame_file + && let Some(project) = flame_projects.iter().find(|x| &x.id == flame_project_id) { missing_metadata.flame_files.insert(sha1, MissingMetadataFlame { title: project.name.clone(), file_name, @@ -592,7 +589,6 @@ impl AutomatedModerationQueue { continue; } - } missing_metadata.unknown_files.insert(sha1, file_name); } diff --git a/apps/labrinth/src/queue/payouts.rs b/apps/labrinth/src/queue/payouts.rs index 740e91dd5..ccdeb678a 100644 --- a/apps/labrinth/src/queue/payouts.rs +++ b/apps/labrinth/src/queue/payouts.rs @@ -257,31 +257,30 @@ impl PayoutsQueue { ) })?; - if !status.is_success() { - if let Some(obj) = value.as_object() { - if let Some(array) = obj.get("errors") { - #[derive(Deserialize)] - struct TremendousError { - message: String, - } - - let err = serde_json::from_value::( - array.clone(), - ) - .map_err(|_| { - ApiError::Payments( - "could not retrieve Tremendous error json body" - .to_string(), - ) - })?; - - return Err(ApiError::Payments(err.message)); + if !status.is_success() + && let Some(obj) = value.as_object() + { + if let Some(array) = obj.get("errors") { + #[derive(Deserialize)] + struct TremendousError { + message: String, } - return Err(ApiError::Payments( - "could not retrieve Tremendous error body".to_string(), - )); + let err = + serde_json::from_value::(array.clone()) + .map_err(|_| { + ApiError::Payments( + "could not retrieve Tremendous error json body" + .to_string(), + ) + })?; + + return Err(ApiError::Payments(err.message)); } + + return Err(ApiError::Payments( + "could not retrieve Tremendous error body".to_string(), + )); } Ok(serde_json::from_value(value)?) @@ -449,10 +448,10 @@ impl PayoutsQueue { }; // we do not support interval gift cards with non US based currencies since we cannot do currency conversions properly - if let PayoutInterval::Fixed { .. } = method.interval { - if !product.currency_codes.contains(&"USD".to_string()) { - continue; - } + if let PayoutInterval::Fixed { .. } = method.interval + && !product.currency_codes.contains(&"USD".to_string()) + { + continue; } methods.push(method); diff --git a/apps/labrinth/src/routes/internal/billing.rs b/apps/labrinth/src/routes/internal/billing.rs index 49e50eac7..c27a507fd 100644 --- a/apps/labrinth/src/routes/internal/billing.rs +++ b/apps/labrinth/src/routes/internal/billing.rs @@ -286,17 +286,17 @@ pub async fn refund_charge( .upsert(&mut transaction) .await?; - if body.0.unprovision.unwrap_or(false) { - if let Some(subscription_id) = charge.subscription_id { - let open_charge = - DBCharge::get_open_subscription(subscription_id, &**pool) - .await?; - if let Some(mut open_charge) = open_charge { - open_charge.status = ChargeStatus::Cancelled; - open_charge.due = Utc::now(); + if body.0.unprovision.unwrap_or(false) + && let Some(subscription_id) = charge.subscription_id + { + let open_charge = + DBCharge::get_open_subscription(subscription_id, &**pool) + .await?; + if let Some(mut open_charge) = open_charge { + open_charge.status = ChargeStatus::Cancelled; + open_charge.due = Utc::now(); - open_charge.upsert(&mut transaction).await?; - } + open_charge.upsert(&mut transaction).await?; } } @@ -392,17 +392,16 @@ pub async fn edit_subscription( } } - if let Some(interval) = &edit_subscription.interval { - if let Price::Recurring { intervals } = ¤t_price.prices { - if let Some(price) = intervals.get(interval) { - open_charge.subscription_interval = Some(*interval); - open_charge.amount = *price as i64; - } else { - return Err(ApiError::InvalidInput( - "Interval is not valid for this subscription!" - .to_string(), - )); - } + if let Some(interval) = &edit_subscription.interval + && let Price::Recurring { intervals } = ¤t_price.prices + { + if let Some(price) = intervals.get(interval) { + open_charge.subscription_interval = Some(*interval); + open_charge.amount = *price as i64; + } else { + return Err(ApiError::InvalidInput( + "Interval is not valid for this subscription!".to_string(), + )); } } @@ -1225,38 +1224,36 @@ pub async fn initiate_payment( } }; - if let Price::Recurring { .. } = price_item.prices { - if product.unitary { - let user_subscriptions = + if let Price::Recurring { .. } = price_item.prices + && product.unitary + { + let user_subscriptions = user_subscription_item::DBUserSubscription::get_all_user( user.id.into(), &**pool, ) .await?; - let user_products = - product_item::DBProductPrice::get_many( - &user_subscriptions - .iter() - .filter(|x| { - x.status - == SubscriptionStatus::Provisioned - }) - .map(|x| x.price_id) - .collect::>(), - &**pool, - ) - .await?; + let user_products = product_item::DBProductPrice::get_many( + &user_subscriptions + .iter() + .filter(|x| { + x.status == SubscriptionStatus::Provisioned + }) + .map(|x| x.price_id) + .collect::>(), + &**pool, + ) + .await?; - if user_products - .into_iter() - .any(|x| x.product_id == product.id) - { - return Err(ApiError::InvalidInput( - "You are already subscribed to this product!" - .to_string(), - )); - } + if user_products + .into_iter() + .any(|x| x.product_id == product.id) + { + return Err(ApiError::InvalidInput( + "You are already subscribed to this product!" + .to_string(), + )); } } @@ -2004,38 +2001,36 @@ pub async fn stripe_webhook( EventType::PaymentMethodAttached => { if let EventObject::PaymentMethod(payment_method) = event.data.object - { - if let Some(customer_id) = + && let Some(customer_id) = payment_method.customer.map(|x| x.id()) + { + let customer = stripe::Customer::retrieve( + &stripe_client, + &customer_id, + &[], + ) + .await?; + + if customer + .invoice_settings + .is_none_or(|x| x.default_payment_method.is_none()) { - let customer = stripe::Customer::retrieve( + stripe::Customer::update( &stripe_client, &customer_id, - &[], + UpdateCustomer { + invoice_settings: Some( + CustomerInvoiceSettings { + default_payment_method: Some( + payment_method.id.to_string(), + ), + ..Default::default() + }, + ), + ..Default::default() + }, ) .await?; - - if customer - .invoice_settings - .is_none_or(|x| x.default_payment_method.is_none()) - { - stripe::Customer::update( - &stripe_client, - &customer_id, - UpdateCustomer { - invoice_settings: Some( - CustomerInvoiceSettings { - default_payment_method: Some( - payment_method.id.to_string(), - ), - ..Default::default() - }, - ), - ..Default::default() - }, - ) - .await?; - } } } } diff --git a/apps/labrinth/src/routes/internal/flows.rs b/apps/labrinth/src/routes/internal/flows.rs index cba2de5d9..0c7a37ba2 100644 --- a/apps/labrinth/src/routes/internal/flows.rs +++ b/apps/labrinth/src/routes/internal/flows.rs @@ -79,13 +79,12 @@ impl TempUser { file_host: &Arc, redis: &RedisPool, ) -> Result { - if let Some(email) = &self.email { - if crate::database::models::DBUser::get_by_email(email, client) + if let Some(email) = &self.email + && crate::database::models::DBUser::get_by_email(email, client) .await? .is_some() - { - return Err(AuthenticationError::DuplicateUser); - } + { + return Err(AuthenticationError::DuplicateUser); } let user_id = @@ -1269,19 +1268,19 @@ pub async fn delete_auth_provider( .update_user_id(user.id.into(), None, &mut transaction) .await?; - if delete_provider.provider != AuthProvider::PayPal { - if let Some(email) = user.email { - send_email( - email, - "Authentication method removed", - &format!( - "When logging into Modrinth, you can no longer log in using the {} authentication provider.", - delete_provider.provider.as_str() - ), - "If you did not make this change, please contact us immediately through our support channels on Discord or via email (support@modrinth.com).", - None, - )?; - } + if delete_provider.provider != AuthProvider::PayPal + && let Some(email) = user.email + { + send_email( + email, + "Authentication method removed", + &format!( + "When logging into Modrinth, you can no longer log in using the {} authentication provider.", + delete_provider.provider.as_str() + ), + "If you did not make this change, please contact us immediately through our support channels on Discord or via email (support@modrinth.com).", + None, + )?; } transaction.commit().await?; diff --git a/apps/labrinth/src/routes/internal/moderation.rs b/apps/labrinth/src/routes/internal/moderation.rs index ff28901f2..049ce727a 100644 --- a/apps/labrinth/src/routes/internal/moderation.rs +++ b/apps/labrinth/src/routes/internal/moderation.rs @@ -189,17 +189,16 @@ pub async fn get_project_meta( .iter() .find(|x| Some(x.1.id as i32) == row.flame_project_id) .map(|x| x.0.clone()) + && let Some(val) = merged.flame_files.remove(&sha1) { - if let Some(val) = merged.flame_files.remove(&sha1) { - merged.identified.insert( - sha1, - IdentifiedFile { - file_name: val.file_name.clone(), - status: ApprovalType::from_string(&row.status) - .unwrap_or(ApprovalType::Unidentified), - }, - ); - } + merged.identified.insert( + sha1, + IdentifiedFile { + file_name: val.file_name.clone(), + status: ApprovalType::from_string(&row.status) + .unwrap_or(ApprovalType::Unidentified), + }, + ); } } diff --git a/apps/labrinth/src/routes/internal/pats.rs b/apps/labrinth/src/routes/internal/pats.rs index ad0ebe942..fa10d97c5 100644 --- a/apps/labrinth/src/routes/internal/pats.rs +++ b/apps/labrinth/src/routes/internal/pats.rs @@ -185,69 +185,69 @@ pub async fn edit_pat( ) .await?; - if let Some(pat) = pat { - if pat.user_id == user.id.into() { - let mut transaction = pool.begin().await?; + if let Some(pat) = pat + && pat.user_id == user.id.into() + { + let mut transaction = pool.begin().await?; - if let Some(scopes) = &info.scopes { - if scopes.is_restricted() { - return Err(ApiError::InvalidInput( - "Invalid scopes requested!".to_string(), - )); - } + if let Some(scopes) = &info.scopes { + if scopes.is_restricted() { + return Err(ApiError::InvalidInput( + "Invalid scopes requested!".to_string(), + )); + } - sqlx::query!( - " + sqlx::query!( + " UPDATE pats SET scopes = $1 WHERE id = $2 ", - scopes.bits() as i64, - pat.id.0 - ) - .execute(&mut *transaction) - .await?; - } - if let Some(name) = &info.name { - sqlx::query!( - " + scopes.bits() as i64, + pat.id.0 + ) + .execute(&mut *transaction) + .await?; + } + if let Some(name) = &info.name { + sqlx::query!( + " UPDATE pats SET name = $1 WHERE id = $2 ", - name, - pat.id.0 - ) - .execute(&mut *transaction) - .await?; + name, + pat.id.0 + ) + .execute(&mut *transaction) + .await?; + } + if let Some(expires) = &info.expires { + if expires < &Utc::now() { + return Err(ApiError::InvalidInput( + "Expire date must be in the future!".to_string(), + )); } - if let Some(expires) = &info.expires { - if expires < &Utc::now() { - return Err(ApiError::InvalidInput( - "Expire date must be in the future!".to_string(), - )); - } - sqlx::query!( - " + sqlx::query!( + " UPDATE pats SET expires = $1 WHERE id = $2 ", - expires, - pat.id.0 - ) - .execute(&mut *transaction) - .await?; - } - - transaction.commit().await?; - database::models::pat_item::DBPersonalAccessToken::clear_cache( - vec![(Some(pat.id), Some(pat.access_token), Some(pat.user_id))], - &redis, + expires, + pat.id.0 ) + .execute(&mut *transaction) .await?; } + + transaction.commit().await?; + database::models::pat_item::DBPersonalAccessToken::clear_cache( + vec![(Some(pat.id), Some(pat.access_token), Some(pat.user_id))], + &redis, + ) + .await?; } Ok(HttpResponse::NoContent().finish()) @@ -276,21 +276,21 @@ pub async fn delete_pat( ) .await?; - if let Some(pat) = pat { - if pat.user_id == user.id.into() { - let mut transaction = pool.begin().await?; - database::models::pat_item::DBPersonalAccessToken::remove( - pat.id, - &mut transaction, - ) - .await?; - transaction.commit().await?; - database::models::pat_item::DBPersonalAccessToken::clear_cache( - vec![(Some(pat.id), Some(pat.access_token), Some(pat.user_id))], - &redis, - ) - .await?; - } + if let Some(pat) = pat + && pat.user_id == user.id.into() + { + let mut transaction = pool.begin().await?; + database::models::pat_item::DBPersonalAccessToken::remove( + pat.id, + &mut transaction, + ) + .await?; + transaction.commit().await?; + database::models::pat_item::DBPersonalAccessToken::clear_cache( + vec![(Some(pat.id), Some(pat.access_token), Some(pat.user_id))], + &redis, + ) + .await?; } Ok(HttpResponse::NoContent().finish()) diff --git a/apps/labrinth/src/routes/internal/session.rs b/apps/labrinth/src/routes/internal/session.rs index 63ac84bd8..1b20e3aee 100644 --- a/apps/labrinth/src/routes/internal/session.rs +++ b/apps/labrinth/src/routes/internal/session.rs @@ -185,21 +185,21 @@ pub async fn delete( let session = DBSession::get(info.into_inner().0, &**pool, &redis).await?; - if let Some(session) = session { - if session.user_id == current_user.id.into() { - let mut transaction = pool.begin().await?; - DBSession::remove(session.id, &mut transaction).await?; - transaction.commit().await?; - DBSession::clear_cache( - vec![( - Some(session.id), - Some(session.session), - Some(session.user_id), - )], - &redis, - ) - .await?; - } + if let Some(session) = session + && session.user_id == current_user.id.into() + { + let mut transaction = pool.begin().await?; + DBSession::remove(session.id, &mut transaction).await?; + transaction.commit().await?; + DBSession::clear_cache( + vec![( + Some(session.id), + Some(session.session), + Some(session.user_id), + )], + &redis, + ) + .await?; } Ok(HttpResponse::NoContent().body("")) diff --git a/apps/labrinth/src/routes/internal/statuses.rs b/apps/labrinth/src/routes/internal/statuses.rs index 7be8d40ea..416ea8053 100644 --- a/apps/labrinth/src/routes/internal/statuses.rs +++ b/apps/labrinth/src/routes/internal/statuses.rs @@ -401,14 +401,13 @@ async fn broadcast_to_known_local_friends( friend.user_id }; - if friend.accepted { - if let Some(socket_ids) = + if friend.accepted + && let Some(socket_ids) = sockets.sockets_by_user_id.get(&friend_id.into()) - { - for socket_id in socket_ids.iter() { - if let Some(socket) = sockets.sockets.get(&socket_id) { - let _ = send_message(socket.value(), &message).await; - } + { + for socket_id in socket_ids.iter() { + if let Some(socket) = sockets.sockets.get(&socket_id) { + let _ = send_message(socket.value(), &message).await; } } } diff --git a/apps/labrinth/src/routes/v3/analytics_get.rs b/apps/labrinth/src/routes/v3/analytics_get.rs index b32f5b0f8..b2c615726 100644 --- a/apps/labrinth/src/routes/v3/analytics_get.rs +++ b/apps/labrinth/src/routes/v3/analytics_get.rs @@ -387,17 +387,16 @@ pub async fn revenue_get( .map(|x| (x.to_string(), HashMap::new())) .collect::>(); for value in payouts_values { - if let Some(mod_id) = value.mod_id { - if let Some(amount) = value.amount_sum { - if let Some(interval_start) = value.interval_start { - let id_string = to_base62(mod_id as u64); - if !hm.contains_key(&id_string) { - hm.insert(id_string.clone(), HashMap::new()); - } - if let Some(hm) = hm.get_mut(&id_string) { - hm.insert(interval_start.timestamp(), amount); - } - } + if let Some(mod_id) = value.mod_id + && let Some(amount) = value.amount_sum + && let Some(interval_start) = value.interval_start + { + let id_string = to_base62(mod_id as u64); + if !hm.contains_key(&id_string) { + hm.insert(id_string.clone(), HashMap::new()); + } + if let Some(hm) = hm.get_mut(&id_string) { + hm.insert(interval_start.timestamp(), amount); } } } diff --git a/apps/labrinth/src/routes/v3/collections.rs b/apps/labrinth/src/routes/v3/collections.rs index ab8058e0f..15488ba05 100644 --- a/apps/labrinth/src/routes/v3/collections.rs +++ b/apps/labrinth/src/routes/v3/collections.rs @@ -192,10 +192,10 @@ pub async fn collection_get( .map(|x| x.1) .ok(); - if let Some(data) = collection_data { - if is_visible_collection(&data, &user_option, false).await? { - return Ok(HttpResponse::Ok().json(Collection::from(data))); - } + if let Some(data) = collection_data + && is_visible_collection(&data, &user_option, false).await? + { + return Ok(HttpResponse::Ok().json(Collection::from(data))); } Err(ApiError::NotFound) } diff --git a/apps/labrinth/src/routes/v3/payouts.rs b/apps/labrinth/src/routes/v3/payouts.rs index 1dca7939d..19a0d4814 100644 --- a/apps/labrinth/src/routes/v3/payouts.rs +++ b/apps/labrinth/src/routes/v3/payouts.rs @@ -536,11 +536,9 @@ pub async fn create_payout( Some(true), ) .await + && let Some(data) = res.items.first() { - if let Some(data) = res.items.first() { - payout_item.platform_id = - Some(data.payout_item_id.clone()); - } + payout_item.platform_id = Some(data.payout_item_id.clone()); } } diff --git a/apps/labrinth/src/routes/v3/projects.rs b/apps/labrinth/src/routes/v3/projects.rs index c6be6e5a6..eb4dadb66 100644 --- a/apps/labrinth/src/routes/v3/projects.rs +++ b/apps/labrinth/src/routes/v3/projects.rs @@ -182,10 +182,10 @@ pub async fn project_get( .map(|x| x.1) .ok(); - if let Some(data) = project_data { - if is_visible_project(&data.inner, &user_option, &pool, false).await? { - return Ok(HttpResponse::Ok().json(Project::from(data))); - } + if let Some(data) = project_data + && is_visible_project(&data.inner, &user_option, &pool, false).await? + { + return Ok(HttpResponse::Ok().json(Project::from(data))); } Err(ApiError::NotFound) } @@ -403,34 +403,36 @@ pub async fn project_edit( .await?; } - if status.is_searchable() && !project_item.inner.webhook_sent { - if let Ok(webhook_url) = dotenvy::var("PUBLIC_DISCORD_WEBHOOK") { - crate::util::webhook::send_discord_webhook( - project_item.inner.id.into(), - &pool, - &redis, - webhook_url, - None, - ) - .await - .ok(); + if status.is_searchable() + && !project_item.inner.webhook_sent + && let Ok(webhook_url) = dotenvy::var("PUBLIC_DISCORD_WEBHOOK") + { + crate::util::webhook::send_discord_webhook( + project_item.inner.id.into(), + &pool, + &redis, + webhook_url, + None, + ) + .await + .ok(); - sqlx::query!( - " + sqlx::query!( + " UPDATE mods SET webhook_sent = TRUE WHERE id = $1 ", - id as db_ids::DBProjectId, - ) - .execute(&mut *transaction) - .await?; - } + id as db_ids::DBProjectId, + ) + .execute(&mut *transaction) + .await?; } - if user.role.is_mod() { - if let Ok(webhook_url) = dotenvy::var("MODERATION_SLACK_WEBHOOK") { - crate::util::webhook::send_slack_webhook( + if user.role.is_mod() + && let Ok(webhook_url) = dotenvy::var("MODERATION_SLACK_WEBHOOK") + { + crate::util::webhook::send_slack_webhook( project_item.inner.id.into(), &pool, &redis, @@ -449,7 +451,6 @@ pub async fn project_edit( ) .await .ok(); - } } if team_member.is_none_or(|x| !x.accepted) { @@ -692,45 +693,45 @@ pub async fn project_edit( .await?; } - if let Some(links) = &new_project.link_urls { - if !links.is_empty() { - if !perms.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::CustomAuthentication( + if let Some(links) = &new_project.link_urls + && !links.is_empty() + { + if !perms.contains(ProjectPermissions::EDIT_DETAILS) { + return Err(ApiError::CustomAuthentication( "You do not have the permissions to edit the links of this project!" .to_string(), )); - } + } - let ids_to_delete = links.keys().cloned().collect::>(); - // Deletes all links from hashmap- either will be deleted or be replaced - sqlx::query!( - " + let ids_to_delete = links.keys().cloned().collect::>(); + // Deletes all links from hashmap- either will be deleted or be replaced + sqlx::query!( + " DELETE FROM mods_links WHERE joining_mod_id = $1 AND joining_platform_id IN ( SELECT id FROM link_platforms WHERE name = ANY($2) ) ", - id as db_ids::DBProjectId, - &ids_to_delete - ) - .execute(&mut *transaction) - .await?; + id as db_ids::DBProjectId, + &ids_to_delete + ) + .execute(&mut *transaction) + .await?; - for (platform, url) in links { - if let Some(url) = url { - let platform_id = - db_models::categories::LinkPlatform::get_id( - platform, - &mut *transaction, - ) - .await? - .ok_or_else(|| { - ApiError::InvalidInput(format!( - "Platform {} does not exist.", - platform.clone() - )) - })?; - sqlx::query!( + for (platform, url) in links { + if let Some(url) = url { + let platform_id = db_models::categories::LinkPlatform::get_id( + platform, + &mut *transaction, + ) + .await? + .ok_or_else(|| { + ApiError::InvalidInput(format!( + "Platform {} does not exist.", + platform.clone() + )) + })?; + sqlx::query!( " INSERT INTO mods_links (joining_mod_id, joining_platform_id, url) VALUES ($1, $2, $3) @@ -741,7 +742,6 @@ pub async fn project_edit( ) .execute(&mut *transaction) .await?; - } } } } @@ -2430,7 +2430,7 @@ pub async fn project_get_organization( organization, team_members, ); - return Ok(HttpResponse::Ok().json(organization)); + Ok(HttpResponse::Ok().json(organization)) } else { Err(ApiError::NotFound) } diff --git a/apps/labrinth/src/routes/v3/teams.rs b/apps/labrinth/src/routes/v3/teams.rs index 29cd57a09..1a6b3e166 100644 --- a/apps/labrinth/src/routes/v3/teams.rs +++ b/apps/labrinth/src/routes/v3/teams.rs @@ -767,12 +767,13 @@ pub async fn edit_team_member( )); } - if let Some(new_permissions) = edit_member.permissions { - if !permissions.contains(new_permissions) { - return Err(ApiError::InvalidInput( - "The new permissions have permissions that you don't have".to_string(), - )); - } + if let Some(new_permissions) = edit_member.permissions + && !permissions.contains(new_permissions) + { + return Err(ApiError::InvalidInput( + "The new permissions have permissions that you don't have" + .to_string(), + )); } if edit_member.organization_permissions.is_some() { @@ -800,13 +801,12 @@ pub async fn edit_team_member( } if let Some(new_permissions) = edit_member.organization_permissions + && !organization_permissions.contains(new_permissions) { - if !organization_permissions.contains(new_permissions) { - return Err(ApiError::InvalidInput( + return Err(ApiError::InvalidInput( "The new organization permissions have permissions that you don't have" .to_string(), )); - } } if edit_member.permissions.is_some() @@ -822,13 +822,13 @@ pub async fn edit_team_member( } } - if let Some(payouts_split) = edit_member.payouts_split { - if payouts_split < Decimal::ZERO || payouts_split > Decimal::from(5000) - { - return Err(ApiError::InvalidInput( - "Payouts split must be between 0 and 5000!".to_string(), - )); - } + if let Some(payouts_split) = edit_member.payouts_split + && (payouts_split < Decimal::ZERO + || payouts_split > Decimal::from(5000)) + { + return Err(ApiError::InvalidInput( + "Payouts split must be between 0 and 5000!".to_string(), + )); } DBTeamMember::edit_team_member( @@ -883,13 +883,13 @@ pub async fn transfer_ownership( DBTeam::get_association(id.into(), &**pool).await?; if let Some(TeamAssociationId::Project(pid)) = team_association_id { let result = DBProject::get_id(pid, &**pool, &redis).await?; - if let Some(project_item) = result { - if project_item.inner.organization_id.is_some() { - return Err(ApiError::InvalidInput( + if let Some(project_item) = result + && project_item.inner.organization_id.is_some() + { + return Err(ApiError::InvalidInput( "You cannot transfer ownership of a project team that is owend by an organization" .to_string(), )); - } } } diff --git a/apps/labrinth/src/routes/v3/threads.rs b/apps/labrinth/src/routes/v3/threads.rs index 364b94a44..b8785db67 100644 --- a/apps/labrinth/src/routes/v3/threads.rs +++ b/apps/labrinth/src/routes/v3/threads.rs @@ -289,36 +289,33 @@ pub async fn thread_get( .await? .1; - if let Some(mut data) = thread_data { - if is_authorized_thread(&data, &user, &pool).await? { - let authors = &mut data.members; + if let Some(mut data) = thread_data + && is_authorized_thread(&data, &user, &pool).await? + { + let authors = &mut data.members; - authors.append( - &mut data - .messages - .iter() - .filter_map(|x| { - if x.hide_identity && !user.role.is_mod() { - None - } else { - x.author_id - } - }) - .collect::>(), - ); + authors.append( + &mut data + .messages + .iter() + .filter_map(|x| { + if x.hide_identity && !user.role.is_mod() { + None + } else { + x.author_id + } + }) + .collect::>(), + ); - let users: Vec = database::models::DBUser::get_many_ids( - authors, &**pool, &redis, - ) - .await? - .into_iter() - .map(From::from) - .collect(); + let users: Vec = + database::models::DBUser::get_many_ids(authors, &**pool, &redis) + .await? + .into_iter() + .map(From::from) + .collect(); - return Ok( - HttpResponse::Ok().json(Thread::from(data, users, &user)) - ); - } + return Ok(HttpResponse::Ok().json(Thread::from(data, users, &user))); } Err(ApiError::NotFound) } @@ -454,33 +451,32 @@ pub async fn thread_send_message( ) .await?; - if let Some(project) = project { - if project.inner.status != ProjectStatus::Processing - && user.role.is_mod() - { - let members = - database::models::DBTeamMember::get_from_team_full( - project.inner.team_id, - &**pool, - &redis, - ) - .await?; - - NotificationBuilder { - body: NotificationBody::ModeratorMessage { - thread_id: thread.id.into(), - message_id: id.into(), - project_id: Some(project.inner.id.into()), - report_id: None, - }, - } - .insert_many( - members.into_iter().map(|x| x.user_id).collect(), - &mut transaction, + if let Some(project) = project + && project.inner.status != ProjectStatus::Processing + && user.role.is_mod() + { + let members = + database::models::DBTeamMember::get_from_team_full( + project.inner.team_id, + &**pool, &redis, ) .await?; + + NotificationBuilder { + body: NotificationBody::ModeratorMessage { + thread_id: thread.id.into(), + message_id: id.into(), + project_id: Some(project.inner.id.into()), + report_id: None, + }, } + .insert_many( + members.into_iter().map(|x| x.user_id).collect(), + &mut transaction, + &redis, + ) + .await?; } } else if let Some(report_id) = thread.report_id { let report = database::models::report_item::DBReport::get( diff --git a/apps/labrinth/src/routes/v3/version_creation.rs b/apps/labrinth/src/routes/v3/version_creation.rs index d992fd6ca..dd49340e2 100644 --- a/apps/labrinth/src/routes/v3/version_creation.rs +++ b/apps/labrinth/src/routes/v3/version_creation.rs @@ -522,10 +522,10 @@ async fn version_create_inner( .fetch_optional(pool) .await?; - if let Some(project_status) = project_status { - if project_status.status == ProjectStatus::Processing.as_str() { - moderation_queue.projects.insert(project_id.into()); - } + if let Some(project_status) = project_status + && project_status.status == ProjectStatus::Processing.as_str() + { + moderation_queue.projects.insert(project_id.into()); } Ok(HttpResponse::Ok().json(response)) @@ -871,16 +871,16 @@ pub async fn upload_file( ref format, ref files, } = validation_result + && dependencies.is_empty() { - if dependencies.is_empty() { - let hashes: Vec> = format - .files - .iter() - .filter_map(|x| x.hashes.get(&PackFileHash::Sha1)) - .map(|x| x.as_bytes().to_vec()) - .collect(); + let hashes: Vec> = format + .files + .iter() + .filter_map(|x| x.hashes.get(&PackFileHash::Sha1)) + .map(|x| x.as_bytes().to_vec()) + .collect(); - let res = sqlx::query!( + let res = sqlx::query!( " SELECT v.id version_id, v.mod_id project_id, h.hash hash FROM hashes h INNER JOIN files f on h.file_id = f.id @@ -892,45 +892,44 @@ pub async fn upload_file( .fetch_all(&mut **transaction) .await?; - for file in &format.files { - if let Some(dep) = res.iter().find(|x| { - Some(&*x.hash) - == file - .hashes - .get(&PackFileHash::Sha1) - .map(|x| x.as_bytes()) - }) { - dependencies.push(DependencyBuilder { - project_id: Some(models::DBProjectId(dep.project_id)), - version_id: Some(models::DBVersionId(dep.version_id)), - file_name: None, - dependency_type: DependencyType::Embedded.to_string(), - }); - } else if let Some(first_download) = file.downloads.first() { - dependencies.push(DependencyBuilder { - project_id: None, - version_id: None, - file_name: Some( - first_download - .rsplit('/') - .next() - .unwrap_or(first_download) - .to_string(), - ), - dependency_type: DependencyType::Embedded.to_string(), - }); - } + for file in &format.files { + if let Some(dep) = res.iter().find(|x| { + Some(&*x.hash) + == file + .hashes + .get(&PackFileHash::Sha1) + .map(|x| x.as_bytes()) + }) { + dependencies.push(DependencyBuilder { + project_id: Some(models::DBProjectId(dep.project_id)), + version_id: Some(models::DBVersionId(dep.version_id)), + file_name: None, + dependency_type: DependencyType::Embedded.to_string(), + }); + } else if let Some(first_download) = file.downloads.first() { + dependencies.push(DependencyBuilder { + project_id: None, + version_id: None, + file_name: Some( + first_download + .rsplit('/') + .next() + .unwrap_or(first_download) + .to_string(), + ), + dependency_type: DependencyType::Embedded.to_string(), + }); } + } - for file in files { - if !file.is_empty() { - dependencies.push(DependencyBuilder { - project_id: None, - version_id: None, - file_name: Some(file.to_string()), - dependency_type: DependencyType::Embedded.to_string(), - }); - } + for file in files { + if !file.is_empty() { + dependencies.push(DependencyBuilder { + project_id: None, + version_id: None, + file_name: Some(file.to_string()), + dependency_type: DependencyType::Embedded.to_string(), + }); } } } @@ -974,10 +973,10 @@ pub async fn upload_file( )); } - if let ValidationResult::Warning(msg) = validation_result { - if primary { - return Err(CreateError::InvalidInput(msg.to_string())); - } + if let ValidationResult::Warning(msg) = validation_result + && primary + { + return Err(CreateError::InvalidInput(msg.to_string())); } let url = format!("{cdn_url}/{file_path_encode}"); diff --git a/apps/labrinth/src/routes/v3/version_file.rs b/apps/labrinth/src/routes/v3/version_file.rs index f7d2defa0..49567dd15 100644 --- a/apps/labrinth/src/routes/v3/version_file.rs +++ b/apps/labrinth/src/routes/v3/version_file.rs @@ -148,65 +148,55 @@ pub async fn get_update_from_hash( &redis, ) .await? - { - if let Some(project) = database::models::DBProject::get_id( + && let Some(project) = database::models::DBProject::get_id( file.project_id, &**pool, &redis, ) .await? - { - let mut versions = database::models::DBVersion::get_many( - &project.versions, - &**pool, - &redis, - ) - .await? - .into_iter() - .filter(|x| { - let mut bool = true; - if let Some(version_types) = &update_data.version_types { - bool &= version_types - .iter() - .any(|y| y.as_str() == x.inner.version_type); - } - if let Some(loaders) = &update_data.loaders { - bool &= x.loaders.iter().any(|y| loaders.contains(y)); - } - if let Some(loader_fields) = &update_data.loader_fields { - for (key, values) in loader_fields { - bool &= if let Some(x_vf) = x - .version_fields - .iter() - .find(|y| y.field_name == *key) - { - values - .iter() - .any(|v| x_vf.value.contains_json_value(v)) - } else { - true - }; - } - } - bool - }) - .sorted(); - - if let Some(first) = versions.next_back() { - if !is_visible_version( - &first.inner, - &user_option, - &pool, - &redis, - ) - .await? - { - return Err(ApiError::NotFound); - } - - return Ok(HttpResponse::Ok() - .json(models::projects::Version::from(first))); + { + let mut versions = database::models::DBVersion::get_many( + &project.versions, + &**pool, + &redis, + ) + .await? + .into_iter() + .filter(|x| { + let mut bool = true; + if let Some(version_types) = &update_data.version_types { + bool &= version_types + .iter() + .any(|y| y.as_str() == x.inner.version_type); } + if let Some(loaders) = &update_data.loaders { + bool &= x.loaders.iter().any(|y| loaders.contains(y)); + } + if let Some(loader_fields) = &update_data.loader_fields { + for (key, values) in loader_fields { + bool &= if let Some(x_vf) = + x.version_fields.iter().find(|y| y.field_name == *key) + { + values.iter().any(|v| x_vf.value.contains_json_value(v)) + } else { + true + }; + } + } + bool + }) + .sorted(); + + if let Some(first) = versions.next_back() { + if !is_visible_version(&first.inner, &user_option, &pool, &redis) + .await? + { + return Err(ApiError::NotFound); + } + + return Ok( + HttpResponse::Ok().json(models::projects::Version::from(first)) + ); } } Err(ApiError::NotFound) @@ -398,13 +388,12 @@ pub async fn update_files( if let Some(version) = versions .iter() .find(|x| x.inner.project_id == file.project_id) + && let Some(hash) = file.hashes.get(&algorithm) { - if let Some(hash) = file.hashes.get(&algorithm) { - response.insert( - hash.clone(), - models::projects::Version::from(version.clone()), - ); - } + response.insert( + hash.clone(), + models::projects::Version::from(version.clone()), + ); } } @@ -484,69 +473,59 @@ pub async fn update_individual_files( for project in projects { for file in files.iter().filter(|x| x.project_id == project.inner.id) { - if let Some(hash) = file.hashes.get(&algorithm) { - if let Some(query_file) = + if let Some(hash) = file.hashes.get(&algorithm) + && let Some(query_file) = update_data.hashes.iter().find(|x| &x.hash == hash) - { - let version = all_versions - .iter() - .filter(|x| x.inner.project_id == file.project_id) - .filter(|x| { - let mut bool = true; + { + let version = all_versions + .iter() + .filter(|x| x.inner.project_id == file.project_id) + .filter(|x| { + let mut bool = true; - if let Some(version_types) = - &query_file.version_types - { - bool &= version_types.iter().any(|y| { - y.as_str() == x.inner.version_type - }); - } - if let Some(loaders) = &query_file.loaders { - bool &= x - .loaders - .iter() - .any(|y| loaders.contains(y)); - } - - if let Some(loader_fields) = - &query_file.loader_fields - { - for (key, values) in loader_fields { - bool &= if let Some(x_vf) = x - .version_fields - .iter() - .find(|y| y.field_name == *key) - { - values.iter().any(|v| { - x_vf.value.contains_json_value(v) - }) - } else { - true - }; - } - } - bool - }) - .sorted() - .next_back(); - - if let Some(version) = version { - if is_visible_version( - &version.inner, - &user_option, - &pool, - &redis, - ) - .await? - { - response.insert( - hash.clone(), - models::projects::Version::from( - version.clone(), - ), - ); + if let Some(version_types) = &query_file.version_types { + bool &= version_types + .iter() + .any(|y| y.as_str() == x.inner.version_type); } - } + if let Some(loaders) = &query_file.loaders { + bool &= + x.loaders.iter().any(|y| loaders.contains(y)); + } + + if let Some(loader_fields) = &query_file.loader_fields { + for (key, values) in loader_fields { + bool &= if let Some(x_vf) = x + .version_fields + .iter() + .find(|y| y.field_name == *key) + { + values.iter().any(|v| { + x_vf.value.contains_json_value(v) + }) + } else { + true + }; + } + } + bool + }) + .sorted() + .next_back(); + + if let Some(version) = version + && is_visible_version( + &version.inner, + &user_option, + &pool, + &redis, + ) + .await? + { + response.insert( + hash.clone(), + models::projects::Version::from(version.clone()), + ); } } } diff --git a/apps/labrinth/src/routes/v3/versions.rs b/apps/labrinth/src/routes/v3/versions.rs index 5a921a52f..cdca24074 100644 --- a/apps/labrinth/src/routes/v3/versions.rs +++ b/apps/labrinth/src/routes/v3/versions.rs @@ -106,13 +106,12 @@ pub async fn version_project_get_helper( || x.inner.version_number == id.1 }); - if let Some(version) = version { - if is_visible_version(&version.inner, &user_option, &pool, &redis) + if let Some(version) = version + && is_visible_version(&version.inner, &user_option, &pool, &redis) .await? - { - return Ok(HttpResponse::Ok() - .json(models::projects::Version::from(version))); - } + { + return Ok(HttpResponse::Ok() + .json(models::projects::Version::from(version))); } } @@ -190,12 +189,12 @@ pub async fn version_get_helper( .map(|x| x.1) .ok(); - if let Some(data) = version_data { - if is_visible_version(&data.inner, &user_option, &pool, &redis).await? { - return Ok( - HttpResponse::Ok().json(models::projects::Version::from(data)) - ); - } + if let Some(data) = version_data + && is_visible_version(&data.inner, &user_option, &pool, &redis).await? + { + return Ok( + HttpResponse::Ok().json(models::projects::Version::from(data)) + ); } Err(ApiError::NotFound) diff --git a/apps/labrinth/src/sync/status.rs b/apps/labrinth/src/sync/status.rs index 2e94625af..58f4a9602 100644 --- a/apps/labrinth/src/sync/status.rs +++ b/apps/labrinth/src/sync/status.rs @@ -15,14 +15,12 @@ pub async fn get_user_status( return Some(friend_status); } - if let Ok(mut conn) = redis.pool.get().await { - if let Ok(mut statuses) = + if let Ok(mut conn) = redis.pool.get().await + && let Ok(mut statuses) = conn.sscan::<_, String>(get_field_name(user)).await - { - if let Some(status_json) = statuses.next_item().await { - return serde_json::from_str::(&status_json).ok(); - } - } + && let Some(status_json) = statuses.next_item().await + { + return serde_json::from_str::(&status_json).ok(); } None diff --git a/apps/labrinth/src/util/img.rs b/apps/labrinth/src/util/img.rs index 680b48417..9287c8873 100644 --- a/apps/labrinth/src/util/img.rs +++ b/apps/labrinth/src/util/img.rs @@ -138,12 +138,11 @@ fn process_image( let (orig_width, orig_height) = img.dimensions(); let aspect_ratio = orig_width as f32 / orig_height as f32; - if let Some(target_width) = target_width { - if img.width() > target_width { - let new_height = - (target_width as f32 / aspect_ratio).round() as u32; - img = img.resize(target_width, new_height, FilterType::Lanczos3); - } + if let Some(target_width) = target_width + && img.width() > target_width + { + let new_height = (target_width as f32 / aspect_ratio).round() as u32; + img = img.resize(target_width, new_height, FilterType::Lanczos3); } if let Some(min_aspect_ratio) = min_aspect_ratio { diff --git a/apps/labrinth/src/util/ratelimit.rs b/apps/labrinth/src/util/ratelimit.rs index 4f7b10342..c64c801fe 100644 --- a/apps/labrinth/src/util/ratelimit.rs +++ b/apps/labrinth/src/util/ratelimit.rs @@ -133,12 +133,11 @@ pub async fn rate_limit_middleware( .expect("Rate limiter not configured properly") .clone(); - if let Some(key) = req.headers().get("x-ratelimit-key") { - if key.to_str().ok() + if let Some(key) = req.headers().get("x-ratelimit-key") + && key.to_str().ok() == dotenvy::var("RATE_LIMIT_IGNORE_KEY").ok().as_deref() - { - return Ok(next.call(req).await?.map_into_left_body()); - } + { + return Ok(next.call(req).await?.map_into_left_body()); } let conn_info = req.connection_info().clone(); diff --git a/apps/labrinth/src/util/validate.rs b/apps/labrinth/src/util/validate.rs index dfa4b7a71..06af10317 100644 --- a/apps/labrinth/src/util/validate.rs +++ b/apps/labrinth/src/util/validate.rs @@ -22,46 +22,47 @@ pub fn validation_errors_to_string( let key_option = map.keys().next(); - if let Some(field) = key_option { - if let Some(error) = map.get(field) { - return match error { - ValidationErrorsKind::Struct(errors) => { - validation_errors_to_string( + if let Some(field) = key_option + && let Some(error) = map.get(field) + { + return match error { + ValidationErrorsKind::Struct(errors) => { + validation_errors_to_string( + *errors.clone(), + Some(format!("of item {field}")), + ) + } + ValidationErrorsKind::List(list) => { + if let Some((index, errors)) = list.iter().next() { + output.push_str(&validation_errors_to_string( *errors.clone(), - Some(format!("of item {field}")), - ) + Some(format!("of list {field} with index {index}")), + )); } - ValidationErrorsKind::List(list) => { - if let Some((index, errors)) = list.iter().next() { - output.push_str(&validation_errors_to_string( - *errors.clone(), - Some(format!("of list {field} with index {index}")), - )); - } - output - } - ValidationErrorsKind::Field(errors) => { - if let Some(error) = errors.first() { - if let Some(adder) = adder { - write!( + output + } + ValidationErrorsKind::Field(errors) => { + if let Some(error) = errors.first() { + if let Some(adder) = adder { + write!( &mut output, "Field {field} {adder} failed validation with error: {}", error.code ).unwrap(); - } else { - write!( - &mut output, - "Field {field} failed validation with error: {}", - error.code - ).unwrap(); - } + } else { + write!( + &mut output, + "Field {field} failed validation with error: {}", + error.code + ) + .unwrap(); } - - output } - }; - } + + output + } + }; } String::new() diff --git a/apps/labrinth/src/util/webhook.rs b/apps/labrinth/src/util/webhook.rs index 88eaa1d6f..1d7be03ab 100644 --- a/apps/labrinth/src/util/webhook.rs +++ b/apps/labrinth/src/util/webhook.rs @@ -238,17 +238,17 @@ pub async fn send_slack_webhook( } }); - if let Some(icon_url) = metadata.project_icon_url { - if let Some(project_block) = project_block.as_object_mut() { - project_block.insert( - "accessory".to_string(), - serde_json::json!({ - "type": "image", - "image_url": icon_url, - "alt_text": metadata.project_title - }), - ); - } + if let Some(icon_url) = metadata.project_icon_url + && let Some(project_block) = project_block.as_object_mut() + { + project_block.insert( + "accessory".to_string(), + serde_json::json!({ + "type": "image", + "image_url": icon_url, + "alt_text": metadata.project_title + }), + ); } blocks.push(project_block); diff --git a/apps/labrinth/tests/common/permissions.rs b/apps/labrinth/tests/common/permissions.rs index e4ce62e1e..00614a477 100644 --- a/apps/labrinth/tests/common/permissions.rs +++ b/apps/labrinth/tests/common/permissions.rs @@ -222,10 +222,10 @@ impl<'a, A: Api> PermissionsTest<'a, A> { resp.status().as_u16() )); } - if resp.status() == StatusCode::OK { - if let Some(failure_json_check) = &self.failure_json_check { - failure_json_check(&test::read_body_json(resp).await); - } + if resp.status() == StatusCode::OK + && let Some(failure_json_check) = &self.failure_json_check + { + failure_json_check(&test::read_body_json(resp).await); } // Failure test- logged in on a non-team user @@ -246,10 +246,10 @@ impl<'a, A: Api> PermissionsTest<'a, A> { resp.status().as_u16() )); } - if resp.status() == StatusCode::OK { - if let Some(failure_json_check) = &self.failure_json_check { - failure_json_check(&test::read_body_json(resp).await); - } + if resp.status() == StatusCode::OK + && let Some(failure_json_check) = &self.failure_json_check + { + failure_json_check(&test::read_body_json(resp).await); } // Failure test- logged in with EVERY non-relevant permission @@ -270,10 +270,10 @@ impl<'a, A: Api> PermissionsTest<'a, A> { resp.status().as_u16() )); } - if resp.status() == StatusCode::OK { - if let Some(failure_json_check) = &self.failure_json_check { - failure_json_check(&test::read_body_json(resp).await); - } + if resp.status() == StatusCode::OK + && let Some(failure_json_check) = &self.failure_json_check + { + failure_json_check(&test::read_body_json(resp).await); } // Patch user's permissions to success permissions @@ -300,10 +300,10 @@ impl<'a, A: Api> PermissionsTest<'a, A> { resp.status().as_u16() )); } - if resp.status() == StatusCode::OK { - if let Some(success_json_check) = &self.success_json_check { - success_json_check(&test::read_body_json(resp).await); - } + if resp.status() == StatusCode::OK + && let Some(success_json_check) = &self.success_json_check + { + success_json_check(&test::read_body_json(resp).await); } // If the remove_user flag is set, remove the user from the project diff --git a/clippy.toml b/clippy.toml index 434acf91a..b77c92414 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1,2 +1,2 @@ allow-dbg-in-tests = true -msrv = "1.88.0" +msrv = "1.89.0" diff --git a/packages/app-lib/src/api/handler.rs b/packages/app-lib/src/api/handler.rs index 67e36b2f1..362f6de01 100644 --- a/packages/app-lib/src/api/handler.rs +++ b/packages/app-lib/src/api/handler.rs @@ -50,10 +50,10 @@ pub async fn parse_command( // We assume anything else is a filepath to an .mrpack file let path = PathBuf::from(command_string); let path = io::canonicalize(path)?; - if let Some(ext) = path.extension() { - if ext == "mrpack" { - return Ok(CommandPayload::RunMRPack { path }); - } + if let Some(ext) = path.extension() + && ext == "mrpack" + { + return Ok(CommandPayload::RunMRPack { path }); } emit_warning(&format!( "Invalid command, unrecognized filetype: {}", diff --git a/packages/app-lib/src/api/jre.rs b/packages/app-lib/src/api/jre.rs index 412d44720..680b85295 100644 --- a/packages/app-lib/src/api/jre.rs +++ b/packages/app-lib/src/api/jre.rs @@ -106,13 +106,13 @@ pub async fn auto_install_java(java_version: u32) -> crate::Result { })?; // removes the old installation of java - if let Some(file) = archive.file_names().next() { - if let Some(dir) = file.split('/').next() { - let path = path.join(dir); + if let Some(file) = archive.file_names().next() + && let Some(dir) = file.split('/').next() + { + let path = path.join(dir); - if path.exists() { - io::remove_dir_all(path).await?; - } + if path.exists() { + io::remove_dir_all(path).await?; } } diff --git a/packages/app-lib/src/api/minecraft_auth.rs b/packages/app-lib/src/api/minecraft_auth.rs index 568a6aca1..ae5e1a6d7 100644 --- a/packages/app-lib/src/api/minecraft_auth.rs +++ b/packages/app-lib/src/api/minecraft_auth.rs @@ -54,11 +54,11 @@ pub async fn remove_user(uuid: uuid::Uuid) -> crate::Result<()> { if let Some((uuid, user)) = users.remove(&uuid) { Credentials::remove(uuid, &state.pool).await?; - if user.active { - if let Some((_, mut user)) = users.into_iter().next() { - user.active = true; - user.upsert(&state.pool).await?; - } + if user.active + && let Some((_, mut user)) = users.into_iter().next() + { + user.active = true; + user.upsert(&state.pool).await?; } } diff --git a/packages/app-lib/src/api/pack/import/atlauncher.rs b/packages/app-lib/src/api/pack/import/atlauncher.rs index 1c8ba084d..f5e052c64 100644 --- a/packages/app-lib/src/api/pack/import/atlauncher.rs +++ b/packages/app-lib/src/api/pack/import/atlauncher.rs @@ -221,14 +221,14 @@ async fn import_atlauncher_unmanaged( .unwrap_or_else(|| backup_name.to_string()); prof.install_stage = ProfileInstallStage::PackInstalling; - if let Some(ref project_id) = description.project_id { - if let Some(ref version_id) = description.version_id { - prof.linked_data = Some(LinkedData { - project_id: project_id.clone(), - version_id: version_id.clone(), - locked: true, - }) - } + if let Some(ref project_id) = description.project_id + && let Some(ref version_id) = description.version_id + { + prof.linked_data = Some(LinkedData { + project_id: project_id.clone(), + version_id: version_id.clone(), + locked: true, + }) } prof.icon_path = description diff --git a/packages/app-lib/src/api/pack/install_from.rs b/packages/app-lib/src/api/pack/install_from.rs index d3ec041cf..29f616aac 100644 --- a/packages/app-lib/src/api/pack/install_from.rs +++ b/packages/app-lib/src/api/pack/install_from.rs @@ -383,18 +383,18 @@ pub async fn set_profile_information( .unwrap_or_else(|| backup_name.to_string()); prof.install_stage = ProfileInstallStage::PackInstalling; - if let Some(ref project_id) = description.project_id { - if let Some(ref version_id) = description.version_id { - prof.linked_data = Some(LinkedData { - project_id: project_id.clone(), - version_id: version_id.clone(), - locked: if !ignore_lock { - true - } else { - prof.linked_data.as_ref().is_none_or(|x| x.locked) - }, - }) - } + if let Some(ref project_id) = description.project_id + && let Some(ref version_id) = description.version_id + { + prof.linked_data = Some(LinkedData { + project_id: project_id.clone(), + version_id: version_id.clone(), + locked: if !ignore_lock { + true + } else { + prof.linked_data.as_ref().is_none_or(|x| x.locked) + }, + }) } prof.icon_path = description diff --git a/packages/app-lib/src/api/pack/install_mrpack.rs b/packages/app-lib/src/api/pack/install_mrpack.rs index d65991a65..9831b8e54 100644 --- a/packages/app-lib/src/api/pack/install_mrpack.rs +++ b/packages/app-lib/src/api/pack/install_mrpack.rs @@ -149,13 +149,12 @@ pub async fn install_zipped_mrpack_files( let profile_path = profile_path.clone(); async move { //TODO: Future update: prompt user for optional files in a modpack - if let Some(env) = project.env { - if env + if let Some(env) = project.env + && env .get(&EnvType::Client) .is_some_and(|x| x == &SideType::Unsupported) - { - return Ok(()); - } + { + return Ok(()); } let file = fetch_mirrors( @@ -375,12 +374,12 @@ pub async fn remove_all_related_files( ) .await? { - if let Some(metadata) = &project.metadata { - if to_remove.contains(&metadata.project_id) { - let path = profile_full_path.join(file_path); - if path.exists() { - io::remove_file(&path).await?; - } + if let Some(metadata) = &project.metadata + && to_remove.contains(&metadata.project_id) + { + let path = profile_full_path.join(file_path); + if path.exists() { + io::remove_file(&path).await?; } } } diff --git a/packages/app-lib/src/api/profile/mod.rs b/packages/app-lib/src/api/profile/mod.rs index e30ff2e3b..f5338017c 100644 --- a/packages/app-lib/src/api/profile/mod.rs +++ b/packages/app-lib/src/api/profile/mod.rs @@ -337,28 +337,26 @@ pub async fn update_project( ) .await? .remove(project_path) + && let Some(update_version) = &file.update_version_id { - if let Some(update_version) = &file.update_version_id { - let path = Profile::add_project_version( - profile_path, - update_version, - &state.pool, - &state.fetch_semaphore, - &state.io_semaphore, - ) - .await?; + let path = Profile::add_project_version( + profile_path, + update_version, + &state.pool, + &state.fetch_semaphore, + &state.io_semaphore, + ) + .await?; - if path != project_path { - Profile::remove_project(profile_path, project_path).await?; - } - - if !skip_send_event.unwrap_or(false) { - emit_profile(profile_path, ProfilePayloadType::Edited) - .await?; - } - - return Ok(path); + if path != project_path { + Profile::remove_project(profile_path, project_path).await?; } + + if !skip_send_event.unwrap_or(false) { + emit_profile(profile_path, ProfilePayloadType::Edited).await?; + } + + return Ok(path); } Err(crate::ErrorKind::InputError( @@ -479,10 +477,10 @@ pub async fn export_mrpack( let included_export_candidates = included_export_candidates .into_iter() .filter(|x| { - if let Some(f) = PathBuf::from(x).file_name() { - if f.to_string_lossy().starts_with(".DS_Store") { - return false; - } + if let Some(f) = PathBuf::from(x).file_name() + && f.to_string_lossy().starts_with(".DS_Store") + { + return false; } true }) diff --git a/packages/app-lib/src/event/mod.rs b/packages/app-lib/src/event/mod.rs index 92b7b53fa..488d56cec 100644 --- a/packages/app-lib/src/event/mod.rs +++ b/packages/app-lib/src/event/mod.rs @@ -191,11 +191,6 @@ pub struct LoadingPayload { pub message: String, } -#[derive(Serialize, Clone)] -pub struct OfflinePayload { - pub offline: bool, -} - #[derive(Serialize, Clone)] pub struct WarningPayload { pub message: String, diff --git a/packages/app-lib/src/launcher/args.rs b/packages/app-lib/src/launcher/args.rs index 23ed3af67..350d67c0b 100644 --- a/packages/app-lib/src/launcher/args.rs +++ b/packages/app-lib/src/launcher/args.rs @@ -32,15 +32,15 @@ pub fn get_class_paths( let mut cps = libraries .iter() .filter_map(|library| { - if let Some(rules) = &library.rules { - if !parse_rules( + if let Some(rules) = &library.rules + && !parse_rules( rules, java_arch, &QuickPlayType::None, minecraft_updated, - ) { - return None; - } + ) + { + return None; } if !library.include_in_classpath { @@ -504,10 +504,10 @@ pub async fn get_processor_main_class( let mut line = line.map_err(IOError::from)?; line.retain(|c| !c.is_whitespace()); - if line.starts_with("Main-Class:") { - if let Some(class) = line.split(':').nth(1) { - return Ok(Some(class.to_string())); - } + if line.starts_with("Main-Class:") + && let Some(class) = line.split(':').nth(1) + { + return Ok(Some(class.to_string())); } } diff --git a/packages/app-lib/src/launcher/download.rs b/packages/app-lib/src/launcher/download.rs index 4a0a5879f..8fbece3e4 100644 --- a/packages/app-lib/src/launcher/download.rs +++ b/packages/app-lib/src/launcher/download.rs @@ -290,12 +290,11 @@ pub async fn download_libraries( loading_try_for_each_concurrent( stream::iter(libraries.iter()) .map(Ok::<&Library, crate::Error>), None, loading_bar,loading_amount,num_files, None,|library| async move { - if let Some(rules) = &library.rules { - if !parse_rules(rules, java_arch, &QuickPlayType::None, minecraft_updated) { + if let Some(rules) = &library.rules + && !parse_rules(rules, java_arch, &QuickPlayType::None, minecraft_updated) { tracing::trace!("Skipped library {}", &library.name); return Ok(()); } - } if !library.downloadable { tracing::trace!("Skipped non-downloadable library {}", &library.name); @@ -311,15 +310,14 @@ pub async fn download_libraries( return Ok(()); } - if let Some(d::minecraft::LibraryDownloads { artifact: Some(ref artifact), ..}) = library.downloads { - if !artifact.url.is_empty(){ + if let Some(d::minecraft::LibraryDownloads { artifact: Some(ref artifact), ..}) = library.downloads + && !artifact.url.is_empty(){ let bytes = fetch(&artifact.url, Some(&artifact.sha1), &st.fetch_semaphore, &st.pool) .await?; write(&path, &bytes, &st.io_semaphore).await?; tracing::trace!("Fetched library {} to path {:?}", &library.name, &path); return Ok::<_, crate::Error>(()); } - } let url = [ library diff --git a/packages/app-lib/src/launcher/mod.rs b/packages/app-lib/src/launcher/mod.rs index f5c4e50b0..64eb1d90e 100644 --- a/packages/app-lib/src/launcher/mod.rs +++ b/packages/app-lib/src/launcher/mod.rs @@ -341,10 +341,10 @@ pub async fn install_minecraft( // Forge processors (90-100) for (index, processor) in processors.iter().enumerate() { - if let Some(sides) = &processor.sides { - if !sides.contains(&String::from("client")) { - continue; - } + if let Some(sides) = &processor.sides + && !sides.contains(&String::from("client")) + { + continue; } let cp = { diff --git a/packages/app-lib/src/state/dirs.rs b/packages/app-lib/src/state/dirs.rs index 21f62eb78..1f577f7c4 100644 --- a/packages/app-lib/src/state/dirs.rs +++ b/packages/app-lib/src/state/dirs.rs @@ -385,10 +385,10 @@ impl DirectoryInfo { return Err(e); } } else { - if let Some(disk_usage) = get_disk_usage(&move_dir)? { - if total_size > disk_usage { - return Err(crate::ErrorKind::DirectoryMoveError(format!("Not enough space to move directory to {}: only {} bytes available", app_dir.display(), disk_usage)).into()); - } + if let Some(disk_usage) = get_disk_usage(&move_dir)? + && total_size > disk_usage + { + return Err(crate::ErrorKind::DirectoryMoveError(format!("Not enough space to move directory to {}: only {} bytes available", app_dir.display(), disk_usage)).into()); } let loader_bar_id = Arc::new(&loader_bar_id); diff --git a/packages/app-lib/src/state/friends.rs b/packages/app-lib/src/state/friends.rs index 0079daa40..af9f36d8d 100644 --- a/packages/app-lib/src/state/friends.rs +++ b/packages/app-lib/src/state/friends.rs @@ -180,27 +180,24 @@ impl FriendsSocket { ServerToClientMessage::FriendSocketStoppedListening { .. } => {}, // TODO ServerToClientMessage::SocketConnected { to_socket, new_socket } => { - if let Some(connected_to) = sockets.get(&to_socket) { - if let InternalTunnelSocket::Listening(local_addr) = *connected_to.value().clone() { - if let Ok(new_stream) = TcpStream::connect(local_addr).await { + if let Some(connected_to) = sockets.get(&to_socket) + && let InternalTunnelSocket::Listening(local_addr) = *connected_to.value().clone() + && let Ok(new_stream) = TcpStream::connect(local_addr).await { let (read, write) = new_stream.into_split(); sockets.insert(new_socket, Arc::new(InternalTunnelSocket::Connected(Mutex::new(write)))); Self::socket_read_loop(write_handle.clone(), read, new_socket); continue; } - } - } let _ = Self::send_message(&write_handle, ClientToServerMessage::SocketClose { socket: new_socket }).await; }, ServerToClientMessage::SocketClosed { socket } => { sockets.remove_if(&socket, |_, x| matches!(*x.clone(), InternalTunnelSocket::Connected(_))); }, ServerToClientMessage::SocketData { socket, data } => { - if let Some(mut socket) = sockets.get_mut(&socket) { - if let InternalTunnelSocket::Connected(ref stream) = *socket.value_mut().clone() { + if let Some(mut socket) = sockets.get_mut(&socket) + && let InternalTunnelSocket::Connected(ref stream) = *socket.value_mut().clone() { let _ = stream.lock().await.write_all(&data).await; } - } }, } } diff --git a/packages/app-lib/src/state/fs_watcher.rs b/packages/app-lib/src/state/fs_watcher.rs index 12bd89313..c0b1128d9 100644 --- a/packages/app-lib/src/state/fs_watcher.rs +++ b/packages/app-lib/src/state/fs_watcher.rs @@ -100,8 +100,8 @@ pub async fn init_watcher() -> crate::Result { let profile_path_str = profile_path_str.clone(); let world = world.clone(); tokio::spawn(async move { - if let Ok(state) = State::get().await { - if let Err(e) = attached_world_data::AttachedWorldData::remove_for_world( + if let Ok(state) = State::get().await + && let Err(e) = attached_world_data::AttachedWorldData::remove_for_world( &profile_path_str, WorldType::Singleplayer, &world, @@ -109,7 +109,6 @@ pub async fn init_watcher() -> crate::Result { ).await { tracing::warn!("Failed to remove AttachedWorldData for '{world}': {e}") } - } }); } Some(ProfilePayloadType::WorldUpdated { world }) @@ -150,14 +149,14 @@ pub(crate) async fn watch_profiles_init( ) { if let Ok(profiles_dir) = std::fs::read_dir(dirs.profiles_dir()) { for profile_dir in profiles_dir { - if let Ok(file_name) = profile_dir.map(|x| x.file_name()) { - if let Some(file_name) = file_name.to_str() { - if file_name.starts_with(".DS_Store") { - continue; - }; + if let Ok(file_name) = profile_dir.map(|x| x.file_name()) + && let Some(file_name) = file_name.to_str() + { + if file_name.starts_with(".DS_Store") { + continue; + }; - watch_profile(file_name, watcher, dirs).await; - } + watch_profile(file_name, watcher, dirs).await; } } } diff --git a/packages/app-lib/src/state/legacy_converter.rs b/packages/app-lib/src/state/legacy_converter.rs index 7a04defde..df043de35 100644 --- a/packages/app-lib/src/state/legacy_converter.rs +++ b/packages/app-lib/src/state/legacy_converter.rs @@ -76,10 +76,9 @@ where .loaded_config_dir .clone() .and_then(|x| x.to_str().map(|x| x.to_string())) + && path != old_launcher_root_str { - if path != old_launcher_root_str { - settings.custom_dir = Some(path); - } + settings.custom_dir = Some(path); } settings.prev_custom_dir = Some(old_launcher_root_str.clone()); @@ -136,31 +135,27 @@ where .await?; } - if let Some(device_token) = minecraft_auth.token { - if let Ok(private_key) = + if let Some(device_token) = minecraft_auth.token + && let Ok(private_key) = SigningKey::from_pkcs8_pem(&device_token.private_key) - { - if let Ok(uuid) = Uuid::parse_str(&device_token.id) { - DeviceTokenPair { - token: DeviceToken { - issue_instant: device_token.token.issue_instant, - not_after: device_token.token.not_after, - token: device_token.token.token, - display_claims: device_token - .token - .display_claims, - }, - key: DeviceTokenKey { - id: uuid, - key: private_key, - x: device_token.x, - y: device_token.y, - }, - } - .upsert(exec) - .await?; - } + && let Ok(uuid) = Uuid::parse_str(&device_token.id) + { + DeviceTokenPair { + token: DeviceToken { + issue_instant: device_token.token.issue_instant, + not_after: device_token.token.not_after, + token: device_token.token.token, + display_claims: device_token.token.display_claims, + }, + key: DeviceTokenKey { + id: uuid, + key: private_key, + x: device_token.x, + y: device_token.y, + }, } + .upsert(exec) + .await?; } } @@ -207,100 +202,93 @@ where update_version, .. } = project.metadata - { - if let Some(file) = version + && let Some(file) = version .files .iter() .find(|x| x.hashes.get("sha512") == Some(&sha512)) - { - if let Some(sha1) = file.hashes.get("sha1") { - if let Ok(metadata) = full_path.metadata() { - let file_name = format!( - "{}/{}", - profile.path, - path.replace('\\', "/") - .replace(".disabled", "") - ); + && let Some(sha1) = file.hashes.get("sha1") + { + if let Ok(metadata) = full_path.metadata() { + let file_name = format!( + "{}/{}", + profile.path, + path.replace('\\', "/") + .replace(".disabled", "") + ); - cached_entries.push(CacheValue::FileHash( - CachedFileHash { - path: file_name, - size: metadata.len(), - hash: sha1.clone(), - project_type: ProjectType::get_from_parent_folder(&full_path), - }, - )); - } - - cached_entries.push(CacheValue::File( - CachedFile { - hash: sha1.clone(), - project_id: version.project_id.clone(), - version_id: version.id.clone(), - }, - )); - - if let Some(update_version) = update_version { - let mod_loader: ModLoader = - profile.metadata.loader.into(); - cached_entries.push( - CacheValue::FileUpdate( - CachedFileUpdate { - hash: sha1.clone(), - game_version: profile - .metadata - .game_version - .clone(), - loaders: vec![ - mod_loader - .as_str() - .to_string(), - ], - update_version_id: - update_version.id.clone(), - }, + cached_entries.push(CacheValue::FileHash( + CachedFileHash { + path: file_name, + size: metadata.len(), + hash: sha1.clone(), + project_type: + ProjectType::get_from_parent_folder( + &full_path, ), - ); - - cached_entries.push(CacheValue::Version( - (*update_version).into(), - )); - } - - let members = members - .into_iter() - .map(|x| { - let user = User { - id: x.user.id, - username: x.user.username, - avatar_url: x.user.avatar_url, - bio: x.user.bio, - created: x.user.created, - role: x.user.role, - badges: 0, - }; - - cached_entries.push(CacheValue::User( - user.clone(), - )); - - TeamMember { - team_id: x.team_id, - user, - is_owner: x.role == "Owner", - role: x.role, - ordering: x.ordering, - } - }) - .collect::>(); - - cached_entries.push(CacheValue::Team(members)); - - cached_entries.push(CacheValue::Version( - (*version).into(), - )); - } + }, + )); } + + cached_entries.push(CacheValue::File(CachedFile { + hash: sha1.clone(), + project_id: version.project_id.clone(), + version_id: version.id.clone(), + })); + + if let Some(update_version) = update_version { + let mod_loader: ModLoader = + profile.metadata.loader.into(); + cached_entries.push(CacheValue::FileUpdate( + CachedFileUpdate { + hash: sha1.clone(), + game_version: profile + .metadata + .game_version + .clone(), + loaders: vec![ + mod_loader.as_str().to_string(), + ], + update_version_id: update_version + .id + .clone(), + }, + )); + + cached_entries.push(CacheValue::Version( + (*update_version).into(), + )); + } + + let members = members + .into_iter() + .map(|x| { + let user = User { + id: x.user.id, + username: x.user.username, + avatar_url: x.user.avatar_url, + bio: x.user.bio, + created: x.user.created, + role: x.user.role, + badges: 0, + }; + + cached_entries + .push(CacheValue::User(user.clone())); + + TeamMember { + team_id: x.team_id, + user, + is_owner: x.role == "Owner", + role: x.role, + ordering: x.ordering, + } + }) + .collect::>(); + + cached_entries.push(CacheValue::Team(members)); + + cached_entries + .push(CacheValue::Version((*version).into())); } } @@ -332,16 +320,15 @@ where .map(|x| x.id), groups: profile.metadata.groups, linked_data: profile.metadata.linked_data.and_then(|x| { - if let Some(project_id) = x.project_id { - if let Some(version_id) = x.version_id { - if let Some(locked) = x.locked { - return Some(LinkedData { - project_id, - version_id, - locked, - }); - } - } + if let Some(project_id) = x.project_id + && let Some(version_id) = x.version_id + && let Some(locked) = x.locked + { + return Some(LinkedData { + project_id, + version_id, + locked, + }); } None diff --git a/packages/app-lib/src/state/minecraft_auth.rs b/packages/app-lib/src/state/minecraft_auth.rs index fb9129989..1b5a43986 100644 --- a/packages/app-lib/src/state/minecraft_auth.rs +++ b/packages/app-lib/src/state/minecraft_auth.rs @@ -393,10 +393,9 @@ impl Credentials { .. }, ) = *err.raw + && (source.is_connect() || source.is_timeout()) { - if source.is_connect() || source.is_timeout() { - return Ok(Some(creds)); - } + return Ok(Some(creds)); } Err(err) @@ -640,36 +639,31 @@ impl DeviceTokenPair { .fetch_optional(exec) .await?; - if let Some(x) = res { - if let Ok(uuid) = Uuid::parse_str(&x.uuid) { - if let Ok(private_key) = - SigningKey::from_pkcs8_pem(&x.private_key) - { - return Ok(Some(Self { - token: DeviceToken { - issue_instant: Utc - .timestamp_opt(x.issue_instant, 0) - .single() - .unwrap_or_else(Utc::now), - not_after: Utc - .timestamp_opt(x.not_after, 0) - .single() - .unwrap_or_else(Utc::now), - token: x.token, - display_claims: serde_json::from_value( - x.display_claims, - ) - .unwrap_or_default(), - }, - key: DeviceTokenKey { - id: uuid, - key: private_key, - x: x.x, - y: x.y, - }, - })); - } - } + if let Some(x) = res + && let Ok(uuid) = Uuid::parse_str(&x.uuid) + && let Ok(private_key) = SigningKey::from_pkcs8_pem(&x.private_key) + { + return Ok(Some(Self { + token: DeviceToken { + issue_instant: Utc + .timestamp_opt(x.issue_instant, 0) + .single() + .unwrap_or_else(Utc::now), + not_after: Utc + .timestamp_opt(x.not_after, 0) + .single() + .unwrap_or_else(Utc::now), + token: x.token, + display_claims: serde_json::from_value(x.display_claims) + .unwrap_or_default(), + }, + key: DeviceTokenKey { + id: uuid, + key: private_key, + x: x.x, + y: x.y, + }, + })); } Ok(None) diff --git a/packages/app-lib/src/state/process.rs b/packages/app-lib/src/state/process.rs index da9a59c3c..d8ed187e7 100644 --- a/packages/app-lib/src/state/process.rs +++ b/packages/app-lib/src/state/process.rs @@ -360,18 +360,17 @@ impl Process { } // Write the throwable if present - if !current_content.is_empty() { - if let Err(e) = + if !current_content.is_empty() + && let Err(e) = Process::append_to_log_file( &log_path, ¤t_content, ) - { - tracing::error!( - "Failed to write throwable to log file: {}", - e - ); - } + { + tracing::error!( + "Failed to write throwable to log file: {}", + e + ); } } } @@ -429,15 +428,13 @@ impl Process { if let Some(timestamp) = current_event.timestamp.as_deref() - { - if let Err(e) = Self::maybe_handle_server_join_logging( + && let Err(e) = Self::maybe_handle_server_join_logging( profile_path, timestamp, message ).await { tracing::error!("Failed to handle server join logging: {e}"); } - } } } _ => {} @@ -451,29 +448,26 @@ impl Process { } else if !in_event && !e.inplace_trim_end() && !e.inplace_trim_start() + && let Ok(text) = e.unescape() + && let Err(e) = Process::append_to_log_file( + &log_path, + &format!("{text}\n"), + ) { - if let Ok(text) = e.unescape() { - if let Err(e) = Process::append_to_log_file( - &log_path, - &format!("{text}\n"), - ) { - tracing::error!( - "Failed to write to log file: {}", - e - ); - } - } + tracing::error!( + "Failed to write to log file: {}", + e + ); } } Ok(Event::CData(e)) => { - if in_message || in_throwable { - if let Ok(text) = e + if (in_message || in_throwable) + && let Ok(text) = e .escape() .map_err(|x| x.into()) .and_then(|x| x.unescape()) - { - current_content.push_str(&text); - } + { + current_content.push_str(&text); } } _ => (), @@ -720,16 +714,13 @@ impl Process { let logs_folder = state.directories.profile_logs_dir(&profile_path); let log_path = logs_folder.join(LAUNCHER_LOG_PATH); - if log_path.exists() { - if let Err(e) = Process::append_to_log_file( + if log_path.exists() + && let Err(e) = Process::append_to_log_file( &log_path, &format!("\n# Process exited with status: {mc_exit_status}\n"), - ) { - tracing::warn!( - "Failed to write exit status to log file: {}", - e - ); - } + ) + { + tracing::warn!("Failed to write exit status to log file: {}", e); } let _ = state.discord_rpc.clear_to_default(true).await; diff --git a/packages/app-lib/src/state/profiles.rs b/packages/app-lib/src/state/profiles.rs index 14cce61cb..d8194794a 100644 --- a/packages/app-lib/src/state/profiles.rs +++ b/packages/app-lib/src/state/profiles.rs @@ -629,21 +629,20 @@ impl Profile { { let subdirectory = subdirectory.map_err(io::IOError::from)?.path(); - if subdirectory.is_file() { - if let Some(file_name) = subdirectory + if subdirectory.is_file() + && let Some(file_name) = subdirectory .file_name() .and_then(|x| x.to_str()) - { - let file_size = subdirectory - .metadata() - .map_err(io::IOError::from)? - .len(); + { + let file_size = subdirectory + .metadata() + .map_err(io::IOError::from)? + .len(); - keys.push(format!( - "{file_size}-{}/{folder}/{file_name}", - profile.path - )); - } + keys.push(format!( + "{file_size}-{}/{folder}/{file_name}", + profile.path + )); } } } @@ -901,30 +900,29 @@ impl Profile { { let subdirectory = subdirectory.map_err(io::IOError::from)?.path(); - if subdirectory.is_file() { - if let Some(file_name) = + if subdirectory.is_file() + && let Some(file_name) = subdirectory.file_name().and_then(|x| x.to_str()) - { - let file_size = subdirectory - .metadata() - .map_err(io::IOError::from)? - .len(); + { + let file_size = subdirectory + .metadata() + .map_err(io::IOError::from)? + .len(); - keys.push(InitialScanFile { - path: format!( - "{}/{folder}/{}", - self.path, - file_name.trim_end_matches(".disabled") - ), - file_name: file_name.to_string(), - project_type, - size: file_size, - cache_key: format!( - "{file_size}-{}/{folder}/{file_name}", - self.path - ), - }); - } + keys.push(InitialScanFile { + path: format!( + "{}/{folder}/{}", + self.path, + file_name.trim_end_matches(".disabled") + ), + file_name: file_name.to_string(), + project_type, + size: file_size, + cache_key: format!( + "{file_size}-{}/{folder}/{file_name}", + self.path + ), + }); } } } diff --git a/packages/app-lib/src/util/jre.rs b/packages/app-lib/src/util/jre.rs index ed197a32b..4e2c3c4b5 100644 --- a/packages/app-lib/src/util/jre.rs +++ b/packages/app-lib/src/util/jre.rs @@ -191,22 +191,21 @@ async fn get_all_autoinstalled_jre_path() -> Result, JREError> let mut jre_paths = HashSet::new(); let base_path = state.directories.java_versions_dir(); - if base_path.is_dir() { - if let Ok(dir) = std::fs::read_dir(base_path) { - for entry in dir.flatten() { - let file_path = entry.path().join("bin"); + if base_path.is_dir() + && let Ok(dir) = std::fs::read_dir(base_path) + { + for entry in dir.flatten() { + let file_path = entry.path().join("bin"); - if let Ok(contents) = - std::fs::read_to_string(file_path.clone()) + if let Ok(contents) = std::fs::read_to_string(file_path.clone()) + { + let entry = entry.path().join(contents); + jre_paths.insert(entry); + } else { + #[cfg(not(target_os = "macos"))] { - let entry = entry.path().join(contents); - jre_paths.insert(entry); - } else { - #[cfg(not(target_os = "macos"))] - { - let file_path = file_path.join(JAVA_BIN); - jre_paths.insert(file_path); - } + let file_path = file_path.join(JAVA_BIN); + jre_paths.insert(file_path); } } } @@ -300,20 +299,20 @@ pub async fn check_java_at_filepath(path: &Path) -> crate::Result { } // Extract version info from it - if let Some(arch) = java_arch { - if let Some(version) = java_version { - if let Ok(version) = extract_java_version(version) { - let path = java.to_string_lossy().to_string(); - return Ok(JavaVersion { - parsed_version: version, - path, - version: version.to_string(), - architecture: arch.to_string(), - }); - } - - return Err(JREError::InvalidJREVersion(version.to_owned()).into()); + if let Some(arch) = java_arch + && let Some(version) = java_version + { + if let Ok(version) = extract_java_version(version) { + let path = java.to_string_lossy().to_string(); + return Ok(JavaVersion { + parsed_version: version, + path, + version: version.to_string(), + architecture: arch.to_string(), + }); } + + return Err(JREError::InvalidJREVersion(version.to_owned()).into()); } Err(JREError::FailedJavaCheck(java).into()) diff --git a/packages/ariadne/src/versions.rs b/packages/ariadne/src/versions.rs index 8cc295145..eaf65c51b 100644 --- a/packages/ariadne/src/versions.rs +++ b/packages/ariadne/src/versions.rs @@ -33,12 +33,11 @@ pub fn is_feature_supported_in( if part_version == part_first_release { continue; } - if let Ok(part_version) = part_version.parse::() { - if let Ok(part_first_release) = part_first_release.parse::() { - if part_version > part_first_release { - return true; - } - } + if let Ok(part_version) = part_version.parse::() + && let Ok(part_first_release) = part_first_release.parse::() + && part_version > part_first_release + { + return true; } } false diff --git a/rust-toolchain.toml b/rust-toolchain.toml index e88baf106..b67e7d534 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,2 +1,2 @@ [toolchain] -channel = "1.88.0" +channel = "1.89.0"