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
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 45 additions and 8 deletions

View File

@ -877,6 +877,27 @@
"nullable": []
}
},
"331041c6a4f27f4a6ac2873332074c0127e7368c8ab803843760530d29aaef08": {
"query": "SELECT id FROM versions\n WHERE (version_number = $1 AND mod_id = $2)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Text",
"Int8"
]
},
"nullable": [
false
]
}
},
"33a965c7dc615d3b701c05299889357db8dd36d378850625d2602ba471af4885": {
"query": "\n UPDATE mods\n SET downloads = downloads + $1\n WHERE (id = $2)\n ",
"describe": {

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>,