Fix download count logic (#347)

This commit is contained in:
Geometrically
2022-05-14 18:55:02 -04:00
committed by GitHub
parent 3533d2a2cc
commit b9b4f2bb7f
3 changed files with 45 additions and 8 deletions

View File

@@ -3,10 +3,13 @@ use crate::util::guards::admin_key_guard;
use actix_web::{patch, web, HttpResponse};
use serde::Deserialize;
use sqlx::PgPool;
use crate::models::ids::ProjectId;
#[derive(Deserialize)]
pub struct DownloadBody {
pub url: String,
pub hash: ProjectId,
pub version_name: String,
}
// This is an internal route, cannot be used without key
@@ -15,7 +18,18 @@ pub async fn count_download(
pool: web::Data<PgPool>,
download_body: web::Json<DownloadBody>,
) -> Result<HttpResponse, ApiError> {
let version = sqlx::query!(
let project_id : crate::database::models::ids::ProjectId = download_body.hash.into();
let version_id = if let Some(version) = sqlx::query!(
"SELECT id FROM versions
WHERE (version_number = $1 AND mod_id = $2)",
download_body.version_name,
project_id as crate::database::models::ids::ProjectId
)
.fetch_optional(pool.as_ref())
.await? {
version.id
} else if let Some(version) = sqlx::query!(
"
SELECT v.id id, v.mod_id project_id FROM files f
INNER JOIN versions v ON v.id = f.version_id
@@ -23,11 +37,12 @@ pub async fn count_download(
",
download_body.url,
)
.fetch_optional(pool.as_ref())
.await?
.ok_or_else(|| {
ApiError::InvalidInput("Specified version does not exist!".to_string())
})?;
.fetch_optional(pool.as_ref())
.await? {
version.id
} else {
return Err(ApiError::InvalidInput("Specified version does not exist!".to_string()));
};
let mut transaction = pool.begin().await?;
@@ -35,7 +50,7 @@ pub async fn count_download(
"UPDATE versions
SET downloads = downloads + 1
WHERE (id = $1)",
version.id
version_id
)
.execute(&mut *transaction)
.await?;
@@ -44,7 +59,7 @@ pub async fn count_download(
"UPDATE mods
SET downloads = downloads + 1
WHERE (id = $1)",
version.project_id
version_id
)
.execute(&mut *transaction)
.await?;

View File

@@ -27,6 +27,7 @@ pub struct PackFormat<'a> {
}
#[derive(Serialize, Deserialize, Validate)]
#[serde(rename_all = "camelCase")]
pub struct PackFile<'a> {
pub path: &'a str,
pub hashes: std::collections::HashMap<FileHash, &'a str>,