Skip to content

Commit

Permalink
temp commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Fleeym committed Dec 4, 2024
1 parent ef53c35 commit 97dbd85
Show file tree
Hide file tree
Showing 4 changed files with 212 additions and 80 deletions.
87 changes: 55 additions & 32 deletions src/endpoints/mod_versions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,21 @@ use serde::Deserialize;
use sqlx::{types::ipnetwork::IpNetwork, Acquire};

use crate::{
extractors::auth::Auth, types::{
extractors::auth::Auth,
types::{
api::{ApiError, ApiResponse},
mod_json::{split_version_and_compare, ModJson},
models::{
developer::Developer,
download,
mod_entity::{download_geode_file, Mod},
mod_gd_version::{GDVersionEnum, VerPlatform},
mod_gd_version::{add_all_to_gdvec, GDVersionEnum, VerPlatform},
mod_version::{self, ModVersion},
mod_version_status::ModVersionStatusEnum,
},
}, webhook::send_webhook, AppData
},
webhook::send_webhook,
AppData,
};

#[derive(Deserialize)]
Expand Down Expand Up @@ -92,9 +95,8 @@ pub async fn get_version_index(
let mut pool = data.db.acquire().await.or(Err(ApiError::DbAcquireError))?;

let has_extended_permissions = match auth.developer() {
Ok(dev) => dev.admin ||
Developer::has_access_to_mod(dev.id, &path.id, &mut pool).await?,
_ => false
Ok(dev) => dev.admin || Developer::has_access_to_mod(dev.id, &path.id, &mut pool).await?,
_ => false,
};

let mut result = ModVersion::get_index(
Expand Down Expand Up @@ -130,20 +132,21 @@ pub async fn get_one(
let mut pool = data.db.acquire().await.or(Err(ApiError::DbAcquireError))?;

let has_extended_permissions = match auth.developer() {
Ok(dev) => dev.admin ||
Developer::has_access_to_mod(dev.id, &path.id, &mut pool).await?,
_ => false
Ok(dev) => dev.admin || Developer::has_access_to_mod(dev.id, &path.id, &mut pool).await?,
_ => false,
};

let mut version = {
if path.version == "latest" {
let gd: Option<GDVersionEnum> = match query.gd {
Some(ref gd) => Some(
GDVersionEnum::from_str(gd)
.or(Err(ApiError::BadRequest("Invalid gd".to_string())))?,
),
None => None,
};
let mut gd = match query.gd {
Some(ref gd) => match GDVersionEnum::from_str(gd) {
Ok(g) => Ok(vec![g]),
Err(_) => Err(ApiError::BadRequest("Invalid gd".to_string())),
},
None => Ok(vec![]),
}?;

add_all_to_gdvec(&mut gd);

let platform_string = query.platforms.clone().unwrap_or_default();
let platforms = VerPlatform::parse_query_string(&platform_string);
Expand Down Expand Up @@ -178,10 +181,18 @@ pub async fn download_version(
) -> Result<impl Responder, ApiError> {
let mut pool = data.db.acquire().await.or(Err(ApiError::DbAcquireError))?;
let mod_version = {
let mut gd_vec: Vec<GDVersionEnum> = Vec::with_capacity(2);

if let Some(gd) = query.gd {
gd_vec.push(gd);
}

add_all_to_gdvec(&mut gd_vec);

let platform_str = query.platforms.clone().unwrap_or_default();
let platforms = VerPlatform::parse_query_string(&platform_str);
if path.version == "latest" {
let platform_str = query.platforms.clone().unwrap_or_default();
let platforms = VerPlatform::parse_query_string(&platform_str);
ModVersion::get_latest_for_mod(&path.id, query.gd, platforms, query.major, &mut pool)
ModVersion::get_latest_for_mod(&path.id, gd_vec, platforms, query.major, &mut pool)
.await?
} else {
ModVersion::get_one(&path.id, &path.version, false, false, &mut pool).await?
Expand All @@ -202,16 +213,18 @@ pub async fn download_version(
};
let net: IpNetwork = ip.parse().or(Err(ApiError::InternalError))?;

if let Ok((downloaded_version, downloaded_mod)) = download::create_download(
net, mod_version.id, &mod_version.mod_id, &mut pool
).await {
if let Ok((downloaded_version, downloaded_mod)) =
download::create_download(net, mod_version.id, &mod_version.mod_id, &mut pool).await
{
let name = mod_version.mod_id.clone();
let version = mod_version.version.clone();

// only accepted mods can have their download counts incremented
// we'll just fix this once they're updated anyways

if (downloaded_version || downloaded_mod) && mod_version.status == ModVersionStatusEnum::Accepted {
if (downloaded_version || downloaded_mod)
&& mod_version.status == ModVersionStatusEnum::Accepted
{
tokio::spawn(async move {
if downloaded_version {
// we must nest more
Expand Down Expand Up @@ -264,8 +277,11 @@ pub async fn create_version(
}

// remove invalid characters from link - they break the location header on download
let download_link: String = payload.download_link.chars()
.filter(|c| c.is_ascii() && *c != '\0').collect();
let download_link: String = payload
.download_link
.chars()
.filter(|c| c.is_ascii() && *c != '\0')
.collect();

let mut file_path = download_geode_file(&download_link).await?;
let json = ModJson::from_zip(&mut file_path, &download_link, dev.verified)
Expand All @@ -283,10 +299,15 @@ pub async fn create_version(
json.name.clone(),
json.version.clone(),
true,
Developer { id: dev.id, username: dev.username.clone(), display_name: dev.display_name.clone(), is_owner: true },
Developer {
id: dev.id,
username: dev.username.clone(),
display_name: dev.display_name.clone(),
is_owner: true,
},
dev.clone(),
data.webhook_url.clone(),
data.app_url.clone()
data.app_url.clone(),
)
.await;
}
Expand Down Expand Up @@ -324,8 +345,9 @@ pub async fn update_version(
path.version.as_str(),
false,
false,
&mut pool
).await?;
&mut pool,
)
.await?;
let approved_count = ModVersion::get_accepted_count(version.mod_id.as_str(), &mut pool).await?;
let mut transaction = pool.begin().await.or(Err(ApiError::TransactionError))?;
let id = match sqlx::query!(
Expand Down Expand Up @@ -365,7 +387,7 @@ pub async fn update_version(
.commit()
.await
.or(Err(ApiError::TransactionError))?;

if payload.status == ModVersionStatusEnum::Accepted {
let is_update = approved_count > 0;

Expand All @@ -382,8 +404,9 @@ pub async fn update_version(
owner.as_ref().unwrap().clone(),
dev.clone(),
data.webhook_url.clone(),
data.app_url.clone()
).await;
data.app_url.clone(),
)
.await;
}

Ok(HttpResponse::NoContent())
Expand Down
29 changes: 20 additions & 9 deletions src/types/models/dependency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{collections::HashMap, fmt::Display};
use serde::{Deserialize, Serialize};
use sqlx::{PgConnection, Postgres, QueryBuilder};

use crate::types::api::ApiError;
use crate::types::{api::ApiError, models::mod_gd_version::add_all_to_gdvec};

use super::mod_gd_version::{GDVersionEnum, VerPlatform};

Expand Down Expand Up @@ -130,8 +130,8 @@ impl Dependency {

pub async fn get_for_mod_versions(
ids: &Vec<i32>,
platform: Option<VerPlatform>,
gd: Option<GDVersionEnum>,
platforms: Vec<VerPlatform>,
gd: Vec<GDVersionEnum>,
geode: Option<&semver::Version>,
pool: &mut PgConnection,
) -> Result<HashMap<i32, Vec<FetchedDependency>>, ApiError> {
Expand All @@ -145,6 +145,17 @@ impl Dependency {
dependency: String,
importance: DependencyImportance,
}

let mut gd = gd;
add_all_to_gdvec(&mut gd);

let platforms = {
if !platforms.is_empty() {
platforms
} else {
VerPlatform::all_platforms()
}
};

let q = sqlx::query_as::<Postgres, QueryResult>(
r#"
Expand Down Expand Up @@ -176,8 +187,8 @@ impl Dependency {
INNER JOIN mod_version_statuses dpcy_status ON dpcy_version.status_id = dpcy_status.id
WHERE dpcy_status.status = 'accepted'
AND mv.id = ANY($1)
AND ($2 IS NULL OR dpcy_mgv.gd = $2 OR dpcy_mgv.gd = '*')
AND ($3 IS NULL OR dpcy_mgv.platform = $3)
AND dpcy_mgv.gd = ANY($2)
AND dpcy_mgv.platform = ANY($3)
AND ($4 IS NULL OR (
CASE
WHEN SPLIT_PART($4, '-', 2) ILIKE 'alpha%' THEN $4 = dpcy_version.geode
Expand Down Expand Up @@ -230,8 +241,8 @@ impl Dependency {
INNER JOIN mod_version_statuses dpcy_status2 ON dpcy_version2.status_id = dpcy_status2.id
INNER JOIN dep_tree dt ON dt.dependency_vid = mv2.id
WHERE dpcy_status2.status = 'accepted'
AND ($2 IS NULL OR dpcy_mgv2.gd = $2 OR dpcy_mgv2.gd = '*')
AND ($3 IS NULL OR dpcy_mgv2.platform = $3)
AND dpcy_mgv2.gd = ANY($2)
AND dpcy_mgv2.platform = ANY($3)
AND ($4 IS NULL OR (
CASE
WHEN SPLIT_PART($4, '-', 2) ILIKE 'alpha%' THEN $4 = dpcy_version2.geode
Expand Down Expand Up @@ -260,8 +271,8 @@ impl Dependency {
SELECT * FROM dep_tree;
"#,
).bind(ids)
.bind(gd)
.bind(platform)
.bind(&gd)
.bind(&platforms)
.bind(geode.map(|x| x.to_string()));

let result = match q.fetch_all(&mut *pool).await {
Expand Down
90 changes: 88 additions & 2 deletions src/types/models/mod_gd_version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ use std::{
};

use serde::{Deserialize, Serialize};
use sqlx::{PgConnection, Postgres, QueryBuilder};
use sqlx::{
postgres::{PgHasArrayType, PgTypeInfo},
PgConnection, Postgres, QueryBuilder,
};

use crate::types::{api::ApiError, mod_json::ModJson};

#[derive(sqlx::Type, Debug, Deserialize, Serialize, Clone, Copy)]
#[derive(sqlx::Type, Debug, Deserialize, Serialize, Clone, Copy, PartialEq)]
#[sqlx(type_name = "gd_version")]
pub enum GDVersionEnum {
#[serde(rename = "*")]
Expand Down Expand Up @@ -46,6 +49,12 @@ pub enum GDVersionEnum {
GD22074,
}

impl PgHasArrayType for GDVersionEnum {
fn array_type_info() -> PgTypeInfo {
PgTypeInfo::with_name("gd_version[]")
}
}

impl FromStr for GDVersionEnum {
type Err = ();
fn from_str(s: &str) -> Result<Self, ()> {
Expand Down Expand Up @@ -86,6 +95,12 @@ pub enum VerPlatform {
Win,
}

impl PgHasArrayType for VerPlatform {
fn array_type_info() -> sqlx::postgres::PgTypeInfo {
PgTypeInfo::with_name("gd_ver_platform[]")
}
}

impl FromStr for VerPlatform {
type Err = ();
fn from_str(s: &str) -> Result<Self, ()> {
Expand All @@ -106,6 +121,16 @@ impl FromStr for VerPlatform {
}

impl VerPlatform {
pub fn all_platforms() -> Vec<VerPlatform> {
vec![
VerPlatform::Android32,
VerPlatform::Android64,
VerPlatform::Win,
VerPlatform::MacArm,
VerPlatform::MacIntel,
]
}

pub fn parse_query_string(s: &str) -> Vec<VerPlatform> {
let mut ret = vec![];
if s.is_empty() {
Expand Down Expand Up @@ -163,6 +188,58 @@ pub struct DetailedGDVersion {
}

impl DetailedGDVersion {
pub fn to_platform_vec(&self) -> Vec<VerPlatform> {
let mut ret = Vec::with_capacity(6);

if self.android32.is_some() {
ret.push(VerPlatform::Android32);
}

if self.android64.is_some() {
ret.push(VerPlatform::Android64);
}

if self.win.is_some() {
ret.push(VerPlatform::Win);
}

if self.mac_arm.is_some() {
ret.push(VerPlatform::MacArm);
}

if self.mac_intel.is_some() {
ret.push(VerPlatform::MacIntel);
}

ret
}

pub fn to_vec(&self) -> Vec<GDVersionEnum> {
let mut ret = Vec::with_capacity(6);

if let Some(v) = self.android32 {
ret.push(v);
}

if let Some(v) = self.android64 {
ret.push(v);
}

if let Some(v) = self.win {
ret.push(v);
}

if let Some(v) = self.mac_arm {
ret.push(v);
}

if let Some(v) = self.mac_intel {
ret.push(v);
}

ret
}

pub fn to_create_payload(&self, json: &ModJson) -> Vec<ModGDVersionCreate> {
let mut ret: Vec<_> = vec![];
if self.android.is_some() {
Expand Down Expand Up @@ -371,6 +448,15 @@ impl ModGDVersion {
}
}

pub fn add_all_to_gdvec(v: &mut Vec<GDVersionEnum>) {
for i in v.iter() {
if *i == GDVersionEnum::All {
return;
}
}
v.push(GDVersionEnum::All);
}

fn check_for_duplicate_platforms(versions: &Vec<ModGDVersionCreate>) -> Result<(), String> {
let mut found: HashMap<VerPlatform, GDVersionEnum> = HashMap::new();
for i in versions {
Expand Down
Loading

0 comments on commit 97dbd85

Please sign in to comment.