Skip to content

Commit

Permalink
Servers list route
Browse files Browse the repository at this point in the history
  • Loading branch information
Geometrically committed Dec 5, 2024
1 parent 61dec32 commit 1a3ff3e
Show file tree
Hide file tree
Showing 3 changed files with 125 additions and 0 deletions.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions apps/labrinth/src/database/models/user_subscription_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,29 @@ impl UserSubscriptionItem {
.collect::<Result<Vec<_>, serde_json::Error>>()?)
}

pub async fn get_all_servers(
status: Option<SubscriptionStatus>,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<UserSubscriptionItem>, DatabaseError> {
let status = status.map(|x| x.as_str());

let results = select_user_subscriptions_with_predicate!(
r#"
INNER JOIN products_prices pp ON us.price_id = pp.id
INNER JOIN products p ON p.metadata @> '{"type": "pyro"}'
WHERE $1::text IS NULL OR us.status = $1::text
"#,
status
)
.fetch_all(exec)
.await?;

Ok(results
.into_iter()
.map(|r| r.try_into())
.collect::<Result<Vec<_>, serde_json::Error>>()?)
}

pub async fn upsert(
&self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
Expand Down
44 changes: 44 additions & 0 deletions apps/labrinth/src/routes/internal/billing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ pub fn config(cfg: &mut web::ServiceConfig) {
.service(edit_payment_method)
.service(remove_payment_method)
.service(charges)
.service(active_servers)
.service(initiate_payment)
.service(stripe_webhook),
);
Expand Down Expand Up @@ -797,6 +798,49 @@ pub async fn payment_methods(
}
}

#[derive(Deserialize)]
pub struct ActiveServersQuery {
pub subscription_status: Option<SubscriptionStatus>,
}

#[get("active_servers")]
pub async fn active_servers(
req: HttpRequest,
pool: web::Data<PgPool>,
query: web::Query<ActiveServersQuery>,
) -> Result<HttpResponse, ApiError> {
let master_key = dotenvy::var("PYRO_API_KEY")?;

if !req
.head()
.headers()
.get("X-Master-Key")
.map_or(false, |it| it.as_bytes() == master_key.as_bytes())
{
return Err(ApiError::CustomAuthentication(
"Invalid master key".to_string(),
));
}

let servers =
user_subscription_item::UserSubscriptionItem::get_all_servers(
query.subscription_status,
&**pool,
)
.await?;

let server_ids = servers
.into_iter()
.filter_map(|x| {
x.metadata.and_then(|x| match x {
SubscriptionMetadata::Pyro { id } => Some(id),
})
})
.collect::<Vec<_>>();

Ok(HttpResponse::Ok().json(server_ids))
}

#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum PaymentRequestType {
Expand Down

0 comments on commit 1a3ff3e

Please sign in to comment.