4 Commits

Author SHA1 Message Date
b1eaa1b6e9 Reworked agent UI. Artist management form.
All checks were successful
Publish Metadata Agent Image (dev) / build-and-push-image (push) Successful in 1m8s
Publish Web Player Image (dev) / build-and-push-image (push) Successful in 1m9s
Publish Metadata Agent Image / build-and-push-image (push) Successful in 1m7s
Publish Web Player Image / build-and-push-image (push) Successful in 1m10s
Publish Server Image / build-and-push-image (push) Successful in 2m23s
2026-03-19 13:25:37 +00:00
7c2c7b0ce5 Fix dev CI
All checks were successful
Publish Server Image / build-and-push-image (push) Successful in 2m11s
2026-03-19 13:16:24 +00:00
Boris Cherepanov
4f239c2546 feat: added disable auth mode
All checks were successful
Publish Metadata Agent Image / build-and-push-image (push) Successful in 1m6s
Publish Web Player Image / build-and-push-image (push) Successful in 1m14s
Publish Server Image / build-and-push-image (push) Successful in 2m9s
2026-03-19 15:47:21 +03:00
Boris Cherepanov
cfcf6e4029 feat: added express + vite app + oidc
All checks were successful
Publish Metadata Agent Image / build-and-push-image (push) Successful in 3m28s
Publish Web Player Image / build-and-push-image (push) Successful in 1m9s
Publish Server Image / build-and-push-image (push) Successful in 2m16s
2026-03-19 15:06:32 +03:00
39 changed files with 7759 additions and 38 deletions

View File

@@ -0,0 +1,50 @@
name: Publish Metadata Agent Image (dev)
on:
push:
branches:
- DEV
env:
REGISTRY: docker.io
IMAGE_NAME: ${{ secrets.DOCKERHUB_USERNAME }}/furumi-metadata-agent
jobs:
build-and-push-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Determine version and tags
id: info
run: |
IMAGE="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}"
SHORT_SHA="$(echo '${{ github.sha }}' | cut -c1-7)"
echo "tags=${IMAGE}:dev" >> "$GITHUB_OUTPUT"
echo "version=dev-${SHORT_SHA}" >> "$GITHUB_OUTPUT"
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: Dockerfile.agent
push: true
tags: ${{ steps.info.outputs.tags }}
build-args: |
FURUMI_VERSION=${{ steps.info.outputs.version }}
cache-from: type=gha
cache-to: type=gha,mode=max

View File

@@ -4,6 +4,7 @@ on:
push:
branches:
- '**'
- '!DEV'
tags:
- 'v*.*.*'

View File

@@ -0,0 +1,50 @@
name: Publish Web Player Image (dev)
on:
push:
branches:
- DEV
env:
REGISTRY: docker.io
IMAGE_NAME: ${{ secrets.DOCKERHUB_USERNAME }}/furumi-web-player
jobs:
build-and-push-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Determine version and tags
id: info
run: |
IMAGE="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}"
SHORT_SHA="$(echo '${{ github.sha }}' | cut -c1-7)"
echo "tags=${IMAGE}:dev" >> "$GITHUB_OUTPUT"
echo "version=dev-${SHORT_SHA}" >> "$GITHUB_OUTPUT"
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: Dockerfile.web-player
push: true
tags: ${{ steps.info.outputs.tags }}
build-args: |
FURUMI_VERSION=${{ steps.info.outputs.version }}
cache-from: type=gha
cache-to: type=gha,mode=max

View File

@@ -4,6 +4,7 @@ on:
push:
branches:
- '**'
- '!DEV'
tags:
- 'v*.*.*'

View File

@@ -0,0 +1,12 @@
ALTER TABLE albums
ADD COLUMN IF NOT EXISTS release_type TEXT NOT NULL DEFAULT 'album',
ADD COLUMN IF NOT EXISTS hidden BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE tracks
ADD COLUMN IF NOT EXISTS hidden BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE artists
ADD COLUMN IF NOT EXISTS hidden BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE pending_tracks
ADD COLUMN IF NOT EXISTS norm_release_type TEXT;

View File

@@ -70,12 +70,33 @@ You are a music metadata normalization assistant. Your job is to take raw metada
- 0.5-0.8: Some guesswork involved, human review recommended.
- Below 0.5: Significant uncertainty, definitely needs review.
12. **Release type**: Determine the type of release based on all available evidence.
Allowed values (use exactly one, lowercase):
- `album`: Full-length release, typically 4+ tracks
- `single`: One or two tracks released as a single, OR folder/tag explicitly says "Single", "Сингл"
- `ep`: Short release, typically 3-6 tracks, OR folder/path contains "EP" or "ЕП"
- `compilation`: Best-of, greatest hits, anthology, сборник, compilation
- `live`: Live recording, concert, live album — folder or tags contain "Live", "Concert", "Концерт"
Determination rules (in priority order):
- If the folder path contains keywords like "Single", "Сингл", "single" → `single`
- If the folder path contains "EP", "ЕП", "ep" (case-insensitive) → `ep`
- If the folder path contains "Live", "Concert", "Концерт", "live" → `live`
- If the folder path contains "Compilation", "сборник", "Anthology", "Greatest Hits" → `compilation`
- If album name contains these keywords → apply same logic
- If track count in folder is 12 → likely `single`
- If track count in folder is 36 and no other evidence → likely `ep`
- If track count is 7+ → likely `album`
- When in doubt with 36 tracks, prefer `ep` over `album` only if EP indicators present, otherwise `album`
## Response format
You MUST respond with a single JSON object, no markdown fences, no extra text:
{"artist": "...", "album": "...", "title": "...", "year": 2000, "track_number": 1, "genre": "...", "featured_artists": ["...", "..."], "confidence": 0.95, "notes": "brief explanation of changes made"}
{"artist": "...", "album": "...", "title": "...", "year": 2000, "track_number": 1, "genre": "...", "featured_artists": [], "release_type": "album", "confidence": 0.95, "notes": "brief explanation of changes made"}
- Use null for fields you cannot determine.
- Use an empty array [] for "featured_artists" if there are no featured artists.
- The "notes" field should briefly explain what you changed and why.
- "release_type" must be exactly one of: "album", "single", "ep", "compilation", "live"

View File

