add new features and format

This commit is contained in:
Mustafa Soylu
2025-06-11 10:41:32 +02:00
parent c6023a9c2e
commit bb9187e9a0
34 changed files with 3405 additions and 2544 deletions

View File

@@ -0,0 +1,9 @@
node_modules
dist
.DS_Store
coverage
.pnpm-store
.vite
.env
.env.*
!.env.example

View File

@@ -0,0 +1,7 @@
{
"semi": true,
"singleQuote": false,
"trailingComma": "all",
"printWidth": 120,
"tabWidth": 2
}

View File

@@ -24,31 +24,31 @@ export default tseslint.config({
languageOptions: {
// other options...
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
project: ["./tsconfig.node.json", "./tsconfig.app.json"],
tsconfigRootDir: import.meta.dirname,
},
},
})
});
```
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'
import reactX from "eslint-plugin-react-x";
import reactDom from "eslint-plugin-react-dom";
export default tseslint.config({
plugins: {
// Add the react-x and react-dom plugins
'react-x': reactX,
'react-dom': reactDom,
"react-x": reactX,
"react-dom": reactDom,
},
rules: {
// other rules...
// Enable its recommended typescript rules
...reactX.configs['recommended-typescript'].rules,
...reactX.configs["recommended-typescript"].rules,
...reactDom.configs.recommended.rules,
},
})
});
```

View File

@@ -1,28 +1,33 @@
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 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 prettier from "eslint-plugin-prettier";
import { readFileSync } from "node:fs";
export default tseslint.config(
{ ignores: ['dist'] },
// Read Prettier configuration from .prettierrc.json
const prettierOptions = JSON.parse(readFileSync("./.prettierrc.json", "utf8"));
export default [
{ ignores: ["dist"] },
js.configs.recommended,
...tseslint.configs.recommended,
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
files: ["**/*.{ts,tsx}"],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
prettier: prettier,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
"react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
"prettier/prettier": ["error", prettierOptions],
},
},
)
];

View File

