include premium account info in the endpoint

This commit is contained in:
Brandon Thomas committed 2024-09-10 18:35:04 -04:00
1 parent 9dfaf44ac9
commit 87f70d507f
3 files changed
+108 -8

No files matched your search

@@ -0,0 +1,58 @@
use billing_component::stripe::traits::internal_user_lookup::UserMetadata;
use utoipa::ToSchema;
#[derive(Serialize, ToSchema)]
pub struct AppStatePremiumInfo {
/// If the user has premium perks. This can be the result of
/// having *either* a loyalty perk or a paid subscription.
pub user_has_premium: bool,
/// If the user has paid for a premium subscription, this will
/// be true. Loyalty perks are not considered paid.
pub user_has_paid_premium: bool,
/// If the user is in a loyalty tier, we'll return something here.
/// Users that contribute models can get extra perks for free.
pub maybe_loyalty_program: Option<String>,
/// Information on any subscriptions the user has.
pub active_subscriptions: Vec<AppStateSubscriptionProductKey>,
}
#[derive(Serialize, ToSchema)]
pub struct AppStateSubscriptionProductKey {
/// This should always be "fakeyou".
pub namespace: String,
/// Possible values: fakeyou_plus, fakeyou_pro, fakeyou_elite, etc.
pub product_slug: String,
}
pub fn get_premium_info(
user_metadata: &UserMetadata,
) -> AppStatePremiumInfo {
let maybe_loyalty_program = user_metadata
.maybe_loyalty_program_key
.as_deref()
.map(|lp| lp.to_string());
let active_subscriptions = user_metadata
.existing_subscription_keys
.iter()
.map(|sub| AppStateSubscriptionProductKey {
namespace: sub.internal_subscription_namespace.to_string(),
product_slug: sub.internal_subscription_product_slug.to_string(),
})
.collect::<Vec<_>>();
let user_has_paid_premium = !active_subscriptions.is_empty();
let user_has_premium = user_has_paid_premium || maybe_loyalty_program.is_some();
AppStatePremiumInfo {
user_has_premium,
user_has_paid_premium,
maybe_loyalty_program,
active_subscriptions,
}
}
@@ -1,3 +1,4 @@
pub mod get_premium_info;
pub mod get_server_info;
pub mod get_status_alert;
pub mod get_user_locale;
@@ -1,24 +1,26 @@
use actix_web::http::StatusCode;
use actix_web::web::Json;
use actix_web::{web, HttpRequest, HttpResponse, ResponseError};
use log::{error, info};
use std::sync::Arc;
use std::time::Duration;
use utoipa::ToSchema;
use crate::http_server::endpoints::app_state::components::get_premium_info::{get_premium_info, AppStatePremiumInfo};
use crate::http_server::endpoints::app_state::components::get_server_info::{get_server_info, AppStateServerInfo};
use crate::http_server::endpoints::app_state::components::get_status_alert::{get_status_alert, AppStateStatusAlertInfo};
use crate::http_server::endpoints::app_state::components::get_user_locale::{get_user_locale, AppStateUserLocale};
use crate::state::server_state::ServerState;
use actix_web::http::StatusCode;
use actix_web::web::Json;
use actix_web::{web, HttpRequest, HttpResponse, ResponseError};
use billing_component::stripe::traits::internal_user_lookup::InternalUserLookup;
use billing_component::users::http_endpoints::list_active_user_subscriptions_handler::ListActiveUserSubscriptionsError;
use enums::by_table::user_ratings::entity_type::UserRatingEntityType;
use enums::by_table::user_ratings::rating_value::UserRatingValue;
use http_server_common::response::serialize_as_json_error::serialize_as_json_error;
use log::{error, info};
use mysql_queries::composite_keys::by_table::user_ratings::user_rating_entity::UserRatingEntity;
use mysql_queries::queries::users::user_ratings::get_user_rating::{get_user_rating, Args};
use std::sync::Arc;
use std::time::Duration;
use tokens::tokens::media_files::MediaFileToken;
use tokens::tokens::model_weights::ModelWeightToken;
use tokens::tokens::tts_models::TtsModelToken;
use tokens::tokens::w2l_templates::W2lTemplateToken;
use utoipa::ToSchema;
// TODO: This is based on status_alert_handler
/// How often the client should poll
@@ -39,6 +41,11 @@ pub struct AppStateResponse {
/// Tell the frontend client how fast to refresh their view of this state.
/// During an attack or outage, we may want this to go extremely slow.
///
/// Regardless of this value, the client should preemptively refresh if the
/// user logs in, logs out, creates an account, or subscribes to a premium plan,
/// as those changes will impact some of the underlying state returned by this
/// endpoint.
pub refresh_interval_millis: u128,
/// Information about the HTTP app server.
@@ -51,6 +58,18 @@ pub struct AppStateResponse {
/// Information on user locale (language codes, etc.)
pub user_locale: AppStateUserLocale,
/// If the user is logged into an account with a valid session, this will
/// contain the user's account info.
pub maybe_user: Option<AppStateUserAccountInfo>,
}
/// User account information.
/// This is only for valid logged-in users.
#[derive(Serialize, ToSchema)]
pub struct AppStateUserAccountInfo {
/// Details on the user's premium account status.
pub premium: AppStatePremiumInfo,
}
// =============== Error Response ===============
@@ -96,6 +115,8 @@ impl std::fmt::Display for AppStateError {
/// - `GET /server_info`
/// - `GET /v1/status_alert_check`
///
/// TODO: - `GET /v1/billing/active_subscriptions`
///
/// This endpoint will probably grow new functionality in the future as well.
#[utoipa::path(
get,
@@ -114,9 +135,11 @@ impl std::fmt::Display for AppStateError {
)]
pub async fn get_app_state_handler(
http_request: HttpRequest,
internal_user_lookup: web::Data<dyn InternalUserLookup>,
server_state: web::Data<Arc<ServerState>>
) -> Result<Json<AppStateResponse>, AppStateError>
{
/*
let mut mysql_connection = server_state.mysql_pool.acquire()
.await
.map_err(|e| {
@@ -140,16 +163,34 @@ pub async fn get_app_state_handler(
return Err(AppStateError::NotAuthorized);
}
};
*/
let maybe_user_metadata = internal_user_lookup
.lookup_user_from_http_request(&http_request)
.await
.map_err(|err| {
error!("Error looking up user: {:?}", err);
AppStateError::ServerError // NB: This was probably *our* fault.
})?;
let server_info = get_server_info(&server_state);
let user_locale = get_user_locale(&http_request);
let maybe_alert = get_status_alert(&server_state);
let mut maybe_user = None;
if let Some(user_metadata) = maybe_user_metadata {
maybe_user = Some(AppStateUserAccountInfo {
premium: get_premium_info(&user_metadata),
});
}
Ok(Json(AppStateResponse {
success: true,
refresh_interval_millis: REFRESH_INTERVAL.as_millis(),
server_info,
user_locale,
maybe_alert,
maybe_user,
}))
}