This commit is contained in:
1 parent
bcb5d378c8
commit
4141562e33
51 files changed
+2235
-4754
No files matched your search
@@ -0,0 +1,167 @@
|
||||
use super::v2::{json_error, require_admin_json};
|
||||
use crate::{auth::Role, user::User};
|
||||
use cot::{db::Database, http::StatusCode, json::Json, response::IntoResponse, session::Session};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(super) struct UserRequest {
|
||||
action: String,
|
||||
id: Option<i64>,
|
||||
#[serde(default)]
|
||||
username: String,
|
||||
#[serde(default)]
|
||||
email: String,
|
||||
#[serde(default)]
|
||||
display_name: String,
|
||||
#[serde(default)]
|
||||
password: String,
|
||||
#[serde(default)]
|
||||
role: String,
|
||||
}
|
||||
|
||||
pub(super) async fn manage_user(
|
||||
session: Session,
|
||||
db: Database,
|
||||
Json(body): Json<UserRequest>,
|
||||
) -> cot::Result<cot::response::Response> {
|
||||
let admin = match require_admin_json(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(r) => return Ok(r),
|
||||
};
|
||||
if body.action == "delete" {
|
||||
let Some(id) = body.id.filter(|id| *id > 0) else {
|
||||
return Ok(json_error(StatusCode::BAD_REQUEST, "Invalid user"));
|
||||
};
|
||||
if id == admin.id {
|
||||
return Ok(json_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"You cannot delete your own account",
|
||||
));
|
||||
}
|
||||
User::delete_by_id(&db, id).await?;
|
||||
} else {
|
||||
if !["create", "update"].contains(&body.action.as_str())
|
||||
|| body.username.trim().is_empty()
|
||||
|| body.username.chars().count() > 255
|
||||
|| Role::from_code(&body.role).is_none()
|
||||
|| (body.action == "create" && body.password.is_empty())
|
||||
{
|
||||
return Ok(json_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Provide a username, valid role, and a password for new accounts",
|
||||
));
|
||||
}
|
||||
let optional = |s: String| if s.trim().is_empty() { None } else { Some(s) };
|
||||
let email = optional(body.email);
|
||||
let display_name = optional(body.display_name);
|
||||
if body.action == "create" {
|
||||
if User::get_by_username(&db, body.username.trim())
|
||||
.await?
|
||||
.is_some()
|
||||
{
|
||||
return Ok(json_error(StatusCode::CONFLICT, "Username already exists"));
|
||||
}
|
||||
User::create(
|
||||
&db,
|
||||
body.username.trim(),
|
||||
email.as_deref(),
|
||||
display_name.as_deref(),
|
||||
&body.password,
|
||||
&body.role,
|
||||
)
|
||||
.await?;
|
||||
} else {
|
||||
let Some(id) = body.id.filter(|id| *id > 0) else {
|
||||
return Ok(json_error(StatusCode::BAD_REQUEST, "Invalid user"));
|
||||
};
|
||||
if id == admin.id && body.role != "admin" {
|
||||
return Ok(json_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"You cannot remove your own administrator role",
|
||||
));
|
||||
}
|
||||
let Some(mut user) = User::get_by_id(&db, id).await? else {
|
||||
return Ok(json_error(StatusCode::NOT_FOUND, "User not found"));
|
||||
};
|
||||
if User::get_by_username(&db, body.username.trim())
|
||||
.await?
|
||||
.is_some_and(|u| u.id_val() != id)
|
||||
{
|
||||
return Ok(json_error(StatusCode::CONFLICT, "Username already exists"));
|
||||
}
|
||||
user.update_fields(
|
||||
&db,
|
||||
body.username.trim(),
|
||||
email.as_deref(),
|
||||
display_name.as_deref(),
|
||||
(!body.password.is_empty()).then_some(body.password.as_str()),
|
||||
&body.role,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
Json(serde_json::json!({"ok": true})).into_response()
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(super) struct ScheduleRequest {
|
||||
cron: String,
|
||||
}
|
||||
|
||||
pub(super) async fn schedule(
|
||||
session: Session,
|
||||
db: Database,
|
||||
handle: &std::sync::Arc<
|
||||
tokio::sync::OnceCell<std::sync::Arc<crate::scheduler::SchedulerHandle>>,
|
||||
>,
|
||||
name: &str,
|
||||
Json(body): Json<ScheduleRequest>,
|
||||
) -> cot::Result<cot::response::Response> {
|
||||
if let Err(response) = require_admin_json(&session, &db).await {
|
||||
return Ok(response);
|
||||
}
|
||||
let cron = body.cron.trim();
|
||||
if !valid_schedule(cron) {
|
||||
return Ok(json_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Invalid cron schedule: include the seconds field",
|
||||
));
|
||||
}
|
||||
if crate::scheduler::ScheduledJob::get_by_name(&db, name)
|
||||
.await?
|
||||
.is_none()
|
||||
{
|
||||
return Ok(json_error(StatusCode::NOT_FOUND, "Job not found"));
|
||||
}
|
||||
let Some(handle) = handle.get() else {
|
||||
return Ok(json_error(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"Scheduler is not ready",
|
||||
));
|
||||
};
|
||||
handle
|
||||
.reschedule_job(name, cron)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
Json(serde_json::json!({"ok": true})).into_response()
|
||||
}
|
||||
|
||||
fn valid_schedule(cron: &str) -> bool {
|
||||
cron.len() <= 100
|
||||
&& croner::parser::CronParser::builder()
|
||||
.seconds(croner::parser::Seconds::Required)
|
||||
.build()
|
||||
.parse(cron)
|
||||
.is_ok()
|
||||
&& crate::scheduler::compute_next_run(cron).is_some()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn schedules_use_the_same_seconds_field_as_the_scheduler() {
|
||||
assert!(super::valid_schedule("0 17 3 * * *"));
|
||||
assert!(!super::valid_schedule("17 3 * * *"));
|
||||
assert!(!super::valid_schedule("invalid"));
|
||||
}
|
||||
}
|
||||
+47
-717
@@ -1,6 +1,8 @@
|
||||
mod management;
|
||||
mod metadata_fix;
|
||||
mod setup;
|
||||
mod statistics;
|
||||
mod v2;
|
||||
pub mod views;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -20,15 +22,7 @@ use crate::config::AppConfig;
|
||||
use crate::i18n::I18n;
|
||||
use crate::scheduler::{JobRegistry, SchedulerHandle};
|
||||
use crate::user::User;
|
||||
use views::{
|
||||
ArtistForm, CronForm, MetadataBackfillForm, OidcSettingsForm, ReleaseForm, ReviewApproveForm,
|
||||
ReviewsBulkForm, SetImageBody, SetupForm, UploadImageBody, UserForm,
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ReviewsQuery {
|
||||
status: Option<String>,
|
||||
}
|
||||
use setup::SetupForm;
|
||||
|
||||
/// Build-time metadata baked in by `build.rs` and Cargo env vars.
|
||||
#[derive(Debug)]
|
||||
@@ -72,11 +66,6 @@ impl AdminApp {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SettingsQuery {
|
||||
saved: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct PathId {
|
||||
id: i64,
|
||||
@@ -98,11 +87,6 @@ struct PathNameRunId {
|
||||
run_id: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ReleasesQuery {
|
||||
artist_id: Option<i64>,
|
||||
}
|
||||
|
||||
impl App for AdminApp {
|
||||
fn name(&self) -> &'static str {
|
||||
"admin"
|
||||
@@ -122,7 +106,7 @@ impl App for AdminApp {
|
||||
if count > 0 {
|
||||
return Ok(auth::redirect("/admin/"));
|
||||
}
|
||||
views::setup_page(i18n, String::new())
|
||||
setup::setup_page(i18n, String::new())
|
||||
.await?
|
||||
.into_response()
|
||||
})
|
||||
@@ -133,7 +117,7 @@ impl App for AdminApp {
|
||||
if count > 0 {
|
||||
return Ok(auth::redirect("/admin/"));
|
||||
}
|
||||
views::setup_submit(i18n, &db, &session, form).await
|
||||
setup::setup_submit(i18n, &db, &session, form).await
|
||||
},
|
||||
),
|
||||
"admin_setup",
|
||||
@@ -180,6 +164,26 @@ impl App for AdminApp {
|
||||
},
|
||||
"admin_v2_dashboard",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/v2/api/statistics",
|
||||
{
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
get(move |session: Session, db: Database,
|
||||
query: UrlQuery<statistics::StatisticsQuery>| {
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
async move {
|
||||
let pg_pool = pool.get_or_init(|| async {
|
||||
sqlx::postgres::PgPoolOptions::new().max_connections(5)
|
||||
.connect(&pool_config.database_url).await.expect("admin pool")
|
||||
}).await;
|
||||
statistics::statistics(session, db, pg_pool, query.0).await
|
||||
}
|
||||
})
|
||||
},
|
||||
"admin_statistics",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/v2/api/reviews",
|
||||
{
|
||||
@@ -233,6 +237,25 @@ impl App for AdminApp {
|
||||
},
|
||||
"admin_v2_reviews_bulk",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/v2/api/users/manage",
|
||||
cot::router::method::post(management::manage_user),
|
||||
"admin_manage_user",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/v2/api/jobs/{name}/schedule",
|
||||
cot::router::method::post({
|
||||
let handle = Arc::clone(&self.scheduler_handle);
|
||||
move |session: Session, db: Database, path: Path<PathName>,
|
||||
json: Json<management::ScheduleRequest>| {
|
||||
let handle = Arc::clone(&handle);
|
||||
async move {
|
||||
management::schedule(session, db, &handle, &path.0.name, json).await
|
||||
}
|
||||
}
|
||||
}),
|
||||
"admin_job_schedule",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/v2/api/users",
|
||||
{
|
||||
@@ -584,7 +607,7 @@ impl App for AdminApp {
|
||||
.expect("admin pool")
|
||||
})
|
||||
.await;
|
||||
v2::job_run_detail(session, db, pg_pool, path.0.run_id).await
|
||||
v2::job_run_detail(session, db, pg_pool, &path.0.name, path.0.run_id).await
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -907,699 +930,6 @@ impl App for AdminApp {
|
||||
},
|
||||
"admin_index",
|
||||
),
|
||||
// -- Debug --------------------------------------------------------
|
||||
Route::with_handler_and_name(
|
||||
"/debug",
|
||||
{
|
||||
let config = Arc::clone(&self.config);
|
||||
move |session: Session, db: Database, i18n: I18n| {
|
||||
let config = Arc::clone(&config);
|
||||
async move {
|
||||
let admin =
|
||||
match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::debug_handler(admin, i18n, &config, &db)
|
||||
.await?
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
},
|
||||
"admin_debug",
|
||||
),
|
||||
// -- Settings -----------------------------------------------------
|
||||
Route::with_handler_and_name(
|
||||
"/settings",
|
||||
get({
|
||||
let config = Arc::clone(&self.config);
|
||||
move |session: Session, db: Database, i18n: I18n,
|
||||
query: UrlQuery<SettingsQuery>| {
|
||||
let config = Arc::clone(&config);
|
||||
async move {
|
||||
let admin =
|
||||
match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
let saved = query.0.saved.as_deref() == Some("1");
|
||||
views::settings_handler(admin, i18n, &config, &db, saved)
|
||||
.await?
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
})
|
||||
.post({
|
||||
let config = Arc::clone(&self.config);
|
||||
move |session: Session, db: Database, i18n: I18n,
|
||||
form: RequestForm<OidcSettingsForm>| {
|
||||
let config = Arc::clone(&config);
|
||||
async move {
|
||||
let admin =
|
||||
match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::settings_submit(admin, i18n, &config, &db, form).await
|
||||
}
|
||||
}
|
||||
}),
|
||||
"admin_settings",
|
||||
),
|
||||
// -- Settings probe (HTMX fragment) -----------------------------------
|
||||
Route::with_handler_and_name(
|
||||
"/settings/probe",
|
||||
{
|
||||
let config = Arc::clone(&self.config);
|
||||
move |session: Session, db: Database, i18n: I18n| {
|
||||
let config = Arc::clone(&config);
|
||||
async move {
|
||||
let admin =
|
||||
match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::settings_probe_handler(admin, i18n, &config, &db)
|
||||
.await?
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
},
|
||||
"admin_settings_probe",
|
||||
),
|
||||
// -- Users --------------------------------------------------------
|
||||
Route::with_handler_and_name(
|
||||
"/users",
|
||||
|session: Session, db: Database, i18n: I18n| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::users_list(admin, i18n, &db).await?.into_response()
|
||||
},
|
||||
"admin_users",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/users/new",
|
||||
get(|session: Session, db: Database, i18n: I18n| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::users_new(admin, i18n).await?.into_response()
|
||||
})
|
||||
.post(
|
||||
|session: Session, db: Database, form: RequestForm<UserForm>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::users_create(admin, &db, form).await
|
||||
},
|
||||
),
|
||||
"admin_users_new",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/users/{id}/edit",
|
||||
get(
|
||||
|session: Session, db: Database, i18n: I18n,
|
||||
path: Path<PathId>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::users_edit(admin, i18n, &db, path.0.id)
|
||||
.await?
|
||||
.into_response()
|
||||
},
|
||||
)
|
||||
.post(
|
||||
|session: Session, db: Database, path: Path<PathId>,
|
||||
form: RequestForm<UserForm>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::users_update(admin, &db, path.0.id, form).await
|
||||
},
|
||||
),
|
||||
"admin_users_edit",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/users/{id}/delete",
|
||||
cot::router::method::post(
|
||||
|session: Session, db: Database, path: Path<PathId>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::users_delete(admin, &db, path.0.id).await
|
||||
},
|
||||
),
|
||||
"admin_users_delete",
|
||||
),
|
||||
// -- Artists ------------------------------------------------------
|
||||
Route::with_handler_and_name(
|
||||
"/artists",
|
||||
|session: Session, db: Database, i18n: I18n| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::artists_list(admin, i18n, &db).await?.into_response()
|
||||
},
|
||||
"admin_artists",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/artists/new",
|
||||
get(|session: Session, db: Database, i18n: I18n| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::artists_new(admin, i18n).await?.into_response()
|
||||
})
|
||||
.post(
|
||||
|session: Session, db: Database, form: RequestForm<ArtistForm>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::artists_create(admin, &db, form).await
|
||||
},
|
||||
),
|
||||
"admin_artists_new",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/artists/{id}/edit",
|
||||
get(
|
||||
|session: Session, db: Database, i18n: I18n,
|
||||
path: Path<PathId>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::artists_edit(admin, i18n, &db, path.0.id)
|
||||
.await?
|
||||
.into_response()
|
||||
},
|
||||
)
|
||||
.post(
|
||||
|session: Session, db: Database, path: Path<PathId>,
|
||||
form: RequestForm<ArtistForm>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::artists_update(admin, &db, path.0.id, form).await
|
||||
},
|
||||
),
|
||||
"admin_artists_edit",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/artists/{id}/delete",
|
||||
cot::router::method::post(
|
||||
|session: Session, db: Database, path: Path<PathId>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::artists_delete(admin, &db, path.0.id).await
|
||||
},
|
||||
),
|
||||
"admin_artists_delete",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/artists/{id}/available-covers",
|
||||
get(
|
||||
|session: Session, db: Database, path: Path<PathId>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::artists_available_covers(admin, &db, path.0.id).await
|
||||
},
|
||||
),
|
||||
"admin_artists_available_covers",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/artists/{id}/set-image",
|
||||
cot::router::method::post(
|
||||
|session: Session, db: Database, path: Path<PathId>,
|
||||
json: Json<SetImageBody>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::artists_set_image(admin, &db, path.0.id, json.0).await
|
||||
},
|
||||
),
|
||||
"admin_artists_set_image",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/artists/{id}/upload-image",
|
||||
cot::router::method::post({
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
move |session: Session, db: Database, path: Path<PathId>,
|
||||
json: Json<UploadImageBody>| {
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
let pg_pool = pool.get_or_init(|| async {
|
||||
sqlx::postgres::PgPoolOptions::new()
|
||||
.max_connections(3)
|
||||
.connect(&pool_config.database_url)
|
||||
.await
|
||||
.expect("admin pool")
|
||||
}).await;
|
||||
let (live_config, _) = AppConfig::load_with_db(&db).await;
|
||||
views::artists_upload_image(admin, &db, pg_pool, &live_config, path.0.id, json.0).await
|
||||
}
|
||||
}
|
||||
}),
|
||||
"admin_artists_upload_image",
|
||||
),
|
||||
// -- Releases -----------------------------------------------------
|
||||
Route::with_handler_and_name(
|
||||
"/releases",
|
||||
|session: Session, db: Database, i18n: I18n,
|
||||
query: UrlQuery<ReleasesQuery>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::releases_list(admin, i18n, &db, query.0.artist_id)
|
||||
.await?
|
||||
.into_response()
|
||||
},
|
||||
"admin_releases",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/releases/new",
|
||||
get(|session: Session, db: Database, i18n: I18n| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::releases_new(admin, i18n, &db).await?.into_response()
|
||||
})
|
||||
.post(
|
||||
|session: Session, db: Database,
|
||||
form: RequestForm<ReleaseForm>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::releases_create(admin, &db, form).await
|
||||
},
|
||||
),
|
||||
"admin_releases_new",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/releases/{id}/edit",
|
||||
get(
|
||||
|session: Session, db: Database, i18n: I18n,
|
||||
path: Path<PathId>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::releases_edit(admin, i18n, &db, path.0.id)
|
||||
.await?
|
||||
.into_response()
|
||||
},
|
||||
)
|
||||
.post(
|
||||
|session: Session, db: Database, path: Path<PathId>,
|
||||
form: RequestForm<ReleaseForm>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::releases_update(admin, &db, path.0.id, form).await
|
||||
},
|
||||
),
|
||||
"admin_releases_edit",
|
||||
),
|
||||
{
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
Route::with_handler_and_name(
|
||||
"/releases/{id}/delete",
|
||||
cot::router::method::post(move |session: Session, db: Database, path: Path<PathId>| {
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
let pg_pool = pool
|
||||
.get_or_init(|| async {
|
||||
sqlx::postgres::PgPoolOptions::new()
|
||||
.max_connections(5)
|
||||
.connect(&pool_config.database_url)
|
||||
.await
|
||||
.expect("admin pool")
|
||||
})
|
||||
.await;
|
||||
views::releases_delete(admin, &db, pg_pool, path.0.id).await
|
||||
}
|
||||
}),
|
||||
"admin_releases_delete",
|
||||
)
|
||||
},
|
||||
// -- Media Files --------------------------------------------------
|
||||
Route::with_handler_and_name(
|
||||
"/media-files",
|
||||
|session: Session, db: Database, i18n: I18n| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::media_files_list(admin, i18n, &db).await?.into_response()
|
||||
},
|
||||
"admin_media_files",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/media-files/{id}/delete",
|
||||
cot::router::method::post(
|
||||
|session: Session, db: Database, path: Path<PathId>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::media_files_delete(admin, &db, path.0.id).await
|
||||
},
|
||||
),
|
||||
"admin_media_files_delete",
|
||||
),
|
||||
// -- Jobs ---------------------------------------------------------
|
||||
Route::with_handler_and_name(
|
||||
"/jobs",
|
||||
{
|
||||
let registry = Arc::clone(&self.registry);
|
||||
move |session: Session, db: Database, i18n: I18n| {
|
||||
let registry = Arc::clone(®istry);
|
||||
async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::jobs_list(admin, i18n, &db, ®istry).await?.into_response()
|
||||
}
|
||||
}
|
||||
},
|
||||
"admin_jobs",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/jobs/metadata_backfill/run-options",
|
||||
cot::router::method::post({
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
move |session: Session, db: Database,
|
||||
form: RequestForm<MetadataBackfillForm>| {
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
let pg_pool = pool.get_or_init(|| async {
|
||||
sqlx::postgres::PgPoolOptions::new()
|
||||
.max_connections(3)
|
||||
.connect(&pool_config.database_url)
|
||||
.await
|
||||
.expect("admin pool")
|
||||
}).await;
|
||||
views::metadata_backfill_run(admin, &db, pg_pool, form).await
|
||||
}
|
||||
}
|
||||
}),
|
||||
"admin_metadata_backfill_run",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/jobs/lastfm_popularity/run-options",
|
||||
cot::router::method::post({
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
move |session: Session, db: Database,
|
||||
form: RequestForm<views::LastfmPopularityForm>| {
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
let pg_pool = pool.get_or_init(|| async {
|
||||
sqlx::postgres::PgPoolOptions::new()
|
||||
.max_connections(3)
|
||||
.connect(&pool_config.database_url)
|
||||
.await
|
||||
.expect("admin pool")
|
||||
}).await;
|
||||
views::lastfm_popularity_run(admin, &db, pg_pool, form).await
|
||||
}
|
||||
}
|
||||
}),
|
||||
"admin_lastfm_popularity_run",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/jobs/{name}/run",
|
||||
cot::router::method::post({
|
||||
let handle = Arc::clone(&self.scheduler_handle);
|
||||
move |session: Session, db: Database, path: Path<PathName>| {
|
||||
let handle = Arc::clone(&handle);
|
||||
async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::job_run_now(admin, &handle, &path.0.name).await
|
||||
}
|
||||
}
|
||||
}),
|
||||
"admin_job_run",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/jobs/{name}/toggle",
|
||||
cot::router::method::post({
|
||||
let handle = Arc::clone(&self.scheduler_handle);
|
||||
move |session: Session, db: Database, path: Path<PathName>| {
|
||||
let handle = Arc::clone(&handle);
|
||||
async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::job_toggle_enabled(admin, &db, &handle, &path.0.name).await
|
||||
}
|
||||
}
|
||||
}),
|
||||
"admin_job_toggle",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/jobs/{name}/cron",
|
||||
cot::router::method::post({
|
||||
let handle = Arc::clone(&self.scheduler_handle);
|
||||
move |session: Session, db: Database, path: Path<PathName>,
|
||||
form: RequestForm<CronForm>| {
|
||||
let handle = Arc::clone(&handle);
|
||||
async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::job_update_cron(admin, &db, &handle, &path.0.name, form).await
|
||||
}
|
||||
}
|
||||
}),
|
||||
"admin_job_cron",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/jobs/{name}/runs/{run_id}",
|
||||
{
|
||||
move |session: Session, db: Database, i18n: I18n,
|
||||
path: Path<PathNameRunId>| {
|
||||
async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::job_run_detail(admin, i18n, &db, &path.0.name, path.0.run_id)
|
||||
.await?
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
},
|
||||
"admin_job_run_detail",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/jobs/{name}",
|
||||
{
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
move |session: Session, db: Database, i18n: I18n,
|
||||
path: Path<PathName>| {
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
let pg_pool = pool.get_or_init(|| async {
|
||||
sqlx::postgres::PgPoolOptions::new()
|
||||
.max_connections(3)
|
||||
.connect(&pool_config.database_url)
|
||||
.await
|
||||
.expect("admin pool")
|
||||
}).await;
|
||||
views::job_detail(admin, i18n, &db, pg_pool, &path.0.name)
|
||||
.await?
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
},
|
||||
"admin_job_detail",
|
||||
),
|
||||
// -- Reviews: clear -----------------------------------------------
|
||||
Route::with_handler_and_name(
|
||||
"/reviews/clear",
|
||||
cot::router::method::post(
|
||||
|session: Session, db: Database,
|
||||
query: UrlQuery<ReviewsQuery>| async move {
|
||||
let admin =
|
||||
match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::reviews_clear(admin, &db, query.0.status.as_deref()).await
|
||||
},
|
||||
),
|
||||
"admin_reviews_clear",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/reviews/bulk",
|
||||
cot::router::method::post(
|
||||
|session: Session, db: Database,
|
||||
form: RequestForm<ReviewsBulkForm>| async move {
|
||||
let admin =
|
||||
match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::reviews_bulk(admin, &db, form).await
|
||||
},
|
||||
),
|
||||
"admin_reviews_bulk",
|
||||
),
|
||||
// -- Reviews ------------------------------------------------------
|
||||
Route::with_handler_and_name(
|
||||
"/reviews",
|
||||
{
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
move |session: Session, db: Database, i18n: I18n,
|
||||
query: UrlQuery<ReviewsQuery>| {
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
let pg_pool = pool.get_or_init(|| async {
|
||||
sqlx::postgres::PgPoolOptions::new()
|
||||
.max_connections(3)
|
||||
.connect(&pool_config.database_url)
|
||||
.await
|
||||
.expect("admin pool")
|
||||
}).await;
|
||||
views::reviews_list(admin, i18n, &db, pg_pool, query.0.status.as_deref())
|
||||
.await?
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
},
|
||||
"admin_reviews",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/reviews/{id}",
|
||||
|session: Session, db: Database, i18n: I18n,
|
||||
path: Path<PathId>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::review_detail(admin, i18n, &db, path.0.id)
|
||||
.await?
|
||||
.into_response()
|
||||
},
|
||||
"admin_review_detail",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/reviews/{id}/approve",
|
||||
cot::router::method::post({
|
||||
let config = Arc::clone(&self.config);
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
move |session: Session, db: Database, path: Path<PathId>,
|
||||
form: RequestForm<ReviewApproveForm>| {
|
||||
let config = Arc::clone(&config);
|
||||
let pool = Arc::clone(&pool);
|
||||
let pool_config = Arc::clone(&pool_config);
|
||||
async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
let pg_pool = pool.get_or_init(|| async {
|
||||
sqlx::postgres::PgPoolOptions::new()
|
||||
.max_connections(3)
|
||||
.connect(&pool_config.database_url)
|
||||
.await
|
||||
.expect("admin pool")
|
||||
}).await;
|
||||
views::review_approve(admin, &config, &db, pg_pool, path.0.id, form).await
|
||||
}
|
||||
}
|
||||
}),
|
||||
"admin_review_approve",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/reviews/{id}/reject",
|
||||
cot::router::method::post(
|
||||
|session: Session, db: Database, path: Path<PathId>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::review_reject(admin, &db, path.0.id).await
|
||||
},
|
||||
),
|
||||
"admin_review_reject",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/reviews/{id}/requeue",
|
||||
cot::router::method::post(
|
||||
|session: Session, db: Database, path: Path<PathId>| async move {
|
||||
let admin = match auth::require_admin_or_redirect(&session, &db).await {
|
||||
Ok(u) => u,
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
views::review_requeue(admin, &db, path.0.id).await
|
||||
},
|
||||
),
|
||||
"admin_review_requeue",
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -1625,7 +955,7 @@ impl App for AdminApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Start an options-based run for both admin interfaces. Ordinary scheduler
|
||||
/// Start an options-based run for the admin interface. Ordinary scheduler
|
||||
/// entry points continue to call Job::run with light-mode defaults.
|
||||
async fn start_lastfm_popularity(
|
||||
db: &Database,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
use crate::auth;
|
||||
use crate::i18n::{I18n, Translations};
|
||||
use crate::user::User;
|
||||
use cot::Template;
|
||||
use cot::db::Database;
|
||||
use cot::form::{Form, FormResult};
|
||||
use cot::html::Html;
|
||||
use cot::request::extractors::RequestForm;
|
||||
use cot::response::IntoResponse;
|
||||
use cot::session::Session;
|
||||
|
||||
#[derive(Debug, Template)]
|
||||
#[template(path = "admin/setup.html")]
|
||||
struct SetupTemplate {
|
||||
t: &'static Translations,
|
||||
message: String,
|
||||
}
|
||||
|
||||
pub async fn setup_page(i18n: I18n, message: String) -> cot::Result<Html> {
|
||||
let template = SetupTemplate { t: i18n.t, message };
|
||||
Ok(Html::new(template.render()?))
|
||||
}
|
||||
|
||||
#[derive(Debug, Form)]
|
||||
pub struct SetupForm {
|
||||
username: String,
|
||||
password: String,
|
||||
confirm_password: String,
|
||||
}
|
||||
|
||||
pub async fn setup_submit(
|
||||
i18n: I18n,
|
||||
db: &Database,
|
||||
session: &Session,
|
||||
form: RequestForm<SetupForm>,
|
||||
) -> cot::Result<cot::response::Response> {
|
||||
let RequestForm(result) = form;
|
||||
let data = match result {
|
||||
FormResult::Ok(data) => data,
|
||||
FormResult::ValidationError(_) => {
|
||||
return setup_page(i18n, String::new()).await?.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
if data.password != data.confirm_password {
|
||||
let msg = i18n.t.setup_mismatch.to_owned();
|
||||
return setup_page(i18n, msg).await?.into_response();
|
||||
}
|
||||
|
||||
let user = User::create(db, &data.username, None, None, &data.password, "admin")
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(format!("failed to create admin: {e}")))?;
|
||||
|
||||
auth::login(session, user.id_val()).await?;
|
||||
Ok(auth::redirect("/admin/"))
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
WITH listens AS (
|
||||
SELECT le.*, COALESCE(NULLIF(u.display_name, ''), u.username::text, 'Deleted user #' || le.user_id) AS user_name,
|
||||
COALESCE(NULLIF(le.metadata_json->>'title', ''), 'Unknown track') AS title,
|
||||
COALESCE(le.metadata_json->>'release_title', '') AS release_title,
|
||||
ARRAY(SELECT DISTINCT trim(name) FROM jsonb_array_elements_text(
|
||||
COALESCE(le.metadata_json->'artist_names', '[]'::jsonb) ||
|
||||
COALESCE(le.metadata_json->'featured_artist_names', '[]'::jsonb)
|
||||
) AS names(name) WHERE trim(name) <> '' ORDER BY trim(name)) AS artist_names,
|
||||
CASE WHEN le.origin_device_id = ident.device_id THEN 'instance' ELSE 'synced' END AS source,
|
||||
COALESCE(NULLIF(d.name, ''), le.origin_device_id) AS device_name
|
||||
FROM furumusic__listen_event le
|
||||
LEFT JOIN furumusic__user u ON u.id = le.user_id
|
||||
LEFT JOIN furumusic__fed_device_identity ident ON ident.user_id = le.user_id
|
||||
LEFT JOIN furumusic__fed_device d ON d.user_id = le.user_id AND d.device_id = le.origin_device_id
|
||||
WHERE le.started_at_ms >= $1 AND le.started_at_ms < $2
|
||||
AND ($3::bigint IS NULL OR le.user_id = $3)
|
||||
AND ($4::text IS NULL OR le.content_id = $4)
|
||||
), filtered AS (
|
||||
SELECT * FROM listens
|
||||
WHERE ($5::text IS NULL OR EXISTS (SELECT 1 FROM unnest(artist_names) n WHERE lower(n) = lower($5)))
|
||||
AND ($6 = 'all' OR source = $6)
|
||||
)
|
||||
@@ -0,0 +1,403 @@
|
||||
use chrono::{NaiveDate, Utc};
|
||||
use cot::{db::Database, http::StatusCode, json::Json, response::IntoResponse, session::Session};
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use super::v2::{json_error, require_admin_json};
|
||||
|
||||
const LISTENS: &str = include_str!("sql/listens.sql");
|
||||
const PAGE_SIZE: i64 = 25;
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub(super) struct StatisticsQuery {
|
||||
pub from: Option<String>,
|
||||
pub to: Option<String>,
|
||||
pub user_id: Option<i64>,
|
||||
pub content_id: Option<String>,
|
||||
pub artist: Option<String>,
|
||||
pub source: Option<String>,
|
||||
pub kind: Option<String>,
|
||||
pub search: Option<String>,
|
||||
pub rank_page: Option<i64>,
|
||||
pub history_page: Option<i64>,
|
||||
pub history_kind: Option<String>,
|
||||
}
|
||||
|
||||
struct Filter {
|
||||
from: i64,
|
||||
to: i64,
|
||||
user_id: Option<i64>,
|
||||
content_id: Option<String>,
|
||||
artist: Option<String>,
|
||||
source: String,
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
fn parse(query: &StatisticsQuery) -> Result<Self, String> {
|
||||
fn date(value: &str) -> Result<i64, String> {
|
||||
NaiveDate::parse_from_str(value, "%Y-%m-%d")
|
||||
.ok()
|
||||
.and_then(|d| d.and_hms_opt(0, 0, 0))
|
||||
.map(|d| d.and_utc().timestamp_millis())
|
||||
.filter(|d| *d >= 0)
|
||||
.ok_or_else(|| "Use dates in YYYY-MM-DD format (1970 or later)".to_owned())
|
||||
}
|
||||
let to = match query.to.as_deref().filter(|s| !s.is_empty()) {
|
||||
Some(value) => date(value)?
|
||||
.checked_add(86_400_000)
|
||||
.ok_or("Invalid end date")?,
|
||||
None => Utc::now().timestamp_millis(),
|
||||
};
|
||||
let from = match query.from.as_deref().filter(|s| !s.is_empty()) {
|
||||
Some("all") => 0,
|
||||
Some(value) => date(value)?,
|
||||
None => to.saturating_sub(30 * 86_400_000),
|
||||
};
|
||||
if from >= to {
|
||||
return Err("Start date must not be after end date".into());
|
||||
}
|
||||
let source = query.source.as_deref().unwrap_or("all");
|
||||
if !["all", "instance", "synced"].contains(&source) {
|
||||
return Err("Unknown playback source".into());
|
||||
}
|
||||
if query.user_id.is_some_and(|id| id <= 0) {
|
||||
return Err("Invalid user".into());
|
||||
}
|
||||
if query.artist.as_ref().is_some_and(|s| s.len() > 1024)
|
||||
|| query.content_id.as_ref().is_some_and(|s| s.len() > 256)
|
||||
|| query.search.as_ref().is_some_and(|s| s.len() > 1024)
|
||||
{
|
||||
return Err("Filter is too long".into());
|
||||
}
|
||||
Ok(Self {
|
||||
from,
|
||||
to,
|
||||
user_id: query.user_id,
|
||||
content_id: query.content_id.clone(),
|
||||
artist: query.artist.clone(),
|
||||
source: source.into(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn query(&self, pool: &PgPool, suffix: &str) -> anyhow::Result<Value> {
|
||||
let sql = format!("{LISTENS}{suffix}");
|
||||
Ok(sqlx::query_scalar(&sql)
|
||||
.bind(self.from)
|
||||
.bind(self.to)
|
||||
.bind(self.user_id)
|
||||
.bind(&self.content_id)
|
||||
.bind(&self.artist)
|
||||
.bind(&self.source)
|
||||
.fetch_one(pool)
|
||||
.await?)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn statistics(
|
||||
session: Session,
|
||||
db: Database,
|
||||
pool: &PgPool,
|
||||
query: StatisticsQuery,
|
||||
) -> cot::Result<cot::response::Response> {
|
||||
if let Err(response) = require_admin_json(&session, &db).await {
|
||||
return Ok(response);
|
||||
}
|
||||
let filter = match Filter::parse(&query) {
|
||||
Ok(filter) => filter,
|
||||
Err(message) => return Ok(json_error(StatusCode::BAD_REQUEST, &message)),
|
||||
};
|
||||
let kind = query.kind.as_deref().unwrap_or("artists");
|
||||
if !["artists", "tracks", "releases", "users"].contains(&kind) {
|
||||
return Ok(json_error(StatusCode::BAD_REQUEST, "Unknown ranking"));
|
||||
}
|
||||
let history_kind = query.history_kind.as_deref().unwrap_or("all");
|
||||
if !["all", "plays", "short"].contains(&history_kind) {
|
||||
return Ok(json_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Unknown history filter",
|
||||
));
|
||||
}
|
||||
let result = load(pool, &filter, &query, kind, history_kind)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
Json(result).into_response()
|
||||
}
|
||||
|
||||
async fn load(
|
||||
pool: &PgPool,
|
||||
filter: &Filter,
|
||||
query: &StatisticsQuery,
|
||||
kind: &str,
|
||||
history_kind: &str,
|
||||
) -> anyhow::Result<Value> {
|
||||
let summary_sql = r#"
|
||||
SELECT to_jsonb(s) FROM (
|
||||
SELECT COUNT(*) AS events, COUNT(*) FILTER (WHERE qualified) AS plays,
|
||||
COUNT(*) FILTER (WHERE NOT qualified) AS short_listens,
|
||||
COUNT(*) FILTER (WHERE trim(both '"' from ended_reason) = 'finished') AS completed,
|
||||
COALESCE(SUM(listened_ms), 0)::bigint / 1000 AS listened_seconds,
|
||||
COUNT(DISTINCT user_id) FILTER (WHERE qualified) AS listeners,
|
||||
COUNT(DISTINCT content_id) FILTER (WHERE qualified) AS tracks,
|
||||
COUNT(*) FILTER (WHERE qualified AND source = 'instance') AS instance_plays,
|
||||
COUNT(*) FILTER (WHERE qualified AND source = 'synced') AS synced_plays
|
||||
FROM filtered
|
||||
) s"#;
|
||||
let daily_sql = r#",
|
||||
bounds AS (
|
||||
SELECT COALESCE(MIN(started_at_ms), $2) AS first_ms FROM filtered
|
||||
), granularity AS (
|
||||
SELECT CASE WHEN $2 - GREATEST($1, first_ms) > 120::bigint * 86400000
|
||||
THEN 'month' ELSE 'day' END AS unit FROM bounds
|
||||
), daily AS (
|
||||
SELECT date_trunc(g.unit, to_timestamp(started_at_ms / 1000.0) AT TIME ZONE 'UTC') AS bucket,
|
||||
COUNT(*) FILTER (WHERE qualified) AS plays,
|
||||
COUNT(DISTINCT user_id) FILTER (WHERE qualified) AS listeners,
|
||||
COALESCE(SUM(listened_ms), 0)::bigint / 1000 AS listened_seconds
|
||||
FROM filtered CROSS JOIN granularity g GROUP BY bucket
|
||||
), series AS (
|
||||
SELECT generate_series((SELECT MIN(bucket) FROM daily), (SELECT MAX(bucket) FROM daily),
|
||||
CASE WHEN unit = 'month' THEN interval '1 month' ELSE interval '1 day' END) AS bucket
|
||||
FROM granularity
|
||||
), filled AS (
|
||||
SELECT s.bucket, COALESCE(d.plays, 0) AS plays, COALESCE(d.listeners, 0) AS listeners,
|
||||
COALESCE(d.listened_seconds, 0) AS listened_seconds
|
||||
FROM series s LEFT JOIN daily d USING (bucket)
|
||||
)
|
||||
SELECT jsonb_build_object('unit', (SELECT unit FROM granularity), 'items',
|
||||
COALESCE((SELECT jsonb_agg(to_jsonb(d) ORDER BY bucket) FROM filled d), '[]'::jsonb))"#;
|
||||
let (summary, daily, ranking, history, instance) = tokio::try_join!(
|
||||
filter.query(pool, summary_sql),
|
||||
filter.query(pool, daily_sql),
|
||||
ranking(pool, filter, query, kind),
|
||||
history(pool, filter, query, history_kind),
|
||||
instance(pool),
|
||||
)?;
|
||||
Ok(
|
||||
serde_json::json!({"summary": summary, "daily": daily, "ranking": ranking,
|
||||
"history": history, "instance": instance, "from_ms": filter.from, "to_ms": filter.to}),
|
||||
)
|
||||
}
|
||||
|
||||
async fn ranking(
|
||||
pool: &PgPool,
|
||||
filter: &Filter,
|
||||
query: &StatisticsQuery,
|
||||
kind: &str,
|
||||
) -> anyhow::Result<Value> {
|
||||
// Only fixed SQL fragments are interpolated; every user filter is bound.
|
||||
let (key, label, extra, join) = match kind {
|
||||
"users" => ("user_id::text", "MIN(user_name)", "''::text", ""),
|
||||
"tracks" => (
|
||||
"content_id",
|
||||
"MIN(title)",
|
||||
"MIN(array_to_string(artist_names, ', '))",
|
||||
"",
|
||||
),
|
||||
"releases" => (
|
||||
"jsonb_build_array(release_title, artist_names)::text",
|
||||
"MIN(NULLIF(release_title, ''))",
|
||||
"MIN(array_to_string(artist_names, ', '))",
|
||||
"",
|
||||
),
|
||||
_ => (
|
||||
"lower(artist.name)",
|
||||
"MIN(artist.name)",
|
||||
"''::text",
|
||||
"CROSS JOIN LATERAL (SELECT DISTINCT ON (lower(n)) n AS name FROM unnest(artist_names) n ORDER BY lower(n), n) artist",
|
||||
),
|
||||
};
|
||||
let sql = format!(
|
||||
r#"{LISTENS}, ranked AS (
|
||||
SELECT {key} AS key, {label} AS label, {extra} AS detail, COUNT(*) AS plays,
|
||||
COUNT(DISTINCT user_id) AS listeners,
|
||||
SUM(listened_ms)::bigint / 1000 AS listened_seconds, MAX(started_at_ms) AS last_play_ms
|
||||
FROM filtered {join} WHERE qualified GROUP BY {key}
|
||||
), searched AS (
|
||||
SELECT * FROM ranked WHERE label IS NOT NULL
|
||||
AND ($7::text IS NULL OR strpos(lower(label || ' ' || detail), lower($7)) > 0)
|
||||
), page AS (SELECT * FROM searched ORDER BY plays DESC, key LIMIT $8 OFFSET $9)
|
||||
SELECT jsonb_build_object('total', (SELECT COUNT(*) FROM searched),
|
||||
'items', COALESCE((SELECT jsonb_agg(to_jsonb(p) ORDER BY plays DESC, key) FROM page p), '[]'::jsonb))"#
|
||||
);
|
||||
let page = query.rank_page.unwrap_or(1).clamp(1, 1_000_000);
|
||||
let mut result: Value = sqlx::query_scalar(&sql)
|
||||
.bind(filter.from)
|
||||
.bind(filter.to)
|
||||
.bind(filter.user_id)
|
||||
.bind(&filter.content_id)
|
||||
.bind(&filter.artist)
|
||||
.bind(&filter.source)
|
||||
.bind(query.search.as_deref().filter(|s| !s.is_empty()))
|
||||
.bind(PAGE_SIZE)
|
||||
.bind((page - 1) * PAGE_SIZE)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
result["page"] = page.into();
|
||||
result["limit"] = PAGE_SIZE.into();
|
||||
result["kind"] = kind.into();
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn history(
|
||||
pool: &PgPool,
|
||||
filter: &Filter,
|
||||
query: &StatisticsQuery,
|
||||
kind: &str,
|
||||
) -> anyhow::Result<Value> {
|
||||
let sql = format!(
|
||||
r#"{LISTENS}, selected AS (
|
||||
SELECT user_id, user_name, listen_id, content_id, title, artist_names, release_title,
|
||||
started_at_ms, listened_ms, track_duration_ms, qualified,
|
||||
trim(both '"' from ended_reason) AS ended_reason, device_name, source
|
||||
FROM filtered WHERE $7 = 'all' OR ($7 = 'plays' AND qualified) OR ($7 = 'short' AND NOT qualified)
|
||||
), page AS (SELECT * FROM selected ORDER BY started_at_ms DESC, user_id, listen_id LIMIT $8 OFFSET $9)
|
||||
SELECT jsonb_build_object('total', (SELECT COUNT(*) FROM selected),
|
||||
'items', COALESCE((SELECT jsonb_agg(to_jsonb(p) ORDER BY started_at_ms DESC, user_id, listen_id) FROM page p), '[]'::jsonb))"#
|
||||
);
|
||||
let page = query.history_page.unwrap_or(1).clamp(1, 1_000_000);
|
||||
let mut result: Value = sqlx::query_scalar(&sql)
|
||||
.bind(filter.from)
|
||||
.bind(filter.to)
|
||||
.bind(filter.user_id)
|
||||
.bind(&filter.content_id)
|
||||
.bind(&filter.artist)
|
||||
.bind(&filter.source)
|
||||
.bind(kind)
|
||||
.bind(PAGE_SIZE)
|
||||
.bind((page - 1) * PAGE_SIZE)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
result["page"] = page.into();
|
||||
result["limit"] = PAGE_SIZE.into();
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn instance(pool: &PgPool) -> anyhow::Result<Value> {
|
||||
Ok(sqlx::query_scalar(r#"SELECT jsonb_build_object(
|
||||
'users', (SELECT COUNT(*) FROM furumusic__user),
|
||||
'tracks', (SELECT COUNT(*) FROM furumusic__track),
|
||||
'releases', (SELECT COUNT(*) FROM furumusic__release),
|
||||
'artists', (SELECT COUNT(*) FROM furumusic__artist),
|
||||
'playlists', (SELECT COUNT(*) FROM furumusic__playlist),
|
||||
'media_bytes', (SELECT COALESCE(SUM(file_size_bytes), 0)::bigint FROM furumusic__media_file),
|
||||
'formats', (SELECT COALESCE(jsonb_agg(to_jsonb(f)), '[]'::jsonb) FROM (
|
||||
SELECT COALESCE(audio_format, 'unknown') AS label, COUNT(*) AS count
|
||||
FROM furumusic__media_file WHERE file_type = 'audio' GROUP BY audio_format ORDER BY count DESC
|
||||
) f),
|
||||
'reviews', (SELECT COALESCE(jsonb_agg(to_jsonb(r)), '[]'::jsonb) FROM (
|
||||
SELECT status::text AS label, COUNT(*) AS count FROM furumusic__pending_review GROUP BY status ORDER BY status
|
||||
) r),
|
||||
'jobs', (SELECT COALESCE(jsonb_agg(to_jsonb(j)), '[]'::jsonb) FROM (
|
||||
SELECT status::text AS label, COUNT(*) AS count FROM furumusic__job_run GROUP BY status ORDER BY status
|
||||
) j),
|
||||
'scrobbles', (SELECT COALESCE(jsonb_agg(to_jsonb(s)), '[]'::jsonb) FROM (
|
||||
SELECT status::text AS label, COUNT(*) AS count FROM furumusic__lastfm_scrobble_outbox GROUP BY status ORDER BY status
|
||||
) s)
|
||||
)"#).fetch_one(pool).await?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn dates_are_inclusive_utc_and_filters_are_validated() {
|
||||
let q = StatisticsQuery {
|
||||
from: Some("2026-11-01".into()),
|
||||
to: Some("2026-11-01".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let f = Filter::parse(&q).unwrap();
|
||||
assert_eq!(f.to - f.from, 86_400_000);
|
||||
assert!(
|
||||
Filter::parse(&StatisticsQuery {
|
||||
from: Some("broken".into()),
|
||||
..q
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
Filter::parse(&StatisticsQuery {
|
||||
source: Some("invalid".into()),
|
||||
..Default::default()
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
#[ignore = "requires FURU_STATISTICS_TEST_DATABASE_URL pointing at a disposable PostgreSQL"]
|
||||
async fn postgres_statistics_drilldown_and_pagination() {
|
||||
let url = std::env::var("FURU_STATISTICS_TEST_DATABASE_URL").expect("test database URL");
|
||||
// Temporary tables are isolated to this one connection and disappear on close.
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect(&url)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::raw_sql(include_str!("../../tests/statistics_fixture.sql"))
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut q = StatisticsQuery {
|
||||
from: Some("2026-11-01".into()),
|
||||
to: Some("2026-11-03".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let result = load(&pool, &Filter::parse(&q).unwrap(), &q, "artists", "all")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result["summary"]["plays"], 32);
|
||||
assert_eq!(result["summary"]["short_listens"], 1);
|
||||
assert_eq!(result["summary"]["listeners"], 2);
|
||||
assert_eq!(result["summary"]["listened_seconds"], 5618);
|
||||
assert_eq!(result["summary"]["synced_plays"], 1);
|
||||
assert_eq!(result["ranking"]["items"][0]["label"], "Artist A");
|
||||
assert_eq!(result["ranking"]["items"][0]["plays"], 31); // duplicate artist credits never multiply plays
|
||||
assert_eq!(result["ranking"]["items"][0]["listeners"], 2);
|
||||
assert_eq!(result["history"]["total"], 33);
|
||||
assert_eq!(result["history"]["items"].as_array().unwrap().len(), 25);
|
||||
assert_eq!(result["daily"]["items"].as_array().unwrap().len(), 3);
|
||||
assert_eq!(result["daily"]["items"][1]["plays"], 0); // fill the silent day
|
||||
q.artist = Some("artist a".into());
|
||||
let result = load(&pool, &Filter::parse(&q).unwrap(), &q, "users", "all")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result["ranking"]["total"], 2);
|
||||
assert_eq!(result["ranking"]["items"][0]["label"], "Alice");
|
||||
assert_eq!(result["ranking"]["items"][0]["plays"], 30);
|
||||
q.user_id = Some(2);
|
||||
let result = load(&pool, &Filter::parse(&q).unwrap(), &q, "tracks", "short")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result["summary"]["plays"], 1);
|
||||
assert_eq!(result["history"]["total"], 1);
|
||||
assert_eq!(result["history"]["items"][0]["ended_reason"], "skipped");
|
||||
assert_eq!(result["ranking"]["items"][0]["label"], "First song"); // no local track exists
|
||||
q.user_id = None;
|
||||
q.artist = None;
|
||||
q.history_page = Some(2);
|
||||
let result = load(&pool, &Filter::parse(&q).unwrap(), &q, "releases", "all")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result["history"]["items"].as_array().unwrap().len(), 8);
|
||||
q.source = Some("synced".into());
|
||||
let result = load(&pool, &Filter::parse(&q).unwrap(), &q, "users", "all")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result["summary"]["plays"], 1);
|
||||
q.source = Some("instance".into());
|
||||
q.search = Some("' OR 1=1 --".into());
|
||||
let result = load(&pool, &Filter::parse(&q).unwrap(), &q, "artists", "all")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result["summary"]["plays"], 31);
|
||||
assert_eq!(result["ranking"]["total"], 0);
|
||||
q.user_id = Some(3);
|
||||
let result = load(&pool, &Filter::parse(&q).unwrap(), &q, "users", "all")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result["summary"]["plays"], 0);
|
||||
assert_eq!(result["history"]["total"], 0);
|
||||
pool.close().await;
|
||||
}
|
||||
}
|
||||
+54
-42
@@ -232,6 +232,9 @@ struct AdminUserRowDto {
|
||||
is_active: bool,
|
||||
is_online: bool,
|
||||
last_seen_ms: Option<i64>,
|
||||
plays: i64,
|
||||
listened_seconds: i64,
|
||||
last_play_ms: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
@@ -257,7 +260,7 @@ struct AdminUserStatsDto {
|
||||
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
struct AdminUserPlayDto {
|
||||
history_id: i64,
|
||||
history_id: String,
|
||||
played_at: String,
|
||||
duration_listened: Option<i32>,
|
||||
completed: bool,
|
||||
@@ -1958,6 +1961,7 @@ pub async fn job_run_detail(
|
||||
session: Session,
|
||||
db: Database,
|
||||
pool: &PgPool,
|
||||
job_name: &str,
|
||||
run_id: i64,
|
||||
) -> cot::Result<cot::response::Response> {
|
||||
if let Err(response) = require_admin_json(&session, &db).await {
|
||||
@@ -1967,9 +1971,10 @@ pub async fn job_run_detail(
|
||||
"SELECT id, job_name::text AS job_name, status::text AS status, started_at::text AS started_at, \
|
||||
finished_at, duration_ms, trigger::text AS trigger, error_message, \
|
||||
LEFT(COALESCE(log_output, ''), 1600) AS log_excerpt, log_output \
|
||||
FROM furumusic__job_run WHERE id = $1",
|
||||
FROM furumusic__job_run WHERE id = $1 AND job_name = $2",
|
||||
)
|
||||
.bind(run_id)
|
||||
.bind(job_name)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
@@ -2662,6 +2667,9 @@ struct AdminUserSqlRow {
|
||||
email: Option<String>,
|
||||
role: String,
|
||||
is_active: bool,
|
||||
plays: i64,
|
||||
listened_seconds: i64,
|
||||
last_play_ms: Option<i64>,
|
||||
}
|
||||
|
||||
async fn load_admin_users_page(
|
||||
@@ -2692,7 +2700,11 @@ async fn load_admin_users_page(
|
||||
let total: i64 = count_qb.build_query_scalar().fetch_one(pool).await?;
|
||||
|
||||
let mut qb = QueryBuilder::<Postgres>::new(
|
||||
"SELECT id, username::text, display_name, email, role::text, is_active FROM furumusic__user WHERE 1=1",
|
||||
"SELECT id, username::text, display_name, email, role::text, is_active, \
|
||||
(SELECT COUNT(*) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS plays, \
|
||||
(SELECT (COALESCE(SUM(listened_ms), 0) / 1000)::bigint FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id) AS listened_seconds, \
|
||||
(SELECT MAX(started_at_ms) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS last_play_ms \
|
||||
FROM furumusic__user WHERE 1=1",
|
||||
);
|
||||
if let Some(pattern) = pattern.as_ref() {
|
||||
qb.push(" AND (username ILIKE ");
|
||||
@@ -2735,7 +2747,11 @@ async fn load_admin_user_detail(
|
||||
user_id: i64,
|
||||
) -> anyhow::Result<Option<AdminUserDetailDto>> {
|
||||
let row = sqlx::query_as::<_, AdminUserSqlRow>(
|
||||
"SELECT id, username::text, display_name, email, role::text, is_active FROM furumusic__user WHERE id = $1",
|
||||
"SELECT id, username::text, display_name, email, role::text, is_active, \
|
||||
(SELECT COUNT(*) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS plays, \
|
||||
(SELECT (COALESCE(SUM(listened_ms), 0) / 1000)::bigint FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id) AS listened_seconds, \
|
||||
(SELECT MAX(started_at_ms) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS last_play_ms \
|
||||
FROM furumusic__user WHERE id = $1",
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_optional(pool)
|
||||
@@ -2759,17 +2775,17 @@ async fn load_admin_user_detail(
|
||||
lastfm_connected,
|
||||
) = tokio::try_join!(
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"SELECT COUNT(*) FROM furumusic__play_history WHERE user_id = $1"
|
||||
"SELECT COUNT(*) FROM furumusic__listen_event WHERE user_id = $1 AND qualified"
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_one(pool),
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"SELECT COUNT(*) FROM furumusic__play_history WHERE user_id = $1 AND completed"
|
||||
"SELECT COUNT(*) FROM furumusic__listen_event WHERE user_id = $1 AND qualified AND ended_reason = '\"finished\"'"
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_one(pool),
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"SELECT COALESCE(SUM(duration_listened), 0)::bigint FROM furumusic__play_history WHERE user_id = $1"
|
||||
"SELECT (COALESCE(SUM(listened_ms), 0) / 1000)::bigint FROM furumusic__listen_event WHERE user_id = $1"
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_one(pool),
|
||||
@@ -2835,34 +2851,27 @@ async fn load_admin_user_recent_plays(
|
||||
limit: i64,
|
||||
) -> anyhow::Result<Vec<AdminUserPlayDto>> {
|
||||
let rows = sqlx::query_as::<_, AdminUserPlaySqlRow>(
|
||||
r#"SELECT ph.id AS history_id,
|
||||
ph.played_at::text AS played_at,
|
||||
ph.duration_listened,
|
||||
ph.completed,
|
||||
t.id AS track_id,
|
||||
t.title::text AS title,
|
||||
COALESCE(NULLIF(STRING_AGG(a.name::text, ', ' ORDER BY ta.position), ''), 'Unknown artist') AS artists,
|
||||
t.release_id,
|
||||
COALESCE(r.title::text, '') AS release_title,
|
||||
r.year AS release_year,
|
||||
t.cover_file_id,
|
||||
r.cover_file_id AS release_cover_file_id,
|
||||
t.duration_seconds AS track_duration_seconds,
|
||||
COALESCE(mf.uploader_name, 'UFO')::text AS uploader_name,
|
||||
mf.audio_format,
|
||||
mf.audio_bitrate
|
||||
FROM furumusic__play_history ph
|
||||
JOIN furumusic__track t ON t.id = ph.track_id
|
||||
r#"SELECT le.listen_id AS history_id,
|
||||
to_timestamp(le.started_at_ms / 1000.0)::text AS played_at,
|
||||
LEAST(le.listened_ms / 1000, 2147483647)::integer AS duration_listened,
|
||||
le.ended_reason = '"finished"' AS completed,
|
||||
COALESCE(t.id, 0) AS track_id,
|
||||
COALESCE(le.metadata_json->>'title', 'Unknown track') AS title,
|
||||
COALESCE((SELECT string_agg(name, ', ') FROM jsonb_array_elements_text(
|
||||
COALESCE(le.metadata_json->'artist_names', '[]'::jsonb)) names(name)), 'Unknown artist') AS artists,
|
||||
COALESCE(t.release_id, 0) AS release_id,
|
||||
COALESCE(le.metadata_json->>'release_title', '') AS release_title,
|
||||
r.year AS release_year, t.cover_file_id, r.cover_file_id AS release_cover_file_id,
|
||||
COALESCE(le.track_duration_ms / 1000.0, 0)::float8 AS track_duration_seconds,
|
||||
COALESCE(mf.uploader_name, '')::text AS uploader_name,
|
||||
mf.audio_format, mf.audio_bitrate
|
||||
FROM furumusic__listen_event le
|
||||
LEFT JOIN furumusic__track_ref tr ON tr.content_id = le.content_id
|
||||
LEFT JOIN furumusic__track t ON t.id = COALESCE(le.local_track_id, tr.local_track_id)
|
||||
LEFT JOIN furumusic__release r ON r.id = t.release_id
|
||||
LEFT JOIN furumusic__media_file mf ON mf.id = t.audio_file_id
|
||||
LEFT JOIN furumusic__track_artist ta ON ta.track_id = t.id AND ta.role = 'main'
|
||||
LEFT JOIN furumusic__artist a ON a.id = ta.artist_id
|
||||
WHERE ph.user_id = $1
|
||||
GROUP BY ph.id, ph.played_at, ph.duration_listened, ph.completed, t.id, t.title,
|
||||
t.release_id, r.title, r.year, t.cover_file_id, r.cover_file_id,
|
||||
t.duration_seconds, mf.uploader_name, mf.audio_format, mf.audio_bitrate
|
||||
ORDER BY ph.played_at DESC, ph.id DESC
|
||||
LIMIT $2"#,
|
||||
WHERE le.user_id = $1 AND le.qualified
|
||||
ORDER BY le.started_at_ms DESC, le.listen_id DESC LIMIT $2"#,
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(limit)
|
||||
@@ -2893,7 +2902,7 @@ async fn load_admin_user_recent_plays(
|
||||
|
||||
#[derive(Debug, sqlx::FromRow)]
|
||||
struct AdminUserPlaySqlRow {
|
||||
history_id: i64,
|
||||
history_id: String,
|
||||
played_at: String,
|
||||
duration_listened: Option<i32>,
|
||||
completed: bool,
|
||||
@@ -2930,6 +2939,9 @@ fn admin_user_row(
|
||||
email: row.email,
|
||||
role: row.role,
|
||||
is_active: row.is_active,
|
||||
plays: row.plays,
|
||||
listened_seconds: row.listened_seconds,
|
||||
last_play_ms: row.last_play_ms,
|
||||
is_online: last_seen_ms.is_some_and(|value| value <= online_cutoff_ms),
|
||||
last_seen_ms,
|
||||
}
|
||||
@@ -3549,13 +3561,13 @@ async fn fetch_library_item(
|
||||
(COALESCE(NULLIF(STRING_AGG(DISTINCT a.name::text, ', '), ''), 'Unknown artist') || COALESCE(' / ' || r.year::text, '')) AS subtitle, \
|
||||
r.is_hidden, COUNT(DISTINCT t.id)::bigint AS primary_count, \
|
||||
COUNT(DISTINCT ra.artist_id)::bigint AS secondary_count, \
|
||||
COUNT(DISTINCT ph.id)::bigint AS tertiary_count, \
|
||||
COUNT(DISTINCT (ph.user_id, ph.listen_id)) FILTER (WHERE ph.listen_id IS NOT NULL)::bigint AS tertiary_count, \
|
||||
r.updated_at::text AS updated_at \
|
||||
FROM furumusic__release r \
|
||||
LEFT JOIN furumusic__track t ON t.release_id = r.id \
|
||||
LEFT JOIN furumusic__release_artist ra ON ra.release_id = r.id \
|
||||
LEFT JOIN furumusic__artist a ON a.id = ra.artist_id \
|
||||
LEFT JOIN furumusic__play_history ph ON ph.track_id = t.id \
|
||||
LEFT JOIN furumusic__track_ref playback_ref ON playback_ref.local_track_id = t.id LEFT JOIN furumusic__listen_event ph ON ph.content_id = playback_ref.content_id AND ph.qualified \
|
||||
WHERE r.id = $1 \
|
||||
GROUP BY r.id",
|
||||
)
|
||||
@@ -3585,13 +3597,13 @@ async fn fetch_library_item(
|
||||
"SELECT t.id, t.title::text AS title, \
|
||||
CONCAT(COALESCE(r.title::text, 'No release'), COALESCE(' / #' || t.track_number::text, '')) AS subtitle, \
|
||||
t.is_hidden, COUNT(DISTINCT ta.artist_id)::bigint AS primary_count, \
|
||||
COUNT(DISTINCT ph.id)::bigint AS secondary_count, \
|
||||
COUNT(DISTINCT (ph.user_id, ph.listen_id)) FILTER (WHERE ph.listen_id IS NOT NULL)::bigint AS secondary_count, \
|
||||
COUNT(DISTINCT pt.playlist_id)::bigint AS tertiary_count, \
|
||||
t.updated_at::text AS updated_at \
|
||||
FROM furumusic__track t \
|
||||
LEFT JOIN furumusic__release r ON r.id = t.release_id \
|
||||
LEFT JOIN furumusic__track_artist ta ON ta.track_id = t.id \
|
||||
LEFT JOIN furumusic__play_history ph ON ph.track_id = t.id \
|
||||
LEFT JOIN furumusic__track_ref playback_ref ON playback_ref.local_track_id = t.id LEFT JOIN furumusic__listen_event ph ON ph.content_id = playback_ref.content_id AND ph.qualified \
|
||||
LEFT JOIN furumusic__playlist_track pt ON pt.track_id = t.id \
|
||||
WHERE t.id = $1 \
|
||||
GROUP BY t.id, r.title",
|
||||
@@ -4362,13 +4374,13 @@ async fn load_release_items(
|
||||
(COALESCE(NULLIF(STRING_AGG(DISTINCT a.name::text, ', '), ''), 'Unknown artist') || COALESCE(' / ' || r.year::text, '')) AS subtitle, \
|
||||
r.is_hidden, COUNT(DISTINCT t.id)::bigint AS primary_count, \
|
||||
COUNT(DISTINCT ra.artist_id)::bigint AS secondary_count, \
|
||||
COUNT(DISTINCT ph.id)::bigint AS tertiary_count, \
|
||||
COUNT(DISTINCT (ph.user_id, ph.listen_id)) FILTER (WHERE ph.listen_id IS NOT NULL)::bigint AS tertiary_count, \
|
||||
r.updated_at::text AS updated_at \
|
||||
FROM furumusic__release r \
|
||||
LEFT JOIN furumusic__track t ON t.release_id = r.id \
|
||||
LEFT JOIN furumusic__release_artist ra ON ra.release_id = r.id \
|
||||
LEFT JOIN furumusic__artist a ON a.id = ra.artist_id \
|
||||
LEFT JOIN furumusic__play_history ph ON ph.track_id = t.id \
|
||||
LEFT JOIN furumusic__track_ref playback_ref ON playback_ref.local_track_id = t.id LEFT JOIN furumusic__listen_event ph ON ph.content_id = playback_ref.content_id AND ph.qualified \
|
||||
WHERE 1=1",
|
||||
);
|
||||
if let Some(pattern) = search_pattern {
|
||||
@@ -4398,14 +4410,14 @@ async fn load_track_items(
|
||||
"SELECT t.id, t.title::text AS title, \
|
||||
CONCAT(COALESCE(r.title::text, 'No release'), COALESCE(' / #' || t.track_number::text, '')) AS subtitle, \
|
||||
t.is_hidden, COUNT(DISTINCT ta.artist_id)::bigint AS primary_count, \
|
||||
COUNT(DISTINCT ph.id)::bigint AS secondary_count, \
|
||||
COUNT(DISTINCT (ph.user_id, ph.listen_id)) FILTER (WHERE ph.listen_id IS NOT NULL)::bigint AS secondary_count, \
|
||||
COUNT(DISTINCT pt.playlist_id)::bigint AS tertiary_count, \
|
||||
t.updated_at::text AS updated_at \
|
||||
FROM furumusic__track t \
|
||||
LEFT JOIN furumusic__release r ON r.id = t.release_id \
|
||||
LEFT JOIN furumusic__track_artist ta ON ta.track_id = t.id \
|
||||
LEFT JOIN furumusic__artist a ON a.id = ta.artist_id \
|
||||
LEFT JOIN furumusic__play_history ph ON ph.track_id = t.id \
|
||||
LEFT JOIN furumusic__track_ref playback_ref ON playback_ref.local_track_id = t.id LEFT JOIN furumusic__listen_event ph ON ph.content_id = playback_ref.content_id AND ph.qualified \
|
||||
LEFT JOIN furumusic__playlist_track pt ON pt.track_id = t.id \
|
||||
WHERE 1=1",
|
||||
);
|
||||
|
||||
-2170
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user