@@ -6,7 +6,8 @@
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"lint": "eslint . --fix",
"format": "prettier --write .",
"preview": "vite preview"
},
"dependencies": {
@@ -16,13 +17,15 @@
"@tanstack/react-router": "^1.120.18",
"@tanstack/react-table": "^8.21.3",
"@tanstack/router-devtools": "^1.120.18",
"@types/uuid": "^10.0.0",
"axios": "^1.9.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-hook-form": "^7.57.0",
"sonner": "^2.0.5",
"tailwindcss": "^4.1.8",
"use-debounce": "^10.0.5"
"use-debounce": "^10.0.5",
"uuid": "^11.1.0"
},
"devDependencies": {
"@eslint/js": "^9.25.0",
@@ -31,9 +34,12 @@
"@types/react-dom": "^19.1.2",
"@vitejs/plugin-react": "^4.4.1",
"eslint": "^9.25.0",
"eslint-config-prettier": "^10.1.5",
"eslint-plugin-prettier": "^5.4.1",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.19",
"globals": "^16.0.0",
"prettier": "^3.5.3",
"typescript": "~5.8.3",
"typescript-eslint": "^8.30.1",
"vite": "^6.3.5"

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,4 @@
import tailwindcss from '@tailwindcss/postcss';
import tailwindcss from "@tailwindcss/postcss";
export default {
plugins: [tailwindcss],

View File

@@ -1,73 +1,162 @@
import { useQueue, type QueueItem } from '../contexts/queue-context';
import { useQueue, type QueueItem } from "../contexts/queue-context";
export function Queue() {
const { items, isVisible, removeItem, clearQueue, toggleVisibility } = useQueue();
const { items, isVisible, removeItem, retryItem, clearQueue, toggleVisibility, clearCompleted } = useQueue();
if (!isVisible) return null;
const renderStatus = (item: QueueItem) => {
switch (item.status) {
case 'downloading':
return (
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-1.5">
<div
className="bg-blue-600 h-1.5 rounded-full"
style={{ width: `${item.progress || 0}%` }}
></div>
</div>
);
case 'completed':
return <span className="text-green-500 font-semibold">Completed</span>;
case 'error':
return <span className="text-red-500 font-semibold truncate" title={item.error}>{item.error || 'Failed'}</span>;
default:
return <span className="text-gray-500">{item.status}</span>;
const handleClearQueue = () => {
if (confirm("Are you sure you want to cancel all downloads and clear the queue?")) {
clearQueue();
}
};
const renderItemDetails = (item: QueueItem) => {
if (item.status !== 'downloading' || !item.progress) return null;
return (
<div className="text-xs text-gray-400 flex justify-between w-full">
<span>{item.progress.toFixed(0)}%</span>
<span>{item.speed}</span>
<span>{item.size}</span>
<span>{item.eta}</span>
const renderProgress = (item: QueueItem) => {
if (item.status === "downloading" || item.status === "processing") {
const isMultiTrack = item.totalTracks && item.totalTracks > 1;
const overallProgress =
isMultiTrack && item.totalTracks
? ((item.currentTrackNumber || 0) / item.totalTracks) * 100
: item.progress || 0;
return (
<div className="w-full bg-gray-700 rounded-full h-2.5 mt-1">
<div className="bg-green-600 h-2.5 rounded-full" style={{ width: `${overallProgress}%` }}></div>
{isMultiTrack && (
<div className="w-full bg-gray-600 rounded-full h-1.5 mt-1">
<div className="bg-blue-500 h-1.5 rounded-full" style={{ width: `${item.progress || 0}%` }}></div>
</div>
)}
</div>
)
}
);
}
return null;
};
const renderStatusDetails = (item: QueueItem) => {
const statusClass = {
initializing: "text-gray-400",
pending: "text-gray-400",
downloading: "text-blue-400",
processing: "text-purple-400",
completed: "text-green-500 font-semibold",
error: "text-red-500 font-semibold",
skipped: "text-yellow-500",
cancelled: "text-gray-500",
queued: "text-gray-400",
}[item.status];
const isMultiTrack = item.totalTracks && item.totalTracks > 1;
return (
<div className="text-xs text-gray-400 flex justify-between w-full mt-1">
<span className={statusClass}>{item.status.toUpperCase()}</span>
{item.status === "downloading" && (
<>
<span>{item.progress?.toFixed(0)}%</span>
<span>{item.speed}</span>
<span>{item.eta}</span>
</>
)}
{isMultiTrack && (
<span>
{item.currentTrackNumber}/{item.totalTracks}
</span>
)}
</div>
);
};
const renderSummary = (item: QueueItem) => {
if (item.status !== "completed" || !item.summary) return null;
return (
<div className="text-xs text-gray-300 mt-1">
<span>
Success: <span className="text-green-500">{item.summary.successful}</span>
</span>{" "}
|{" "}
<span>
Skipped: <span className="text-yellow-500">{item.summary.skipped}</span>
</span>{" "}
|{" "}
<span>
Failed: <span className="text-red-500">{item.summary.failed}</span>
</span>
</div>
);
};
return (
<div className="fixed bottom-4 right-4 w-96 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50 flex flex-col">
<div className="flex justify-between items-center p-3 border-b border-gray-200 dark:border-gray-700">
<h3 className="font-semibold">Download Queue</h3>
<div className="flex items-center gap-2">
<button onClick={clearQueue} className="text-sm text-gray-500 hover:text-red-500" title="Clear All">Clear</button>
<button onClick={() => toggleVisibility()} className="text-gray-500 hover:text-white" title="Close">
<img src="/cross.svg" alt="Close" className="w-4 h-4" />
</button>
</div>
</div>
<div className="p-3 max-h-96 overflow-y-auto space-y-3">
<aside className="fixed top-0 right-0 h-full w-96 bg-gray-900 border-l border-gray-700 z-50 flex flex-col shadow-2xl">
<header className="flex justify-between items-center p-4 border-b border-gray-700 flex-shrink-0">
<h3 className="font-semibold text-lg">Download Queue ({items.length})</h3>
<button onClick={() => toggleVisibility()} className="text-gray-400 hover:text-white" title="Close">
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</header>
<main className="p-3 flex-grow overflow-y-auto space-y-4">
{items.length === 0 ? (
<p className="text-gray-500 dark:text-gray-400 text-center py-4">Queue is empty.</p>
<div className="text-gray-400 text-center py-10">
<p>The queue is empty.</p>
</div>
) : (
items.map((item) => (
<div key={item.id} className="text-sm">
<div className="flex justify-between items-center">
<span className="font-medium truncate pr-2">{item.name}</span>
<button onClick={() => removeItem(item.id)} className="text-gray-400 hover:text-red-500 flex-shrink-0">
<img src="/cross.svg" alt="Remove" className="w-4 h-4" />
</button>
<div key={item.id} className="text-sm bg-gray-800 p-3 rounded-md border border-gray-700">
<div className="flex justify-between items-start">
<span className="font-medium truncate pr-2 flex-grow">{item.name}</span>
<button
onClick={() => removeItem(item.id)}
className="text-gray-500 hover:text-red-500 flex-shrink-0"
title="Cancel Download"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div className="mt-1 space-y-1">
{renderStatus(item)}
{renderItemDetails(item)}
<div className="mt-2 space-y-1">
{renderProgress(item)}
{renderStatusDetails(item)}
{renderSummary(item)}
{item.status === "error" && (
<div className="flex items-center justify-between mt-2">
<p className="text-red-500 text-xs truncate" title={item.error}>
{item.error || "An unknown error occurred."}
</p>
{item.canRetry && (
<button
onClick={() => retryItem(item.id)}
className="text-xs bg-blue-600 hover:bg-blue-700 text-white py-1 px-2 rounded"
>
Retry
</button>
)}
</div>
)}
</div>
</div>
))
)}
</div>
</div>
</main>
<footer className="p-3 border-t border-gray-700 flex-shrink-0 flex gap-2">
<button
onClick={handleClearQueue}
className="text-sm bg-red-800 hover:bg-red-700 text-white py-2 px-4 rounded w-full"
>
Clear All
</button>
<button
onClick={clearCompleted}
className="text-sm bg-gray-700 hover:bg-gray-600 text-white py-2 px-4 rounded w-full"
>
Clear Completed
</button>
</footer>
</aside>
);
}

View File

@@ -1,11 +1,11 @@
import { useState } from 'react';
import { useForm, type SubmitHandler } from 'react-hook-form';
import apiClient from '../../lib/api-client';
import { toast } from 'sonner';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useState } from "react";
import { useForm, type SubmitHandler } from "react-hook-form";
import apiClient from "../../lib/api-client";
import { toast } from "sonner";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
// --- Type Definitions ---
type Service = 'spotify' | 'deezer';
type Service = "spotify" | "deezer";
interface Credential {
name: string;
@@ -16,25 +16,26 @@ interface AccountFormData {
accountName: string;
accountRegion?: string;
authBlob?: string; // Spotify specific
arl?: string; // Deezer specific
arl?: string; // Deezer specific
}
// --- API Functions ---
const fetchCredentials = async (service: Service): Promise<Credential[]> => {
const { data } = await apiClient.get<string[]>(`/credentials/${service}`);
return data.map(name => ({ name }));
return data.map((name) => ({ name }));
};
const addCredential = async ({ service, data }: { service: Service, data: AccountFormData }) => {
const payload = service === 'spotify'
? { blob_content: data.authBlob, region: data.accountRegion }
: { arl: data.arl, region: data.accountRegion };
const addCredential = async ({ service, data }: { service: Service; data: AccountFormData }) => {
const payload =
service === "spotify"
? { blob_content: data.authBlob, region: data.accountRegion }
: { arl: data.arl, region: data.accountRegion };
const { data: response } = await apiClient.post(`/credentials/${service}/${data.accountName}`, payload);
return response;
};
const deleteCredential = async ({ service, name }: { service: Service, name:string }) => {
const deleteCredential = async ({ service, name }: { service: Service; name: string }) => {
const { data: response } = await apiClient.delete(`/credentials/${service}/${name}`);
return response;
};
@@ -42,21 +43,26 @@ const deleteCredential = async ({ service, name }: { service: Service, name:stri
// --- Component ---
export function AccountsTab() {
const queryClient = useQueryClient();
const [activeService, setActiveService] = useState<Service>('spotify');
const [activeService, setActiveService] = useState<Service>("spotify");
const [isAdding, setIsAdding] = useState(false);
const { data: credentials, isLoading } = useQuery({
queryKey: ['credentials', activeService],
queryKey: ["credentials", activeService],
queryFn: () => fetchCredentials(activeService),
});
const { register, handleSubmit, reset, formState: { errors } } = useForm<AccountFormData>();
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm<AccountFormData>();
const addMutation = useMutation({
mutationFn: addCredential,
onSuccess: () => {
toast.success('Account added successfully!');
queryClient.invalidateQueries({ queryKey: ['credentials', activeService] });
toast.success("Account added successfully!");
queryClient.invalidateQueries({ queryKey: ["credentials", activeService] });
setIsAdding(false);
reset();
},
@@ -69,7 +75,7 @@ export function AccountsTab() {
mutationFn: deleteCredential,
onSuccess: (_, variables) => {
toast.success(`Account "${variables.name}" deleted.`);
queryClient.invalidateQueries({ queryKey: ['credentials', activeService] });
queryClient.invalidateQueries({ queryKey: ["credentials", activeService] });
},
onError: (error) => {
toast.error(`Failed to delete account: ${error.message}`);
@@ -82,35 +88,61 @@ export function AccountsTab() {
const renderAddForm = () => (
<form onSubmit={handleSubmit(onSubmit)} className="p-4 border rounded-lg mt-4 space-y-4">
<h4 className="font-semibold">Add New {activeService === 'spotify' ? 'Spotify' : 'Deezer'} Account</h4>
<div className="flex flex-col gap-2">
<label htmlFor="accountName">Account Name</label>
<input id="accountName" {...register('accountName', { required: 'This field is required' })} className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" />
{errors.accountName && <p className="text-red-500 text-sm">{errors.accountName.message}</p>}
<h4 className="font-semibold">Add New {activeService === "spotify" ? "Spotify" : "Deezer"} Account</h4>
<div className="flex flex-col gap-2">
<label htmlFor="accountName">Account Name</label>
<input
id="accountName"
{...register("accountName", { required: "This field is required" })}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
{errors.accountName && <p className="text-red-500 text-sm">{errors.accountName.message}</p>}
</div>
{activeService === 'spotify' && (
{activeService === "spotify" && (
<div className="flex flex-col gap-2">
<label htmlFor="authBlob">Auth Blob (JSON)</label>
<textarea id="authBlob" {...register('authBlob', { required: activeService === 'spotify' ? 'Auth Blob is required' : false })} className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" rows={4}></textarea>
{errors.authBlob && <p className="text-red-500 text-sm">{errors.authBlob.message}</p>}
<textarea
id="authBlob"
{...register("authBlob", { required: activeService === "spotify" ? "Auth Blob is required" : false })}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
rows={4}
></textarea>
{errors.authBlob && <p className="text-red-500 text-sm">{errors.authBlob.message}</p>}
</div>
)}
{activeService === 'deezer' && (
{activeService === "deezer" && (
<div className="flex flex-col gap-2">
<label htmlFor="arl">ARL Token</label>
<input id="arl" {...register('arl', { required: activeService === 'deezer' ? 'ARL is required' : false })} className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" />
{errors.arl && <p className="text-red-500 text-sm">{errors.arl.message}</p>}
<input
id="arl"
{...register("arl", { required: activeService === "deezer" ? "ARL is required" : false })}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
{errors.arl && <p className="text-red-500 text-sm">{errors.arl.message}</p>}
</div>
)}
<div className="flex flex-col gap-2">
<label htmlFor="accountRegion">Region (Optional)</label>
<input id="accountRegion" {...register('accountRegion')} placeholder="e.g. US, GB" className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" />
<div className="flex flex-col gap-2">
<label htmlFor="accountRegion">Region (Optional)</label>
<input
id="accountRegion"
{...register("accountRegion")}
placeholder="e.g. US, GB"
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div className="flex gap-2">
<button type="submit" disabled={addMutation.isPending} className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50">
{addMutation.isPending ? 'Saving...' : 'Save Account'}
<button
type="submit"
disabled={addMutation.isPending}
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{addMutation.isPending ? "Saving..." : "Save Account"}
</button>
<button type="button" onClick={() => setIsAdding(false)} className="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700">
<button
type="button"
onClick={() => setIsAdding(false)}
className="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700"
>
Cancel
</button>
</div>
@@ -120,29 +152,46 @@ export function AccountsTab() {
return (
<div className="space-y-6">
<div className="flex gap-2 border-b">
<button onClick={() => setActiveService('spotify')} className={`p-2 ${activeService === 'spotify' ? 'border-b-2 border-blue-500 font-semibold' : ''}`}>Spotify</button>
<button onClick={() => setActiveService('deezer')} className={`p-2 ${activeService === 'deezer' ? 'border-b-2 border-blue-500 font-semibold' : ''}`}>Deezer</button>
<button
onClick={() => setActiveService("spotify")}
className={`p-2 ${activeService === "spotify" ? "border-b-2 border-blue-500 font-semibold" : ""}`}
>
Spotify
</button>
<button
onClick={() => setActiveService("deezer")}
className={`p-2 ${activeService === "deezer" ? "border-b-2 border-blue-500 font-semibold" : ""}`}
>
Deezer
</button>
</div>
{isLoading ? (
<p>Loading accounts...</p>
) : (
<div className="space-y-2">
{credentials?.map(cred => (
<div key={cred.name} className="flex justify-between items-center p-3 bg-gray-800 rounded-md">
<span>{cred.name}</span>
<button onClick={() => deleteMutation.mutate({ service: activeService, name: cred.name })} disabled={deleteMutation.isPending && deleteMutation.variables?.name === cred.name} className="text-red-500 hover:text-red-400">
Delete
</button>
</div>
))}
{credentials?.map((cred) => (
<div key={cred.name} className="flex justify-between items-center p-3 bg-gray-800 rounded-md">
<span>{cred.name}</span>
<button
onClick={() => deleteMutation.mutate({ service: activeService, name: cred.name })}
disabled={deleteMutation.isPending && deleteMutation.variables?.name === cred.name}
className="text-red-500 hover:text-red-400"
>
Delete
</button>
</div>
))}
</div>
)}
{!isAdding && (
<button onClick={() => setIsAdding(true)} className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50">
Add Account
</button>
<button
onClick={() => setIsAdding(true)}
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
Add Account
</button>
)}
{isAdding && renderAddForm()}
</div>

View File

@@ -1,14 +1,14 @@
import { useForm, type SubmitHandler } from 'react-hook-form';
import apiClient from '../../lib/api-client';
import { toast } from 'sonner';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm, type SubmitHandler } from "react-hook-form";
import apiClient from "../../lib/api-client";
import { toast } from "sonner";
import { useMutation, useQueryClient } from "@tanstack/react-query";
// --- Type Definitions ---
interface DownloadSettings {
maxConcurrentDownloads: number;
realTime: boolean;
fallback: boolean;
convertTo: 'MP3' | 'AAC' | 'OGG' | 'OPUS' | 'FLAC' | 'WAV' | 'ALAC' | '';
convertTo: "MP3" | "AAC" | "OGG" | "OPUS" | "FLAC" | "WAV" | "ALAC" | "";
bitrate: string;
maxRetries: number;
retryDelaySeconds: number;
@@ -26,18 +26,18 @@ interface DownloadsTabProps {
}
const CONVERSION_FORMATS: Record<string, string[]> = {
MP3: ['32k', '64k', '96k', '128k', '192k', '256k', '320k'],
AAC: ['32k', '64k', '96k', '128k', '192k', '256k'],
OGG: ['64k', '96k', '128k', '192k', '256k', '320k'],
OPUS: ['32k', '64k', '96k', '128k', '192k', '256k'],
FLAC: [],
WAV: [],
ALAC: []
MP3: ["32k", "64k", "96k", "128k", "192k", "256k", "320k"],
AAC: ["32k", "64k", "96k", "128k", "192k", "256k"],
OGG: ["64k", "96k", "128k", "192k", "256k", "320k"],
OPUS: ["32k", "64k", "96k", "128k", "192k", "256k"],
FLAC: [],
WAV: [],
ALAC: [],
};
// --- API Functions ---
const saveDownloadConfig = async (data: Partial<DownloadSettings>) => {
const { data: response } = await apiClient.post('/config', data);
const { data: response } = await apiClient.post("/config", data);
return response;
};
@@ -48,8 +48,8 @@ export function DownloadsTab({ config, isLoading }: DownloadsTabProps) {
const mutation = useMutation({
mutationFn: saveDownloadConfig,
onSuccess: () => {
toast.success('Download settings saved successfully!');
queryClient.invalidateQueries({ queryKey: ['config'] });
toast.success("Download settings saved successfully!");
queryClient.invalidateQueries({ queryKey: ["config"] });
},
onError: (error) => {
toast.error(`Failed to save settings: ${error.message}`);
@@ -60,15 +60,15 @@ export function DownloadsTab({ config, isLoading }: DownloadsTabProps) {
values: config,
});
const selectedFormat = watch('convertTo');
const selectedFormat = watch("convertTo");
const onSubmit: SubmitHandler<DownloadSettings> = (data) => {
mutation.mutate({
...data,
maxConcurrentDownloads: Number(data.maxConcurrentDownloads),
maxRetries: Number(data.maxRetries),
retryDelaySeconds: Number(data.retryDelaySeconds),
retryDelayIncrease: Number(data.retryDelayIncrease),
...data,
maxConcurrentDownloads: Number(data.maxConcurrentDownloads),
maxRetries: Number(data.maxRetries),
retryDelaySeconds: Number(data.retryDelaySeconds),
retryDelayIncrease: Number(data.retryDelayIncrease),
});
};
@@ -82,16 +82,22 @@ export function DownloadsTab({ config, isLoading }: DownloadsTabProps) {
<div className="space-y-4">
<h3 className="text-xl font-semibold">Download Behavior</h3>
<div className="flex flex-col gap-2">
<label htmlFor="maxConcurrentDownloads">Max Concurrent Downloads</label>
<input id="maxConcurrentDownloads" type="number" min="1" {...register('maxConcurrentDownloads')} className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" />
<label htmlFor="maxConcurrentDownloads">Max Concurrent Downloads</label>
<input
id="maxConcurrentDownloads"
type="number"
min="1"
{...register("maxConcurrentDownloads")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div className="flex items-center justify-between">
<label htmlFor="realTimeToggle">Real-time downloading</label>
<input id="realTimeToggle" type="checkbox" {...register('realTime')} className="h-6 w-6 rounded" />
<label htmlFor="realTimeToggle">Real-time downloading</label>
<input id="realTimeToggle" type="checkbox" {...register("realTime")} className="h-6 w-6 rounded" />
</div>
<div className="flex items-center justify-between">
<label htmlFor="fallbackToggle">Download Fallback</label>
<input id="fallbackToggle" type="checkbox" {...register('fallback')} className="h-6 w-6 rounded" />
<label htmlFor="fallbackToggle">Download Fallback</label>
<input id="fallbackToggle" type="checkbox" {...register("fallback")} className="h-6 w-6 rounded" />
</div>
</div>
@@ -99,22 +105,35 @@ export function DownloadsTab({ config, isLoading }: DownloadsTabProps) {
<div className="space-y-4">
<h3 className="text-xl font-semibold">Conversion</h3>
<div className="flex flex-col gap-2">
<label htmlFor="convertToSelect">Convert To Format</label>
<select id="convertToSelect" {...register('convertTo')} className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
<option value="">No Conversion</option>
{Object.keys(CONVERSION_FORMATS).map(format => (
<option key={format} value={format}>{format}</option>
))}
</select>
<label htmlFor="convertToSelect">Convert To Format</label>
<select
id="convertToSelect"
{...register("convertTo")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">No Conversion</option>
{Object.keys(CONVERSION_FORMATS).map((format) => (
<option key={format} value={format}>
{format}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-2">
<label htmlFor="bitrateSelect">Bitrate</label>
<select id="bitrateSelect" {...register('bitrate')} className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" disabled={!selectedFormat || CONVERSION_FORMATS[selectedFormat]?.length === 0}>
<option value="">Auto</option>
{(CONVERSION_FORMATS[selectedFormat] || []).map(rate => (
<option key={rate} value={rate}>{rate}</option>
))}
</select>
<label htmlFor="bitrateSelect">Bitrate</label>
<select
id="bitrateSelect"
{...register("bitrate")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
disabled={!selectedFormat || CONVERSION_FORMATS[selectedFormat]?.length === 0}
>
<option value="">Auto</option>
{(CONVERSION_FORMATS[selectedFormat] || []).map((rate) => (
<option key={rate} value={rate}>
{rate}
</option>
))}
</select>
</div>
</div>
@@ -122,21 +141,43 @@ export function DownloadsTab({ config, isLoading }: DownloadsTabProps) {
<div className="space-y-4">
<h3 className="text-xl font-semibold">Retries</h3>
<div className="flex flex-col gap-2">
<label htmlFor="maxRetries">Max Retry Attempts</label>
<input id="maxRetries" type="number" min="0" {...register('maxRetries')} className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" />
<label htmlFor="maxRetries">Max Retry Attempts</label>
<input
id="maxRetries"
type="number"
min="0"
{...register("maxRetries")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div className="flex flex-col gap-2">
<label htmlFor="retryDelaySeconds">Initial Retry Delay (s)</label>
<input id="retryDelaySeconds" type="number" min="1" {...register('retryDelaySeconds')} className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" />
<label htmlFor="retryDelaySeconds">Initial Retry Delay (s)</label>
<input
id="retryDelaySeconds"
type="number"
min="1"
{...register("retryDelaySeconds")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div className="flex flex-col gap-2">
<label htmlFor="retryDelayIncrease">Retry Delay Increase (s)</label>
<input id="retryDelayIncrease" type="number" min="0" {...register('retryDelayIncrease')} className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" />
<label htmlFor="retryDelayIncrease">Retry Delay Increase (s)</label>
<input
id="retryDelayIncrease"
type="number"
min="0"
{...register("retryDelayIncrease")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
</div>
<button type="submit" disabled={mutation.isPending} className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50">
{mutation.isPending ? 'Saving...' : 'Save Download Settings'}
<button
type="submit"
disabled={mutation.isPending}
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{mutation.isPending ? "Saving..." : "Save Download Settings"}
</button>
</form>
);

View File

@@ -1,8 +1,8 @@
import { useRef } from 'react';
import { useForm, type SubmitHandler } from 'react-hook-form';
import apiClient from '../../lib/api-client';
import { toast } from 'sonner';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useRef } from "react";
import { useForm, type SubmitHandler } from "react-hook-form";
import apiClient from "../../lib/api-client";
import { toast } from "sonner";
import { useMutation, useQueryClient } from "@tanstack/react-query";
// --- Type Definitions ---
interface FormattingSettings {
@@ -23,47 +23,46 @@ interface FormattingTabProps {
// --- API Functions ---
const saveFormattingConfig = async (data: Partial<FormattingSettings>) => {
const { data: response } = await apiClient.post('/config', data);
const { data: response } = await apiClient.post("/config", data);
return response;
};
// --- Placeholders ---
const placeholders = {
"Common": {
"%music%": "Track title",
"%artist%": "Track artist",
"%album%": "Album name",
"%ar_album%": "Album artist",
"%tracknum%": "Track number",
"%year%": "Year of release",
},
"Additional": {
"%discnum%": "Disc number",
"%date%": "Release date",
"%genre%": "Music genre",
"%isrc%": "ISRC",
"%explicit%": "Explicit flag",
"%duration%": "Track duration (s)",
},
Common: {
"%music%": "Track title",
"%artist%": "Track artist",
"%album%": "Album name",
"%ar_album%": "Album artist",
"%tracknum%": "Track number",
"%year%": "Year of release",
},
Additional: {
"%discnum%": "Disc number",
"%date%": "Release date",
"%genre%": "Music genre",
"%isrc%": "ISRC",
"%explicit%": "Explicit flag",
"%duration%": "Track duration (s)",
},
};
const PlaceholderSelector = ({ onSelect }: { onSelect: (value: string) => void }) => (
<select
onChange={(e) => onSelect(e.target.value)}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm mt-1"
>
<option value="">-- Insert Placeholder --</option>
{Object.entries(placeholders).map(([group, options]) => (
<optgroup label={group} key={group}>
{Object.entries(options).map(([value, label]) => (
<option key={value} value={value}>{`${value} - ${label}`}</option>
))}
</optgroup>
<select
onChange={(e) => onSelect(e.target.value)}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm mt-1"
>
<option value="">-- Insert Placeholder --</option>
{Object.entries(placeholders).map(([group, options]) => (
<optgroup label={group} key={group}>
{Object.entries(options).map(([value, label]) => (
<option key={value} value={value}>{`${value} - ${label}`}</option>
))}
</select>
</optgroup>
))}
</select>
);
// --- Component ---
export function FormattingTab({ config, isLoading }: FormattingTabProps) {
const queryClient = useQueryClient();
@@ -73,8 +72,8 @@ export function FormattingTab({ config, isLoading }: FormattingTabProps) {
const mutation = useMutation({
mutationFn: saveFormattingConfig,
onSuccess: () => {
toast.success('Formatting settings saved!');
queryClient.invalidateQueries({ queryKey: ['config'] });
toast.success("Formatting settings saved!");
queryClient.invalidateQueries({ queryKey: ["config"] });
},
onError: (error) => {
toast.error(`Failed to save settings: ${error.message}`);
@@ -86,17 +85,19 @@ export function FormattingTab({ config, isLoading }: FormattingTabProps) {
});
// Correctly register the refs for react-hook-form while also holding a local ref.
const { ref: dirFormatRef, ...dirFormatRest } = register('customDirFormat');
const { ref: trackFormatRef, ...trackFormatRest } = register('customTrackFormat');
const handlePlaceholderSelect = (field: 'customDirFormat' | 'customTrackFormat', inputRef: React.RefObject<HTMLInputElement | null>) => (value: string) => {
if (!value || !inputRef.current) return;
const { selectionStart, selectionEnd } = inputRef.current;
const currentValue = inputRef.current.value;
const newValue = currentValue.substring(0, selectionStart ?? 0) + value + currentValue.substring(selectionEnd ?? 0);
setValue(field, newValue);
};
const { ref: dirFormatRef, ...dirFormatRest } = register("customDirFormat");
const { ref: trackFormatRef, ...trackFormatRest } = register("customTrackFormat");
const handlePlaceholderSelect =
(field: "customDirFormat" | "customTrackFormat", inputRef: React.RefObject<HTMLInputElement | null>) =>
(value: string) => {
if (!value || !inputRef.current) return;
const { selectionStart, selectionEnd } = inputRef.current;
const currentValue = inputRef.current.value;
const newValue =
currentValue.substring(0, selectionStart ?? 0) + value + currentValue.substring(selectionEnd ?? 0);
setValue(field, newValue);
};
const onSubmit: SubmitHandler<FormattingSettings> = (data) => {
mutation.mutate(data);
@@ -111,45 +112,54 @@ export function FormattingTab({ config, isLoading }: FormattingTabProps) {
<div className="space-y-4">
<h3 className="text-xl font-semibold">File Naming</h3>
<div className="flex flex-col gap-2">
<label htmlFor="customDirFormat">Custom Directory Format</label>
<input
id="customDirFormat"
type="text"
{...dirFormatRest}
ref={(e) => {
dirFormatRef(e);
dirInputRef.current = e;
}}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<PlaceholderSelector onSelect={handlePlaceholderSelect('customDirFormat', dirInputRef)} />
<label htmlFor="customDirFormat">Custom Directory Format</label>
<input
id="customDirFormat"
type="text"
{...dirFormatRest}
ref={(e) => {
dirFormatRef(e);
dirInputRef.current = e;
}}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<PlaceholderSelector onSelect={handlePlaceholderSelect("customDirFormat", dirInputRef)} />
</div>
<div className="flex flex-col gap-2">
<label htmlFor="customTrackFormat">Custom Track Format</label>
<input
id="customTrackFormat"
type="text"
{...trackFormatRest}
ref={(e) => {
trackFormatRef(e);
trackInputRef.current = e;
}}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<PlaceholderSelector onSelect={handlePlaceholderSelect('customTrackFormat', trackInputRef)} />
<label htmlFor="customTrackFormat">Custom Track Format</label>
<input
id="customTrackFormat"
type="text"
{...trackFormatRest}
ref={(e) => {
trackFormatRef(e);
trackInputRef.current = e;
}}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<PlaceholderSelector onSelect={handlePlaceholderSelect("customTrackFormat", trackInputRef)} />
</div>
<div className="flex items-center justify-between">
<label htmlFor="tracknumPaddingToggle">Track Number Padding</label>
<input id="tracknumPaddingToggle" type="checkbox" {...register('tracknumPadding')} className="h-6 w-6 rounded" />
<label htmlFor="tracknumPaddingToggle">Track Number Padding</label>
<input
id="tracknumPaddingToggle"
type="checkbox"
{...register("tracknumPadding")}
className="h-6 w-6 rounded"
/>
</div>
<div className="flex items-center justify-between">
<label htmlFor="saveCoverToggle">Save Album Cover</label>
<input id="saveCoverToggle" type="checkbox" {...register('saveCover')} className="h-6 w-6 rounded" />
<label htmlFor="saveCoverToggle">Save Album Cover</label>
<input id="saveCoverToggle" type="checkbox" {...register("saveCover")} className="h-6 w-6 rounded" />
</div>
</div>
<button type="submit" disabled={mutation.isPending} className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50">
{mutation.isPending ? 'Saving...' : 'Save Formatting Settings'}
<button
type="submit"
disabled={mutation.isPending}
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{mutation.isPending ? "Saving..." : "Save Formatting Settings"}
</button>
</form>
);

View File

@@ -1,8 +1,8 @@
import { useForm } from 'react-hook-form';
import apiClient from '../../lib/api-client';
import { toast } from 'sonner';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useSettings } from '../../contexts/settings-context';
import { useForm } from "react-hook-form";
import apiClient from "../../lib/api-client";
import { toast } from "sonner";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useSettings } from "../../contexts/settings-context";
// --- Type Definitions ---
interface Credential {
@@ -10,11 +10,11 @@ interface Credential {
}
interface GeneralSettings {
service: 'spotify' | 'deezer';
service: "spotify" | "deezer";
spotify: string;
spotifyQuality: 'NORMAL' | 'HIGH' | 'VERY_HIGH';
spotifyQuality: "NORMAL" | "HIGH" | "VERY_HIGH";
deezer: string;
deezerQuality: 'MP3_128' | 'MP3_320' | 'FLAC';
deezerQuality: "MP3_128" | "MP3_320" | "FLAC";
}
interface GeneralTabProps {
@@ -23,20 +23,26 @@ interface GeneralTabProps {
}
// --- API Functions ---
const fetchCredentials = async (service: 'spotify' | 'deezer'): Promise<Credential[]> => {
const fetchCredentials = async (service: "spotify" | "deezer"): Promise<Credential[]> => {
const { data } = await apiClient.get<string[]>(`/credentials/${service}`);
return data.map(name => ({ name }));
return data.map((name) => ({ name }));
};
const saveGeneralConfig = (data: Partial<GeneralSettings>) => apiClient.post('/config', data);
const saveGeneralConfig = (data: Partial<GeneralSettings>) => apiClient.post("/config", data);
// --- Component ---
export function GeneralTab({ config, isLoading: isConfigLoading }: GeneralTabProps) {
const queryClient = useQueryClient();
const { settings: globalSettings, isLoading: settingsLoading } = useSettings();
const { data: spotifyAccounts, isLoading: spotifyLoading } = useQuery({ queryKey: ['credentials', 'spotify'], queryFn: () => fetchCredentials('spotify') });
const { data: deezerAccounts, isLoading: deezerLoading } = useQuery({ queryKey: ['credentials', 'deezer'], queryFn: () => fetchCredentials('deezer') });
const { data: spotifyAccounts, isLoading: spotifyLoading } = useQuery({
queryKey: ["credentials", "spotify"],
queryFn: () => fetchCredentials("spotify"),
});
const { data: deezerAccounts, isLoading: deezerLoading } = useQuery({
queryKey: ["credentials", "deezer"],
queryFn: () => fetchCredentials("deezer"),
});
const { register, handleSubmit } = useForm<GeneralSettings>({
values: config,
@@ -45,8 +51,8 @@ export function GeneralTab({ config, isLoading: isConfigLoading }: GeneralTabPro
const mutation = useMutation({
mutationFn: saveGeneralConfig,
onSuccess: () => {
toast.success('General settings saved!');
queryClient.invalidateQueries({ queryKey: ['config'] });
toast.success("General settings saved!");
queryClient.invalidateQueries({ queryKey: ["config"] });
},
onError: (e: Error) => toast.error(`Failed to save: ${e.message}`),
});
@@ -58,91 +64,99 @@ export function GeneralTab({ config, isLoading: isConfigLoading }: GeneralTabPro
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-8">
<div className="space-y-4">
<h3 className="text-xl font-semibold">Service Defaults</h3>
<div className="flex flex-col gap-2">
<label htmlFor="service">Default Service</label>
<select
id="service"
{...register('service')}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="spotify">Spotify</option>
<option value="deezer">Deezer</option>
</select>
</div>
<div className="space-y-4">
<h3 className="text-xl font-semibold">Service Defaults</h3>
<div className="flex flex-col gap-2">
<label htmlFor="service">Default Service</label>
<select
id="service"
{...register("service")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="spotify">Spotify</option>
<option value="deezer">Deezer</option>
</select>
</div>
</div>
<div className="space-y-4">
<h3 className="text-xl font-semibold">Spotify Settings</h3>
<div className="flex flex-col gap-2">
<label htmlFor="spotifyAccount">Active Spotify Account</label>
<select
id="spotifyAccount"
{...register('spotify')}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
{spotifyAccounts?.map(acc => <option key={acc.name} value={acc.name}>{acc.name}</option>)}
</select>
</div>
<div className="flex flex-col gap-2">
<label htmlFor="spotifyQuality">Spotify Quality</label>
<select
id="spotifyQuality"
{...register('spotifyQuality')}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="NORMAL">OGG 96kbps</option>
<option value="HIGH">OGG 160kbps</option>
<option value="VERY_HIGH">OGG 320kbps (Premium)</option>
</select>
</div>
<div className="space-y-4">
<h3 className="text-xl font-semibold">Spotify Settings</h3>
<div className="flex flex-col gap-2">
<label htmlFor="spotifyAccount">Active Spotify Account</label>
<select
id="spotifyAccount"
{...register("spotify")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
{spotifyAccounts?.map((acc) => (
<option key={acc.name} value={acc.name}>
{acc.name}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-2">
<label htmlFor="spotifyQuality">Spotify Quality</label>
<select
id="spotifyQuality"
{...register("spotifyQuality")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="NORMAL">OGG 96kbps</option>
<option value="HIGH">OGG 160kbps</option>
<option value="VERY_HIGH">OGG 320kbps (Premium)</option>
</select>
</div>
</div>
<div className="space-y-4">
<h3 className="text-xl font-semibold">Deezer Settings</h3>
<div className="flex flex-col gap-2">
<label htmlFor="deezerAccount">Active Deezer Account</label>
<select
id="deezerAccount"
{...register('deezer')}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
{deezerAccounts?.map(acc => <option key={acc.name} value={acc.name}>{acc.name}</option>)}
</select>
</div>
<div className="flex flex-col gap-2">
<label htmlFor="deezerQuality">Deezer Quality</label>
<select
id="deezerQuality"
{...register('deezerQuality')}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="MP3_128">MP3 128kbps</option>
<option value="MP3_320">MP3 320kbps</option>
<option value="FLAC">FLAC (HiFi)</option>
</select>
</div>
<div className="space-y-4">
<h3 className="text-xl font-semibold">Deezer Settings</h3>
<div className="flex flex-col gap-2">
<label htmlFor="deezerAccount">Active Deezer Account</label>
<select
id="deezerAccount"
{...register("deezer")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
{deezerAccounts?.map((acc) => (
<option key={acc.name} value={acc.name}>
{acc.name}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-2">
<label htmlFor="deezerQuality">Deezer Quality</label>
<select
id="deezerQuality"
{...register("deezerQuality")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="MP3_128">MP3 128kbps</option>
<option value="MP3_320">MP3 320kbps</option>
<option value="FLAC">FLAC (HiFi)</option>
</select>
</div>
</div>
<div className="space-y-4">
<h3 className="text-xl font-semibold">Content Filters</h3>
<div className="form-item--row">
<label>Filter Explicit Content</label>
<div className="flex items-center gap-2">
<span className={`font-semibold ${globalSettings?.explicitFilter ? 'text-green-400' : 'text-red-400'}`}>
{globalSettings?.explicitFilter ? 'Enabled' : 'Disabled'}
</span>
<span className="text-xs bg-gray-600 text-white px-2 py-1 rounded-full">ENV</span>
</div>
</div>
<p className="text-sm text-gray-500 mt-1">
The explicit content filter is controlled by an environment variable and cannot be changed here.
</p>
<div className="space-y-4">
<h3 className="text-xl font-semibold">Content Filters</h3>
<div className="form-item--row">
<label>Filter Explicit Content</label>
<div className="flex items-center gap-2">
<span className={`font-semibold ${globalSettings?.explicitFilter ? "text-green-400" : "text-red-400"}`}>
{globalSettings?.explicitFilter ? "Enabled" : "Disabled"}
</span>
<span className="text-xs bg-gray-600 text-white px-2 py-1 rounded-full">ENV</span>
</div>
</div>
<p className="text-sm text-gray-500 mt-1">
The explicit content filter is controlled by an environment variable and cannot be changed here.
</p>
</div>
<button type="submit" disabled={mutation.isPending} className="btn-primary">
{mutation.isPending ? 'Saving...' : 'Save General Settings'}
{mutation.isPending ? "Saving..." : "Save General Settings"}
</button>
</form>
);

View File

@@ -1,8 +1,8 @@
import { useEffect } from 'react';
import { useForm, Controller } from 'react-hook-form';
import apiClient from '../../lib/api-client';
import { toast } from 'sonner';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useEffect } from "react";
import { useForm, Controller } from "react-hook-form";
import apiClient from "../../lib/api-client";
import { toast } from "sonner";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
// --- Type Definitions ---
interface SpotifyApiSettings {
@@ -18,16 +18,16 @@ interface WebhookSettings {
// --- API Functions ---
const fetchSpotifyApiConfig = async (): Promise<SpotifyApiSettings> => {
const { data } = await apiClient.get('/credentials/spotify_api_config');
const { data } = await apiClient.get("/credentials/spotify_api_config");
return data;
};
const saveSpotifyApiConfig = (data: SpotifyApiSettings) => apiClient.put('/credentials/spotify_api_config', data);
const saveSpotifyApiConfig = (data: SpotifyApiSettings) => apiClient.put("/credentials/spotify_api_config", data);
const fetchWebhookConfig = async (): Promise<WebhookSettings> => {
// Mock a response since backend endpoint doesn't exist
// This will prevent the UI from crashing.
return Promise.resolve({
url: '',
url: "",
events: [],
available_events: ["download_start", "download_complete", "download_failed", "watch_added"],
});
@@ -39,120 +39,153 @@ const saveWebhookConfig = (data: Partial<WebhookSettings>) => {
const testWebhook = (url: string) => {
toast.info("Webhook testing is not available.");
return Promise.resolve(url);
}
};
// --- Components ---
function SpotifyApiForm() {
const queryClient = useQueryClient();
const { data, isLoading } = useQuery({ queryKey: ['spotifyApiConfig'], queryFn: fetchSpotifyApiConfig });
const { register, handleSubmit, reset } = useForm<SpotifyApiSettings>();
const queryClient = useQueryClient();
const { data, isLoading } = useQuery({ queryKey: ["spotifyApiConfig"], queryFn: fetchSpotifyApiConfig });
const { register, handleSubmit, reset } = useForm<SpotifyApiSettings>();
const mutation = useMutation({
mutationFn: saveSpotifyApiConfig,
onSuccess: () => {
toast.success('Spotify API settings saved!');
queryClient.invalidateQueries({ queryKey: ['spotifyApiConfig'] });
},
onError: (e) => toast.error(`Failed to save: ${e.message}`),
});
const mutation = useMutation({
mutationFn: saveSpotifyApiConfig,
onSuccess: () => {
toast.success("Spotify API settings saved!");
queryClient.invalidateQueries({ queryKey: ["spotifyApiConfig"] });
},
onError: (e) => toast.error(`Failed to save: ${e.message}`),
});
useEffect(() => { if (data) reset(data); }, [data, reset]);
useEffect(() => {
if (data) reset(data);
}, [data, reset]);
const onSubmit = (formData: SpotifyApiSettings) => mutation.mutate(formData);
const onSubmit = (formData: SpotifyApiSettings) => mutation.mutate(formData);
if (isLoading) return <p>Loading Spotify API settings...</p>;
if (isLoading) return <p>Loading Spotify API settings...</p>;
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className="flex flex-col gap-2">
<label htmlFor="client_id">Client ID</label>
<input id="client_id" type="password" {...register('client_id')} className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Optional"/>
</div>
<div className="flex flex-col gap-2">
<label htmlFor="client_secret">Client Secret</label>
<input id="client_secret" type="password" {...register('client_secret')} className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Optional" />
</div>
<button type="submit" disabled={mutation.isPending} className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50">
{mutation.isPending ? 'Saving...' : 'Save Spotify API'}
</button>
</form>
);
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className="flex flex-col gap-2">
<label htmlFor="client_id">Client ID</label>
<input
id="client_id"
type="password"
{...register("client_id")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="Optional"
/>
</div>
<div className="flex flex-col gap-2">
<label htmlFor="client_secret">Client Secret</label>
<input
id="client_secret"
type="password"
{...register("client_secret")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="Optional"
/>
</div>
<button
type="submit"
disabled={mutation.isPending}
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{mutation.isPending ? "Saving..." : "Save Spotify API"}
</button>
</form>
);
}
function WebhookForm() {
const queryClient = useQueryClient();
const { data, isLoading } = useQuery({ queryKey: ['webhookConfig'], queryFn: fetchWebhookConfig });
const { register, handleSubmit, control, reset, watch } = useForm<WebhookSettings>();
const currentUrl = watch('url');
const queryClient = useQueryClient();
const { data, isLoading } = useQuery({ queryKey: ["webhookConfig"], queryFn: fetchWebhookConfig });
const { register, handleSubmit, control, reset, watch } = useForm<WebhookSettings>();
const currentUrl = watch("url");
const mutation = useMutation({
mutationFn: saveWebhookConfig,
onSuccess: () => {
// No toast needed since the function shows one
queryClient.invalidateQueries({ queryKey: ['webhookConfig'] });
},
onError: (e) => toast.error(`Failed to save: ${e.message}`),
});
const mutation = useMutation({
mutationFn: saveWebhookConfig,
onSuccess: () => {
// No toast needed since the function shows one
queryClient.invalidateQueries({ queryKey: ["webhookConfig"] });
},
onError: (e) => toast.error(`Failed to save: ${e.message}`),
});
const testMutation = useMutation({
mutationFn: testWebhook,
onSuccess: () => {
// No toast needed
},
onError: (e) => toast.error(`Webhook test failed: ${e.message}`),
});
const testMutation = useMutation({
mutationFn: testWebhook,
onSuccess: () => {
// No toast needed
},
onError: (e) => toast.error(`Webhook test failed: ${e.message}`),
});
useEffect(() => { if (data) reset(data); }, [data, reset]);
useEffect(() => {
if (data) reset(data);
}, [data, reset]);
const onSubmit = (formData: WebhookSettings) => mutation.mutate(formData);
const onSubmit = (formData: WebhookSettings) => mutation.mutate(formData);
if (isLoading) return <p>Loading Webhook settings...</p>;
if (isLoading) return <p>Loading Webhook settings...</p>;
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
<div className="flex flex-col gap-2">
<label htmlFor="webhookUrl">Webhook URL</label>
<input id="webhookUrl" type="url" {...register('url')} className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="https://example.com/webhook" />
</div>
<div className="flex flex-col gap-2">
<label>Webhook Events</label>
<div className="grid grid-cols-2 gap-4 pt-2">
{data?.available_events.map((event) => (
<Controller
key={event}
name="events"
control={control}
render={({ field }) => (
<label className="flex items-center gap-2">
<input
type="checkbox"
className="h-5 w-5 rounded"
checked={field.value?.includes(event) ?? false}
onChange={(e) => {
const value = field.value || [];
const newValues = e.target.checked
? [...value, event]
: value.filter((v) => v !== event);
field.onChange(newValues);
}}
/>
<span className="capitalize">{event.replace(/_/g, ' ')}</span>
</label>
)}
/>
))}
</div>
</div>
<div className="flex gap-2">
<button type="submit" disabled={mutation.isPending} className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50">
{mutation.isPending ? 'Saving...' : 'Save Webhook'}
</button>
<button type="button" onClick={() => testMutation.mutate(currentUrl)} disabled={!currentUrl || testMutation.isPending} className="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 disabled:opacity-50">
Test
</button>
</div>
</form>
);
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
<div className="flex flex-col gap-2">
<label htmlFor="webhookUrl">Webhook URL</label>
<input
id="webhookUrl"
type="url"
{...register("url")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="https://example.com/webhook"
/>
</div>
<div className="flex flex-col gap-2">
<label>Webhook Events</label>
<div className="grid grid-cols-2 gap-4 pt-2">
{data?.available_events.map((event) => (
<Controller
key={event}
name="events"
control={control}
render={({ field }) => (
<label className="flex items-center gap-2">
<input
type="checkbox"
className="h-5 w-5 rounded"
checked={field.value?.includes(event) ?? false}
onChange={(e) => {
const value = field.value || [];
const newValues = e.target.checked ? [...value, event] : value.filter((v) => v !== event);
field.onChange(newValues);
}}
/>
<span className="capitalize">{event.replace(/_/g, " ")}</span>
</label>
)}
/>
))}
</div>
</div>
<div className="flex gap-2">
<button
type="submit"
disabled={mutation.isPending}
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{mutation.isPending ? "Saving..." : "Save Webhook"}
</button>
<button
type="button"
onClick={() => testMutation.mutate(currentUrl)}
disabled={!currentUrl || testMutation.isPending}
className="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 disabled:opacity-50"
>
Test
</button>
</div>
</form>
);
}
export function ServerTab() {
@@ -166,7 +199,9 @@ export function ServerTab() {
<hr className="border-gray-600" />
<div>
<h3 className="text-xl font-semibold">Webhooks</h3>
<p className="text-sm text-gray-500 mt-1">Get notifications for events like download completion. (Currently disabled)</p>
<p className="text-sm text-gray-500 mt-1">
Get notifications for events like download completion. (Currently disabled)
</p>
<WebhookForm />
</div>
</div>

View File

@@ -1,13 +1,13 @@
import { useEffect } from 'react';
import { useForm, type SubmitHandler, Controller } from 'react-hook-form';
import apiClient from '../../lib/api-client';
import { toast } from 'sonner';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useEffect } from "react";
import { useForm, type SubmitHandler, Controller } from "react-hook-form";
import apiClient from "../../lib/api-client";
import { toast } from "sonner";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
// --- Type Definitions ---
const ALBUM_GROUPS = ["album", "single", "compilation", "appears_on"] as const;
type AlbumGroup = typeof ALBUM_GROUPS[number];
type AlbumGroup = (typeof ALBUM_GROUPS)[number];
interface WatchSettings {
enabled: boolean;
@@ -17,12 +17,12 @@ interface WatchSettings {
// --- API Functions ---
const fetchWatchConfig = async (): Promise<WatchSettings> => {
const { data } = await apiClient.get('/config/watch');
const { data } = await apiClient.get("/config/watch");
return data;
};
const saveWatchConfig = async (data: Partial<WatchSettings>) => {
const { data: response } = await apiClient.post('/config/watch', data);
const { data: response } = await apiClient.post("/config/watch", data);
return response;
};
@@ -31,15 +31,15 @@ export function WatchTab() {
const queryClient = useQueryClient();
const { data: config, isLoading } = useQuery({
queryKey: ['watchConfig'],
queryKey: ["watchConfig"],
queryFn: fetchWatchConfig,
});
const mutation = useMutation({
mutationFn: saveWatchConfig,
onSuccess: () => {
toast.success('Watch settings saved successfully!');
queryClient.invalidateQueries({ queryKey: ['watchConfig'] });
toast.success("Watch settings saved successfully!");
queryClient.invalidateQueries({ queryKey: ["watchConfig"] });
},
onError: (error) => {
toast.error(`Failed to save settings: ${error.message}`);
@@ -56,8 +56,8 @@ export function WatchTab() {
const onSubmit: SubmitHandler<WatchSettings> = (data) => {
mutation.mutate({
...data,
watchPollIntervalSeconds: Number(data.watchPollIntervalSeconds),
...data,
watchPollIntervalSeconds: Number(data.watchPollIntervalSeconds),
});
};
@@ -67,54 +67,60 @@ export function WatchTab() {
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-8">
<div className="space-y-4">
<h3 className="text-xl font-semibold">Watchlist Behavior</h3>
<div className="flex items-center justify-between">
<label htmlFor="watchEnabledToggle">Enable Watchlist</label>
<input id="watchEnabledToggle" type="checkbox" {...register('enabled')} className="h-6 w-6 rounded" />
</div>
<div className="flex flex-col gap-2">
<label htmlFor="watchPollIntervalSeconds">Watch Poll Interval (seconds)</label>
<input id="watchPollIntervalSeconds" type="number" min="60" {...register('watchPollIntervalSeconds')} className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500" />
<p className="text-sm text-gray-500 mt-1">
How often to check watched items for updates.
</p>
</div>
<div className="space-y-4">
<h3 className="text-xl font-semibold">Watchlist Behavior</h3>
<div className="flex items-center justify-between">
<label htmlFor="watchEnabledToggle">Enable Watchlist</label>
<input id="watchEnabledToggle" type="checkbox" {...register("enabled")} className="h-6 w-6 rounded" />
</div>
<div className="space-y-4">
<h3 className="text-xl font-semibold">Artist Album Groups</h3>
<p className="text-sm text-gray-500">Select which album groups to monitor for watched artists.</p>
<div className="grid grid-cols-2 gap-4 pt-2">
{ALBUM_GROUPS.map((group) => (
<Controller
key={group}
name="watchedArtistAlbumGroup"
control={control}
render={({ field }) => (
<label className="flex items-center gap-2">
<input
type="checkbox"
className="h-5 w-5 rounded"
checked={field.value?.includes(group) ?? false}
onChange={(e) => {
const value = field.value || [];
const newValues = e.target.checked
? [...value, group]
: value.filter((v) => v !== group);
field.onChange(newValues);
}}
/>
<span className="capitalize">{group.replace('_', ' ')}</span>
</label>
)}
/>
))}
</div>
<div className="flex flex-col gap-2">
<label htmlFor="watchPollIntervalSeconds">Watch Poll Interval (seconds)</label>
<input
id="watchPollIntervalSeconds"
type="number"
min="60"
{...register("watchPollIntervalSeconds")}
className="block w-full p-2 border rounded-md bg-gray-50 dark:bg-gray-800 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<p className="text-sm text-gray-500 mt-1">How often to check watched items for updates.</p>
</div>
</div>
<button type="submit" disabled={mutation.isPending} className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50">
{mutation.isPending ? 'Saving...' : 'Save Watch Settings'}
<div className="space-y-4">
<h3 className="text-xl font-semibold">Artist Album Groups</h3>
<p className="text-sm text-gray-500">Select which album groups to monitor for watched artists.</p>
<div className="grid grid-cols-2 gap-4 pt-2">
{ALBUM_GROUPS.map((group) => (
<Controller
key={group}
name="watchedArtistAlbumGroup"
control={control}
render={({ field }) => (
<label className="flex items-center gap-2">
<input
type="checkbox"
className="h-5 w-5 rounded"
checked={field.value?.includes(group) ?? false}
onChange={(e) => {
const value = field.value || [];
const newValues = e.target.checked ? [...value, group] : value.filter((v) => v !== group);
field.onChange(newValues);
}}
/>
<span className="capitalize">{group.replace("_", " ")}</span>
</label>
)}
/>
))}
</div>
</div>
<button
type="submit"
disabled={mutation.isPending}
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{mutation.isPending ? "Saving..." : "Save Watch Settings"}
</button>
</form>
);

View File

@@ -1,117 +1,282 @@
import { useState, useCallback, type ReactNode, useEffect, useRef } from 'react';
import apiClient from '../lib/api-client';
import { QueueContext, type QueueItem } from './queue-context';
import { useState, useCallback, type ReactNode, useEffect, useRef } from "react";
import apiClient from "../lib/api-client";
import { QueueContext, type QueueItem, type DownloadType, type QueueStatus } from "./queue-context";
import { toast } from "sonner";
import { v4 as uuidv4 } from "uuid";
// --- Helper Types ---
interface TaskStatus {
status: 'downloading' | 'completed' | 'error' | 'queued';
progress?: number;
speed?: string;
size?: string;
eta?: string;
message?: string;
// This represents the raw status object from the backend polling endpoint
interface TaskStatusDTO {
status: QueueStatus;
message?: string;
can_retry?: boolean;
// Progress indicators
progress?: number;
speed?: string;
size?: string;
eta?: string;
// Multi-track progress
current_track?: number;
total_tracks?: number;
summary?: {
successful_tracks: number;
skipped_tracks: number;
failed_tracks: number;
failed_track_details: { name: string; reason: string }[];
};
}
const isTerminalStatus = (status: QueueStatus) => ["completed", "error", "cancelled", "skipped"].includes(status);
export function QueueProvider({ children }: { children: ReactNode }) {
const [items, setItems] = useState<QueueItem[]>([]);
const [isVisible, setIsVisible] = useState(false);
const pollingIntervals = useRef<Record<string, number>>({});
const [items, setItems] = useState<QueueItem[]>(() => {
try {
const storedItems = localStorage.getItem("queueItems");
return storedItems ? JSON.parse(storedItems) : [];
} catch {
return [];
}
});
const [isVisible, setIsVisible] = useState(false);
const pollingIntervals = useRef<Record<string, number>>({});
// --- Core Action: Add Item ---
const addItem = useCallback(async (item: Omit<QueueItem, 'status'>) => {
const newItem: QueueItem = { ...item, status: 'queued' };
setItems(prev => [...prev, newItem]);
toggleVisibility();
// --- Persistence ---
useEffect(() => {
localStorage.setItem("queueItems", JSON.stringify(items));
}, [items]);
const stopPolling = useCallback((internalId: string) => {
if (pollingIntervals.current[internalId]) {
clearInterval(pollingIntervals.current[internalId]);
delete pollingIntervals.current[internalId];
}
}, []);
// --- Polling Logic ---
const startPolling = useCallback(
(internalId: string, taskId: string) => {
if (pollingIntervals.current[internalId]) return;
const intervalId = window.setInterval(async () => {
try {
// This endpoint should initiate the download and return a task ID
const response = await apiClient.post<{ taskId: string }>(`/download/${item.type}`, { id: item.id });
const { taskId } = response.data;
const response = await apiClient.get<TaskStatusDTO>(`/download/status/${taskId}`);
const statusUpdate = response.data;
// Update item with taskId and start polling
setItems(prev => prev.map(i => i.id === item.id ? { ...i, taskId, status: 'pending' } : i));
startPolling(taskId);
setItems((prev) =>
prev.map((item) => {
if (item.id === internalId) {
const updatedItem: QueueItem = {
...item,
status: statusUpdate.status,
progress: statusUpdate.progress,
speed: statusUpdate.speed,
size: statusUpdate.size,
eta: statusUpdate.eta,
error: statusUpdate.status === "error" ? statusUpdate.message : undefined,
canRetry: statusUpdate.can_retry,
currentTrackNumber: statusUpdate.current_track,
totalTracks: statusUpdate.total_tracks,
summary: statusUpdate.summary
? {
successful: statusUpdate.summary.successful_tracks,
skipped: statusUpdate.summary.skipped_tracks,
failed: statusUpdate.summary.failed_tracks,
failedTracks: statusUpdate.summary.failed_track_details,
}
: item.summary,
};
if (isTerminalStatus(statusUpdate.status)) {
stopPolling(internalId);
}
return updatedItem;
}
return item;
}),
);
} catch (error) {
console.error(`Failed to start download for ${item.name}:`, error);
setItems(prev => prev.map(i => i.id === item.id ? { ...i, status: 'error', error: 'Failed to start download' } : i));
console.error(`Polling failed for task ${taskId}:`, error);
stopPolling(internalId);
setItems((prev) =>
prev.map((i) =>
i.id === internalId
? {
...i,
status: "error",
error: "Connection lost",
}
: i,
),
);
}
}, []);
}, 2000); // Poll every 2 seconds
// --- Polling Logic ---
const startPolling = (taskId: string) => {
if (pollingIntervals.current[taskId]) return; // Already polling
pollingIntervals.current[internalId] = intervalId;
},
[stopPolling],
);
const intervalId = window.setInterval(async () => {
try {
const response = await apiClient.get<TaskStatus>(`/download/status/${taskId}`);
const statusUpdate = response.data;
// --- Core Action: Add Item ---
const addItem = useCallback(
async (item: { name: string; type: DownloadType; spotifyId: string }) => {
const internalId = uuidv4();
const newItem: QueueItem = {
...item,
id: internalId,
status: "queued",
};
setItems((prev) => [...prev, newItem]);
if (!isVisible) setIsVisible(true);
setItems(prev => prev.map(item => {
if (item.taskId === taskId) {
const updatedItem = {
...item,
status: statusUpdate.status,
progress: statusUpdate.progress,
speed: statusUpdate.speed,
size: statusUpdate.size,
eta: statusUpdate.eta,
error: statusUpdate.status === 'error' ? statusUpdate.message : undefined,
};
try {
const response = await apiClient.post<{ task_id: string }>(`/download`, {
url: `https://open.spotify.com/${item.type}/${item.spotifyId}`,
});
const { task_id } = response.data;
setItems((prev) =>
prev.map((i) => (i.id === internalId ? { ...i, taskId: task_id, status: "initializing" } : i)),
);
startPolling(internalId, task_id);
} catch (error) {
console.error(`Failed to start download for ${item.name}:`, error);
toast.error(`Failed to start download for ${item.name}`);
setItems((prev) =>
prev.map((i) =>
i.id === internalId
? {
...i,
status: "error",
error: "Failed to start download task.",
}
: i,
),
);
}
},
[isVisible, startPolling],
);
if (statusUpdate.status === 'completed' || statusUpdate.status === 'error') {
stopPolling(taskId);
}
return updatedItem;
}
return item;
}));
} catch (error) {
console.error(`Polling failed for task ${taskId}:`, error);
stopPolling(taskId);
setItems(prev => prev.map(i => i.taskId === taskId ? { ...i, status: 'error', error: 'Connection lost' } : i));
const clearAllPolls = useCallback(() => {
Object.values(pollingIntervals.current).forEach(clearInterval);
}, []);
// --- Load existing tasks on startup ---
useEffect(() => {
const syncActiveTasks = async () => {
try {
const response = await apiClient.get<QueueItem[]>("/download/active");
const activeTasks = response.data;
// Basic reconciliation
setItems((prevItems) => {
const newItems = [...prevItems];
activeTasks.forEach((task) => {
if (!newItems.some((item) => item.taskId === task.taskId)) {
newItems.push({
...task,
id: task.taskId || uuidv4(),
});
}
}, 2000); // Poll every 2 seconds
});
return newItems;
});
pollingIntervals.current[taskId] = intervalId;
activeTasks.forEach((item) => {
if (item.id && item.taskId && !isTerminalStatus(item.status)) {
startPolling(item.id, item.taskId);
}
});
} catch (error) {
console.error("Failed to sync active tasks:", error);
}
};
syncActiveTasks();
const stopPolling = (taskId: string) => {
clearInterval(pollingIntervals.current[taskId]);
delete pollingIntervals.current[taskId];
};
// restart polling for any non-terminal items from localStorage
items.forEach((item) => {
if (item.id && item.taskId && !isTerminalStatus(item.status)) {
startPolling(item.id, item.taskId);
}
});
// Cleanup on unmount
useEffect(() => {
return () => {
Object.values(pollingIntervals.current).forEach(clearInterval);
};
}, []);
return clearAllPolls;
// This effect should only run once on mount to initialize the queue.
// We are intentionally omitting 'items' as a dependency to prevent re-runs.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [clearAllPolls, startPolling]);
// --- Other Actions ---
const removeItem = useCallback((id: string) => {
const itemToRemove = items.find(i => i.id === id);
if (itemToRemove && itemToRemove.taskId) {
stopPolling(itemToRemove.taskId);
// Optionally, call an API to cancel the backend task
// apiClient.post(`/download/cancel/${itemToRemove.taskId}`);
// --- Other Actions ---
const removeItem = useCallback(
async (id: string) => {
const itemToRemove = items.find((i) => i.id === id);
if (itemToRemove) {
stopPolling(itemToRemove.id);
if (itemToRemove.taskId) {
try {
await apiClient.post(`/download/cancel/${itemToRemove.taskId}`);
toast.success(`Cancelled download: ${itemToRemove.name}`);
} catch {
toast.error(`Failed to cancel download: ${itemToRemove.name}`);
}
}
setItems(prev => prev.filter(item => item.id !== id));
}, [items]);
}
setItems((prev) => prev.filter((item) => item.id !== id));
},
[items, stopPolling],
);
const clearQueue = useCallback(() => {
Object.values(pollingIntervals.current).forEach(clearInterval);
pollingIntervals.current = {};
setItems([]);
// Optionally, call an API to cancel all tasks
}, []);
const retryItem = useCallback(
async (id: string) => {
const itemToRetry = items.find((i) => i.id === id);
if (!itemToRetry || !itemToRetry.spotifyId) return;
const toggleVisibility = useCallback(() => setIsVisible(prev => !prev), []);
// Remove the old item
setItems((prev) => prev.filter((item) => item.id !== id));
const value = { items, isVisible, addItem, removeItem, clearQueue, toggleVisibility };
// Add it again
await addItem({
name: itemToRetry.name,
type: itemToRetry.type,
spotifyId: itemToRetry.spotifyId,
});
toast.info(`Retrying download: ${itemToRetry.name}`);
},
[items, addItem],
);
return (
<QueueContext.Provider value={value}>
{children}
</QueueContext.Provider>
);
const clearQueue = useCallback(async () => {
for (const item of items) {
if (item.taskId) {
stopPolling(item.id);
try {
await apiClient.post(`/download/cancel/${item.taskId}`);
} catch (err) {
console.error(`Failed to cancel task ${item.taskId}`, err);
}
}
}
setItems([]);
toast.info("Queue cleared.");
}, [items, stopPolling]);
const clearCompleted = useCallback(() => {
setItems((prev) => prev.filter((item) => !isTerminalStatus(item.status)));
}, []);
const toggleVisibility = useCallback(() => setIsVisible((prev) => !prev), []);
const value = {
items,
isVisible,
addItem,
removeItem,
retryItem,
clearQueue,
toggleVisibility,
clearCompleted,
};
return <QueueContext.Provider value={value}>{children}</QueueContext.Provider>;
}

View File

@@ -1,19 +1,19 @@
import { type ReactNode } from 'react';
import apiClient from '../lib/api-client';
import { SettingsContext, type AppSettings } from './settings-context';
import { useQuery } from '@tanstack/react-query';
import { type ReactNode } from "react";
import apiClient from "../lib/api-client";
import { SettingsContext, type AppSettings } from "./settings-context";
import { useQuery } from "@tanstack/react-query";
// --- Case Conversion Utility ---
// This is added here to simplify the fix and avoid module resolution issues.
function snakeToCamel(str: string): string {
return str.replace(/(_\w)/g, m => m[1].toUpperCase());
return str.replace(/(_\w)/g, (m) => m[1].toUpperCase());
}
function convertKeysToCamelCase(obj: unknown): unknown {
if (Array.isArray(obj)) {
return obj.map(v => convertKeysToCamelCase(v));
return obj.map((v) => convertKeysToCamelCase(v));
}
if (typeof obj === 'object' && obj !== null) {
if (typeof obj === "object" && obj !== null) {
return Object.keys(obj).reduce((acc: Record<string, unknown>, key: string) => {
const camelKey = snakeToCamel(key);
acc[camelKey] = convertKeysToCamelCase((obj as Record<string, unknown>)[key]);
@@ -25,15 +25,15 @@ function convertKeysToCamelCase(obj: unknown): unknown {
// Redefine AppSettings to match the flat structure of the API response
export type FlatAppSettings = {
service: 'spotify' | 'deezer';
service: "spotify" | "deezer";
spotify: string;
spotifyQuality: 'NORMAL' | 'HIGH' | 'VERY_HIGH';
spotifyQuality: "NORMAL" | "HIGH" | "VERY_HIGH";
deezer: string;
deezerQuality: 'MP3_128' | 'MP3_320' | 'FLAC';
deezerQuality: "MP3_128" | "MP3_320" | "FLAC";
maxConcurrentDownloads: number;
realTime: boolean;
fallback: boolean;
convertTo: 'MP3' | 'AAC' | 'OGG' | 'OPUS' | 'FLAC' | 'WAV' | 'ALAC' | '';
convertTo: "MP3" | "AAC" | "OGG" | "OPUS" | "FLAC" | "WAV" | "ALAC" | "";
bitrate: string;
maxRetries: number;
retryDelaySeconds: number;
@@ -44,7 +44,7 @@ export type FlatAppSettings = {
saveCover: boolean;
explicitFilter: boolean;
// Add other fields from the old AppSettings as needed by other parts of the app
watch: AppSettings['watch'];
watch: AppSettings["watch"];
// Add defaults for the new download properties
threads: number;
path: string;
@@ -59,60 +59,60 @@ export type FlatAppSettings = {
};
const defaultSettings: FlatAppSettings = {
service: 'spotify',
spotify: '',
spotifyQuality: 'NORMAL',
deezer: '',
deezerQuality: 'MP3_128',
service: "spotify",
spotify: "",
spotifyQuality: "NORMAL",
deezer: "",
deezerQuality: "MP3_128",
maxConcurrentDownloads: 3,
realTime: false,
fallback: false,
convertTo: '',
bitrate: '',
convertTo: "",
bitrate: "",
maxRetries: 3,
retryDelaySeconds: 5,
retryDelayIncrease: 5,
customDirFormat: '%ar_album%/%album%',
customTrackFormat: '%tracknum%. %music%',
customDirFormat: "%ar_album%/%album%",
customTrackFormat: "%tracknum%. %music%",
tracknumPadding: true,
saveCover: true,
explicitFilter: false,
// Add defaults for the new download properties
threads: 4,
path: '/downloads',
path: "/downloads",
skipExisting: true,
m3u: false,
hlsThreads: 8,
// Add defaults for the new formatting properties
track: '{artist_name}/{album_name}/{track_number} - {track_name}',
album: '{artist_name}/{album_name}',
playlist: 'Playlists/{playlist_name}',
compilation: 'Compilations/{album_name}',
track: "{artist_name}/{album_name}/{track_number} - {track_name}",
album: "{artist_name}/{album_name}",
playlist: "Playlists/{playlist_name}",
compilation: "Compilations/{album_name}",
watch: {
enabled: false,
},
};
const fetchSettings = async (): Promise<FlatAppSettings> => {
const { data } = await apiClient.get('/config');
// Transform the keys before returning the data
return convertKeysToCamelCase(data) as FlatAppSettings;
const { data } = await apiClient.get("/config");
// Transform the keys before returning the data
return convertKeysToCamelCase(data) as FlatAppSettings;
};
export function SettingsProvider({ children }: { children: ReactNode }) {
const { data: settings, isLoading, isError } = useQuery({
queryKey: ['config'],
const {
data: settings,
isLoading,
isError,
} = useQuery({
queryKey: ["config"],
queryFn: fetchSettings,
staleTime: 1000 * 60 * 5, // 5 minutes
refetchOnWindowFocus: false,
});
// Use default settings on error to prevent app crash
const value = { settings: isError ? defaultSettings : (settings || null), isLoading };
const value = { settings: isError ? defaultSettings : settings || null, isLoading };
return (
<SettingsContext.Provider value={value}>
{children}
</SettingsContext.Provider>
);
return <SettingsContext.Provider value={value}>{children}</SettingsContext.Provider>;
}

View File

@@ -1,26 +1,55 @@
import { createContext, useContext } from 'react';
import { createContext, useContext } from "react";
export type DownloadType = "track" | "album" | "artist" | "playlist";
export type QueueStatus =
| "initializing"
| "pending"
| "downloading"
| "processing"
| "completed"
| "error"
| "skipped"
| "cancelled"
| "queued";
export interface QueueItem {
id: string; // This is the Spotify ID
type: 'track' | 'album' | 'artist' | 'playlist';
id: string; // Unique ID for the queue item (can be task_id from backend)
name: string;
// --- Real-time progress fields ---
status: 'pending' | 'downloading' | 'completed' | 'error' | 'queued';
type: DownloadType;
spotifyId: string; // Original Spotify ID
// --- Status and Progress ---
status: QueueStatus;
taskId?: string; // The backend task ID for polling
progress?: number;
error?: string;
canRetry?: boolean;
// --- Single Track Progress ---
progress?: number; // 0-100
speed?: string;
size?: string;
eta?: string;
error?: string;
// --- Multi-Track (Album/Playlist) Progress ---
currentTrackNumber?: number;
totalTracks?: number;
summary?: {
successful: number;
skipped: number;
failed: number;
failedTracks?: { name: string; reason: string }[];
};
}
export interface QueueContextType {
items: QueueItem[];
isVisible: boolean;
addItem: (item: Omit<QueueItem, 'status'>) => void;
addItem: (item: { name: string; type: DownloadType; spotifyId: string }) => void;
removeItem: (id: string) => void;
retryItem: (id: string) => void;
clearQueue: () => void;
toggleVisibility: () => void;
clearCompleted: () => void;
}
export const QueueContext = createContext<QueueContextType | undefined>(undefined);
@@ -28,7 +57,7 @@ export const QueueContext = createContext<QueueContextType | undefined>(undefine
export function useQueue() {
const context = useContext(QueueContext);
if (context === undefined) {
throw new Error('useQueue must be used within a QueueProvider');
throw new Error("useQueue must be used within a QueueProvider");
}
return context;
}

View File

@@ -1,16 +1,16 @@
import { createContext, useContext } from 'react';
import { createContext, useContext } from "react";
// This new type reflects the flat structure of the /api/config response
export interface AppSettings {
service: 'spotify' | 'deezer';
service: "spotify" | "deezer";
spotify: string;
spotifyQuality: 'NORMAL' | 'HIGH' | 'VERY_HIGH';
spotifyQuality: "NORMAL" | "HIGH" | "VERY_HIGH";
deezer: string;
deezerQuality: 'MP3_128' | 'MP3_320' | 'FLAC';
deezerQuality: "MP3_128" | "MP3_320" | "FLAC";
maxConcurrentDownloads: number;
realTime: boolean;
fallback: boolean;
convertTo: 'MP3' | 'AAC' | 'OGG' | 'OPUS' | 'FLAC' | 'WAV' | 'ALAC' | '';
convertTo: "MP3" | "AAC" | "OGG" | "OPUS" | "FLAC" | "WAV" | "ALAC" | "";
bitrate: string;
maxRetries: number;
retryDelaySeconds: number;
@@ -48,7 +48,7 @@ export const SettingsContext = createContext<SettingsContextType | undefined>(un
export function useSettings() {
const context = useContext(SettingsContext);
if (context === undefined) {
throw new Error('useSettings must be used within a SettingsProvider');
throw new Error("useSettings must be used within a SettingsProvider");
}
return context;
}

View File

@@ -1,10 +1,10 @@
import axios from 'axios';
import { toast } from 'sonner';
import axios from "axios";
import { toast } from "sonner";
const apiClient = axios.create({
baseURL: '/api',
baseURL: "/api",
headers: {
'Content-Type': 'application/json',
"Content-Type": "application/json",
},
timeout: 10000, // 10 seconds timeout
});
@@ -12,30 +12,30 @@ const apiClient = axios.create({
// Response interceptor for error handling
apiClient.interceptors.response.use(
(response) => {
const contentType = response.headers['content-type'];
if (contentType && contentType.includes('application/json')) {
const contentType = response.headers["content-type"];
if (contentType && contentType.includes("application/json")) {
return response;
}
// If the response is not JSON, reject it to trigger the error handling
const error = new Error('Invalid response type. Expected JSON.');
toast.error('API Error', {
description: 'Received an invalid response from the server. Expected JSON data.',
const error = new Error("Invalid response type. Expected JSON.");
toast.error("API Error", {
description: "Received an invalid response from the server. Expected JSON data.",
});
return Promise.reject(error);
},
(error) => {
if (error.code === 'ECONNABORTED') {
toast.error('Request Timed Out', {
description: 'The server did not respond in time. Please try again later.',
if (error.code === "ECONNABORTED") {
toast.error("Request Timed Out", {
description: "The server did not respond in time. Please try again later.",
});
} else {
const errorMessage = error.response?.data?.error || error.message || 'An unknown error occurred.';
toast.error('API Error', {
description: errorMessage,
});
const errorMessage = error.response?.data?.error || error.message || "An unknown error occurred.";
toast.error("API Error", {
description: errorMessage,
});
}
return Promise.reject(error);
}
},
);
export default apiClient;

View File

@@ -1,10 +1,10 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { RouterProvider } from '@tanstack/react-router';
import { router } from './router';
import './index.css';
import React from "react";
import ReactDOM from "react-dom/client";
import { RouterProvider } from "@tanstack/react-router";
import { router } from "./router";
import "./index.css";
ReactDOM.createRoot(document.getElementById('root')!).render(
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,

View File

@@ -1,13 +1,13 @@
import { createRouter, createRootRoute, createRoute } from '@tanstack/react-router';
import { Root } from './routes/root';
import { Album } from './routes/album';
import { Artist } from './routes/artist';
import { Track } from './routes/track';
import { Home } from './routes/home';
import { Config } from './routes/config';
import { Playlist } from './routes/playlist';
import { History } from './routes/history';
import { Watchlist } from './routes/watchlist';
import { createRouter, createRootRoute, createRoute } from "@tanstack/react-router";
import { Root } from "./routes/root";
import { Album } from "./routes/album";
import { Artist } from "./routes/artist";
import { Track } from "./routes/track";
import { Home } from "./routes/home";
import { Config } from "./routes/config";
import { Playlist } from "./routes/playlist";
import { History } from "./routes/history";
import { Watchlist } from "./routes/watchlist";
const rootRoute = createRootRoute({
component: Root,
@@ -15,49 +15,49 @@ const rootRoute = createRootRoute({
const indexRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/',
path: "/",
component: Home,
});
const albumRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/album/$albumId',
path: "/album/$albumId",
component: Album,
});
const artistRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/artist/$artistId',
path: "/artist/$artistId",
component: Artist,
});
const trackRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/track/$trackId',
path: "/track/$trackId",
component: Track,
});
const configRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/config',
path: "/config",
component: Config,
});
const playlistRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/playlist/$playlistId',
path: "/playlist/$playlistId",
component: Playlist,
});
const historyRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/history',
path: "/history",
component: History,
});
const watchlistRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/watchlist',
path: "/watchlist",
component: Watchlist,
});
@@ -74,7 +74,7 @@ const routeTree = rootRoute.addChildren([
export const router = createRouter({ routeTree });
declare module '@tanstack/react-router' {
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}

View File

@@ -1,25 +1,31 @@
import { Link, useParams } from '@tanstack/react-router';
import { useEffect, useState } from 'react';
import apiClient from '../lib/api-client';
import { useQueue } from '../contexts/queue-context';
import { useSettings } from '../contexts/settings-context';
import type { AlbumType, TrackType } from '../types/spotify';
import { Link, useParams } from "@tanstack/react-router";
import { useEffect, useState, useContext } from "react";
import apiClient from "../lib/api-client";
import { QueueContext } from "../contexts/queue-context";
import { useSettings } from "../contexts/settings-context";
import type { AlbumType, TrackType } from "../types/spotify";
import { toast } from "sonner";
export const Album = () => {
const { albumId } = useParams({ from: '/album/$albumId' });
const { albumId } = useParams({ from: "/album/$albumId" });
const [album, setAlbum] = useState<AlbumType | null>(null);
const [error, setError] = useState<string | null>(null);
const { addItem, toggleVisibility } = useQueue();
const context = useContext(QueueContext);
const { settings } = useSettings();
if (!context) {
throw new Error("useQueue must be used within a QueueProvider");
}
const { addItem } = context;
useEffect(() => {
const fetchAlbum = async () => {
try {
const response = await apiClient.get(`/album/info?id=${albumId}`);
setAlbum(response.data);
} catch (err) {
setError('Failed to load album');
console.error('Error fetching album:', err);
setError("Failed to load album");
console.error("Error fetching album:", err);
}
};
@@ -29,14 +35,15 @@ export const Album = () => {
}, [albumId]);
const handleDownloadTrack = (track: TrackType) => {
addItem({ id: track.id, type: 'track', name: track.name });
toggleVisibility();
if (!track.id) return;
toast.info(`Adding ${track.name} to queue...`);
addItem({ spotifyId: track.id, type: "track", name: track.name });
};
const handleDownloadAlbum = () => {
if (!album) return;
addItem({ id: album.id, type: 'album', name: album.name });
toggleVisibility();
toast.info(`Adding ${album.name} to queue...`);
addItem({ spotifyId: album.id, type: "album", name: album.name });
};
if (error) {
@@ -59,46 +66,42 @@ export const Album = () => {
);
}
const hasExplicitTrack = album.tracks.items.some(track => track.explicit);
const hasExplicitTrack = album.tracks.items.some((track) => track.explicit);
return (
<div className="space-y-6">
<div className="flex flex-col md:flex-row items-start gap-6">
<img
src={album.images[0]?.url || '/placeholder.jpg'}
src={album.images[0]?.url || "/placeholder.jpg"}
alt={album.name}
className="w-48 h-48 object-cover rounded-lg shadow-lg"
/>
<div className="flex-grow space-y-2">
<h1 className="text-3xl font-bold">{album.name}</h1>
<p className="text-lg text-gray-500 dark:text-gray-400">
By{' '}
By{" "}
{album.artists.map((artist, index) => (
<span key={artist.id}>
<Link
to="/artist/$artistId"
params={{ artistId: artist.id }}
className="hover:underline"
>
<Link to="/artist/$artistId" params={{ artistId: artist.id }} className="hover:underline">
{artist.name}
</Link>
{index < album.artists.length - 1 && ', '}
{index < album.artists.length - 1 && ", "}
</span>
))}
</p>
<p className="text-sm text-gray-400 dark:text-gray-500">
{new Date(album.release_date).getFullYear()} {album.total_tracks} songs
</p>
<p className="text-xs text-gray-400 dark:text-gray-600">
{album.label}
</p>
<p className="text-xs text-gray-400 dark:text-gray-600">{album.label}</p>
</div>
<div className="flex flex-col items-center gap-2">
<button
<button
onClick={handleDownloadAlbum}
disabled={isExplicitFilterEnabled && hasExplicitTrack}
className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed"
title={isExplicitFilterEnabled && hasExplicitTrack ? 'Album contains explicit tracks' : 'Download Full Album'}
title={
isExplicitFilterEnabled && hasExplicitTrack ? "Album contains explicit tracks" : "Download Full Album"
}
>
Download Album
</button>
@@ -111,14 +114,17 @@ export const Album = () => {
{album.tracks.items.map((track, index) => {
if (isExplicitFilterEnabled && track.explicit) {
return (
<div key={index} className="flex items-center justify-between p-3 bg-gray-100 dark:bg-gray-800 rounded-lg opacity-50">
<div className="flex items-center gap-4">
<span className="text-gray-500 dark:text-gray-400 w-8 text-right">{index + 1}</span>
<div
key={index}
className="flex items-center justify-between p-3 bg-gray-100 dark:bg-gray-800 rounded-lg opacity-50"
>
<div className="flex items-center gap-4">
<span className="text-gray-500 dark:text-gray-400 w-8 text-right">{index + 1}</span>
<p className="font-medium text-gray-500">Explicit track filtered</p>
</div>
<span className="text-gray-500">--:--</span>
</div>
)
);
}
return (
<div
@@ -131,15 +137,17 @@ export const Album = () => {
<p className="font-medium">{track.name}</p>
<p className="text-sm text-gray-500 dark:text-gray-400">
{track.artists.map((artist, index) => (
<span key={artist.id}>
<span key={artist.id}>
<Link
to="/artist/$artistId"
params={{ artistId: artist.id }}
params={{
artistId: artist.id,
}}
className="hover:underline"
>
{artist.name}
</Link>
{index < track.artists.length - 1 && ', '}
{index < track.artists.length - 1 && ", "}
</span>
))}
</p>
@@ -148,7 +156,7 @@ export const Album = () => {
<div className="flex items-center gap-4">
<span className="text-gray-500 dark:text-gray-400">
{Math.floor(track.duration_ms / 60000)}:
{((track.duration_ms % 60000) / 1000).toFixed(0).padStart(2, '0')}
{((track.duration_ms % 60000) / 1000).toFixed(0).padStart(2, "0")}
</span>
<button
onClick={() => handleDownloadTrack(track)}
@@ -159,10 +167,10 @@ export const Album = () => {
</button>
</div>
</div>
)
);
})}
</div>
</div>
</div>
);
}
};

View File

@@ -1,253 +1,107 @@
import { Link, useParams } from '@tanstack/react-router';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import apiClient from '../lib/api-client';
import { useQueue } from '../contexts/queue-context';
import type { AlbumType } from '../types/spotify';
interface ArtistInfo {
artist: {
name: string;
images: { url: string }[];
followers: { total: number };
};
topTracks: Track[];
albums: AlbumGroup;
}
interface Track {
id: string;
name:string;
duration_ms: number;
album: {
id: string;
name: string;
images: { url: string }[];
};
}
interface UAlbum extends AlbumType {
is_known?: boolean;
}
interface AlbumGroup {
album: UAlbum[];
single: UAlbum[];
appears_on: UAlbum[];
}
import { Link, useParams } from "@tanstack/react-router";
import { useEffect, useState, useContext } from "react";
import { toast } from "sonner";
import apiClient from "../lib/api-client";
import type { AlbumType, ArtistType, TrackType } from "../types/spotify";
import { QueueContext } from "../contexts/queue-context";
import { useSettings } from "../contexts/settings-context";
export const Artist = () => {
const { artistId } = useParams({ from: '/artist/$artistId' });
const [artistInfo, setArtistInfo] = useState<ArtistInfo | null>(null);
const [isWatched, setIsWatched] = useState(false);
const [isWatchEnabled, setIsWatchEnabled] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const { addItem, toggleVisibility } = useQueue();
const { artistId } = useParams({ from: "/artist/$artistId" });
const [artistInfo, setArtistInfo] = useState<{
artist: ArtistType;
top_tracks: TrackType[];
albums: AlbumType[];
} | null>(null);
const [error, setError] = useState<string | null>(null);
const context = useContext(QueueContext);
const { settings } = useSettings();
if (!context) {
throw new Error("useQueue must be used within a QueueProvider");
}
const { addItem } = context;
useEffect(() => {
const fetchAllData = async () => {
if (!artistId) return;
setIsLoading(true);
const fetchArtistInfo = async () => {
try {
const [infoRes, watchConfigRes, watchStatusRes] = await Promise.all([
apiClient.get<ArtistInfo>(`/artist/info?id=${artistId}`),
apiClient.get('/config/watch'),
apiClient.get(`/artist/watch/status?id=${artistId}`),
]);
setArtistInfo(infoRes.data);
setIsWatchEnabled(watchConfigRes.data.enabled);
setIsWatched(watchStatusRes.data.is_watched);
} catch {
// The API client interceptor will now handle showing the error toast
} finally {
setIsLoading(false);
const response = await apiClient.get(`/artist/info?id=${artistId}`);
setArtistInfo(response.data);
} catch (err) {
setError("Failed to load artist");
console.error(err);
}
};
fetchAllData();
if (artistId) {
fetchArtistInfo();
}
}, [artistId]);
const handleDownloadTrack = (track: Track) => {
addItem({ id: track.id, type: 'track', name: track.name });
toggleVisibility();
const handleDownloadTrack = (track: TrackType) => {
if (!track.id) return;
toast.info(`Adding ${track.name} to queue...`);
addItem({ spotifyId: track.id, type: "track", name: track.name });
};
const handleDownloadAll = () => {
const handleDownloadArtist = () => {
if (!artistId || !artistInfo) return;
addItem({ id: artistId, type: 'artist', name: artistInfo.artist.name });
toggleVisibility();
toast.info(`Adding ${artistInfo.artist.name} to queue...`);
addItem({
spotifyId: artistId,
type: "artist",
name: artistInfo.artist.name,
});
};
const handleWatch = async () => {
if (!artistId) return;
const originalState = isWatched;
setIsWatched(!originalState); // Optimistic update
try {
await apiClient.post(originalState ? '/artist/unwatch' : '/artist/watch', { artistId });
toast.success(`Artist ${originalState ? 'unwatched' : 'watched'} successfully.`);
} catch {
setIsWatched(originalState); // Revert on error
if (error) {
return <div className="text-red-500">{error}</div>;
}
if (!artistInfo) {
return <div>Loading...</div>;
}
const filteredAlbums = artistInfo.albums.filter((album) => {
if (settings?.explicitFilter) {
return !album.name.toLowerCase().includes("remix");
}
};
const handleSync = async () => {
if (!artistId) return;
toast.info('Syncing artist...', { id: 'sync-artist' });
try {
await apiClient.post('/artist/sync', { artistId });
toast.success('Artist sync completed.', { id: 'sync-artist' });
} catch {
toast.error('Artist sync failed.', { id: 'sync-artist' });
}
};
const handleMarkAsKnown = async (albumId: string, known: boolean) => {
if (!artistId) return;
try {
await apiClient.post('/artist/album/mark', { artistId, albumId, known });
setArtistInfo(prev => {
if (!prev) return null;
const updateAlbums = (albums: UAlbum[]) => albums.map(a => a.id === albumId ? { ...a, is_known: known } : a);
return {
...prev,
albums: {
album: updateAlbums(prev.albums.album),
single: updateAlbums(prev.albums.single),
appears_on: updateAlbums(prev.albums.appears_on),
}
}
});
toast.success(`Album marked as ${known ? 'seen' : 'unseen'}.`);
} catch {
// Error toast handled by interceptor
}
};
if (isLoading) return <div>Loading artist...</div>;
if (!artistInfo) return <div className="p-4 text-center">Could not load artist details.</div>;
const { artist, topTracks, albums } = artistInfo;
const renderAlbumCard = (album: UAlbum) => (
<div key={album.id} className="w-40 flex-shrink-0 group relative">
<Link to="/album/$albumId" params={{ albumId: album.id }}>
<img
src={album.images[0]?.url || '/placeholder.jpg'}
alt={album.name}
className={`w-full h-40 object-cover rounded-lg shadow-md group-hover:shadow-lg transition-shadow ${album.is_known ? 'opacity-50' : ''}`}
/>
<p className="mt-2 text-sm font-semibold truncate">{album.name}</p>
<p className="text-xs text-gray-500">{new Date(album.release_date).getFullYear()}</p>
</Link>
{isWatched && (
<button
onClick={() => handleMarkAsKnown(album.id, !album.is_known)}
title={album.is_known ? 'Mark as not seen' : 'Mark as seen'}
className="absolute top-1 right-1 bg-white/70 dark:bg-black/70 p-1.5 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
>
<img src={album.is_known ? '/check.svg' : '/plus-circle.svg'} alt="Mark" className="w-5 h-5" />
</button>
)}
</div>
);
return true;
});
return (
<div className="space-y-8">
{/* Artist Header */}
<div className="flex flex-col md:flex-row items-center gap-8">
<img
src={artist.images[0]?.url || '/placeholder.jpg'}
alt={artist.name}
className="w-48 h-48 rounded-full object-cover shadow-2xl"
/>
<div className="text-center md:text-left flex-grow">
<h1 className="text-5xl font-extrabold">{artist.name}</h1>
<p className="text-gray-500 mt-2">{artist.followers.total.toLocaleString()} followers</p>
<div className="mt-4 flex flex-wrap gap-2 justify-center md:justify-start">
<button
onClick={handleDownloadAll}
className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center justify-center gap-2"
>
<img src="/download.svg" alt="" className="w-5 h-5" />
Download All
</button>
{isWatchEnabled && (
<>
<button
onClick={handleWatch}
className={`px-4 py-2 rounded-lg transition-colors flex items-center justify-center gap-2 ${
isWatched
? 'bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600'
: 'bg-blue-600 text-white hover:bg-blue-700'
}`}
>
<img src={isWatched ? '/eye-crossed.svg' : '/eye.svg'} alt="" className="w-5 h-5" />
{isWatched ? 'Unwatch' : 'Watch'}
</button>
{isWatched && (
<button
onClick={handleSync}
className="p-2 rounded-lg bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors"
title="Sync Artist"
>
<img src="/refresh-cw.svg" alt="Sync" className="w-5 h-5" />
</button>
)}
</>
)}
</div>
</div>
<div className="artist-page">
<div className="artist-header">
<img src={artistInfo.artist.images[0]?.url} alt={artistInfo.artist.name} className="artist-image" />
<h1>{artistInfo.artist.name}</h1>
<button onClick={handleDownloadArtist} className="download-all-btn">
Download All
</button>
</div>
{/* Top Tracks */}
<section>
<h2 className="text-2xl font-bold mb-4">Top Tracks</h2>
<div className="space-y-2">
{topTracks.map((track) => (
<div key={track.id} className="flex items-center justify-between p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg">
<div className="flex items-center gap-4">
<img src={track.album.images[2]?.url || '/placeholder.jpg'} alt={track.album.name} className="w-12 h-12 rounded-md" />
<div>
<p className="font-semibold">{track.name}</p>
<p className="text-sm text-gray-500">
{Math.floor(track.duration_ms / 60000)}:
{((track.duration_ms % 60000) / 1000).toFixed(0).padStart(2, '0')}
</p>
</div>
</div>
<button onClick={() => handleDownloadTrack(track)} className="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-full">
<img src="/download.svg" alt="Download" className="w-5 h-5" />
</button>
</div>
))}
</div>
</section>
<h2>Top Tracks</h2>
<div className="track-list">
{artistInfo.top_tracks.map((track) => (
<div key={track.id} className="track-item">
<Link to="/track/$trackId" params={{ trackId: track.id }}>
{track.name}
</Link>
<button onClick={() => handleDownloadTrack(track)}>Download</button>
</div>
))}
</div>
{/* Albums */}
<section>
<h2 className="text-2xl font-bold mb-4">Albums</h2>
<div className="flex gap-4 overflow-x-auto pb-4">
{albums.album.map(renderAlbumCard)}
</div>
</section>
{/* Singles */}
<section>
<h2 className="text-2xl font-bold mb-4">Singles & EPs</h2>
<div className="flex gap-4 overflow-x-auto pb-4">
{albums.single.map(renderAlbumCard)}
</div>
</section>
{/* Appears On */}
<section>
<h2 className="text-2xl font-bold mb-4">Appears On</h2>
<div className="flex gap-4 overflow-x-auto pb-4">
{albums.appears_on.map(renderAlbumCard)}
</div>
</section>
<h2>Albums</h2>
<div className="album-grid">
{filteredAlbums.map((album) => (
<div key={album.id} className="album-card">
<Link to="/album/$albumId" params={{ albumId: album.id }}>
<img src={album.images[0]?.url} alt={album.name} />
<p>{album.name}</p>
</Link>
</div>
))}
</div>
</div>
);
}
};

View File

@@ -1,14 +1,14 @@
import { useState } from 'react';
import { GeneralTab } from '../components/config/GeneralTab';
import { DownloadsTab } from '../components/config/DownloadsTab';
import { FormattingTab } from '../components/config/FormattingTab';
import { AccountsTab } from '../components/config/AccountsTab';
import { WatchTab } from '../components/config/WatchTab';
import { ServerTab } from '../components/config/ServerTab';
import { useSettings } from '../contexts/settings-context';
import { useState } from "react";
import { GeneralTab } from "../components/config/GeneralTab";
import { DownloadsTab } from "../components/config/DownloadsTab";
import { FormattingTab } from "../components/config/FormattingTab";
import { AccountsTab } from "../components/config/AccountsTab";
import { WatchTab } from "../components/config/WatchTab";
import { ServerTab } from "../components/config/ServerTab";
import { useSettings } from "../contexts/settings-context";
const ConfigComponent = () => {
const [activeTab, setActiveTab] = useState('general');
const [activeTab, setActiveTab] = useState("general");
// Get settings from the context instead of fetching here
const { settings: config, isLoading } = useSettings();
@@ -18,24 +18,23 @@ const ConfigComponent = () => {
if (!config) return <p className="text-center text-red-500">Error loading configuration.</p>;
switch (activeTab) {
case 'general':
case "general":
return <GeneralTab config={config} isLoading={isLoading} />;
case 'downloads':
case "downloads":
return <DownloadsTab config={config} isLoading={isLoading} />;
case 'formatting':
case "formatting":
return <FormattingTab config={config} isLoading={isLoading} />;
case 'accounts':
case "accounts":
return <AccountsTab />;
case 'watch':
case "watch":
return <WatchTab />;
case 'server':
case "server":
return <ServerTab />;
default:
return null;
}
};
return (
<div className="space-y-6">
<div>
@@ -46,26 +45,51 @@ const ConfigComponent = () => {
<div className="flex gap-8">
<aside className="w-1/4">
<nav className="flex flex-col space-y-1">
<button onClick={() => setActiveTab('general')} className={`p-2 rounded-md text-left ${activeTab === 'general' ? 'bg-gray-100 dark:bg-gray-800 font-semibold' : ''}`}>General</button>
<button onClick={() => setActiveTab('downloads')} className={`p-2 rounded-md text-left ${activeTab === 'downloads' ? 'bg-gray-100 dark:bg-gray-800 font-semibold' : ''}`}>Downloads</button>
<button onClick={() => setActiveTab('formatting')} className={`p-2 rounded-md text-left ${activeTab === 'formatting' ? 'bg-gray-100 dark:bg-gray-800 font-semibold' : ''}`}>Formatting</button>
<button onClick={() => setActiveTab('accounts')} className={`p-2 rounded-md text-left ${activeTab === 'accounts' ? 'bg-gray-100 dark:bg-gray-800 font-semibold' : ''}`}>Accounts</button>
<button onClick={() => setActiveTab('watch')} className={`p-2 rounded-md text-left ${activeTab === 'watch' ? 'bg-gray-100 dark:bg-gray-800 font-semibold' : ''}`}>Watch</button>
<button onClick={() => setActiveTab('server')} className={`p-2 rounded-md text-left ${activeTab === 'server' ? 'bg-gray-100 dark:bg-gray-800 font-semibold' : ''}`}>Server</button>
<button
onClick={() => setActiveTab("general")}
className={`p-2 rounded-md text-left ${activeTab === "general" ? "bg-gray-100 dark:bg-gray-800 font-semibold" : ""}`}
>
General
</button>
<button
onClick={() => setActiveTab("downloads")}
className={`p-2 rounded-md text-left ${activeTab === "downloads" ? "bg-gray-100 dark:bg-gray-800 font-semibold" : ""}`}
>
Downloads
</button>
<button
onClick={() => setActiveTab("formatting")}
className={`p-2 rounded-md text-left ${activeTab === "formatting" ? "bg-gray-100 dark:bg-gray-800 font-semibold" : ""}`}
>
Formatting
</button>
<button
onClick={() => setActiveTab("accounts")}
className={`p-2 rounded-md text-left ${activeTab === "accounts" ? "bg-gray-100 dark:bg-gray-800 font-semibold" : ""}`}
>
Accounts
</button>
<button
onClick={() => setActiveTab("watch")}
className={`p-2 rounded-md text-left ${activeTab === "watch" ? "bg-gray-100 dark:bg-gray-800 font-semibold" : ""}`}
>
Watch
</button>
<button
onClick={() => setActiveTab("server")}
className={`p-2 rounded-md text-left ${activeTab === "server" ? "bg-gray-100 dark:bg-gray-800 font-semibold" : ""}`}
>
Server
</button>
</nav>
</aside>
<main className="w-3/4">
{renderTabContent()}
</main>
<main className="w-3/4">{renderTabContent()}</main>
</div>
</div>
);
};
export const Config = () => {
return (
<ConfigComponent />
)
return <ConfigComponent />;
};

View File

@@ -1,6 +1,6 @@
import { useEffect, useState, useMemo } from 'react';
import apiClient from '../lib/api-client';
import { toast } from 'sonner';
import { useEffect, useState, useMemo } from "react";
import apiClient from "../lib/api-client";
import { toast } from "sonner";
import {
createColumnHelper,
flexRender,
@@ -8,51 +8,30 @@ import {
useReactTable,
getSortedRowModel,
type SortingState,
} from '@tanstack/react-table';
} from "@tanstack/react-table";
// --- Type Definitions ---
type HistoryEntry = {
task_id: string;
item_name: string;
item_artist: string;
download_type: 'track' | 'album' | 'playlist' | 'artist';
download_type: "track" | "album" | "playlist" | "artist";
service_used: string;
quality_profile: string;
status_final: 'COMPLETED' | 'ERROR' | 'CANCELLED';
convert_to?: string;
bitrate?: string;
status_final: "COMPLETED" | "ERROR" | "CANCELLED" | "SKIPPED";
timestamp_completed: number;
error_message?: string;
parent_task_id?: string;
track_status?: "SUCCESSFUL" | "SKIPPED" | "FAILED";
total_successful?: number;
total_skipped?: number;
total_failed?: number;
};
// --- Column Definitions ---
const columnHelper = createColumnHelper<HistoryEntry>();
const columns = [
columnHelper.accessor('item_name', { header: 'Name' }),
columnHelper.accessor('item_artist', { header: 'Artist' }),
columnHelper.accessor('download_type', { header: 'Type', cell: info => <span className="capitalize">{info.getValue()}</span> }),
columnHelper.accessor('status_final', {
header: 'Status',
cell: info => {
const status = info.getValue();
const statusClass = {
COMPLETED: 'text-green-500',
ERROR: 'text-red-500',
CANCELLED: 'text-yellow-500',
}[status];
return <span className={`font-semibold ${statusClass}`}>{status}</span>;
},
}),
columnHelper.accessor('timestamp_completed', {
header: 'Date Completed',
cell: info => new Date(info.getValue() * 1000).toLocaleString(),
}),
columnHelper.accessor('error_message', {
header: 'Details',
cell: info => info.getValue() ? (
<button onClick={() => toast.info('Error Details', { description: info.getValue() })} className="text-blue-500 hover:underline">
Show Error
</button>
) : null,
})
];
export const History = () => {
const [data, setData] = useState<HistoryEntry[]>([]);
@@ -60,39 +39,165 @@ export const History = () => {
const [isLoading, setIsLoading] = useState(true);
// State for TanStack Table
const [sorting, setSorting] = useState<SortingState>([{ id: 'timestamp_completed', desc: true }]);
const [{ pageIndex, pageSize }, setPagination] = useState({ pageIndex: 0, pageSize: 25 });
const [sorting, setSorting] = useState<SortingState>([{ id: "timestamp_completed", desc: true }]);
const [{ pageIndex, pageSize }, setPagination] = useState({
pageIndex: 0,
pageSize: 25,
});
// State for filters
const [statusFilter, setStatusFilter] = useState('');
const [typeFilter, setTypeFilter] = useState('');
const [statusFilter, setStatusFilter] = useState("");
const [typeFilter, setTypeFilter] = useState("");
const [trackStatusFilter, setTrackStatusFilter] = useState("");
const [hideChildTracks, setHideChildTracks] = useState(true);
const [parentTaskId, setParentTaskId] = useState<string | null>(null);
const pagination = useMemo(() => ({ pageIndex, pageSize }), [pageIndex, pageSize]);
const viewTracksForParent = (taskId: string) => {
setParentTaskId(taskId);
};
const columns = useMemo(
() => [
columnHelper.accessor("item_name", {
header: "Name",
cell: (info) =>
info.row.original.parent_task_id ? (
<span className="pl-4 text-gray-400"> {info.getValue()}</span>
) : (
<span className="font-semibold">{info.getValue()}</span>
),
}),
columnHelper.accessor("item_artist", { header: "Artist" }),
columnHelper.accessor("download_type", {
header: "Type",
cell: (info) => {
const entry = info.row.original;
if (entry.parent_task_id && entry.track_status) {
const statusClass = {
SUCCESSFUL: "text-green-500",
SKIPPED: "text-yellow-500",
FAILED: "text-red-500",
}[entry.track_status];
return (
<span className={`capitalize font-semibold ${statusClass}`}>{entry.track_status.toLowerCase()}</span>
);
}
return <span className="capitalize">{info.getValue()}</span>;
},
}),
columnHelper.accessor("quality_profile", {
header: "Quality",
cell: (info) => {
const entry = info.row.original;
let qualityDisplay = entry.quality_profile || "N/A";
if (entry.convert_to && entry.convert_to !== "None") {
qualityDisplay = `${entry.convert_to.toUpperCase()}`;
if (entry.bitrate && entry.bitrate !== "None") {
qualityDisplay += ` ${entry.bitrate}k`;
}
qualityDisplay += ` (${entry.quality_profile || "Original"})`;
} else if (entry.bitrate && entry.bitrate !== "None") {
qualityDisplay = `${entry.bitrate}k (${entry.quality_profile || "Profile"})`;
}
return qualityDisplay;
},
}),
columnHelper.accessor("status_final", {
header: "Status",
cell: (info) => {
const status = info.getValue();
const statusClass = {
COMPLETED: "text-green-500",
ERROR: "text-red-500",
CANCELLED: "text-gray-500",
SKIPPED: "text-yellow-500",
}[status];
return <span className={`font-semibold ${statusClass}`}>{status}</span>;
},
}),
columnHelper.accessor("timestamp_completed", {
header: "Date Completed",
cell: (info) => new Date(info.getValue() * 1000).toLocaleString(),
}),
columnHelper.accessor("error_message", {
header: "Details",
cell: (info) =>
info.getValue() ? (
<button
onClick={() =>
toast.info("Error Details", {
description: info.getValue(),
})
}
className="text-blue-500 hover:underline"
>
Show Error
</button>
) : null,
}),
columnHelper.display({
id: "actions",
header: "Actions",
cell: ({ row }) => {
const entry = row.original;
if (!entry.parent_task_id && (entry.download_type === "album" || entry.download_type === "playlist")) {
const hasChildren =
(entry.total_successful ?? 0) > 0 || (entry.total_skipped ?? 0) > 0 || (entry.total_failed ?? 0) > 0;
if (hasChildren) {
return (
<div className="flex items-center gap-2">
<button onClick={() => viewTracksForParent(entry.task_id)} className="text-blue-500 hover:underline">
View Tracks
</button>
<span className="text-xs">
<span className="text-green-500">{entry.total_successful ?? 0}</span> /{" "}
<span className="text-yellow-500">{entry.total_skipped ?? 0}</span> /{" "}
<span className="text-red-500">{entry.total_failed ?? 0}</span>
</span>
</div>
);
}
}
return null;
},
}),
],
[],
);
useEffect(() => {
const fetchHistory = async () => {
setIsLoading(true);
try {
const params = new URLSearchParams({
limit: `${pageSize}`,
offset: `${pageIndex * pageSize}`,
sort_by: sorting[0]?.id ?? 'timestamp_completed',
sort_order: sorting[0]?.desc ? 'DESC' : 'ASC',
limit: `${pageSize}`,
offset: `${pageIndex * pageSize}`,
sort_by: sorting[0]?.id ?? "timestamp_completed",
sort_order: sorting[0]?.desc ? "DESC" : "ASC",
});
if (statusFilter) params.append('status_final', statusFilter);
if (typeFilter) params.append('download_type', typeFilter);
if (statusFilter) params.append("status_final", statusFilter);
if (typeFilter) params.append("download_type", typeFilter);
if (trackStatusFilter) params.append("track_status", trackStatusFilter);
if (hideChildTracks) params.append("hide_child_tracks", "true");
if (parentTaskId) params.append("parent_task_id", parentTaskId);
const response = await apiClient.get<{ entries: HistoryEntry[], total_count: number }>(`/history?${params.toString()}`);
const response = await apiClient.get<{
entries: HistoryEntry[];
total_count: number;
}>(`/history?${params.toString()}`);
setData(response.data.entries);
setTotalEntries(response.data.total_count);
} catch {
toast.error('Failed to load history.');
toast.error("Failed to load history.");
} finally {
setIsLoading(false);
}
};
fetchHistory();
}, [pageIndex, pageSize, sorting, statusFilter, typeFilter]);
}, [pageIndex, pageSize, sorting, statusFilter, typeFilter, trackStatusFilter, hideChildTracks, parentTaskId]);
const table = useReactTable({
data,
@@ -107,97 +212,161 @@ export const History = () => {
manualSorting: true,
});
const clearFilters = () => {
setStatusFilter("");
setTypeFilter("");
setTrackStatusFilter("");
setHideChildTracks(true);
};
const viewParentTask = () => {
setParentTaskId(null);
clearFilters();
};
return (
<div className="space-y-4">
<h1 className="text-3xl font-bold">Download History</h1>
{parentTaskId && (
<button onClick={viewParentTask} className="text-blue-500 hover:underline">
&larr; Back to All History
</button>
)}
{/* Filter Controls */}
<div className="flex gap-4">
<select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} className="p-2 border rounded-md dark:bg-gray-800 dark:border-gray-700">
<option value="">All Statuses</option>
<option value="COMPLETED">Completed</option>
<option value="ERROR">Error</option>
<option value="CANCELLED">Cancelled</option>
<div className="flex gap-4 items-center">
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="p-2 border rounded-md dark:bg-gray-800 dark:border-gray-700"
>
<option value="">All Statuses</option>
<option value="COMPLETED">Completed</option>
<option value="ERROR">Error</option>
<option value="CANCELLED">Cancelled</option>
<option value="SKIPPED">Skipped</option>
</select>
<select value={typeFilter} onChange={e => setTypeFilter(e.target.value)} className="p-2 border rounded-md dark:bg-gray-800 dark:border-gray-700">
<option value="">All Types</option>
<option value="track">Track</option>
<option value="album">Album</option>
<option value="playlist">Playlist</option>
<option value="artist">Artist</option>
<select
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value)}
className="p-2 border rounded-md dark:bg-gray-800 dark:border-gray-700"
>
<option value="">All Types</option>
<option value="track">Track</option>
<option value="album">Album</option>
<option value="playlist">Playlist</option>
<option value="artist">Artist</option>
</select>
<select
value={trackStatusFilter}
onChange={(e) => setTrackStatusFilter(e.target.value)}
className="p-2 border rounded-md dark:bg-gray-800 dark:border-gray-700"
>
<option value="">All Track Statuses</option>
<option value="SUCCESSFUL">Successful</option>
<option value="SKIPPED">Skipped</option>
<option value="FAILED">Failed</option>
</select>
<label className="flex items-center gap-2">
<input type="checkbox" checked={hideChildTracks} onChange={(e) => setHideChildTracks(e.target.checked)} />
Hide Child Tracks
</label>
</div>
{/* Table */}
<div className="overflow-x-auto">
<table className="min-w-full">
<thead>
{table.getHeaderGroups().map(headerGroup => (
<tr key={headerGroup.id}>
{headerGroup.headers.map(header => (
<th key={header.id} className="p-2 text-left">
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th key={header.id} className="p-2 text-left">
{header.isPlaceholder ? null : (
<div
{...{
className: header.column.getCanSort() ? 'cursor-pointer select-none' : '',
onClick: header.column.getToggleSortingHandler(),
}}
>
<div
{...{
className: header.column.getCanSort() ? "cursor-pointer select-none" : "",
onClick: header.column.getToggleSortingHandler(),
}}
>
{flexRender(header.column.columnDef.header, header.getContext())}
{{ asc: '', desc: ' ▼'}[header.column.getIsSorted() as string] ?? null}
</div>
{{ asc: "", desc: " ▼" }[header.column.getIsSorted() as string] ?? null}
</div>
)}
</th>
</th>
))}
</tr>
</tr>
))}
</thead>
<tbody>
</thead>
<tbody>
{isLoading ? (
<tr><td colSpan={columns.length} className="text-center p-4">Loading...</td></tr>
<tr>
<td colSpan={columns.length} className="text-center p-4">
Loading...
</td>
</tr>
) : table.getRowModel().rows.length === 0 ? (
<tr><td colSpan={columns.length} className="text-center p-4">No history entries found.</td></tr>
<tr>
<td colSpan={columns.length} className="text-center p-4">
No history entries found.
</td>
</tr>
) : (
table.getRowModel().rows.map(row => (
<tr key={row.id} className="border-b dark:border-gray-700">
{row.getVisibleCells().map(cell => (
<td key={cell.id} className="p-2">
table.getRowModel().rows.map((row) => {
const isParent =
!row.original.parent_task_id &&
(row.original.download_type === "album" || row.original.download_type === "playlist");
const isChild = !!row.original.parent_task_id;
const rowClass = isParent ? "bg-gray-800 font-semibold" : isChild ? "bg-gray-900" : "";
return (
<tr key={row.id} className={`border-b dark:border-gray-700 ${rowClass}`}>
{row.getVisibleCells().map((cell) => (
<td key={cell.id} className="p-2">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
</td>
))}
</tr>
))
</tr>
);
})
)}
</tbody>
</tbody>
</table>
</div>
{/* Pagination Controls */}
<div className="flex items-center justify-between gap-2">
<button onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()} className="p-2 border rounded-md disabled:opacity-50">
Previous
<button
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
className="p-2 border rounded-md disabled:opacity-50"
>
Previous
</button>
<span>
Page{' '}
<strong>
{table.getState().pagination.pageIndex + 1} of {table.getPageCount()}
</strong>
Page{" "}
<strong>
{table.getState().pagination.pageIndex + 1} of {table.getPageCount()}
</strong>
</span>
<button onClick={() => table.nextPage()} disabled={!table.getCanNextPage()} className="p-2 border rounded-md disabled:opacity-50">
Next
<button
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
className="p-2 border rounded-md disabled:opacity-50"
>
Next
</button>
<select
value={table.getState().pagination.pageSize}
onChange={e => table.setPageSize(Number(e.target.value))}
className="p-2 border rounded-md dark:bg-gray-800 dark:border-gray-700"
value={table.getState().pagination.pageSize}
onChange={(e) => table.setPageSize(Number(e.target.value))}
className="p-2 border rounded-md dark:bg-gray-800 dark:border-gray-700"
>
{[10, 25, 50, 100].map(size => (
<option key={size} value={size}>
Show {size}
</option>
))}
{[10, 25, 50, 100].map((size) => (
<option key={size} value={size}>
Show {size}
</option>
))}
</select>
</div>
</div>
);
}
};

View File

@@ -1,44 +1,42 @@
import { useState, useEffect, useMemo } from 'react';
import { Link } from '@tanstack/react-router';
import { useDebounce } from 'use-debounce';
import apiClient from '../lib/api-client';
import { useQueue } from '../contexts/queue-context';
import { useState, useEffect, useMemo, useContext, useCallback } from "react";
import { Link } from "@tanstack/react-router";
import { useDebounce } from "use-debounce";
import apiClient from "../lib/api-client";
import { toast } from "sonner";
import type { TrackType, AlbumType, ArtistType } from "../types/spotify";
import { QueueContext } from "../contexts/queue-context";
// --- Type Definitions ---
interface Image { url: string; }
interface BaseItem { id: string; name: string; }
interface Artist extends BaseItem { images?: Image[]; }
interface Album extends BaseItem { images?: Image[]; artists: Artist[]; }
interface Track extends BaseItem { album: Album; artists: Artist[]; }
interface Playlist extends BaseItem { images?: Image[]; owner: { display_name: string }; }
type SearchResult = (TrackType | AlbumType | ArtistType) & {
model: "track" | "album" | "artist";
};
type SearchResultItem = Artist | Album | Track | Playlist;
type SearchType = 'artist' | 'album' | 'track' | 'playlist';
// --- Component ---
export function Home() {
const [query, setQuery] = useState('');
const [searchType, setSearchType] = useState<SearchType>('track');
const [results, setResults] = useState<SearchResultItem[]>([]);
export const Home = () => {
const [query, setQuery] = useState("");
const [searchType, setSearchType] = useState<"track" | "album" | "artist">("track");
const [results, setResults] = useState<SearchResult[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [debouncedQuery] = useDebounce(query, 500);
const { addItem, toggleVisibility } = useQueue();
const context = useContext(QueueContext);
if (!context) {
throw new Error("useQueue must be used within a QueueProvider");
}
const { addItem } = context;
useEffect(() => {
const performSearch = async () => {
if (debouncedQuery.trim().length < 2) {
if (debouncedQuery.length < 3) {
setResults([]);
return;
}
setIsLoading(true);
try {
const response = await apiClient.get<{ items: SearchResultItem[] }>('/search', {
params: { q: debouncedQuery, search_type: searchType, limit: 40 },
});
setResults(response.data.items);
} catch (error) {
console.error('Search failed:', error);
setResults([]);
const response = await apiClient.get<{
results: SearchResult[];
}>(`/search?q=${debouncedQuery}&type=${searchType}`);
setResults(response.data.results);
} catch {
toast.error("Search failed. Please try again.");
} finally {
setIsLoading(false);
}
@@ -46,105 +44,86 @@ export function Home() {
performSearch();
}, [debouncedQuery, searchType]);
const handleDownloadTrack = (track: Track) => {
addItem({ id: track.id, type: 'track', name: track.name });
toggleVisibility();
};
const handleDownloadTrack = useCallback(
(track: TrackType) => {
addItem({ spotifyId: track.id, type: "track", name: track.name });
toast.info(`Adding ${track.name} to queue...`);
},
[addItem],
);
const renderResult = (item: SearchResultItem) => {
const resultComponent = useMemo(() => {
switch (searchType) {
case 'track': {
const track = item as Track;
case "track":
return (
<div key={track.id} className="p-2 flex items-center gap-4 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg">
<img src={track.album.images?.[0]?.url || '/placeholder.jpg'} alt={track.album.name} className="w-12 h-12 rounded" />
<div className="flex-grow">
<p className="font-semibold">{track.name}</p>
<p className="text-sm text-gray-500">{track.artists.map(a => a.name).join(', ')}</p>
</div>
<button onClick={() => handleDownloadTrack(track)} className="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-full">
<img src="/download.svg" alt="Download" className="w-5 h-5" />
</button>
<div className="track-list">
{results.map(
(item) =>
item.model === "track" && (
<div key={item.id} className="track-item">
<Link to="/track/$trackId" params={{ trackId: item.id }}>
{item.name}
</Link>
<button onClick={() => handleDownloadTrack(item as TrackType)}>Download</button>
</div>
),
)}
</div>
);
}
case 'album': {
const album = item as Album;
case "album":
return (
<Link to="/album/$albumId" params={{ albumId: album.id }} key={album.id} className="block p-2 text-center hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg">
<img src={album.images?.[0]?.url || '/placeholder.jpg'} alt={album.name} className="w-full h-auto object-cover rounded shadow-md aspect-square" />
<p className="mt-2 font-semibold truncate">{album.name}</p>
<p className="text-sm text-gray-500">{album.artists.map(a => a.name).join(', ')}</p>
</Link>
<div className="album-grid">
{results.map(
(item) =>
item.model === "album" && (
<div key={item.id} className="album-card">
<Link to="/album/$albumId" params={{ albumId: item.id }}>
<img src={(item as AlbumType).images[0]?.url} alt={item.name} />
<p>{item.name}</p>
</Link>
</div>
),
)}
</div>
);
}
case 'artist': {
const artist = item as Artist;
case "artist":
return (
<Link to="/artist/$artistId" params={{ artistId: artist.id }} key={artist.id} className="block p-2 text-center hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg">
<img src={artist.images?.[0]?.url || '/placeholder.jpg'} alt={artist.name} className="w-full h-auto object-cover rounded-full shadow-md aspect-square" />
<p className="mt-2 font-semibold truncate">{artist.name}</p>
</Link>
<div className="artist-list">
{results.map(
(item) =>
item.model === "artist" && (
<div key={item.id} className="artist-item">
<Link to="/artist/$artistId" params={{ artistId: item.id }}>
<p>{item.name}</p>
</Link>
</div>
),
)}
</div>
);
}
case 'playlist': {
const playlist = item as Playlist;
return (
<Link to="/playlist/$playlistId" params={{ playlistId: playlist.id }} key={playlist.id} className="block p-2 text-center hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg">
<img src={playlist.images?.[0]?.url || '/placeholder.jpg'} alt={playlist.name} className="w-full h-auto object-cover rounded shadow-md aspect-square" />
<p className="mt-2 font-semibold truncate">{playlist.name}</p>
<p className="text-sm text-gray-500">by {playlist.owner.display_name}</p>
</Link>
);
}
default:
return null;
}
};
const gridClass = useMemo(() => {
switch(searchType) {
case 'album':
case 'artist':
case 'playlist':
return "grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8 gap-4";
case 'track':
return "flex flex-col gap-1";
default:
return "";
}
}, [searchType]);
}, [results, searchType, handleDownloadTrack]);
return (
<div className="space-y-6">
<div className="relative">
<img src="/search.svg" alt="" className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
<div className="home-page">
<h1>Search Spotify</h1>
<div className="search-bar">
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search for songs, albums, artists..."
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-700 rounded-full bg-gray-100 dark:bg-gray-800"
placeholder="Search for a track, album, or artist"
/>
<select
value={searchType}
onChange={(e) => setSearchType(e.target.value as SearchType)}
className="absolute right-2 top-1/2 -translate-y-1/2 bg-transparent border-none text-gray-500"
>
<option value="track">Tracks</option>
<option value="album">Albums</option>
<option value="artist">Artists</option>
<option value="playlist">Playlists</option>
<select value={searchType} onChange={(e) => setSearchType(e.target.value as "track" | "album" | "artist")}>
<option value="track">Track</option>
<option value="album">Album</option>
<option value="artist">Artist</option>
</select>
</div>
<div>
{isLoading && <p>Loading...</p>}
{!isLoading && debouncedQuery && results.length === 0 && <p>No results found.</p>}
<div className={gridClass}>
{results.map(renderResult)}
</div>
</div>
{isLoading && <p>Loading...</p>}
<div className="search-results">{resultComponent}</div>
</div>
);
}
};

View File

@@ -1,134 +1,106 @@
import { Link, useParams } from '@tanstack/react-router';
import { useEffect, useState } from 'react';
import apiClient from '../lib/api-client';
import { useQueue } from '../contexts/queue-context';
import { useSettings } from '../contexts/settings-context';
import { toast } from 'sonner';
import type { ImageType, TrackType } from '../types/spotify';
import { Link, useParams } from "@tanstack/react-router";
import { useEffect, useState, useContext } from "react";
import apiClient from "../lib/api-client";
import { useSettings } from "../contexts/settings-context";
import { toast } from "sonner";
import type { ImageType, TrackType } from "../types/spotify";
import { QueueContext } from "../contexts/queue-context";
// --- Type Definitions ---
interface SimplifiedAlbumType {
interface PlaylistItemType {
track: TrackType | null;
}
interface PlaylistType {
id: string;
name: string;
images: ImageType[];
}
interface PlaylistTrackType extends TrackType {
album: SimplifiedAlbumType;
}
interface PlaylistItemType { track: PlaylistTrackType | null; }
interface PlaylistDetailsType {
id:string;
name: string;
description: string | null;
images: ImageType[];
owner: { display_name?: string };
followers?: { total: number };
tracks: { items: PlaylistItemType[]; total: number; };
tracks: {
items: PlaylistItemType[];
};
}
export const Playlist = () => {
const { playlistId } = useParams({ from: '/playlist/$playlistId' });
const [playlist, setPlaylist] = useState<PlaylistDetailsType | null>(null);
const [isLoading, setIsLoading] = useState(true);
const { addItem, toggleVisibility } = useQueue();
const { playlistId } = useParams({ from: "/playlist/$playlistId" });
const [playlist, setPlaylist] = useState<PlaylistType | null>(null);
const [error, setError] = useState<string | null>(null);
const context = useContext(QueueContext);
const { settings } = useSettings();
if (!context) {
throw new Error("useQueue must be used within a QueueProvider");
}
const { addItem } = context;
useEffect(() => {
const fetchPlaylist = async () => {
if (!playlistId) return;
setIsLoading(true);
try {
const response = await apiClient.get<PlaylistDetailsType>(`/playlist/info?id=${playlistId}`);
const response = await apiClient.get<PlaylistType>(`/playlist/info?id=${playlistId}`);
setPlaylist(response.data);
} catch {
toast.error('Failed to load playlist details.');
} finally {
setIsLoading(false);
} catch (err) {
setError("Failed to load playlist");
console.error(err);
}
};
fetchPlaylist();
}, [playlistId]);
const handleDownloadTrack = (track: PlaylistTrackType) => {
addItem({ id: track.id, type: 'track', name: track.name });
toggleVisibility();
const handleDownloadTrack = (track: TrackType) => {
if (!track?.id) return;
addItem({ spotifyId: track.id, type: "track", name: track.name });
toast.info(`Adding ${track.name} to queue...`);
};
const handleDownloadPlaylist = () => {
if (!playlist) return;
// This assumes a backend endpoint that can handle a whole playlist download by its ID
addItem({ id: playlist.id, type: 'playlist', name: playlist.name });
toggleVisibility();
toast.success(`Queued playlist: ${playlist.name}`);
if (!playlist) return;
addItem({
spotifyId: playlist.id,
type: "playlist",
name: playlist.name,
});
toast.info(`Adding ${playlist.name} to queue...`);
};
if (error) {
return <div className="text-red-500">{error}</div>;
}
if (isLoading) return <div>Loading playlist...</div>;
if (!playlist) return <div>Playlist not found.</div>;
if (!playlist) {
return <div>Loading...</div>;
}
const isExplicitFilterEnabled = settings?.explicitFilter ?? false;
const hasExplicitTrack = playlist.tracks.items.some(item => item.track?.explicit);
const filteredTracks = playlist.tracks.items.filter(({ track }) => {
if (!track) return false;
if (settings?.explicitFilter && track.explicit) return false;
return true;
});
return (
<div className="space-y-6">
<div className="flex flex-col md:flex-row items-start gap-8">
<img src={playlist.images[0]?.url || '/placeholder.jpg'} alt={playlist.name} className="w-48 h-48 object-cover rounded-lg shadow-lg"/>
<div className="flex-grow space-y-2">
<h1 className="text-4xl font-bold">{playlist.name}</h1>
<p className="text-gray-500">By {playlist.owner.display_name}</p>
{playlist.description && <p className="text-sm text-gray-400" dangerouslySetInnerHTML={{ __html: playlist.description }} />}
<p className="text-sm text-gray-500">{playlist.followers?.total.toLocaleString()} followers {playlist.tracks.total} songs</p>
<div className="pt-2">
<button
onClick={handleDownloadPlaylist}
disabled={isExplicitFilterEnabled && hasExplicitTrack}
className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:bg-gray-500"
title={isExplicitFilterEnabled && hasExplicitTrack ? "Playlist contains explicit tracks and can't be downloaded" : 'Download all tracks in playlist'}
>
Download Playlist
</button>
</div>
<div className="playlist-page">
<div className="playlist-header">
<img src={playlist.images[0]?.url} alt={playlist.name} className="playlist-image" />
<div>
<h1>{playlist.name}</h1>
<p>{playlist.description}</p>
<button onClick={handleDownloadPlaylist} className="download-playlist-btn">
Download All
</button>
</div>
</div>
<div>
<div className="flex flex-col">
{playlist.tracks.items.map(({ track }, index) => {
if (!track) return null; // Handle cases where a track might be unavailable
if (isExplicitFilterEnabled && track.explicit) {
return (
<div key={index} className="flex items-center p-3 text-sm bg-gray-100 dark:bg-gray-800 rounded-lg opacity-60">
<span className="w-8 text-gray-500">{index + 1}</span>
<span className="font-medium text-gray-500">Explicit track filtered</span>
</div>
);
}
return (
<div key={track.id} className="flex items-center gap-4 p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg">
<span className="w-6 text-right text-gray-500">{index + 1}</span>
<img src={track.album.images[track.album.images.length - 1]?.url || '/placeholder.jpg'} alt="" className="w-10 h-10 rounded" />
<div className="flex-grow">
<p className="font-semibold">{track.name}</p>
<p className="text-xs text-gray-500">
{track.artists.map(a => <Link key={a.id} to="/artist/$artistId" params={{artistId: a.id}} className="hover:underline">{a.name}</Link>).reduce((prev, curr) => <>{prev}, {curr}</>)}
{' • '}
<Link to="/album/$albumId" params={{albumId: track.album.id}} className="hover:underline">{track.album.name}</Link>
</p>
</div>
<span className="text-sm text-gray-500 hidden md:block">
{Math.floor(track.duration_ms / 60000)}:{((track.duration_ms % 60000) / 1000).toFixed(0).padStart(2, '0')}
</span>
<button onClick={() => handleDownloadTrack(track)} className="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-full">
<img src="/download.svg" alt="Download" className="w-5 h-5" />
</button>
</div>
);
})}
</div>
<div className="track-list">
{filteredTracks.map(({ track }) => {
if (!track) return null;
return (
<div key={track.id} className="track-item">
<Link to="/track/$trackId" params={{ trackId: track.id }}>
{track.name}
</Link>
<button onClick={() => handleDownloadTrack(track)}>Download</button>
</div>
);
})}
</div>
</div>
);
}
};

View File

@@ -1,11 +1,11 @@
import { Outlet } from '@tanstack/react-router';
import { QueueProvider } from '../contexts/QueueProvider';
import { useQueue } from '../contexts/queue-context';
import { Queue } from '../components/Queue';
import { Link } from '@tanstack/react-router';
import { SettingsProvider } from '../contexts/SettingsProvider';
import { Toaster } from 'sonner';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Outlet } from "@tanstack/react-router";
import { QueueProvider } from "../contexts/QueueProvider";
import { useQueue } from "../contexts/queue-context";
import { Queue } from "../components/Queue";
import { Link } from "@tanstack/react-router";
import { SettingsProvider } from "../contexts/SettingsProvider";
import { Toaster } from "sonner";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
// Create a client
const queryClient = new QueryClient();
@@ -17,26 +17,26 @@ function AppLayout() {
<>
<div className="min-h-screen bg-background text-foreground">
<header className="sticky top-0 z-40 w-full border-b bg-background/95 backdrop-blur-sm">
<div className="container mx-auto h-14 flex items-center justify-between">
<Link to="/" className="flex items-center gap-2">
<img src="/music.svg" alt="Logo" className="w-6 h-6" />
<h1 className="text-xl font-bold">Spotizerr</h1>
<div className="container mx-auto h-14 flex items-center justify-between">
<Link to="/" className="flex items-center gap-2">
<img src="/music.svg" alt="Logo" className="w-6 h-6" />
<h1 className="text-xl font-bold">Spotizerr</h1>
</Link>
<div className="flex items-center gap-2">
<Link to="/watchlist" className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700">
<img src="/binoculars.svg" alt="Watchlist" className="w-6 h-6" />
</Link>
<div className="flex items-center gap-2">
<Link to="/watchlist" className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700">
<img src="/binoculars.svg" alt="Watchlist" className="w-6 h-6" />
</Link>
<Link to="/history" className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700">
<img src="/history.svg" alt="History" className="w-6 h-6" />
</Link>
<Link to="/config" className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700">
<img src="/settings.svg" alt="Settings" className="w-6 h-6" />
</Link>
<button onClick={toggleVisibility} className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700">
<img src="/queue.svg" alt="Queue" className="w-6 h-6" />
</button>
</div>
</div>
<Link to="/history" className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700">
<img src="/history.svg" alt="History" className="w-6 h-6" />
</Link>
<Link to="/config" className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700">
<img src="/settings.svg" alt="Settings" className="w-6 h-6" />
</Link>
<button onClick={toggleVisibility} className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700">
<img src="/queue.svg" alt="Queue" className="w-6 h-6" />
</button>
</div>
</div>
</header>
<main className="container mx-auto px-4 py-8">
<Outlet />

View File

@@ -1,92 +1,54 @@
import { Link, useParams } from '@tanstack/react-router';
import { useEffect, useState } from 'react';
import apiClient from '../lib/api-client';
import { useQueue } from '../contexts/queue-context';
import type { TrackType, ImageType } from '../types/spotify';
interface SimplifiedAlbum {
id: string;
name: string;
images: ImageType[];
album_type: string;
}
interface TrackDetails extends TrackType {
album: SimplifiedAlbum;
}
import { useParams } from "@tanstack/react-router";
import { useEffect, useState, useContext } from "react";
import apiClient from "../lib/api-client";
import type { TrackType } from "../types/spotify";
import { toast } from "sonner";
import { QueueContext } from "../contexts/queue-context";
export const Track = () => {
const { trackId } = useParams({ from: '/track/$trackId' });
const [track, setTrack] = useState<TrackDetails | null>(null);
const { trackId } = useParams({ from: "/track/$trackId" });
const [track, setTrack] = useState<TrackType | null>(null);
const [error, setError] = useState<string | null>(null);
const { addItem, toggleVisibility } = useQueue();
const context = useContext(QueueContext);
if (!context) {
throw new Error("useQueue must be used within a QueueProvider");
}
const { addItem } = context;
useEffect(() => {
const fetchTrack = async () => {
if (!trackId) return;
try {
const response = await apiClient.get<TrackDetails>(`/track/info?id=${trackId}`);
const response = await apiClient.get<TrackType>(`/track/info?id=${trackId}`);
setTrack(response.data);
} catch (err) {
setError('Failed to load track details.');
setError("Failed to load track");
console.error(err);
}
};
fetchTrack();
}, [trackId]);
const handleDownload = () => {
const handleDownloadTrack = () => {
if (!track) return;
addItem({ id: track.id, type: 'track', name: track.name });
toggleVisibility();
addItem({ spotifyId: track.id, type: "track", name: track.name });
toast.info(`Adding ${track.name} to queue...`);
};
if (error) return <div className="text-red-500">{error}</div>;
if (!track) return <div>Loading...</div>;
if (error) {
return <div className="text-red-500">{error}</div>;
}
const minutes = Math.floor(track.duration_ms / 60000);
const seconds = ((track.duration_ms % 60000) / 1000).toFixed(0).padStart(2, '0');
if (!track) {
return <div>Loading...</div>;
}
return (
<div className="flex flex-col md:flex-row items-center gap-8 p-4">
<img
src={track.album.images[0]?.url || '/placeholder.jpg'}
alt={track.album.name}
className="w-64 h-64 object-cover rounded-lg shadow-2xl"
/>
<div className="flex-grow space-y-3 text-center md:text-left">
<h1 className="text-4xl font-extrabold">{track.name}</h1>
<p className="text-xl text-gray-500">
By{' '}
{track.artists.map((artist, index) => (
<span key={artist.id}>
<Link to="/artist/$artistId" params={{ artistId: artist.id }} className="hover:underline">
{artist.name}
</Link>
{index < track.artists.length - 1 && ', '}
</span>
))}
</p>
<p className="text-lg text-gray-400">
From the {track.album.album_type}{' '}
<Link to="/album/$albumId" params={{ albumId: track.album.id }} className="hover:underline font-semibold">
{track.album.name}
</Link>
</p>
<div className="flex items-center justify-center md:justify-start gap-4 text-sm text-gray-500">
<span>{minutes}:{seconds}</span>
{track.explicit && <span className="px-2 py-0.5 bg-gray-200 dark:bg-gray-700 text-xs font-semibold rounded-full">EXPLICIT</span>}
</div>
<div className="pt-4">
<button
onClick={handleDownload}
className="px-6 py-3 bg-green-600 text-white rounded-full hover:bg-green-700 transition-colors flex items-center justify-center gap-2 text-lg"
>
<img src="/download.svg" alt="" className="w-6 h-6" />
Download
</button>
</div>
</div>
<div className="track-page">
<h1>{track.name}</h1>
<p>by {track.artists.map((artist) => artist.name).join(", ")}</p>
<button onClick={handleDownloadTrack}>Download</button>
</div>
);
};

View File

@@ -1,8 +1,8 @@
import { useState, useEffect, useCallback } from 'react';
import apiClient from '../lib/api-client';
import { toast } from 'sonner';
import { useSettings } from '../contexts/settings-context';
import { Link } from '@tanstack/react-router';
import { useState, useEffect, useCallback } from "react";
import apiClient from "../lib/api-client";
import { toast } from "sonner";
import { useSettings } from "../contexts/settings-context";
import { Link } from "@tanstack/react-router";
// --- Type Definitions ---
interface Image {
@@ -10,7 +10,7 @@ interface Image {
}
interface WatchedArtist {
itemType: 'artist';
itemType: "artist";
spotify_id: string;
name: string;
images?: Image[];
@@ -18,7 +18,7 @@ interface WatchedArtist {
}
interface WatchedPlaylist {
itemType: 'playlist';
itemType: "playlist";
spotify_id: string;
name: string;
images?: Image[];
@@ -37,16 +37,16 @@ export const Watchlist = () => {
setIsLoading(true);
try {
const [artistsRes, playlistsRes] = await Promise.all([
apiClient.get<Omit<WatchedArtist, 'itemType'>[]>('/artist/watch/list'),
apiClient.get<Omit<WatchedPlaylist, 'itemType'>[]>('/playlist/watch/list'),
apiClient.get<Omit<WatchedArtist, "itemType">[]>("/artist/watch/list"),
apiClient.get<Omit<WatchedPlaylist, "itemType">[]>("/playlist/watch/list"),
]);
const artists: WatchedItem[] = artistsRes.data.map(a => ({ ...a, itemType: 'artist' }));
const playlists: WatchedItem[] = playlistsRes.data.map(p => ({ ...p, itemType: 'playlist' }));
const artists: WatchedItem[] = artistsRes.data.map((a) => ({ ...a, itemType: "artist" }));
const playlists: WatchedItem[] = playlistsRes.data.map((p) => ({ ...p, itemType: "playlist" }));
setItems([...artists, ...playlists]);
} catch {
toast.error('Failed to load watchlist.');
toast.error("Failed to load watchlist.");
} finally {
setIsLoading(false);
}
@@ -61,35 +61,33 @@ export const Watchlist = () => {
}, [settings, settingsLoading, fetchWatchlist]);
const handleUnwatch = async (item: WatchedItem) => {
toast.promise(
apiClient.delete(`/${item.itemType}/watch/${item.spotify_id}`), {
loading: `Unwatching ${item.name}...`,
success: () => {
setItems(prev => prev.filter(i => i.spotify_id !== item.spotify_id));
return `${item.name} has been unwatched.`;
},
error: `Failed to unwatch ${item.name}.`
toast.promise(apiClient.delete(`/${item.itemType}/watch/${item.spotify_id}`), {
loading: `Unwatching ${item.name}...`,
success: () => {
setItems((prev) => prev.filter((i) => i.spotify_id !== item.spotify_id));
return `${item.name} has been unwatched.`;
},
error: `Failed to unwatch ${item.name}.`,
});
};
const handleCheck = async (item: WatchedItem) => {
toast.promise(
apiClient.post(`/${item.itemType}/watch/trigger_check/${item.spotify_id}`), {
loading: `Checking ${item.name} for updates...`,
success: (res: { data: { message?: string }}) => res.data.message || `Check triggered for ${item.name}.`,
error: `Failed to trigger check for ${item.name}.`,
toast.promise(apiClient.post(`/${item.itemType}/watch/trigger_check/${item.spotify_id}`), {
loading: `Checking ${item.name} for updates...`,
success: (res: { data: { message?: string } }) => res.data.message || `Check triggered for ${item.name}.`,
error: `Failed to trigger check for ${item.name}.`,
});
};
const handleCheckAll = () => {
toast.promise(Promise.all([
apiClient.post('/artist/watch/trigger_check'),
apiClient.post('/playlist/watch/trigger_check'),
]), {
loading: 'Triggering checks for all watched items...',
success: 'Successfully triggered checks for all items.',
error: 'Failed to trigger one or more checks.'
});
toast.promise(
Promise.all([apiClient.post("/artist/watch/trigger_check"), apiClient.post("/playlist/watch/trigger_check")]),
{
loading: "Triggering checks for all watched items...",
success: "Successfully triggered checks for all items.",
error: "Failed to trigger one or more checks.",
},
);
};
if (isLoading || settingsLoading) {
@@ -101,7 +99,9 @@ export const Watchlist = () => {
<div className="text-center p-8">
<h2 className="text-2xl font-bold mb-2">Watchlist Disabled</h2>
<p>The watchlist feature is currently disabled. You can enable it in the settings.</p>
<Link to="/config" className="text-blue-500 hover:underline mt-4 inline-block">Go to Settings</Link>
<Link to="/config" className="text-blue-500 hover:underline mt-4 inline-block">
Go to Settings
</Link>
</div>
);
}
@@ -120,28 +120,38 @@ export const Watchlist = () => {
<div className="flex justify-between items-center">
<h1 className="text-3xl font-bold">Watched Artists & Playlists</h1>
<button onClick={handleCheckAll} className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
Check All
Check All
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
{items.map(item => (
{items.map((item) => (
<div key={item.spotify_id} className="bg-card p-4 rounded-lg shadow space-y-2 flex flex-col">
<a href={`/${item.itemType}/${item.spotify_id}`} className="flex-grow">
<img
src={item.images?.[0]?.url || '/images/placeholder.jpg'}
alt={item.name}
className="w-full h-auto object-cover rounded-md aspect-square"
/>
<h3 className="font-bold pt-2 truncate">{item.name}</h3>
<p className="text-sm text-muted-foreground capitalize">{item.itemType}</p>
</a>
<div className="flex gap-2 pt-2">
<button onClick={() => handleUnwatch(item)} className="w-full px-3 py-1.5 text-sm bg-red-600 text-white rounded-md hover:bg-red-700">Unwatch</button>
<button onClick={() => handleCheck(item)} className="w-full px-3 py-1.5 text-sm bg-gray-600 text-white rounded-md hover:bg-gray-700">Check</button>
</div>
<a href={`/${item.itemType}/${item.spotify_id}`} className="flex-grow">
<img
src={item.images?.[0]?.url || "/images/placeholder.jpg"}
alt={item.name}
className="w-full h-auto object-cover rounded-md aspect-square"
/>
<h3 className="font-bold pt-2 truncate">{item.name}</h3>
<p className="text-sm text-muted-foreground capitalize">{item.itemType}</p>
</a>
<div className="flex gap-2 pt-2">
<button
onClick={() => handleUnwatch(item)}
className="w-full px-3 py-1.5 text-sm bg-red-600 text-white rounded-md hover:bg-red-700"
>
Unwatch
</button>
<button
onClick={() => handleCheck(item)}
className="w-full px-3 py-1.5 text-sm bg-gray-600 text-white rounded-md hover:bg-gray-700"
>
Check
</button>
</div>
</div>
))}
</div>
</div>
);
}
};

View File

@@ -1,14 +1,14 @@
// This new type reflects the flat structure of the /api/config response
export interface AppSettings {
service: 'spotify' | 'deezer';
service: "spotify" | "deezer";
spotify: string;
spotifyQuality: 'NORMAL' | 'HIGH' | 'VERY_HIGH';
spotifyQuality: "NORMAL" | "HIGH" | "VERY_HIGH";
deezer: string;
deezerQuality: 'MP3_128' | 'MP3_320' | 'FLAC';
deezerQuality: "MP3_128" | "MP3_320" | "FLAC";
maxConcurrentDownloads: number;
realTime: boolean;
fallback: boolean;
convertTo: 'MP3' | 'AAC' | 'OGG' | 'OPUS' | 'FLAC' | 'WAV' | 'ALAC' | '';
convertTo: "MP3" | "AAC" | "OGG" | "OPUS" | "FLAC" | "WAV" | "ALAC" | "";
bitrate: string;
maxRetries: number;
retryDelaySeconds: number;

View File

@@ -7,6 +7,7 @@ export interface ImageType {
export interface ArtistType {
id: string;
name: string;
images: ImageType[];
}
export interface TrackType {

View File

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

View File

@@ -1,27 +1,26 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { fileURLToPath } from 'url'
import { dirname, resolve } from 'path'
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { fileURLToPath } from "url";
import { dirname, resolve } from "path";
import tailwindcss from "@tailwindcss/vite";
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
'@': resolve(__dirname, './src'),
"@": resolve(__dirname, "./src"),
},
},
server: {
proxy: {
'/api': {
target: 'http://localhost:7171',
"/api": {
target: "http://localhost:7171",
changeOrigin: true,
},
},
},
})
});