@@ -19,6 +19,12 @@ impl IntoResponse for AuthRejection {
|
||||
|
||||
pub struct AuthRejection(String);
|
||||
|
||||
impl AuthRejection {
|
||||
pub fn new(reason: impl Into<String>) -> Self {
|
||||
Self(reason.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> FromRequestParts<S> for AuthenticatedUser
|
||||
where
|
||||
S: Send + Sync,
|
||||
@@ -29,7 +35,7 @@ where
|
||||
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
|
||||
let app_state = AppState::from_ref(state);
|
||||
|
||||
let token = extract_bearer_token(parts)
|
||||
let token = bearer_token(parts)
|
||||
.ok_or_else(|| AuthRejection("missing or invalid authorization header".into()))?;
|
||||
|
||||
let user_id = app_state
|
||||
@@ -42,7 +48,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_bearer_token(parts: &Parts) -> Option<String> {
|
||||
pub fn bearer_token(parts: &Parts) -> Option<String> {
|
||||
let header = parts.headers.get("authorization")?.to_str().ok()?;
|
||||
let token = header.strip_prefix("Bearer ")?;
|
||||
Some(token.to_string())
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
use axum::extract::{FromRef, FromRequestParts};
|
||||
use axum::http::request::Parts;
|
||||
|
||||
use domain::provider::ProviderName;
|
||||
use domain::user::UserId;
|
||||
|
||||
use application::api_token::use_cases::authenticate_api_token;
|
||||
|
||||
use crate::state::AppState;
|
||||
|
||||
use super::authenticated_user::{AuthRejection, bearer_token};
|
||||
|
||||
pub struct ImportingProvider {
|
||||
pub user_id: UserId,
|
||||
pub provider: ProviderName,
|
||||
}
|
||||
|
||||
impl<S> FromRequestParts<S> for ImportingProvider
|
||||
where
|
||||
S: Send + Sync,
|
||||
AppState: FromRef<S>,
|
||||
{
|
||||
type Rejection = AuthRejection;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
|
||||
let app_state = AppState::from_ref(state);
|
||||
|
||||
let presented = bearer_token(parts)
|
||||
.ok_or_else(|| AuthRejection::new("missing or invalid authorization header"))?;
|
||||
|
||||
let deps = authenticate_api_token::Deps {
|
||||
query: app_state.api_token_query,
|
||||
command: app_state.api_token_command,
|
||||
secrets: app_state.api_token_secrets,
|
||||
};
|
||||
|
||||
let token = authenticate_api_token::execute(&presented, &deps)
|
||||
.await
|
||||
.map_err(|_| AuthRejection::new("importing needs an api token minted in settings"))?;
|
||||
|
||||
Ok(Self {
|
||||
user_id: token.user_id().clone(),
|
||||
provider: token.name().clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
53
crates/adapters/http-axum/src/extractors/metric_writer.rs
Normal file
53
crates/adapters/http-axum/src/extractors/metric_writer.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
use axum::extract::{FromRef, FromRequestParts};
|
||||
use axum::http::request::Parts;
|
||||
|
||||
use domain::metric::Source;
|
||||
use domain::user::UserId;
|
||||
|
||||
use application::api_token::use_cases::authenticate_api_token;
|
||||
|
||||
use crate::state::AppState;
|
||||
|
||||
use super::authenticated_user::{AuthRejection, bearer_token};
|
||||
|
||||
pub struct MetricWriter {
|
||||
pub user_id: UserId,
|
||||
pub source: Source,
|
||||
}
|
||||
|
||||
impl<S> FromRequestParts<S> for MetricWriter
|
||||
where
|
||||
S: Send + Sync,
|
||||
AppState: FromRef<S>,
|
||||
{
|
||||
type Rejection = AuthRejection;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
|
||||
let app_state = AppState::from_ref(state);
|
||||
|
||||
let presented = bearer_token(parts)
|
||||
.ok_or_else(|| AuthRejection::new("missing or invalid authorization header"))?;
|
||||
|
||||
if let Ok(user_id) = app_state.auth_service.validate_token(&presented).await {
|
||||
return Ok(Self {
|
||||
user_id,
|
||||
source: Source::Manual,
|
||||
});
|
||||
}
|
||||
|
||||
let deps = authenticate_api_token::Deps {
|
||||
query: app_state.api_token_query,
|
||||
command: app_state.api_token_command,
|
||||
secrets: app_state.api_token_secrets,
|
||||
};
|
||||
|
||||
let token = authenticate_api_token::execute(&presented, &deps)
|
||||
.await
|
||||
.map_err(|_| AuthRejection::new("invalid or expired token"))?;
|
||||
|
||||
Ok(Self {
|
||||
user_id: token.user_id().clone(),
|
||||
source: Source::Provider(token.name().clone()),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
mod authenticated_user;
|
||||
pub mod authenticated_user;
|
||||
mod importing_provider;
|
||||
mod metric_writer;
|
||||
mod multipart;
|
||||
mod path_id;
|
||||
|
||||
pub use authenticated_user::AuthenticatedUser;
|
||||
pub use importing_provider::ImportingProvider;
|
||||
pub use metric_writer::MetricWriter;
|
||||
pub use multipart::{extract_file_bytes, extract_media_upload};
|
||||
pub use path_id::PathId;
|
||||
|
||||
50
crates/adapters/http-axum/src/handlers/correlations.rs
Normal file
50
crates/adapters/http-axum/src/handlers/correlations.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use axum::Json;
|
||||
use axum::extract::{Query, State};
|
||||
|
||||
use api_types::requests::DateSpanParams;
|
||||
use api_types::responses::CorrelationRowResponse;
|
||||
use application::correlation::queries::CorrelationQuery;
|
||||
use application::correlation::use_cases::get_correlations;
|
||||
|
||||
use crate::errors::ApiError;
|
||||
use crate::extractors::AuthenticatedUser;
|
||||
use crate::state::AppState;
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/correlations", tag = "correlations", security(("bearer" = [])),
|
||||
description = "Scores every metric kind, every active activity, and the moon as a control \
|
||||
against the mean mood of each day in the span. Every strategy that fits the \
|
||||
input is run and all of them are returned; agreement across them is the \
|
||||
headline, not any single coefficient. Rows come back in a fixed order and are \
|
||||
never ranked by strength. Below the configured minimum sample size a row \
|
||||
carries its day count and no coefficient.",
|
||||
params(DateSpanParams),
|
||||
responses((status = 200, body = Vec<CorrelationRowResponse>))
|
||||
)]
|
||||
pub async fn handle_list(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
Query(params): Query<DateSpanParams>,
|
||||
) -> Result<Json<Vec<CorrelationRowResponse>>, ApiError> {
|
||||
let span = params.into_span()?;
|
||||
|
||||
let deps = get_correlations::Deps {
|
||||
entries: state.entry_query,
|
||||
metrics: state.daily_metric_query,
|
||||
activities: state.activity_query,
|
||||
cycles: state.cycle_query,
|
||||
weather_store: state.weather_store,
|
||||
preferences: state.preferences_query,
|
||||
users: state.user_query,
|
||||
};
|
||||
|
||||
let query = CorrelationQuery {
|
||||
user_id,
|
||||
span,
|
||||
minimum_sample_size: state.analysis_config.minimum_sample_size,
|
||||
false_discovery_rate: state.analysis_config.false_discovery_rate,
|
||||
};
|
||||
|
||||
let rows = get_correlations::execute(query, &deps).await?;
|
||||
|
||||
Ok(Json(rows.into_iter().map(Into::into).collect()))
|
||||
}
|
||||
109
crates/adapters/http-axum/src/handlers/cycle.rs
Normal file
109
crates/adapters/http-axum/src/handlers/cycle.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
|
||||
use api_types::mappers::parse_date;
|
||||
use api_types::requests::SetPreferencesRequest;
|
||||
use api_types::responses::{CycleViewResponse, PreferencesResponse};
|
||||
use application::cycle::use_cases::{forget_cycle_start, read_cycle, record_cycle_start};
|
||||
use application::user::use_cases::set_preferences;
|
||||
|
||||
use crate::errors::ApiError;
|
||||
use crate::extractors::AuthenticatedUser;
|
||||
use crate::state::AppState;
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/cycle", tag = "cycle", security(("bearer" = [])),
|
||||
description = "The recorded cycle starts and the cycle day derived for today. Cycle day is \
|
||||
never stored: correcting a start corrects every day that depended on it. \
|
||||
Returns nothing at all while cycle tracking is off.",
|
||||
responses((status = 200, body = CycleViewResponse))
|
||||
)]
|
||||
pub async fn handle_read(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
) -> Result<Json<CycleViewResponse>, ApiError> {
|
||||
let deps = read_cycle::Deps {
|
||||
query: state.cycle_query,
|
||||
preferences: state.preferences_query,
|
||||
users: state.user_query,
|
||||
};
|
||||
|
||||
let view = read_cycle::execute(user_id, &deps).await?;
|
||||
|
||||
Ok(Json(view.into()))
|
||||
}
|
||||
|
||||
#[utoipa::path(put, path = "/api/v1/cycle/{date}", tag = "cycle", security(("bearer" = [])),
|
||||
description = "Records that a cycle began on this date. Recording the same date twice \
|
||||
records it once.",
|
||||
params(("date" = String, Path, description = "Calendar date, as YYYY-MM-DD")),
|
||||
responses((status = 204))
|
||||
)]
|
||||
pub async fn handle_record(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
Path(date): Path<String>,
|
||||
) -> Result<StatusCode, ApiError> {
|
||||
let deps = record_cycle_start::Deps {
|
||||
command: state.cycle_command,
|
||||
preferences: state.preferences_query,
|
||||
};
|
||||
|
||||
record_cycle_start::execute(user_id, parse_date(&date)?, &deps).await?;
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[utoipa::path(delete, path = "/api/v1/cycle/{date}", tag = "cycle", security(("bearer" = [])),
|
||||
description = "Forgets a recorded start. Every day that derived its cycle day from it \
|
||||
changes at once.",
|
||||
params(("date" = String, Path, description = "Calendar date, as YYYY-MM-DD")),
|
||||
responses((status = 204))
|
||||
)]
|
||||
pub async fn handle_forget(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
Path(date): Path<String>,
|
||||
) -> Result<StatusCode, ApiError> {
|
||||
let deps = forget_cycle_start::Deps {
|
||||
command: state.cycle_command,
|
||||
};
|
||||
|
||||
forget_cycle_start::execute(user_id, parse_date(&date)?, &deps).await?;
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[utoipa::path(patch, path = "/api/v1/users/me/preferences", tag = "users", security(("bearer" = [])),
|
||||
description = "Turns optional features on or off. Cycle tracking is off until turned on, \
|
||||
and turning it off hides the cycle without forgetting what was recorded.",
|
||||
request_body = SetPreferencesRequest,
|
||||
responses((status = 200, body = PreferencesResponse))
|
||||
)]
|
||||
pub async fn handle_set_preferences(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
Json(body): Json<SetPreferencesRequest>,
|
||||
) -> Result<Json<PreferencesResponse>, ApiError> {
|
||||
let deps = set_preferences::Deps {
|
||||
command: state.preferences_command,
|
||||
query: state.preferences_query,
|
||||
};
|
||||
|
||||
let preferences = set_preferences::execute(user_id, body.tracks_cycle, &deps).await?;
|
||||
|
||||
Ok(Json(preferences.into()))
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/users/me/preferences", tag = "users", security(("bearer" = [])),
|
||||
responses((status = 200, body = PreferencesResponse))
|
||||
)]
|
||||
pub async fn handle_preferences(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
) -> Result<Json<PreferencesResponse>, ApiError> {
|
||||
let preferences =
|
||||
application::user::preferences::preferences_of(&user_id, &state.preferences_query).await?;
|
||||
|
||||
Ok(Json(preferences.into()))
|
||||
}
|
||||
117
crates/adapters/http-axum/src/handlers/data.rs
Normal file
117
crates/adapters/http-axum/src/handlers/data.rs
Normal file
@@ -0,0 +1,117 @@
|
||||
use axum::Json;
|
||||
use axum::extract::{Multipart, State};
|
||||
use axum::http::{StatusCode, header};
|
||||
use axum::response::IntoResponse;
|
||||
|
||||
use api_types::responses::RestoreOutcomeResponse;
|
||||
use application::export::use_cases::{write_backup, write_extract};
|
||||
use application::restore::commands::RestoreBackupCommand;
|
||||
use application::restore::use_cases::restore_backup;
|
||||
|
||||
use crate::errors::ApiError;
|
||||
use crate::extractors::{AuthenticatedUser, extract_file_bytes};
|
||||
use crate::state::AppState;
|
||||
|
||||
const BACKUP_FILENAME: &str = "k-mood-complete-backup.zip";
|
||||
const EXTRACT_FILENAME: &str = "k-mood-shareable-journal.md";
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/data/backup", tag = "data", security(("bearer" = [])),
|
||||
description = "A complete backup: every entry with every dimension, every daily metric, \
|
||||
every cycle start, the activity catalogue, reminders, preferences and all \
|
||||
media. Restores through /data/restore. Keep it private — it holds everything \
|
||||
the account knows.",
|
||||
responses((status = 200, description = "A zip archive", content_type = "application/zip"))
|
||||
)]
|
||||
pub async fn handle_backup(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
) -> Result<impl IntoResponse, ApiError> {
|
||||
let deps = write_backup::Deps {
|
||||
entries: state.entry_query,
|
||||
dimensions: state.dimensions,
|
||||
activities: state.activity_query,
|
||||
reminders: state.reminder_query,
|
||||
metrics: state.daily_metric_query,
|
||||
cycles: state.cycle_query,
|
||||
preferences: state.preferences_query,
|
||||
media_storage: state.media_storage,
|
||||
writer: state.backup_writer,
|
||||
};
|
||||
|
||||
let archive = write_backup::execute(user_id, &deps).await?;
|
||||
|
||||
Ok(attachment("application/zip", BACKUP_FILENAME, archive))
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/data/extract", tag = "data", security(("bearer" = [])),
|
||||
description = "A shareable journal: the mood, what was written and what was tagged, as a \
|
||||
readable markdown document. It carries no places, no health readings, no \
|
||||
cycle records and no media, and it cannot be restored from. This is the one \
|
||||
to hand to someone.",
|
||||
responses((status = 200, description = "A markdown document", content_type = "text/markdown"))
|
||||
)]
|
||||
pub async fn handle_extract(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
) -> Result<impl IntoResponse, ApiError> {
|
||||
let deps = write_extract::Deps {
|
||||
entries: state.entry_query,
|
||||
dimensions: state.dimensions,
|
||||
activities: state.activity_query,
|
||||
writer: state.extract_writer,
|
||||
};
|
||||
|
||||
let document = write_extract::execute(user_id, &deps).await?;
|
||||
|
||||
Ok(attachment(
|
||||
"text/markdown; charset=utf-8",
|
||||
EXTRACT_FILENAME,
|
||||
document,
|
||||
))
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/data/restore", tag = "data", security(("bearer" = [])),
|
||||
description = "Restores a complete backup into this account. Existing data is kept: a \
|
||||
restore adds, it does not replace. Anything in the archive this build cannot \
|
||||
read is reported rather than silently dropped.",
|
||||
responses((status = 200, body = RestoreOutcomeResponse))
|
||||
)]
|
||||
pub async fn handle_restore(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
multipart: Multipart,
|
||||
) -> Result<Json<RestoreOutcomeResponse>, ApiError> {
|
||||
let data = extract_file_bytes(multipart).await?;
|
||||
|
||||
let deps = restore_backup::Deps {
|
||||
reader: state.backup_reader,
|
||||
entry_command: state.entry_command,
|
||||
dimensions: state.dimensions,
|
||||
activity_command: state.activity_command,
|
||||
activity_query: state.activity_query,
|
||||
reminder_command: state.reminder_command,
|
||||
metrics: state.daily_metric_command,
|
||||
cycles: state.cycle_command,
|
||||
preferences_command: state.preferences_command,
|
||||
preferences_query: state.preferences_query,
|
||||
media_storage: state.media_storage,
|
||||
};
|
||||
|
||||
let outcome = restore_backup::execute(RestoreBackupCommand { user_id, data }, &deps).await?;
|
||||
|
||||
Ok(Json(outcome.into()))
|
||||
}
|
||||
|
||||
fn attachment(content_type: &str, filename: &str, body: Vec<u8>) -> impl IntoResponse {
|
||||
(
|
||||
StatusCode::OK,
|
||||
[
|
||||
(header::CONTENT_TYPE, content_type.to_string()),
|
||||
(
|
||||
header::CONTENT_DISPOSITION,
|
||||
format!("attachment; filename=\"{filename}\""),
|
||||
),
|
||||
],
|
||||
body,
|
||||
)
|
||||
}
|
||||
@@ -2,27 +2,43 @@ use axum::Json;
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
|
||||
use api_types::mappers::correlation_response;
|
||||
use api_types::requests::{
|
||||
CreateEntryRequest, DateRangeParams, ListEntriesParams, ReplaceActivityRequest,
|
||||
UpdateEntryRequest,
|
||||
};
|
||||
use api_types::responses::{
|
||||
BulkActionResponse, CalendarDayResponse, CorrelationResponse, EntryResponse, MoodStatsResponse,
|
||||
BulkActionResponse, CalendarDayResponse, EntryResponse, MoodStatsResponse,
|
||||
};
|
||||
use application::entry::composition::EntryComposer;
|
||||
use application::entry::queries::{FilterByActivityQuery, FilterByMoodQuery, MoodStatsQuery};
|
||||
use application::entry::use_cases::{
|
||||
create_entry, delete_entries_by_date_range, delete_entry, filter_by_activity, filter_by_mood,
|
||||
get_activity_correlation, get_calendar, get_entry, get_mood_stats, list_entries,
|
||||
replace_activity, update_entry,
|
||||
get_calendar, get_entry, get_mood_stats, list_entries, replace_activity, update_entry,
|
||||
};
|
||||
use domain::activity::ActivityId;
|
||||
use domain::entry::MoodEntry;
|
||||
use domain::entry::{Mood, MoodEntryId};
|
||||
|
||||
use crate::errors::ApiError;
|
||||
use crate::extractors::{AuthenticatedUser, PathId};
|
||||
use crate::state::AppState;
|
||||
|
||||
async fn compose(
|
||||
dimensions: Vec<std::sync::Arc<dyn domain::ports::EntryDimensionPort>>,
|
||||
entries: Vec<MoodEntry>,
|
||||
) -> Result<Vec<EntryResponse>, ApiError> {
|
||||
let composed = EntryComposer::new(dimensions).compose(entries).await?;
|
||||
Ok(composed.into_iter().map(EntryResponse::from).collect())
|
||||
}
|
||||
|
||||
async fn compose_one(
|
||||
dimensions: Vec<std::sync::Arc<dyn domain::ports::EntryDimensionPort>>,
|
||||
entry: MoodEntry,
|
||||
) -> Result<EntryResponse, ApiError> {
|
||||
let mut responses = compose(dimensions, vec![entry]).await?;
|
||||
Ok(responses.remove(0))
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/entries", tag = "entries", security(("bearer" = [])),
|
||||
request_body = CreateEntryRequest,
|
||||
responses((status = 201, body = EntryResponse))
|
||||
@@ -33,12 +49,17 @@ pub async fn handle_create(
|
||||
Json(body): Json<CreateEntryRequest>,
|
||||
) -> Result<(StatusCode, Json<EntryResponse>), ApiError> {
|
||||
let cmd = body.into_command(user_id, &state.entry_config)?;
|
||||
let dimensions = state.dimensions.clone();
|
||||
let deps = create_entry::Deps {
|
||||
entries: state.entry_command,
|
||||
dimensions: state.dimensions.clone(),
|
||||
events: state.event_publisher,
|
||||
};
|
||||
let entry = create_entry::execute(cmd, &deps).await?;
|
||||
Ok((StatusCode::CREATED, Json(EntryResponse::from(entry))))
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(compose_one(dimensions, entry).await?),
|
||||
))
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/entries/{id}", tag = "entries", security(("bearer" = [])),
|
||||
@@ -50,11 +71,12 @@ pub async fn handle_get(
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
PathId(entry_id): PathId<MoodEntryId>,
|
||||
) -> Result<Json<EntryResponse>, ApiError> {
|
||||
let dimensions = state.dimensions.clone();
|
||||
let deps = get_entry::Deps {
|
||||
query: state.entry_query,
|
||||
};
|
||||
let entry = get_entry::execute(entry_id, user_id, &deps).await?;
|
||||
Ok(Json(EntryResponse::from(entry)))
|
||||
Ok(Json(compose_one(dimensions, entry).await?))
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/entries", tag = "entries", security(("bearer" = [])),
|
||||
@@ -67,11 +89,12 @@ pub async fn handle_list(
|
||||
Query(params): Query<ListEntriesParams>,
|
||||
) -> Result<Json<Vec<EntryResponse>>, ApiError> {
|
||||
let query = params.into_query(user_id)?;
|
||||
let dimensions = state.dimensions.clone();
|
||||
let deps = list_entries::Deps {
|
||||
query: state.entry_query,
|
||||
};
|
||||
let entries = list_entries::execute(query, &deps).await?;
|
||||
Ok(Json(entries.into_iter().map(EntryResponse::from).collect()))
|
||||
Ok(Json(compose(dimensions, entries).await?))
|
||||
}
|
||||
|
||||
#[utoipa::path(patch, path = "/api/v1/entries/{id}", tag = "entries", security(("bearer" = [])),
|
||||
@@ -86,14 +109,16 @@ pub async fn handle_update(
|
||||
Json(body): Json<UpdateEntryRequest>,
|
||||
) -> Result<Json<EntryResponse>, ApiError> {
|
||||
let cmd = body.into_command(entry_id, &state.entry_config)?;
|
||||
let dimensions = state.dimensions.clone();
|
||||
let deps = update_entry::Deps {
|
||||
command: state.entry_command,
|
||||
dimensions: state.dimensions.clone(),
|
||||
query: state.entry_query,
|
||||
media_storage: state.media_storage,
|
||||
events: state.event_publisher,
|
||||
};
|
||||
let entry = update_entry::execute(cmd, user_id, &deps).await?;
|
||||
Ok(Json(EntryResponse::from(entry)))
|
||||
Ok(Json(compose_one(dimensions, entry).await?))
|
||||
}
|
||||
|
||||
#[utoipa::path(delete, path = "/api/v1/entries/{id}", tag = "entries", security(("bearer" = [])),
|
||||
@@ -106,6 +131,7 @@ pub async fn handle_delete(
|
||||
PathId(entry_id): PathId<MoodEntryId>,
|
||||
) -> Result<StatusCode, ApiError> {
|
||||
let deps = delete_entry::Deps {
|
||||
dimensions: state.dimensions.clone(),
|
||||
command: state.entry_command,
|
||||
query: state.entry_query,
|
||||
events: state.event_publisher,
|
||||
@@ -126,11 +152,12 @@ pub async fn handle_filter_by_mood(
|
||||
) -> Result<Json<Vec<EntryResponse>>, ApiError> {
|
||||
let mood = Mood::try_from(mood)?;
|
||||
let query = FilterByMoodQuery { user_id, mood };
|
||||
let dimensions = state.dimensions.clone();
|
||||
let deps = filter_by_mood::Deps {
|
||||
query: state.entry_query,
|
||||
};
|
||||
let entries = filter_by_mood::execute(query, &deps).await?;
|
||||
Ok(Json(entries.into_iter().map(EntryResponse::from).collect()))
|
||||
Ok(Json(compose(dimensions, entries).await?))
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/entries/filter/activity/{id}", tag = "entries", security(("bearer" = [])),
|
||||
@@ -146,11 +173,12 @@ pub async fn handle_filter_by_activity(
|
||||
user_id,
|
||||
activity_id,
|
||||
};
|
||||
let dimensions = state.dimensions.clone();
|
||||
let deps = filter_by_activity::Deps {
|
||||
query: state.entry_query,
|
||||
};
|
||||
let entries = filter_by_activity::execute(query, &deps).await?;
|
||||
Ok(Json(entries.into_iter().map(EntryResponse::from).collect()))
|
||||
Ok(Json(compose(dimensions, entries).await?))
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/entries/stats", tag = "entries", security(("bearer" = [])),
|
||||
@@ -172,6 +200,7 @@ pub async fn handle_stats(
|
||||
};
|
||||
let query = MoodStatsQuery { user_id, range };
|
||||
let deps = get_mood_stats::Deps {
|
||||
users: state.user_query.clone(),
|
||||
query: state.entry_query,
|
||||
};
|
||||
let stats = get_mood_stats::execute(query, &deps).await?;
|
||||
@@ -189,7 +218,11 @@ pub async fn handle_calendar(
|
||||
) -> Result<Json<Vec<CalendarDayResponse>>, ApiError> {
|
||||
let range = params.into_date_range()?;
|
||||
let deps = get_calendar::Deps {
|
||||
users: state.user_query.clone(),
|
||||
query: state.entry_query,
|
||||
dimensions: state.dimensions.clone(),
|
||||
cycles: state.cycle_query,
|
||||
preferences: state.preferences_query,
|
||||
};
|
||||
let days = get_calendar::execute(user_id, range, &deps).await?;
|
||||
Ok(Json(
|
||||
@@ -197,32 +230,6 @@ pub async fn handle_calendar(
|
||||
))
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/entries/correlation/{id}", tag = "entries", security(("bearer" = [])),
|
||||
params(("id" = String, Path, description = "Activity ID"), ListEntriesParams),
|
||||
responses((status = 200, body = CorrelationResponse))
|
||||
)]
|
||||
pub async fn handle_activity_correlation(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
PathId(activity_id): PathId<ActivityId>,
|
||||
Query(params): Query<ListEntriesParams>,
|
||||
) -> Result<Json<CorrelationResponse>, ApiError> {
|
||||
let range = match (params.from, params.to) {
|
||||
(Some(from), Some(to)) => {
|
||||
let from = api_types::mappers::shared::parse_datetime(&from)?;
|
||||
let to = api_types::mappers::shared::parse_datetime(&to)?;
|
||||
Some(domain::entry::DateRange::new(from, to)?)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let deps = get_activity_correlation::Deps {
|
||||
query: state.entry_query,
|
||||
};
|
||||
let correlation =
|
||||
get_activity_correlation::execute(user_id, activity_id.clone(), range, &deps).await?;
|
||||
Ok(Json(correlation_response(activity_id, correlation)))
|
||||
}
|
||||
|
||||
#[utoipa::path(delete, path = "/api/v1/entries/bulk/delete", tag = "entries", security(("bearer" = [])),
|
||||
params(DateRangeParams),
|
||||
responses((status = 200, body = BulkActionResponse))
|
||||
@@ -234,6 +241,8 @@ pub async fn handle_delete_by_date_range(
|
||||
) -> Result<Json<BulkActionResponse>, ApiError> {
|
||||
let range = params.into_date_range()?;
|
||||
let deps = delete_entries_by_date_range::Deps {
|
||||
query: state.entry_query.clone(),
|
||||
dimensions: state.dimensions.clone(),
|
||||
cascade: state.cascade,
|
||||
media_storage: state.media_storage,
|
||||
};
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
use axum::Json;
|
||||
use axum::extract::{Multipart, State};
|
||||
use axum::http::header;
|
||||
use axum::response::IntoResponse;
|
||||
|
||||
use api_types::responses::ImportResultResponse;
|
||||
use application::export::use_cases::export_user_data;
|
||||
use application::import::commands::ImportCommand;
|
||||
use application::import::use_cases::import_entries;
|
||||
|
||||
@@ -12,34 +9,6 @@ use crate::errors::ApiError;
|
||||
use crate::extractors::{AuthenticatedUser, extract_file_bytes};
|
||||
use crate::state::AppState;
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/data/export", tag = "data", security(("bearer" = [])),
|
||||
responses((status = 200, description = "ZIP archive with user data"))
|
||||
)]
|
||||
pub async fn handle_export(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
) -> Result<impl IntoResponse, ApiError> {
|
||||
let deps = export_user_data::Deps {
|
||||
entry_query: state.entry_query,
|
||||
activity_query: state.activity_query,
|
||||
reminder_query: state.reminder_query,
|
||||
media_storage: state.media_storage,
|
||||
exporter: state.export_port.clone(),
|
||||
};
|
||||
let data = export_user_data::execute(user_id, &deps).await?;
|
||||
|
||||
Ok((
|
||||
[
|
||||
(header::CONTENT_TYPE, "application/zip"),
|
||||
(
|
||||
header::CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"k-mood-export.zip\"",
|
||||
),
|
||||
],
|
||||
data,
|
||||
))
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/data/import", tag = "data", security(("bearer" = [])),
|
||||
responses((status = 200, body = ImportResultResponse))
|
||||
)]
|
||||
@@ -57,6 +26,8 @@ pub async fn handle_import(
|
||||
entry_query: state.entry_query,
|
||||
activity_command: state.activity_command,
|
||||
activity_query: state.activity_query,
|
||||
dimensions: state.dimensions.clone(),
|
||||
users: state.user_query,
|
||||
preset: state.preset_config,
|
||||
};
|
||||
let result = import_entries::execute(cmd, &deps).await?;
|
||||
|
||||
127
crates/adapters/http-axum/src/handlers/metrics.rs
Normal file
127
crates/adapters/http-axum/src/handlers/metrics.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
|
||||
use api_types::mappers::parse_date;
|
||||
use api_types::requests::{DateSpanParams, ImportDailyMetricsRequest, SetDailyMetricsRequest};
|
||||
use api_types::responses::{DailyMetricResponse, ImportOutcomeResponse, RejectionResponse};
|
||||
use application::import::commands::ImportDailyMetricsCommand;
|
||||
use application::import::use_cases::import_daily_metrics;
|
||||
use application::metric::commands::SetDailyMetricsCommand;
|
||||
use application::metric::use_cases::{list_daily_metrics, set_daily_metrics};
|
||||
|
||||
use crate::errors::ApiError;
|
||||
use crate::extractors::{AuthenticatedUser, ImportingProvider, MetricWriter};
|
||||
use crate::state::AppState;
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/metrics", tag = "metrics", security(("bearer" = [])),
|
||||
params(DateSpanParams),
|
||||
responses((status = 200, body = Vec<DailyMetricResponse>))
|
||||
)]
|
||||
pub async fn handle_list(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
Query(params): Query<DateSpanParams>,
|
||||
) -> Result<Json<Vec<DailyMetricResponse>>, ApiError> {
|
||||
let span = params.into_span()?;
|
||||
|
||||
let deps = list_daily_metrics::Deps {
|
||||
metrics: state.daily_metric_query,
|
||||
};
|
||||
|
||||
let metrics = list_daily_metrics::execute(user_id, span, &deps).await?;
|
||||
|
||||
Ok(Json(metrics.into_iter().map(Into::into).collect()))
|
||||
}
|
||||
|
||||
#[utoipa::path(put, path = "/api/v1/metrics/{date}", tag = "metrics", security(("bearer" = [])),
|
||||
description = "States the given metrics for one day. A null value clears that kind instead, \
|
||||
after which a later provider import may report it again. Every kind may appear \
|
||||
only once per request.",
|
||||
params(("date" = String, Path, description = "Calendar date, as YYYY-MM-DD")),
|
||||
request_body = SetDailyMetricsRequest,
|
||||
responses((status = 204))
|
||||
)]
|
||||
pub async fn handle_set(
|
||||
State(state): State<AppState>,
|
||||
writer: MetricWriter,
|
||||
Path(date): Path<String>,
|
||||
Json(body): Json<SetDailyMetricsRequest>,
|
||||
) -> Result<StatusCode, ApiError> {
|
||||
let date = parse_date(&date)?;
|
||||
|
||||
let changes = body
|
||||
.metrics
|
||||
.into_iter()
|
||||
.map(|payload| payload.into_change())
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
let deps = set_daily_metrics::Deps {
|
||||
metrics: state.daily_metric_command,
|
||||
users: state.user_query,
|
||||
};
|
||||
|
||||
set_daily_metrics::execute(
|
||||
SetDailyMetricsCommand {
|
||||
user_id: writer.user_id,
|
||||
date,
|
||||
changes,
|
||||
source: writer.source,
|
||||
},
|
||||
&deps,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/metrics/import", tag = "metrics", security(("bearer" = [])),
|
||||
description = "Accepts a batch of days from an automation, authenticated by an api token and \
|
||||
nothing else. A payload carrying only some of the eight kinds is normal. Every \
|
||||
reading is judged on its own: the valid ones are stored and the rest are \
|
||||
rejected and written to a trace the account holder can read, so one bad value \
|
||||
never costs a night of good data. Values are never clamped. A reading the user \
|
||||
has stated by hand is reported as superseding the imported one, which is not a \
|
||||
rejection. Only a payload carrying more days than the configured limit is \
|
||||
refused outright.",
|
||||
request_body = ImportDailyMetricsRequest,
|
||||
responses((status = 200, body = ImportOutcomeResponse))
|
||||
)]
|
||||
pub async fn handle_import(
|
||||
State(state): State<AppState>,
|
||||
importer: ImportingProvider,
|
||||
Json(body): Json<ImportDailyMetricsRequest>,
|
||||
) -> Result<Json<ImportOutcomeResponse>, ApiError> {
|
||||
let deps = import_daily_metrics::Deps {
|
||||
metrics: state.daily_metric_command,
|
||||
rejections: state.rejection_command,
|
||||
};
|
||||
|
||||
let outcome = import_daily_metrics::execute(
|
||||
ImportDailyMetricsCommand {
|
||||
user_id: importer.user_id,
|
||||
provider: importer.provider,
|
||||
days: body.into_days(),
|
||||
maximum_days: state.import_config.maximum_days_per_import,
|
||||
},
|
||||
&deps,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Json(outcome.into()))
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/metrics/rejections", tag = "metrics", security(("bearer" = [])),
|
||||
description = "Readings that could not be used, most recent first, whether they arrived \
|
||||
broken from an importer or were stored by an older build and can no longer be \
|
||||
read. Only the most recent are kept.",
|
||||
responses((status = 200, body = Vec<RejectionResponse>))
|
||||
)]
|
||||
pub async fn handle_rejections(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
) -> Result<Json<Vec<RejectionResponse>>, ApiError> {
|
||||
let rejections = state.rejection_query.find_recent_by_user(&user_id).await?;
|
||||
|
||||
Ok(Json(rejections.into_iter().map(Into::into).collect()))
|
||||
}
|
||||
@@ -1,8 +1,14 @@
|
||||
pub mod activities;
|
||||
pub mod auth;
|
||||
pub mod correlations;
|
||||
pub mod cycle;
|
||||
pub mod data;
|
||||
pub mod entries;
|
||||
pub mod import_export;
|
||||
pub mod media;
|
||||
pub mod metrics;
|
||||
pub mod providers;
|
||||
pub mod push;
|
||||
pub mod reminders;
|
||||
pub mod tokens;
|
||||
pub mod users;
|
||||
|
||||
127
crates/adapters/http-axum/src/handlers/providers.rs
Normal file
127
crates/adapters/http-axum/src/handlers/providers.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
|
||||
use api_types::dimension::DimensionPayload;
|
||||
use api_types::requests::ConnectProviderRequest;
|
||||
use api_types::responses::ProviderConnectionResponse;
|
||||
use application::provider::commands::ConnectProviderCommand;
|
||||
use application::provider::use_cases::{
|
||||
connect_provider, disconnect_provider, get_now_playing, list_connections,
|
||||
};
|
||||
use domain::dimension::DimensionValue;
|
||||
use domain::errors::DomainError;
|
||||
use domain::provider::ProviderName;
|
||||
|
||||
use crate::errors::ApiError;
|
||||
use crate::extractors::AuthenticatedUser;
|
||||
use crate::state::AppState;
|
||||
|
||||
fn cipher(
|
||||
state: &AppState,
|
||||
) -> Result<std::sync::Arc<dyn domain::provider::CredentialCipher>, ApiError> {
|
||||
state.credential_cipher.clone().ok_or_else(|| {
|
||||
DomainError::InvalidInput(
|
||||
"provider connections are unavailable: no credential encryption key is configured"
|
||||
.into(),
|
||||
)
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/providers", tag = "providers", security(("bearer" = [])),
|
||||
responses((status = 200, body = Vec<ProviderConnectionResponse>))
|
||||
)]
|
||||
pub async fn handle_list(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
) -> Result<Json<Vec<ProviderConnectionResponse>>, ApiError> {
|
||||
let deps = list_connections::Deps {
|
||||
query: state.provider_connection_query,
|
||||
};
|
||||
let connections = list_connections::execute(user_id, &deps).await?;
|
||||
|
||||
Ok(Json(connections.into_iter().map(Into::into).collect()))
|
||||
}
|
||||
|
||||
#[utoipa::path(put, path = "/api/v1/providers/{provider}", tag = "providers", security(("bearer" = [])),
|
||||
params(("provider" = String, Path, description = "Provider name")),
|
||||
request_body = ConnectProviderRequest,
|
||||
responses((status = 204))
|
||||
)]
|
||||
pub async fn handle_connect(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
Path(provider): Path<String>,
|
||||
Json(body): Json<ConnectProviderRequest>,
|
||||
) -> Result<StatusCode, ApiError> {
|
||||
let cipher = cipher(&state)?;
|
||||
let provider = ProviderName::new(provider)?;
|
||||
|
||||
let credential = serde_json::to_vec(&body.credential)
|
||||
.map_err(|_| DomainError::InvalidInput("credential must be a JSON object".into()))?;
|
||||
|
||||
let deps = connect_provider::Deps {
|
||||
command: state.provider_connection_command,
|
||||
cipher,
|
||||
};
|
||||
|
||||
connect_provider::execute(
|
||||
ConnectProviderCommand {
|
||||
user_id,
|
||||
provider,
|
||||
credential,
|
||||
},
|
||||
&deps,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[utoipa::path(delete, path = "/api/v1/providers/{provider}", tag = "providers", security(("bearer" = [])),
|
||||
params(("provider" = String, Path, description = "Provider name")),
|
||||
responses((status = 204))
|
||||
)]
|
||||
pub async fn handle_disconnect(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
Path(provider): Path<String>,
|
||||
) -> Result<StatusCode, ApiError> {
|
||||
let provider = ProviderName::new(provider)?;
|
||||
|
||||
let deps = disconnect_provider::Deps {
|
||||
command: state.provider_connection_command,
|
||||
};
|
||||
|
||||
disconnect_provider::execute(user_id, provider, &deps).await?;
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/providers/now-playing", tag = "providers", security(("bearer" = [])),
|
||||
responses((status = 200, body = Option<DimensionPayload>))
|
||||
)]
|
||||
pub async fn handle_now_playing(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
) -> Result<Json<Option<DimensionPayload>>, ApiError> {
|
||||
let cipher = cipher(&state)?;
|
||||
|
||||
let now_playing = state.now_playing.clone().ok_or_else(|| -> ApiError {
|
||||
DomainError::InvalidInput("no music provider is configured".into()).into()
|
||||
})?;
|
||||
|
||||
let deps = get_now_playing::Deps {
|
||||
query: state.provider_connection_query,
|
||||
cipher,
|
||||
now_playing,
|
||||
recordings: state.recording_lookup,
|
||||
};
|
||||
|
||||
let song = get_now_playing::execute(user_id, &deps).await?;
|
||||
|
||||
Ok(Json(song.map(|song| {
|
||||
DimensionPayload::from(&DimensionValue::Song(song))
|
||||
})))
|
||||
}
|
||||
80
crates/adapters/http-axum/src/handlers/tokens.rs
Normal file
80
crates/adapters/http-axum/src/handlers/tokens.rs
Normal file
@@ -0,0 +1,80 @@
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
|
||||
use api_types::requests::MintApiTokenRequest;
|
||||
use api_types::responses::{ApiTokenResponse, MintedApiTokenResponse};
|
||||
use application::api_token::commands::MintApiTokenCommand;
|
||||
use application::api_token::use_cases::{list_api_tokens, mint_api_token, revoke_api_token};
|
||||
use domain::api_token::ApiTokenId;
|
||||
use domain::provider::ProviderName;
|
||||
|
||||
use crate::errors::ApiError;
|
||||
use crate::extractors::{AuthenticatedUser, PathId};
|
||||
use crate::state::AppState;
|
||||
|
||||
#[utoipa::path(get, path = "/api/v1/tokens", tag = "tokens", security(("bearer" = [])),
|
||||
description = "Lists this account's api tokens. Values are never returned; only the name, \
|
||||
when it was minted, and when it was last used.",
|
||||
responses((status = 200, body = Vec<ApiTokenResponse>))
|
||||
)]
|
||||
pub async fn handle_list(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
) -> Result<Json<Vec<ApiTokenResponse>>, ApiError> {
|
||||
let deps = list_api_tokens::Deps {
|
||||
query: state.api_token_query,
|
||||
};
|
||||
|
||||
let tokens = list_api_tokens::execute(user_id, &deps).await?;
|
||||
|
||||
Ok(Json(tokens.into_iter().map(Into::into).collect()))
|
||||
}
|
||||
|
||||
#[utoipa::path(post, path = "/api/v1/tokens", tag = "tokens", security(("bearer" = [])),
|
||||
description = "Mints a token for writing daily metrics. The value comes back once and is \
|
||||
never retrievable again. The name becomes the Provider that the token's \
|
||||
writes are attributed to, so it must be lowercase letters, digits and hyphens.",
|
||||
request_body = MintApiTokenRequest,
|
||||
responses((status = 201, body = MintedApiTokenResponse))
|
||||
)]
|
||||
pub async fn handle_mint(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
Json(body): Json<MintApiTokenRequest>,
|
||||
) -> Result<(StatusCode, Json<MintedApiTokenResponse>), ApiError> {
|
||||
let deps = mint_api_token::Deps {
|
||||
command: state.api_token_command,
|
||||
secrets: state.api_token_secrets,
|
||||
};
|
||||
|
||||
let minted = mint_api_token::execute(
|
||||
MintApiTokenCommand {
|
||||
user_id,
|
||||
name: ProviderName::new(body.name)?,
|
||||
},
|
||||
&deps,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok((StatusCode::CREATED, Json(minted.into())))
|
||||
}
|
||||
|
||||
#[utoipa::path(delete, path = "/api/v1/tokens/{id}", tag = "tokens", security(("bearer" = [])),
|
||||
description = "Revokes a token. It stops working at once.",
|
||||
params(("id" = String, Path, description = "Token ID")),
|
||||
responses((status = 204))
|
||||
)]
|
||||
pub async fn handle_revoke(
|
||||
State(state): State<AppState>,
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
PathId(token_id): PathId<ApiTokenId>,
|
||||
) -> Result<StatusCode, ApiError> {
|
||||
let deps = revoke_api_token::Deps {
|
||||
command: state.api_token_command,
|
||||
};
|
||||
|
||||
revoke_api_token::execute(user_id, token_id, &deps).await?;
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
@@ -97,6 +97,7 @@ pub async fn handle_delete(
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
) -> Result<StatusCode, ApiError> {
|
||||
let deps = delete_user::Deps {
|
||||
dimensions: state.dimensions.clone(),
|
||||
user_query: state.user_query,
|
||||
entry_query: state.entry_query,
|
||||
cascade: state.cascade,
|
||||
@@ -115,6 +116,7 @@ pub async fn handle_clear_data(
|
||||
AuthenticatedUser(user_id): AuthenticatedUser,
|
||||
) -> Result<StatusCode, ApiError> {
|
||||
let deps = clear_data::Deps {
|
||||
dimensions: state.dimensions.clone(),
|
||||
entry_query: state.entry_query,
|
||||
cascade: state.cascade,
|
||||
media_storage: state.media_storage,
|
||||
|
||||
@@ -10,6 +10,10 @@ use utoipa::{Modify, OpenApi};
|
||||
),
|
||||
modifiers(&SecurityAddon),
|
||||
paths(
|
||||
crate::handlers::providers::handle_list,
|
||||
crate::handlers::providers::handle_connect,
|
||||
crate::handlers::providers::handle_disconnect,
|
||||
crate::handlers::providers::handle_now_playing,
|
||||
crate::handlers::auth::handle_login,
|
||||
crate::handlers::auth::handle_refresh,
|
||||
crate::handlers::auth::handle_logout,
|
||||
@@ -22,7 +26,6 @@ use utoipa::{Modify, OpenApi};
|
||||
crate::handlers::entries::handle_filter_by_activity,
|
||||
crate::handlers::entries::handle_stats,
|
||||
crate::handlers::entries::handle_calendar,
|
||||
crate::handlers::entries::handle_activity_correlation,
|
||||
crate::handlers::entries::handle_delete_by_date_range,
|
||||
crate::handlers::entries::handle_replace_activity,
|
||||
crate::handlers::activities::handle_create,
|
||||
@@ -50,12 +53,27 @@ use utoipa::{Modify, OpenApi};
|
||||
crate::handlers::media::handle_serve_voice_memo,
|
||||
crate::handlers::media::handle_delete_photo,
|
||||
crate::handlers::media::handle_delete_voice_memo,
|
||||
crate::handlers::import_export::handle_export,
|
||||
crate::handlers::data::handle_backup,
|
||||
crate::handlers::data::handle_extract,
|
||||
crate::handlers::data::handle_restore,
|
||||
crate::handlers::import_export::handle_import,
|
||||
crate::handlers::push::handle_vapid_key,
|
||||
crate::handlers::push::handle_subscribe,
|
||||
crate::handlers::push::handle_unsubscribe,
|
||||
crate::handlers::push::handle_test,
|
||||
crate::handlers::correlations::handle_list,
|
||||
crate::handlers::cycle::handle_read,
|
||||
crate::handlers::cycle::handle_record,
|
||||
crate::handlers::cycle::handle_forget,
|
||||
crate::handlers::cycle::handle_preferences,
|
||||
crate::handlers::cycle::handle_set_preferences,
|
||||
crate::handlers::tokens::handle_list,
|
||||
crate::handlers::tokens::handle_mint,
|
||||
crate::handlers::tokens::handle_revoke,
|
||||
crate::handlers::metrics::handle_list,
|
||||
crate::handlers::metrics::handle_import,
|
||||
crate::handlers::metrics::handle_rejections,
|
||||
crate::handlers::metrics::handle_set,
|
||||
),
|
||||
components(schemas(
|
||||
api_types::requests::CreateEntryRequest,
|
||||
@@ -83,9 +101,30 @@ use utoipa::{Modify, OpenApi};
|
||||
api_types::responses::MoodFrequency,
|
||||
api_types::responses::CalendarDayResponse,
|
||||
api_types::responses::BulkActionResponse,
|
||||
api_types::responses::CorrelationResponse,
|
||||
api_types::responses::ImportResultResponse,
|
||||
api_types::responses::RestoreOutcomeResponse,
|
||||
api_types::responses::MediaIdResponse,
|
||||
api_types::requests::SetDailyMetricsRequest,
|
||||
api_types::requests::MetricPayload,
|
||||
api_types::requests::DateSpanParams,
|
||||
api_types::responses::DailyMetricResponse,
|
||||
api_types::requests::MintApiTokenRequest,
|
||||
api_types::requests::SetPreferencesRequest,
|
||||
api_types::responses::CycleViewResponse,
|
||||
api_types::responses::CyclePositionResponse,
|
||||
api_types::responses::PreferencesResponse,
|
||||
api_types::requests::ImportDailyMetricsRequest,
|
||||
api_types::requests::ImportedDayPayload,
|
||||
api_types::requests::ImportedMetricPayload,
|
||||
api_types::responses::ImportOutcomeResponse,
|
||||
api_types::responses::RejectedMetricResponse,
|
||||
api_types::responses::RejectionResponse,
|
||||
api_types::responses::ApiTokenResponse,
|
||||
api_types::responses::MintedApiTokenResponse,
|
||||
api_types::responses::CorrelationRowResponse,
|
||||
api_types::responses::CorrelationInputResponse,
|
||||
api_types::responses::AgreementResponse,
|
||||
api_types::responses::StrategyScoreResponse,
|
||||
api_types::requests::PushSubscribeRequest,
|
||||
api_types::requests::PushUnsubscribeRequest,
|
||||
)),
|
||||
@@ -98,6 +137,10 @@ use utoipa::{Modify, OpenApi};
|
||||
(name = "media", description = "Photo and voice memo storage"),
|
||||
(name = "data", description = "Import and export"),
|
||||
(name = "push", description = "Push notifications"),
|
||||
(name = "metrics", description = "Daily metrics"),
|
||||
(name = "correlations", description = "Correlation between metrics and mood"),
|
||||
(name = "tokens", description = "API tokens for headless importers"),
|
||||
(name = "cycle", description = "Menstrual cycle starts and derived cycle day"),
|
||||
)
|
||||
)]
|
||||
pub struct ApiDoc;
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
use axum::extract::DefaultBodyLimit;
|
||||
use axum::http::HeaderValue;
|
||||
use axum::routing::{delete, get, patch, post};
|
||||
use axum::routing::{delete, get, patch, post, put};
|
||||
use axum::{Json, Router};
|
||||
use tower_http::cors::{AllowOrigin, Any, CorsLayer};
|
||||
use tower_http::trace::TraceLayer;
|
||||
use utoipa::OpenApi;
|
||||
use utoipa_scalar::{Scalar, Servable};
|
||||
|
||||
use crate::handlers::{activities, auth, entries, import_export, media, push, reminders, users};
|
||||
use crate::handlers::{
|
||||
activities, auth, correlations, cycle, data, entries, import_export, media, metrics, providers,
|
||||
push, reminders, tokens, users,
|
||||
};
|
||||
use crate::openapi::ApiDoc;
|
||||
use crate::state::AppState;
|
||||
|
||||
@@ -62,10 +65,50 @@ fn api_routes() -> Router<AppState> {
|
||||
.nest("/users", user_routes())
|
||||
.nest("/reminders", reminder_routes())
|
||||
.nest("/media", media_routes())
|
||||
.nest("/metrics", metric_routes())
|
||||
.nest("/correlations", correlation_routes())
|
||||
.nest("/tokens", token_routes())
|
||||
.nest("/cycle", cycle_routes())
|
||||
.nest("/providers", provider_routes())
|
||||
.nest("/push", push_routes())
|
||||
.nest("/data", data_routes())
|
||||
}
|
||||
|
||||
fn cycle_routes() -> Router<AppState> {
|
||||
Router::new().route("/", get(cycle::handle_read)).route(
|
||||
"/{date}",
|
||||
put(cycle::handle_record).delete(cycle::handle_forget),
|
||||
)
|
||||
}
|
||||
|
||||
fn token_routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/", get(tokens::handle_list).post(tokens::handle_mint))
|
||||
.route("/{id}", delete(tokens::handle_revoke))
|
||||
}
|
||||
|
||||
fn correlation_routes() -> Router<AppState> {
|
||||
Router::new().route("/", get(correlations::handle_list))
|
||||
}
|
||||
|
||||
fn metric_routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/", get(metrics::handle_list))
|
||||
.route("/import", post(metrics::handle_import))
|
||||
.route("/rejections", get(metrics::handle_rejections))
|
||||
.route("/{date}", put(metrics::handle_set))
|
||||
}
|
||||
|
||||
fn provider_routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/", get(providers::handle_list))
|
||||
.route("/now-playing", get(providers::handle_now_playing))
|
||||
.route(
|
||||
"/{provider}",
|
||||
put(providers::handle_connect).delete(providers::handle_disconnect),
|
||||
)
|
||||
}
|
||||
|
||||
fn auth_routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/login", post(auth::handle_login))
|
||||
@@ -89,10 +132,6 @@ fn entry_routes() -> Router<AppState> {
|
||||
"/filter/activity/{id}",
|
||||
get(entries::handle_filter_by_activity),
|
||||
)
|
||||
.route(
|
||||
"/correlation/{id}",
|
||||
get(entries::handle_activity_correlation),
|
||||
)
|
||||
.route("/bulk/delete", delete(entries::handle_delete_by_date_range))
|
||||
.route(
|
||||
"/bulk/replace-activity",
|
||||
@@ -127,6 +166,10 @@ fn user_routes() -> Router<AppState> {
|
||||
)
|
||||
.route("/me/password", patch(users::handle_change_password))
|
||||
.route("/me/data", delete(users::handle_clear_data))
|
||||
.route(
|
||||
"/me/preferences",
|
||||
get(cycle::handle_preferences).patch(cycle::handle_set_preferences),
|
||||
)
|
||||
}
|
||||
|
||||
fn reminder_routes() -> Router<AppState> {
|
||||
@@ -167,6 +210,8 @@ fn push_routes() -> Router<AppState> {
|
||||
|
||||
fn data_routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/export", get(import_export::handle_export))
|
||||
.route("/backup", get(data::handle_backup))
|
||||
.route("/extract", get(data::handle_extract))
|
||||
.route("/restore", post(data::handle_restore))
|
||||
.route("/import", post(import_export::handle_import))
|
||||
}
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use config::{AuthConfig, EntryConfig, PresetConfig, PushConfig, ServerConfig};
|
||||
use config::{
|
||||
AnalysisConfig, AuthConfig, EntryConfig, ImportConfig, PresetConfig, PushConfig, ServerConfig,
|
||||
};
|
||||
use domain::ports::{
|
||||
ActivityCommandPort, ActivityQueryPort, AuthServicePort, CascadeDeletePort, EventPublisherPort,
|
||||
ExportPort, ImportSourcePort, MediaStoragePort, MoodEntryCommandPort, MoodEntryQueryPort,
|
||||
PasswordHasherPort, PushSubscriptionCommandPort, PushSubscriptionQueryPort,
|
||||
RefreshSessionCommandPort, RefreshSessionQueryPort, ReminderCommandPort, ReminderQueryPort,
|
||||
ReminderSenderPort, UserCommandPort, UserQueryPort,
|
||||
ActivityCommandPort, ActivityQueryPort, ApiTokenCommandPort, ApiTokenQueryPort,
|
||||
ApiTokenSecretPort, AuthServicePort, BackupReaderPort, BackupWriterPort, CascadeDeletePort,
|
||||
CycleStartCommandPort, CycleStartQueryPort, DailyMetricCommandPort, DailyMetricQueryPort,
|
||||
EntryDimensionPort, EventPublisherPort, ExtractWriterPort, ImportSourcePort, MediaStoragePort,
|
||||
MoodEntryCommandPort, MoodEntryQueryPort, PasswordHasherPort, ProviderConnectionCommandPort,
|
||||
ProviderConnectionQueryPort, PushSubscriptionCommandPort, PushSubscriptionQueryPort,
|
||||
RefreshSessionCommandPort, RefreshSessionQueryPort, RejectionCommandPort, RejectionQueryPort,
|
||||
ReminderCommandPort, ReminderQueryPort, ReminderSenderPort, UserCommandPort,
|
||||
UserPreferencesCommandPort, UserPreferencesQueryPort, UserQueryPort,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub entry_command: Arc<dyn MoodEntryCommandPort>,
|
||||
pub entry_query: Arc<dyn MoodEntryQueryPort>,
|
||||
pub dimensions: Vec<Arc<dyn EntryDimensionPort>>,
|
||||
pub weather_store: Arc<dyn EntryDimensionPort>,
|
||||
pub activity_command: Arc<dyn ActivityCommandPort>,
|
||||
pub activity_query: Arc<dyn ActivityQueryPort>,
|
||||
pub user_command: Arc<dyn UserCommandPort>,
|
||||
@@ -22,17 +30,37 @@ pub struct AppState {
|
||||
pub refresh_session_command: Arc<dyn RefreshSessionCommandPort>,
|
||||
pub refresh_session_query: Arc<dyn RefreshSessionQueryPort>,
|
||||
pub cascade: Arc<dyn CascadeDeletePort>,
|
||||
pub daily_metric_command: Arc<dyn DailyMetricCommandPort>,
|
||||
pub daily_metric_query: Arc<dyn DailyMetricQueryPort>,
|
||||
pub cycle_command: Arc<dyn CycleStartCommandPort>,
|
||||
pub cycle_query: Arc<dyn CycleStartQueryPort>,
|
||||
pub preferences_command: Arc<dyn UserPreferencesCommandPort>,
|
||||
pub preferences_query: Arc<dyn UserPreferencesQueryPort>,
|
||||
pub rejection_command: Arc<dyn RejectionCommandPort>,
|
||||
pub rejection_query: Arc<dyn RejectionQueryPort>,
|
||||
pub api_token_command: Arc<dyn ApiTokenCommandPort>,
|
||||
pub api_token_query: Arc<dyn ApiTokenQueryPort>,
|
||||
pub api_token_secrets: Arc<dyn ApiTokenSecretPort>,
|
||||
pub auth_service: Arc<dyn AuthServicePort>,
|
||||
pub password_hasher: Arc<dyn PasswordHasherPort>,
|
||||
pub event_publisher: Arc<dyn EventPublisherPort>,
|
||||
pub media_storage: Arc<dyn MediaStoragePort>,
|
||||
pub export_port: Arc<dyn ExportPort>,
|
||||
pub backup_writer: Arc<dyn BackupWriterPort>,
|
||||
pub backup_reader: Arc<dyn BackupReaderPort>,
|
||||
pub extract_writer: Arc<dyn ExtractWriterPort>,
|
||||
pub import_source: Arc<dyn ImportSourcePort>,
|
||||
pub provider_connection_command: Arc<dyn ProviderConnectionCommandPort>,
|
||||
pub provider_connection_query: Arc<dyn ProviderConnectionQueryPort>,
|
||||
pub credential_cipher: Option<Arc<dyn domain::provider::CredentialCipher>>,
|
||||
pub now_playing: Option<Arc<dyn domain::ports::NowPlayingPort>>,
|
||||
pub recording_lookup: Arc<dyn domain::ports::RecordingLookupPort>,
|
||||
pub push_subscription_command: Arc<dyn PushSubscriptionCommandPort>,
|
||||
pub push_subscription_query: Arc<dyn PushSubscriptionQueryPort>,
|
||||
pub reminder_sender: Option<Arc<dyn ReminderSenderPort>>,
|
||||
pub server_config: ServerConfig,
|
||||
pub entry_config: EntryConfig,
|
||||
pub analysis_config: AnalysisConfig,
|
||||
pub import_config: ImportConfig,
|
||||
pub auth_config: AuthConfig,
|
||||
pub push_config: PushConfig,
|
||||
pub preset_config: PresetConfig,
|
||||
|
||||
Reference in New Issue
Block a user