@@ -25,6 +25,7 @@ pub async fn migrate(pool: &PgPool) -> Result<(), sqlx::migrate::MigrateError> {
pub struct Artist {
pub id: i64,
pub name: String,
pub hidden: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
@@ -33,6 +34,8 @@ pub struct Album {
pub artist_id: i64,
pub name: String,
pub year: Option<i32>,
pub release_type: String,
pub hidden: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
@@ -64,6 +67,7 @@ pub struct PendingTrack {
pub norm_track_number: Option<i32>,
pub norm_genre: Option<String>,
pub norm_featured_artists: Option<String>, // JSON array
pub norm_release_type: Option<String>,
pub confidence: Option<f64>,
pub llm_notes: Option<String>,
pub error_message: Option<String>,
@@ -172,6 +176,7 @@ pub async fn update_pending_normalized(
norm_year = $6, norm_track_number = $7, norm_genre = $8,
norm_featured_artists = $9,
confidence = $10, llm_notes = $11, error_message = $12,
norm_release_type = $13,
updated_at = NOW()
WHERE id = $1"#,
)
@@ -187,6 +192,7 @@ pub async fn update_pending_normalized(
.bind(norm.confidence)
.bind(&norm.notes)
.bind(error_message)
.bind(&norm.release_type)
.execute(pool)
.await?;
Ok(())
@@ -254,18 +260,19 @@ pub async fn upsert_artist(pool: &PgPool, name: &str) -> Result<i64, sqlx::Error
Ok(row.0)
}
pub async fn upsert_album(pool: &PgPool, artist_id: i64, name: &str, year: Option<i32>) -> Result<i64, sqlx::Error> {
pub async fn upsert_album(pool: &PgPool, artist_id: i64, name: &str, year: Option<i32>, release_type: &str) -> Result<i64, sqlx::Error> {
let slug = generate_slug();
let row: (i64,) = sqlx::query_as(
r#"INSERT INTO albums (artist_id, name, year, slug)
VALUES ($1, $2, $3, $4)
ON CONFLICT (artist_id, name) DO UPDATE SET year = COALESCE(EXCLUDED.year, albums.year)
r#"INSERT INTO albums (artist_id, name, year, slug, release_type)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (artist_id, name) DO UPDATE SET year = COALESCE(EXCLUDED.year, albums.year), release_type = EXCLUDED.release_type
RETURNING id"#
)
.bind(artist_id)
.bind(name)
.bind(year)
.bind(&slug)
.bind(release_type)
.fetch_one(pool)
.await?;
Ok(row.0)
@@ -343,7 +350,7 @@ pub async fn approve_and_finalize(
let artist_id = upsert_artist(pool, artist_name).await?;
let album_id = match pt.norm_album.as_deref() {
Some(album_name) => Some(upsert_album(pool, artist_id, album_name, pt.norm_year).await?),
Some(album_name) => Some(upsert_album(pool, artist_id, album_name, pt.norm_year, pt.norm_release_type.as_deref().unwrap_or("album")).await?),
None => None,
};
@@ -480,6 +487,7 @@ pub struct NormalizedFields {
pub genre: Option<String>,
#[serde(default)]
pub featured_artists: Vec<String>,
pub release_type: Option<String>,
pub confidence: Option<f64>,
pub notes: Option<String>,
}
@@ -526,13 +534,13 @@ pub async fn delete_pending(pool: &PgPool, id: Uuid) -> Result<bool, sqlx::Error
}
pub async fn list_artists_all(pool: &PgPool) -> Result<Vec<Artist>, sqlx::Error> {
sqlx::query_as::<_, Artist>("SELECT id, name FROM artists ORDER BY name")
sqlx::query_as::<_, Artist>("SELECT id, name, hidden FROM artists ORDER BY name")
.fetch_all(pool)
.await
}
pub async fn list_albums_by_artist(pool: &PgPool, artist_id: i64) -> Result<Vec<Album>, sqlx::Error> {
sqlx::query_as::<_, Album>("SELECT id, artist_id, name, year FROM albums WHERE artist_id = $1 ORDER BY year, name")
sqlx::query_as::<_, Album>("SELECT id, artist_id, name, year, release_type, hidden FROM albums WHERE artist_id = $1 ORDER BY year, name")
.bind(artist_id)
.fetch_all(pool)
.await
@@ -603,6 +611,8 @@ pub struct AlbumRow {
pub artist_name: String,
pub year: Option<i32>,
pub track_count: i64,
pub release_type: String,
pub hidden: bool,
}
#[derive(Debug, Serialize, sqlx::FromRow)]
@@ -610,7 +620,12 @@ pub struct ArtistRow {
pub id: i64,
pub name: String,
pub album_count: i64,
pub single_count: i64,
pub ep_count: i64,
pub compilation_count: i64,
pub live_count: i64,
pub track_count: i64,
pub hidden: bool,
}
pub async fn search_tracks(
@@ -657,13 +672,13 @@ pub async fn search_albums(
) -> Result<Vec<AlbumRow>, sqlx::Error> {
sqlx::query_as::<_, AlbumRow>(
r#"SELECT a.id, a.name, ar.name AS artist_name, a.year,
COUNT(t.id) AS track_count
COUNT(t.id) AS track_count, a.release_type, a.hidden
FROM albums a
JOIN artists ar ON ar.id = a.artist_id
LEFT JOIN tracks t ON t.album_id = a.id
WHERE ($1 = '' OR a.name ILIKE '%' || $1 || '%')
AND ($2 = '' OR ar.name ILIKE '%' || $2 || '%')
GROUP BY a.id, a.name, ar.name, a.year
GROUP BY a.id, a.name, ar.name, a.year, a.release_type, a.hidden
ORDER BY ar.name, a.year NULLS LAST, a.name
LIMIT $3 OFFSET $4"#,
)
@@ -690,13 +705,18 @@ pub async fn search_artists_lib(
) -> Result<Vec<ArtistRow>, sqlx::Error> {
sqlx::query_as::<_, ArtistRow>(
r#"SELECT ar.id, ar.name,
COUNT(DISTINCT al.id) AS album_count,
COUNT(DISTINCT ta.track_id) AS track_count
COUNT(DISTINCT CASE WHEN al.release_type = 'album' THEN al.id END) AS album_count,
COUNT(DISTINCT CASE WHEN al.release_type = 'single' THEN al.id END) AS single_count,
COUNT(DISTINCT CASE WHEN al.release_type = 'ep' THEN al.id END) AS ep_count,
COUNT(DISTINCT CASE WHEN al.release_type = 'compilation' THEN al.id END) AS compilation_count,
COUNT(DISTINCT CASE WHEN al.release_type = 'live' THEN al.id END) AS live_count,
COUNT(DISTINCT ta.track_id) AS track_count,
ar.hidden
FROM artists ar
LEFT JOIN albums al ON al.artist_id = ar.id
LEFT JOIN track_artists ta ON ta.artist_id = ar.id AND ta.role = 'primary'
WHERE ($1 = '' OR ar.name ILIKE '%' || $1 || '%')
GROUP BY ar.id, ar.name
GROUP BY ar.id, ar.name, ar.hidden
ORDER BY ar.name
LIMIT $2 OFFSET $3"#,
)
@@ -853,6 +873,11 @@ pub async fn get_album_cover(pool: &PgPool, album_id: i64) -> Result<Option<(Str
Ok(row)
}
pub async fn get_artist_by_id(pool: &PgPool, id: i64) -> Result<Option<Artist>, sqlx::Error> {
sqlx::query_as::<_, Artist>("SELECT id, name, hidden FROM artists WHERE id=$1")
.bind(id).fetch_optional(pool).await
}
pub async fn search_albums_for_artist(pool: &PgPool, q: &str, artist_id: Option<i64>) -> Result<Vec<(i64, String)>, sqlx::Error> {
if let Some(aid) = artist_id {
let rows: Vec<(i64, String)> = sqlx::query_as(
@@ -867,6 +892,120 @@ pub async fn search_albums_for_artist(pool: &PgPool, q: &str, artist_id: Option<
}
}
pub async fn set_track_hidden(pool: &PgPool, id: i64, hidden: bool) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE tracks SET hidden=$2 WHERE id=$1").bind(id).bind(hidden).execute(pool).await?;
Ok(())
}
pub async fn set_album_hidden(pool: &PgPool, id: i64, hidden: bool) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE albums SET hidden=$2 WHERE id=$1").bind(id).bind(hidden).execute(pool).await?;
Ok(())
}
pub async fn set_artist_hidden(pool: &PgPool, id: i64, hidden: bool) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE artists SET hidden=$2 WHERE id=$1").bind(id).bind(hidden).execute(pool).await?;
Ok(())
}
pub async fn set_album_release_type(pool: &PgPool, id: i64, release_type: &str) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE albums SET release_type=$2 WHERE id=$1").bind(id).bind(release_type).execute(pool).await?;
Ok(())
}
pub async fn rename_artist_name(pool: &PgPool, id: i64, name: &str) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE artists SET name=$2 WHERE id=$1").bind(id).bind(name).execute(pool).await?;
Ok(())
}
// Full artist data for admin form
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct ArtistAlbumRow {
pub id: i64,
pub name: String,
pub year: Option<i32>,
pub release_type: String,
pub hidden: bool,
pub track_count: i64,
}
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct ArtistAlbumTrack {
pub id: i64,
pub title: String,
pub track_number: Option<i32>,
pub duration_secs: Option<f64>,
pub hidden: bool,
}
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct AppearanceRow {
pub track_id: i64,
pub track_title: String,
pub primary_artist_id: i64,
pub primary_artist_name: String,
pub album_id: Option<i64>,
pub album_name: Option<String>,
}
pub async fn get_artist_albums(pool: &PgPool, artist_id: i64) -> Result<Vec<ArtistAlbumRow>, sqlx::Error> {
sqlx::query_as::<_, ArtistAlbumRow>(
r#"SELECT a.id, a.name, a.year, a.release_type, a.hidden,
COUNT(t.id) AS track_count
FROM albums a
LEFT JOIN tracks t ON t.album_id = a.id
WHERE a.artist_id = $1
GROUP BY a.id, a.name, a.year, a.release_type, a.hidden
ORDER BY a.year NULLS LAST, a.name"#
).bind(artist_id).fetch_all(pool).await
}
pub async fn get_album_tracks_admin(pool: &PgPool, album_id: i64) -> Result<Vec<ArtistAlbumTrack>, sqlx::Error> {
sqlx::query_as::<_, ArtistAlbumTrack>(
"SELECT id, title, track_number, duration_secs, hidden FROM tracks WHERE album_id=$1 ORDER BY track_number NULLS LAST, title"
).bind(album_id).fetch_all(pool).await
}
pub async fn get_artist_appearances(pool: &PgPool, artist_id: i64) -> Result<Vec<AppearanceRow>, sqlx::Error> {
sqlx::query_as::<_, AppearanceRow>(
r#"SELECT ta.track_id, t.title AS track_title,
ta_p.artist_id AS primary_artist_id, ar_p.name AS primary_artist_name,
t.album_id, al.name AS album_name
FROM track_artists ta
JOIN tracks t ON t.id = ta.track_id
JOIN track_artists ta_p ON ta_p.track_id = t.id AND ta_p.role = 'primary'
JOIN artists ar_p ON ar_p.id = ta_p.artist_id
LEFT JOIN albums al ON al.id = t.album_id
WHERE ta.artist_id = $1 AND ta.role = 'featured'
ORDER BY ar_p.name, al.name NULLS LAST, t.title"#
).bind(artist_id).fetch_all(pool).await
}
pub async fn add_track_appearance(pool: &PgPool, track_id: i64, artist_id: i64) -> Result<(), sqlx::Error> {
sqlx::query(
"INSERT INTO track_artists (track_id, artist_id, role) VALUES ($1, $2, 'featured') ON CONFLICT DO NOTHING"
).bind(track_id).bind(artist_id).execute(pool).await?;
Ok(())
}
pub async fn remove_track_appearance(pool: &PgPool, track_id: i64, artist_id: i64) -> Result<(), sqlx::Error> {
sqlx::query(
"DELETE FROM track_artists WHERE track_id=$1 AND artist_id=$2 AND role='featured'"
).bind(track_id).bind(artist_id).execute(pool).await?;
Ok(())
}
pub async fn search_tracks_for_feat(pool: &PgPool, q: &str) -> Result<Vec<(i64, String, String)>, sqlx::Error> {
// Returns (track_id, track_title, primary_artist_name)
sqlx::query_as::<_, (i64, String, String)>(
r#"SELECT t.id, t.title, ar.name FROM tracks t
JOIN track_artists ta ON ta.track_id=t.id AND ta.role='primary'
JOIN artists ar ON ar.id=ta.artist_id
WHERE t.title ILIKE '%'||$1||'%' OR ar.name ILIKE '%'||$1||'%'
ORDER BY ar.name, t.title LIMIT 15"#
).bind(q).fetch_all(pool).await
}
// =================== Artist Merges ===================
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
@@ -951,7 +1090,7 @@ pub async fn get_pending_merges_for_processing(pool: &PgPool) -> Result<Vec<Uuid
pub async fn get_artists_full_data(pool: &PgPool, ids: &[i64]) -> Result<Vec<ArtistFullData>, sqlx::Error> {
let mut result = Vec::new();
for &id in ids {
let artist: Artist = sqlx::query_as("SELECT id, name FROM artists WHERE id = $1")
let artist: Artist = sqlx::query_as("SELECT id, name, hidden FROM artists WHERE id = $1")
.bind(id).fetch_one(pool).await?;
let albums: Vec<Album> = sqlx::query_as("SELECT * FROM albums WHERE artist_id = $1 ORDER BY year NULLS LAST, name")
.bind(id).fetch_all(pool).await?;

View File

@@ -132,8 +132,8 @@ async fn reprocess_pending(state: &Arc<AppState>) -> anyhow::Result<usize> {
Vec::new()
};
// LLM normalization
match normalize::normalize(state, &raw_meta, &hints, &similar_artists, &similar_albums).await {
// LLM normalization (no folder context available for reprocessing from DB)
match normalize::normalize(state, &raw_meta, &hints, &similar_artists, &similar_albums, None).await {
Ok(normalized) => {
let confidence = normalized.confidence.unwrap_or(0.0);
let status = if confidence >= state.config.confidence_threshold {
@@ -428,9 +428,35 @@ async fn process_file(state: &Arc<AppState>, file_path: &std::path::Path) -> any
tracing::info!(file = filename, matches = ?names, "Found similar albums in DB");
}
// Build folder context for the LLM
let audio_extensions = ["flac", "mp3", "ogg", "wav", "aac", "m4a", "opus", "wma", "ape", "alac"];
let folder_ctx = {
let folder = file_path.parent().unwrap_or(file_path);
let mut folder_files: Vec<String> = std::fs::read_dir(folder)
.ok()
.map(|rd| {
rd.filter_map(|e| e.ok())
.filter_map(|e| {
let name = e.file_name().to_string_lossy().into_owned();
let ext = name.rsplit('.').next().unwrap_or("").to_lowercase();
if audio_extensions.contains(&ext.as_str()) { Some(name) } else { None }
})
.collect()
})
.unwrap_or_default();
folder_files.sort();
let track_count = folder_files.len();
let folder_path = folder
.strip_prefix(&state.config.inbox_dir)
.unwrap_or(folder)
.to_string_lossy()
.into_owned();
normalize::FolderContext { folder_path, folder_files, track_count }
};
// Call LLM for normalization
tracing::info!(file = filename, model = %state.config.ollama_model, "Sending to LLM for normalization...");
match normalize::normalize(state, &raw_meta, &hints, &similar_artists, &similar_albums).await {
match normalize::normalize(state, &raw_meta, &hints, &similar_artists, &similar_albums, Some(&folder_ctx)).await {
Ok(normalized) => {
let confidence = normalized.confidence.unwrap_or(0.0);
let status = if confidence >= state.config.confidence_threshold {

View File

@@ -7,6 +7,13 @@ use crate::web::AppState;
use super::metadata::RawMetadata;
#[derive(Debug)]
pub struct FolderContext {
pub folder_path: String, // path relative to inbox_dir (e.g. "Kunteynir/Синглы/Пьюк")
pub folder_files: Vec<String>, // audio filenames in the same folder
pub track_count: usize, // number of audio files in folder
}
/// Build the user message with all context and call Ollama for normalization.
pub async fn normalize(
state: &Arc<AppState>,
@@ -14,8 +21,9 @@ pub async fn normalize(
hints: &crate::db::PathHints,
similar_artists: &[SimilarArtist],
similar_albums: &[SimilarAlbum],
folder_ctx: Option<&FolderContext>,
) -> anyhow::Result<NormalizedFields> {
let user_message = build_user_message(raw, hints, similar_artists, similar_albums);
let user_message = build_user_message(raw, hints, similar_artists, similar_albums, folder_ctx);
let response = call_ollama(
&state.config.ollama_url,
@@ -34,6 +42,7 @@ fn build_user_message(
hints: &crate::db::PathHints,
similar_artists: &[SimilarArtist],
similar_albums: &[SimilarAlbum],
folder_ctx: Option<&FolderContext>,
) -> String {
let mut msg = String::from("## Raw metadata from file tags\n");
@@ -88,6 +97,18 @@ fn build_user_message(
}
}
if let Some(ctx) = folder_ctx {
msg.push_str("\n## Folder context\n");
msg.push_str(&format!("Folder path: \"{}\"\n", ctx.folder_path));
msg.push_str(&format!("Track count in folder: {}\n", ctx.track_count));
if !ctx.folder_files.is_empty() {
msg.push_str("Files in folder:\n");
for f in &ctx.folder_files {
msg.push_str(&format!(" - {}\n", f));
}
}
}
msg
}
@@ -201,6 +222,7 @@ fn parse_response(response: &str) -> anyhow::Result<NormalizedFields> {
genre: Option<String>,
#[serde(default)]
featured_artists: Vec<String>,
release_type: Option<String>,
confidence: Option<f64>,
notes: Option<String>,
}
@@ -216,6 +238,7 @@ fn parse_response(response: &str) -> anyhow::Result<NormalizedFields> {
track_number: parsed.track_number,
genre: parsed.genre,
featured_artists: parsed.featured_artists,
release_type: parsed.release_type,
confidence: parsed.confidence,
notes: parsed.notes,
})

View File

@@ -162,6 +162,37 @@ details.llm-expand pre { background: var(--bg-card); border: 1px solid var(--bor
.pagination button:hover:not(:disabled) { border-color: var(--accent); color: var(--text); }
.pagination button.active { background: var(--accent); border-color: var(--accent); color: #fff; }
.pagination button:disabled { opacity: 0.3; cursor: default; }
/* Release type badges */
.release-badge { font-size: 9px; font-weight: 700; text-transform: uppercase; padding: 1px 5px; border-radius: 3px; letter-spacing: 0.04em; }
.rb-album { background: #1e2740; color: var(--text-dim); }
.rb-single { background: #1e3a2e; color: #6ee7b7; }
.rb-ep { background: #2e1e3a; color: #c4b5fd; }
.rb-compilation{ background: #3a2e1e; color: #fcd34d; }
.rb-live { background: #3a1e1e; color: #fca5a5; }
.hidden-badge { font-size: 9px; font-weight: 700; text-transform: uppercase; padding: 1px 5px; border-radius: 3px; background: #1a1a1a; color: #555; letter-spacing: 0.04em; }
/* Artist admin form */
.artist-section { margin-top: 14px; }
.artist-section-title { font-size: 11px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 6px; display: flex; align-items: center; gap: 8px; }
.album-block { border: 1px solid var(--border); border-radius: 6px; margin-bottom: 8px; overflow: hidden; }
.album-block-header { display: flex; align-items: center; gap: 8px; padding: 7px 10px; background: var(--bg-card); cursor: pointer; }
.album-block-header img { width: 36px; height: 36px; border-radius: 3px; object-fit: cover; flex-shrink: 0; }
.album-block-header .ab-name { flex: 1; font-size: 12px; font-weight: 500; }
.album-block-header .ab-year { font-size: 10px; color: var(--text-muted); flex-shrink: 0; }
.album-block-body { display: none; padding: 0; }
.album-block-body.open { display: block; }
.album-track-row { display: flex; align-items: center; gap: 8px; padding: 4px 10px; border-top: 1px solid var(--border); font-size: 11px; background: var(--bg-base); }
.album-track-row.hidden-track { opacity: 0.45; }
.album-track-row .atr-num { color: var(--text-muted); width: 22px; text-align: right; flex-shrink: 0; }
.album-track-row .atr-title { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.album-track-row .atr-dur { color: var(--text-muted); font-size: 10px; flex-shrink: 0; }
.appearance-row { display: flex; align-items: center; gap: 8px; padding: 4px 0; font-size: 12px; border-bottom: 1px solid var(--border); }
.appearance-row:last-child { border-bottom: none; }
.btn-hide { background: #1e293b; color: var(--text-muted); border: none; padding: 2px 7px; border-radius: 3px; cursor: pointer; font-size: 10px; font-family: inherit; }
.btn-hide:hover { background: #334155; }
.btn-show { background: #052e16; color: var(--success); border: none; padding: 2px 7px; border-radius: 3px; cursor: pointer; font-size: 10px; font-family: inherit; }
.btn-show:hover { background: #065f46; }
</style>
</head>
<body>
@@ -740,7 +771,7 @@ async function loadLibAlbums() {
let html = `<table><tr><th>Album</th><th>Artist</th><th style="width:50px">Year</th><th style="width:60px">Tracks</th><th style="width:50px">Edit</th></tr>`;
for (const a of data.items) {
html += `<tr>
<td><span style="display:inline-flex;align-items:center;gap:5px"><img src="${API}/albums/${a.id}/cover" style="width:20px;height:20px;border-radius:2px;object-fit:cover;flex-shrink:0" onerror="this.style.display='none'"><span>${esc(a.name)}</span></span></td>
<td><span style="display:inline-flex;align-items:center;gap:5px"><img src="${API}/albums/${a.id}/cover" style="width:20px;height:20px;border-radius:2px;object-fit:cover;flex-shrink:0" onerror="this.style.display='none'"><span>${esc(a.name)}</span></span> ${releaseBadge(a.release_type)} ${a.hidden?'<span class="hidden-badge">Hidden</span>':''}</td>
<td>${esc(a.artist_name)}</td>
<td>${a.year ?? ''}</td>
<td style="color:var(--text-muted)">${a.track_count}</td>
@@ -768,18 +799,30 @@ async function loadLibArtists() {
el.innerHTML = '<div class="empty">No artists found</div>';
} else {
let html = `<table><tr>
<th style="width:30px"></th><th style="width:50px">ID</th><th>Name</th>
<th style="width:60px">Albums</th><th style="width:60px">Tracks</th>
<th style="width:80px">Actions</th>
<th style="width:30px"></th><th style="width:40px">ID</th><th>Name</th>
<th style="width:46px" title="Albums">LP</th>
<th style="width:42px" title="Singles">Sng</th>
<th style="width:34px" title="EPs">EP</th>
<th style="width:40px" title="Compilations">Cmp</th>
<th style="width:36px" title="Live">Live</th>
<th style="width:46px" title="Tracks">Trk</th>
<th style="width:60px">Actions</th>
</tr>`;
for (const a of data.items) {
html += `<tr>
const dim = 'style="color:var(--text-muted);text-align:center"';
html += `<tr ${a.hidden?'style="opacity:0.5"':''}>
<td><input type="checkbox" class="cb" ${selectedArtists.has(a.id)?'checked':''} onchange="toggleSelectArtist(${a.id},this.checked)"></td>
<td style="color:var(--text-muted)">${a.id}</td>
<td class="editable" ondblclick="inlineEditArtist(this,${a.id})">${esc(a.name)}</td>
<td style="color:var(--text-muted)">${a.album_count}</td>
<td style="color:var(--text-muted)">${a.track_count}</td>
<td class="actions"><button class="btn btn-edit" onclick="editArtist(${a.id},'${esc(a.name)}')">Rename</button></td>
<td>${a.hidden?'<span class="hidden-badge" style="margin-right:4px">H</span>':''}${esc(a.name)}</td>
<td ${dim}>${a.album_count||''}</td>
<td ${dim}>${a.single_count||''}</td>
<td ${dim}>${a.ep_count||''}</td>
<td ${dim}>${a.compilation_count||''}</td>
<td ${dim}>${a.live_count||''}</td>
<td ${dim}>${a.track_count||''}</td>
<td class="actions">
<button class="btn btn-edit" onclick="openArtistForm(${a.id})">Edit</button>
</td>
</tr>`;
}
el.innerHTML = html + '</table>';
@@ -844,10 +887,11 @@ async function editArtist(id, currentName) {
}
// --- Track edit modal ---
async function openTrackEdit(id) {
async function openTrackEdit(id, returnCb) {
const t = await api(`/tracks/${id}`);
if (!t) return;
editReturnCallback = returnCb || null;
editFeatured = [...(t.featured_artists || [])];
document.getElementById('modal').className = 'modal';
@@ -899,7 +943,7 @@ async function openTrackEdit(id) {
</div>
<div class="modal-actions">
<button class="btn btn-cancel" onclick="closeModal()">Cancel</button>
<button class="btn btn-cancel" onclick="cancelTrackEdit()">Cancel</button>
<button class="btn btn-primary" onclick="saveTrackEdit(${t.id})">Save</button>
</div>
`;
@@ -908,6 +952,7 @@ async function openTrackEdit(id) {
}
let teArtistTimer = null, teAlbumTimer = null;
let editReturnCallback = null;
function onTeArtistSearch(q) {
clearTimeout(teArtistTimer);
@@ -973,12 +1018,21 @@ async function saveTrackEdit(id) {
featured_artists: editFeatured,
};
await api(`/tracks/${id}`, { method: 'PUT', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body) });
closeModal();
if (currentTab === 'tracks') loadLibTracks();
const cb = editReturnCallback;
editReturnCallback = null;
if (cb) { cb(); } else { closeModal(); if (currentTab === 'tracks') loadLibTracks(); }
}
function cancelTrackEdit() {
const cb = editReturnCallback;
editReturnCallback = null;
if (cb) { cb(); } else { closeModal(); }
}
// --- Album edit modal ---
async function openAlbumEdit(id) {
let albumEditReturnCallback = null;
async function openAlbumEdit(id, returnCb) {
albumEditReturnCallback = returnCb || null;
const d = await api(`/albums/${id}/full`);
if (!d) return;
@@ -1023,7 +1077,7 @@ async function openAlbumEdit(id) {
</ul>
<div class="modal-actions">
<button class="btn btn-cancel" onclick="closeModal()">Cancel</button>
<button class="btn btn-cancel" onclick="cancelAlbumEdit()">Cancel</button>
<button class="btn btn-edit" onclick="saveAlbumReorder(${id})">Save Order</button>
<button class="btn btn-primary" onclick="saveAlbumEdit(${id})">Save Album</button>
</div>
@@ -1073,6 +1127,12 @@ function selectAeArtist(id, name) {
document.getElementById('ae-artist-dropdown').classList.remove('open');
}
function cancelAlbumEdit() {
const cb = albumEditReturnCallback;
albumEditReturnCallback = null;
if (cb) { cb(); } else { closeModal(); }
}
async function saveAlbumEdit(id) {
const artistId = parseInt(document.getElementById('ae-artist-id').value);
if (!artistId) { alert('Please select an artist from the dropdown'); return; }
@@ -1082,7 +1142,9 @@ async function saveAlbumEdit(id) {
artist_id: artistId,
};
await api(`/albums/${id}/edit`, { method: 'PUT', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body) });
if (currentTab === 'albums') loadLibAlbums();
const cb = albumEditReturnCallback;
albumEditReturnCallback = null;
if (cb) { cb(); } else { closeModal(); if (currentTab === 'albums') loadLibAlbums(); }
}
async function saveAlbumReorder(id) {
@@ -1094,8 +1156,11 @@ async function saveAlbumReorder(id) {
}
async function openTrackEditFromAlbum(trackId, albumId) {
closeModal();
await openTrackEdit(trackId);
const parentCb = albumEditReturnCallback;
await openTrackEdit(trackId, () => openAlbumEdit(albumId, parentCb));
}
function openTrackEditForArtist(trackId, artistId) {
openTrackEdit(trackId, () => openArtistForm(artistId));
}
// --- Helpers ---
@@ -1329,6 +1394,198 @@ async function retryMerge(id) {
loadMerges();
}
// --- Release badge helper ---
function releaseBadge(t) {
const labels = {album:'Album',single:'Single',ep:'EP',compilation:'Comp',live:'Live'};
return `<span class="release-badge rb-${t||'album'}">${labels[t]||t||'Album'}</span>`;
}
// --- Artist full admin form ---
async function openArtistForm(id) {
const d = await api(`/artists/${id}/full`);
if (!d) return;
const { artist, albums, appearances } = d;
// Separate albums by type
const mainAlbums = albums.filter(a => a.release_type === 'album' || a.release_type === 'compilation' || a.release_type === 'live');
const singles = albums.filter(a => a.release_type === 'single' || a.release_type === 'ep');
function renderAlbumBlock(alb) {
const hiddenCls = alb.hidden ? ' style="opacity:0.55"' : '';
const tracks = (alb.tracks || []).map(t => `
<div class="album-track-row ${t.hidden?'hidden-track':''}" data-tid="${t.id}">
<span class="atr-num">${t.track_number??''}</span>
<span class="atr-title">${esc(t.title)}</span>
<span class="atr-dur">${fmtDuration(t.duration_secs)}</span>
<button class="btn btn-edit" style="font-size:10px;padding:2px 6px" onclick="openTrackEditForArtist(${t.id},${id})">Edit</button>
<button data-hidden="${t.hidden}" onclick="toggleTrackHidden(${t.id},this)">${t.hidden?'Show':'Hide'}</button>
</div>`).join('');
const releaseTypes = ['album','single','ep','compilation','live'];
const typeOpts = releaseTypes.map(rt => `<option value="${rt}" ${alb.release_type===rt?'selected':''}>${rt.charAt(0).toUpperCase()+rt.slice(1)}</option>`).join('');
return `<div class="album-block" id="album-block-${alb.id}"${hiddenCls}>
<div class="album-block-header" onclick="toggleAlbumBlock(${alb.id})">
<img src="${API}/albums/${alb.id}/cover" onerror="this.style.display='none'">
<span class="ab-name">${esc(alb.name)}</span>
${alb.year ? `<span class="ab-year">${alb.year}</span>` : ''}
${releaseBadge(alb.release_type)}
${alb.hidden?'<span class="hidden-badge">Hidden</span>':''}
<select onclick="event.stopPropagation()" onchange="changeReleaseType(${alb.id},this.value)" style="background:var(--bg-base);border:1px solid var(--border);border-radius:3px;color:var(--text);font-size:10px;padding:2px 4px;font-family:inherit">${typeOpts}</select>
<button data-hidden="${alb.hidden}" onclick="event.stopPropagation();toggleAlbumHidden(${alb.id},this)">${alb.hidden?'Show':'Hide'}</button>
</div>
<div class="album-block-body" id="album-body-${alb.id}"></div>
</div>`;
}
const albumsHtml = mainAlbums.map(renderAlbumBlock).join('') || '<div style="color:var(--text-muted);font-size:12px;padding:4px 0">No albums</div>';
const singlesHtml = singles.map(renderAlbumBlock).join('') || '<div style="color:var(--text-muted);font-size:12px;padding:4px 0">No singles/EPs</div>';
const appHtml = appearances.map(ap => `
<div class="appearance-row">
<span style="flex:1">${esc(ap.primary_artist_name)} — <strong>${esc(ap.track_title)}</strong>${ap.album_name?` <span style="color:var(--text-muted)">(${esc(ap.album_name)})</span>`:''}</span>
<button class="btn btn-reject" style="font-size:10px;padding:2px 6px" onclick="removeAppearance(${id},${ap.track_id},this)">Remove</button>
</div>`).join('') || '<div style="color:var(--text-muted);font-size:12px;padding:4px 0">No appearances</div>';
document.getElementById('modal').className = 'modal modal-wide';
document.getElementById('modal').innerHTML = `
<div style="display:flex;align-items:center;gap:10px;margin-bottom:12px">
<h2 style="flex:1;margin:0">${esc(artist.name)}</h2>
${artist.hidden?'<span class="hidden-badge" style="font-size:11px">Hidden</span>':''}
<button data-hidden="${artist.hidden}" onclick="toggleArtistHidden(${id},this)">${artist.hidden?'Unhide Artist':'Hide Artist'}</button>
<button class="btn btn-edit" onclick="promptRenameArtist(${id})">Rename</button>
</div>
<div class="artist-section">
<div class="artist-section-title">Albums &amp; Compilations <span style="color:var(--text-dim);font-weight:400">(${mainAlbums.length})</span></div>
${albumsHtml}
</div>
<div class="artist-section">
<div class="artist-section-title">Singles &amp; EPs <span style="color:var(--text-dim);font-weight:400">(${singles.length})</span></div>
${singlesHtml}
</div>
<div class="artist-section">
<div class="artist-section-title">Appearances (feat.) <span style="color:var(--text-dim);font-weight:400">(${appearances.length})</span></div>
<div id="appearances-list">${appHtml}</div>
<div style="margin-top:8px;display:flex;gap:6px;align-items:center">
<div style="position:relative;flex:1">
<input id="feat-track-search" placeholder="Search track to add appearance…" autocomplete="off"
oninput="onFeatTrackSearch(${id},this.value)" style="width:100%;background:var(--bg-card);border:1px solid var(--border);border-radius:5px;padding:6px 9px;color:var(--text);font-family:inherit;font-size:12px">
<div class="artist-dropdown" id="feat-track-dropdown"></div>
</div>
</div>
</div>
<div class="modal-actions">
<button class="btn btn-cancel" onclick="closeModal()">Close</button>
</div>
`;
// Fill album body content and restore open state
for (const alb of albums) {
const body = document.getElementById(`album-body-${alb.id}`);
if (!body) continue;
const tracks = (alb.tracks || []).map(t => `
<div class="album-track-row ${t.hidden?'hidden-track':''}" data-tid="${t.id}">
<span class="atr-num">${t.track_number??''}</span>
<span class="atr-title">${esc(t.title)}</span>
<span class="atr-dur">${fmtDuration(t.duration_secs)}</span>
<button class="btn btn-edit" style="font-size:10px;padding:2px 6px" onclick="openTrackEditForArtist(${t.id},${id})">Edit</button>
<button data-hidden="${t.hidden}" onclick="toggleTrackHidden(${t.id},this)">${t.hidden?'Show':'Hide'}</button>
</div>`).join('');
body.innerHTML = tracks;
if (openAlbumBlocks.has(alb.id)) body.classList.add('open');
}
openModal();
}
const openAlbumBlocks = new Set();
function toggleAlbumBlock(id) {
const body = document.getElementById(`album-body-${id}`);
if (!body) return;
body.classList.toggle('open');
if (body.classList.contains('open')) openAlbumBlocks.add(id);
else openAlbumBlocks.delete(id);
}
async function toggleTrackHidden(id, btn) {
const hidden = btn.dataset.hidden !== 'true'; // toggle
await api(`/tracks/${id}/hidden`, { method:'PUT', headers:{'Content-Type':'application/json'}, body: JSON.stringify({hidden}) });
btn.dataset.hidden = String(hidden);
btn.textContent = hidden ? 'Show' : 'Hide';
const row = btn.closest('.album-track-row');
if (row) row.classList.toggle('hidden-track', hidden);
}
async function toggleAlbumHidden(id, btn) {
const hidden = btn.dataset.hidden !== 'true'; // toggle
await api(`/albums/${id}/hidden`, { method:'PUT', headers:{'Content-Type':'application/json'}, body: JSON.stringify({hidden}) });
btn.dataset.hidden = String(hidden);
btn.textContent = hidden ? 'Show' : 'Hide';
const block = btn.closest('.album-block');
if (block) block.style.opacity = hidden ? '0.55' : '';
const header = block?.querySelector('.album-block-header');
let badge = header?.querySelector('.hidden-badge');
if (hidden && !badge) { badge = document.createElement('span'); badge.className='hidden-badge'; badge.textContent='Hidden'; header.insertBefore(badge, btn); }
else if (!hidden && badge) badge.remove();
}
async function toggleArtistHidden(id, btn) {
const hidden = btn.dataset.hidden !== 'true'; // toggle
await api(`/artists/${id}/hidden`, { method:'PUT', headers:{'Content-Type':'application/json'}, body: JSON.stringify({hidden}) });
btn.dataset.hidden = String(hidden);
btn.textContent = hidden ? 'Unhide Artist' : 'Hide Artist';
}
async function changeReleaseType(id, type) {
await api(`/albums/${id}/release_type`, { method:'PUT', headers:{'Content-Type':'application/json'}, body: JSON.stringify({release_type: type}) });
}
async function promptRenameArtist(id) {
const name = prompt('New artist name:');
if (!name) return;
await api(`/artists/${id}/rename`, { method:'PUT', headers:{'Content-Type':'application/json'}, body: JSON.stringify({name}) });
// refresh
closeModal();
openArtistForm(id);
}
let featTrackTimer = null;
function onFeatTrackSearch(artistId, q) {
clearTimeout(featTrackTimer);
const dd = document.getElementById('feat-track-dropdown');
if (q.length < 2) { dd.classList.remove('open'); return; }
featTrackTimer = setTimeout(async () => {
const results = await api(`/tracks/search?q=${encodeURIComponent(q)}`);
if (!results || !results.length) { dd.classList.remove('open'); return; }
dd.innerHTML = results.map(t =>
`<div class="artist-option" onclick="addAppearance(${artistId},${t.id},'${esc(t.artist_name+' — '+t.title)}')">${esc(t.artist_name)}${esc(t.title)}</div>`
).join('');
dd.classList.add('open');
}, 250);
}
async function addAppearance(artistId, trackId, label) {
await api(`/artists/${artistId}/appearances`, { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({track_id: trackId}) });
document.getElementById('feat-track-search').value = '';
document.getElementById('feat-track-dropdown').classList.remove('open');
// Add row to appearances list
const list = document.getElementById('appearances-list');
const row = document.createElement('div');
row.className = 'appearance-row';
row.innerHTML = `<span style="flex:1">${esc(label)}</span><button class="btn btn-reject" style="font-size:10px;padding:2px 6px" onclick="removeAppearance(${artistId},${trackId},this)">Remove</button>`;
list.appendChild(row);
}
async function removeAppearance(artistId, trackId, btn) {
await api(`/artists/${artistId}/appearances/${trackId}`, { method:'DELETE' });
btn.closest('.appearance-row').remove();
}
// --- Init ---
loadStats();
loadQueue();

View File

@@ -143,6 +143,7 @@ pub async fn update_queue_item(
track_number: body.norm_track_number,
genre: body.norm_genre,
featured_artists: body.featured_artists,
release_type: None,
confidence: Some(1.0), // manual edit = full confidence
notes: Some("Manually edited".to_owned()),
};
@@ -574,6 +575,116 @@ pub async fn search_albums_for_artist(State(state): State<S>, Query(q): Query<Al
}
}
// --- Artist full admin form ---
pub async fn get_artist_full(State(state): State<S>, Path(id): Path<i64>) -> impl IntoResponse {
let artist = match db::get_artist_by_id(&state.pool, id).await {
Ok(Some(a)) => a,
Ok(None) => return error_response(StatusCode::NOT_FOUND, "not found"),
Err(e) => return error_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
};
let (albums, appearances) = tokio::join!(
db::get_artist_albums(&state.pool, id),
db::get_artist_appearances(&state.pool, id),
);
// For each album, load tracks
let albums = match albums {
Ok(a) => a,
Err(e) => return error_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
};
let mut albums_with_tracks = Vec::new();
for album in albums {
let tracks = db::get_album_tracks_admin(&state.pool, album.id).await.unwrap_or_default();
albums_with_tracks.push(serde_json::json!({
"id": album.id, "name": album.name, "year": album.year,
"release_type": album.release_type, "hidden": album.hidden,
"track_count": album.track_count, "tracks": tracks,
}));
}
(StatusCode::OK, Json(serde_json::json!({
"artist": artist,
"albums": albums_with_tracks,
"appearances": appearances.unwrap_or_default(),
}))).into_response()
}
#[derive(Deserialize)]
pub struct SetHiddenBody { pub hidden: bool }
pub async fn set_track_hidden(State(state): State<S>, Path(id): Path<i64>, Json(b): Json<SetHiddenBody>) -> impl IntoResponse {
match db::set_track_hidden(&state.pool, id, b.hidden).await {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(e) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
pub async fn set_album_hidden(State(state): State<S>, Path(id): Path<i64>, Json(b): Json<SetHiddenBody>) -> impl IntoResponse {
match db::set_album_hidden(&state.pool, id, b.hidden).await {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(e) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
pub async fn set_artist_hidden(State(state): State<S>, Path(id): Path<i64>, Json(b): Json<SetHiddenBody>) -> impl IntoResponse {
match db::set_artist_hidden(&state.pool, id, b.hidden).await {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(e) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
#[derive(Deserialize)]
pub struct SetReleaseTypeBody { pub release_type: String }
pub async fn set_album_release_type(State(state): State<S>, Path(id): Path<i64>, Json(b): Json<SetReleaseTypeBody>) -> impl IntoResponse {
let valid = ["album","single","ep","compilation","live"];
if !valid.contains(&b.release_type.as_str()) {
return error_response(StatusCode::BAD_REQUEST, "invalid release_type");
}
match db::set_album_release_type(&state.pool, id, &b.release_type).await {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(e) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
#[derive(Deserialize)]
pub struct RenameArtistBody { pub name: String }
pub async fn rename_artist_api(State(state): State<S>, Path(id): Path<i64>, Json(b): Json<RenameArtistBody>) -> impl IntoResponse {
match db::rename_artist_name(&state.pool, id, &b.name).await {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(e) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
#[derive(Deserialize)]
pub struct AddAppearanceBody { pub track_id: i64 }
pub async fn add_appearance(State(state): State<S>, Path(artist_id): Path<i64>, Json(b): Json<AddAppearanceBody>) -> impl IntoResponse {
match db::add_track_appearance(&state.pool, b.track_id, artist_id).await {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(e) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
pub async fn remove_appearance(State(state): State<S>, Path((artist_id, track_id)): Path<(i64, i64)>) -> impl IntoResponse {
match db::remove_track_appearance(&state.pool, track_id, artist_id).await {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(e) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
#[derive(Deserialize)]
pub struct SearchTracksQuery { #[serde(default)] pub q: String }
pub async fn search_tracks_feat(State(state): State<S>, Query(q): Query<SearchTracksQuery>) -> impl IntoResponse {
match db::search_tracks_for_feat(&state.pool, &q.q).await {
Ok(rows) => (StatusCode::OK, Json(serde_json::to_value(
rows.iter().map(|(id, title, artist)| serde_json::json!({"id": id, "title": title, "artist_name": artist})).collect::<Vec<_>>()
).unwrap())).into_response(),
Err(e) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
// --- Helpers ---
fn error_response(status: StatusCode, message: &str) -> axum::response::Response {

View File

@@ -2,7 +2,7 @@ pub mod api;
use std::sync::Arc;
use axum::{Router, routing::{get, post, put}};
use axum::{Router, routing::{delete, get, post, put}};
use sqlx::PgPool;
use crate::config::Args;
@@ -32,12 +32,21 @@ pub fn build_router(state: Arc<AppState>) -> Router {
.route("/artists", get(api::list_artists))
.route("/artists/:id", put(api::update_artist))
.route("/artists/:id/albums", get(api::list_albums))
.route("/artists/:id/full", get(api::get_artist_full))
.route("/artists/:id/hidden", put(api::set_artist_hidden))
.route("/artists/:id/rename", put(api::rename_artist_api))
.route("/artists/:id/appearances", post(api::add_appearance))
.route("/artists/:id/appearances/:track_id", delete(api::remove_appearance))
.route("/tracks/search", get(api::search_tracks_feat))
.route("/tracks/:id", get(api::get_track).put(api::update_track))
.route("/tracks/:id/hidden", put(api::set_track_hidden))
.route("/albums/search", get(api::search_albums_for_artist))
.route("/albums/:id/cover", get(api::album_cover))
.route("/albums/:id/full", get(api::get_album_full))
.route("/albums/:id/reorder", put(api::reorder_album_tracks))
.route("/albums/:id/edit", put(api::update_album_full))
.route("/albums/:id/hidden", put(api::set_album_hidden))
.route("/albums/:id/release_type", put(api::set_album_release_type))
.route("/albums/:id", put(api::update_album))
.route("/merges", get(api::list_merges).post(api::create_merge))
.route("/merges/:id", get(api::get_merge).put(api::update_merge))

View File

@@ -0,0 +1,19 @@
# auth-app
Проект состоит из двух частей:
- `client` - Vite + React + TypeScript
- `server` - Express + TypeScript + OIDC авторизация
## Запуск
1. Скопируй `server/.env.example` в `server/.env` и заполни OIDC параметры.
- Если нужно запустить без авторизации, поставь `DISABLE_AUTH=true` (OIDC параметры тогда не требуются).
2. В одном терминале:
- `cd server`
- `npm run dev`
3. В другом терминале:
- `cd client`
- `npm run dev`
Клиент откроется на `http://localhost:5173`, сервер на `http://localhost:3001`.

24
furumi-node-player/client/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>client</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

2965
furumi-node-player/client/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,30 @@
{
"name": "client",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.4",
"react-dom": "^19.2.4"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@types/node": "^24.12.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.57.0",
"vite": "^8.0.1"
}
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

View File

@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

View File

@@ -0,0 +1,71 @@
.page {
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
}
.card {
width: min(520px, 100%);
border: 1px solid #d8dde6;
border-radius: 14px;
padding: 24px;
background-color: #ffffff;
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.08);
}
.subtitle {
margin-top: 0;
margin-bottom: 20px;
color: #5a6475;
}
.settings {
margin-bottom: 16px;
padding: 12px;
border: 1px solid #e6eaf2;
border-radius: 10px;
background: #f8fafc;
}
.toggle {
display: flex;
align-items: center;
gap: 10px;
color: #0f172a;
font-weight: 600;
}
.toggle input {
width: 18px;
height: 18px;
}
.hint {
margin: 10px 0 0;
color: #5a6475;
}
.btn {
display: inline-block;
text-decoration: none;
background: #2251ff;
color: #ffffff;
padding: 10px 16px;
border-radius: 8px;
font-weight: 600;
}
.btn.ghost {
background: #edf1ff;
color: #1e3fc4;
margin-top: 10px;
}
.profile p {
margin: 8px 0;
}
.error {
color: #cc1e1e;
}

View File

@@ -0,0 +1,134 @@
import { useEffect, useMemo, useState } from 'react'
import './App.css'
type UserProfile = {
sub: string
name?: string
email?: string
}
const NO_AUTH_STORAGE_KEY = 'furumiNodePlayer.runWithoutAuth'
function App() {
const [loading, setLoading] = useState(true)
const [user, setUser] = useState<UserProfile | null>(null)
const [error, setError] = useState<string | null>(null)
const [runWithoutAuth, setRunWithoutAuth] = useState(() => {
try {
return window.localStorage.getItem(NO_AUTH_STORAGE_KEY) === '1'
} catch {
return false
}
})
const apiBase = useMemo(() => import.meta.env.VITE_API_BASE_URL ?? '', [])
useEffect(() => {
if (runWithoutAuth) {
setError(null)
setUser({ sub: 'noauth', name: 'No Auth' })
setLoading(false)
return
}
const loadMe = async () => {
try {
const response = await fetch(`${apiBase}/api/me`, {
credentials: 'include',
})
if (response.status === 401) {
setUser(null)
return
}
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`)
}
const data = await response.json()
setUser(data.user ?? null)
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load session')
} finally {
setLoading(false)
}
}
void loadMe()
}, [apiBase, runWithoutAuth])
const loginUrl = `${apiBase}/api/login`
const logoutUrl = `${apiBase}/api/logout`
return (
<main className="page">
<section className="card">
<h1>OIDC Login</h1>
<p className="subtitle">Авторизация обрабатывается на Express сервере.</p>
<div className="settings">
<label className="toggle">
<input
type="checkbox"
checked={runWithoutAuth}
onChange={(e) => {
const next = e.target.checked
setRunWithoutAuth(next)
try {
if (next) window.localStorage.setItem(NO_AUTH_STORAGE_KEY, '1')
else window.localStorage.removeItem(NO_AUTH_STORAGE_KEY)
} catch {
// ignore
}
setLoading(true)
setUser(null)
}}
/>
<span>Запускать без авторизации</span>
</label>
</div>
{loading && <p>Проверяю сессию...</p>}
{error && <p className="error">Ошибка: {error}</p>}
{!loading && runWithoutAuth && (
<p className="hint">
Режим без авторизации включён. Для входа отключи настройку выше.
</p>
)}
{!loading && !user && (
<a className="btn" href={loginUrl}>
Войти через OIDC
</a>
)}
{!loading && user && (
<div className="profile">
<p>
<strong>ID:</strong> {user.sub}
</p>
{user.name && (
<p>
<strong>Имя:</strong> {user.name}
</p>
)}
{user.email && (
<p>
<strong>Email:</strong> {user.email}
</p>
)}
{!runWithoutAuth && (
<a className="btn ghost" href={logoutUrl}>
Выйти
</a>
)}
</div>
)}
</section>
</main>
)
}
export default App

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

View File

@@ -0,0 +1,15 @@
body {
margin: 0;
font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
color: #0f172a;
background-color: #f3f6fb;
}
* {
box-sizing: border-box;
}
h1 {
margin-top: 0;
margin-bottom: 10px;
}

View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2023",
"useDefineForClassFields": true,
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

View File

@@ -0,0 +1,15 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': {
target: 'http://localhost:3001',
changeOrigin: true,
},
},
},
})

View File

@@ -0,0 +1,12 @@
PORT=3001
BASE_URL=http://localhost:3001
FRONTEND_ORIGIN=http://localhost:5173
SESSION_SECRET=super-long-random-secret
# Если true/1/on/yes — сервер стартует без OIDC и не требует авторизации.
DISABLE_AUTH=false
OIDC_ISSUER_BASE_URL=https://your-issuer.example.com
OIDC_CLIENT_ID=your-client-id
OIDC_CLIENT_SECRET=your-client-secret
OIDC_SCOPE="openid profile email"

24
furumi-node-player/server/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

3355
furumi-node-player/server/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,28 @@
{
"name": "server",
"version": "1.0.0",
"type": "module",
"main": "dist/index.js",
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc -p tsconfig.json",
"start": "node dist/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"cors": "^2.8.6",
"dotenv": "^17.3.1",
"express": "^5.2.1",
"express-openid-connect": "^2.19.4"
},
"devDependencies": {
"@types/cors": "^2.8.19",
"@types/express": "^5.0.6",
"@types/node": "^25.5.0",
"tsx": "^4.21.0",
"typescript": "^5.9.3"
}
}

View File

@@ -0,0 +1,103 @@
import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import { auth } from 'express-openid-connect';
const app = express();
const port = Number(process.env.PORT ?? 3001);
const frontendOrigin = process.env.FRONTEND_ORIGIN ?? 'http://localhost:5173';
const disableAuth = ['1', 'true', 'yes', 'on'].includes(
String(process.env.DISABLE_AUTH ?? '').trim().toLowerCase(),
);
const oidcConfig = {
authRequired: false,
auth0Logout: false,
secret: process.env.SESSION_SECRET ?? 'change-me-in-env',
baseURL: process.env.BASE_URL ?? `http://localhost:${port}`,
clientID: process.env.OIDC_CLIENT_ID ?? '',
issuerBaseURL: process.env.OIDC_ISSUER_BASE_URL ?? '',
clientSecret: process.env.OIDC_CLIENT_SECRET ?? '',
authorizationParams: {
response_type: 'code',
scope: process.env.OIDC_SCOPE ?? 'openid profile email',
},
};
if (!disableAuth && (!oidcConfig.clientID || !oidcConfig.issuerBaseURL || !oidcConfig.clientSecret)) {
// Keep a clear startup failure if OIDC is not configured.
throw new Error(
'OIDC config is missing. Set OIDC_ISSUER_BASE_URL, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET in server/.env (or set DISABLE_AUTH=true)',
);
}
app.use(
cors({
origin: frontendOrigin,
credentials: true,
}),
);
app.use(express.json());
if (!disableAuth) {
app.use(auth(oidcConfig));
}
app.get('/api/health', (_req, res) => {
res.json({ ok: true });
});
app.get('/api/me', (req, res) => {
if (disableAuth) {
res.json({
authenticated: false,
bypassAuth: true,
user: {
sub: 'noauth',
name: 'No Auth',
},
});
return;
}
if (!req.oidc.isAuthenticated()) {
res.status(401).json({ authenticated: false });
return;
}
res.json({
authenticated: true,
user: req.oidc.user,
});
});
app.get('/api/login', (req, res) => {
if (disableAuth) {
res.status(204).end();
return;
}
res.oidc.login({
returnTo: frontendOrigin,
});
});
app.get('/api/logout', (req, res) => {
if (disableAuth) {
res.status(204).end();
return;
}
res.oidc.logout({
returnTo: frontendOrigin,
});
});
app.listen(port, () => {
console.log(
`${disableAuth ? 'NO-AUTH' : 'OIDC auth'} server listening on http://localhost:${port}`,
);
});

View File

@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"outDir": "dist",
"rootDir": "src"
},
"include": ["src"]
}

View File

@@ -92,6 +92,7 @@ pub async fn list_artists(pool: &PgPool) -> Result<Vec<ArtistListItem>, sqlx::Er
FROM artists ar
LEFT JOIN albums al ON al.artist_id = ar.id
LEFT JOIN tracks t ON t.artist_id = ar.id
WHERE NOT ar.hidden
GROUP BY ar.id, ar.slug, ar.name
HAVING COUNT(DISTINCT t.id) > 0
ORDER BY ar.name"#
@@ -116,8 +117,10 @@ pub async fn list_albums_by_artist(pool: &PgPool, artist_slug: &str) -> Result<V
EXISTS(SELECT 1 FROM album_images ai WHERE ai.album_id = al.id AND ai.image_type = 'cover') AS has_cover
FROM albums al
JOIN artists ar ON al.artist_id = ar.id
LEFT JOIN tracks t ON t.album_id = al.id
LEFT JOIN tracks t ON t.album_id = al.id AND NOT t.hidden
WHERE ar.slug = $1
AND NOT al.hidden
AND EXISTS (SELECT 1 FROM tracks t2 WHERE t2.album_id = al.id AND NOT t2.hidden)
GROUP BY al.id, al.slug, al.name, al.year
ORDER BY al.year NULLS LAST, al.name"#
)
@@ -135,6 +138,7 @@ pub async fn list_tracks_by_album(pool: &PgPool, album_slug: &str) -> Result<Vec
JOIN artists ar ON t.artist_id = ar.id
LEFT JOIN albums al ON t.album_id = al.id
WHERE al.slug = $1
AND NOT t.hidden
ORDER BY t.track_number NULLS LAST, t.title"#
)
.bind(album_slug)
@@ -221,6 +225,7 @@ pub async fn list_all_tracks_by_artist(pool: &PgPool, artist_slug: &str) -> Resu
JOIN artists ar ON t.artist_id = ar.id
LEFT JOIN albums al ON t.album_id = al.id
WHERE ar.slug = $1
AND NOT t.hidden
ORDER BY al.year NULLS LAST, al.name, t.track_number NULLS LAST, t.title"#
)
.bind(artist_slug)