Add first-run setup wizard and file browser for library creation
- On first start (no users in DB), show a setup page in the web UI to create the admin account instead of reading credentials from .env - New public endpoints: GET /api/setup/status, POST /api/setup - New admin endpoint: GET /api/filebrowser?path=... for directory listing - FileBrowser modal component with navigation, used in Admin > Libraries - Remove _seed_admin / _seed_default_library from server startup Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
import uuid
|
||||
import logging
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -7,13 +6,10 @@ from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
|
||||
from .database import init_db, AsyncSessionLocal
|
||||
from .database import init_db
|
||||
from .config import get_settings
|
||||
from .models import User, Library
|
||||
from .services.auth import hash_password, verify_password, create_token
|
||||
from .services.file_watcher import start_file_watcher, stop_file_watcher
|
||||
from .services.podcast_feed import update_all_feeds
|
||||
from sqlalchemy import select
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -21,50 +17,6 @@ logger = logging.getLogger(__name__)
|
||||
_scheduler = AsyncIOScheduler()
|
||||
|
||||
|
||||
async def _seed_admin():
|
||||
settings = get_settings()
|
||||
async with AsyncSessionLocal() as db:
|
||||
result = await db.execute(select(User).where(User.is_admin == True))
|
||||
existing = result.scalar_one_or_none()
|
||||
if existing:
|
||||
if not verify_password(settings.admin_password, existing.password_hash):
|
||||
existing.password_hash = hash_password(settings.admin_password)
|
||||
await db.commit()
|
||||
logger.info("Admin-Passwort aus ENV aktualisiert.")
|
||||
return
|
||||
logger.info(f"Lege Admin-User an: {settings.admin_username}")
|
||||
admin = User(
|
||||
id=str(uuid.uuid4()),
|
||||
username=settings.admin_username,
|
||||
email=settings.admin_email,
|
||||
password_hash=hash_password(settings.admin_password),
|
||||
is_admin=True,
|
||||
)
|
||||
db.add(admin)
|
||||
await db.flush()
|
||||
admin.token = create_token(admin.id)
|
||||
await db.commit()
|
||||
logger.info("Admin-User angelegt.")
|
||||
|
||||
|
||||
async def _seed_default_library():
|
||||
settings = get_settings()
|
||||
async with AsyncSessionLocal() as db:
|
||||
result = await db.execute(select(Library))
|
||||
if result.scalar_one_or_none():
|
||||
return
|
||||
folder_id = str(uuid.uuid4())
|
||||
lib = Library(
|
||||
id=str(uuid.uuid4()),
|
||||
name="Hörbücher",
|
||||
display_name="Hörbücher",
|
||||
folders=[{"id": folder_id, "fullPath": settings.audiofiles_path}],
|
||||
media_type="book",
|
||||
settings={"icon": "headphones", "provider": "google"},
|
||||
)
|
||||
db.add(lib)
|
||||
await db.commit()
|
||||
logger.info(f"Standard-Library angelegt: {settings.audiofiles_path}")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -74,8 +26,6 @@ async def lifespan(app: FastAPI):
|
||||
os.makedirs(d, exist_ok=True)
|
||||
|
||||
await init_db()
|
||||
await _seed_admin()
|
||||
await _seed_default_library()
|
||||
await start_file_watcher()
|
||||
|
||||
# Podcast-Feed-Scheduler
|
||||
@@ -105,8 +55,9 @@ if os.path.exists(settings.covers_dir):
|
||||
app.mount("/covers", StaticFiles(directory=settings.covers_dir), name="covers")
|
||||
|
||||
from .routers import auth, libraries, items, stream, me, users, settings as settings_router
|
||||
from .routers import matching, podcasts
|
||||
from .routers import matching, podcasts, setup, filebrowser
|
||||
|
||||
app.include_router(setup.router)
|
||||
app.include_router(auth.router)
|
||||
app.include_router(libraries.router)
|
||||
app.include_router(items.router)
|
||||
@@ -116,3 +67,4 @@ app.include_router(users.router)
|
||||
app.include_router(settings_router.router)
|
||||
app.include_router(matching.router)
|
||||
app.include_router(podcasts.router)
|
||||
app.include_router(filebrowser.router)
|
||||
|
||||
37
backend/app/routers/filebrowser.py
Normal file
37
backend/app/routers/filebrowser.py
Normal file
@@ -0,0 +1,37 @@
|
||||
import os
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from ..dependencies import require_admin
|
||||
from ..models.user import User
|
||||
|
||||
router = APIRouter(prefix="/api/filebrowser", tags=["filebrowser"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def browse(
|
||||
path: str = Query("/"),
|
||||
_admin: User = Depends(require_admin),
|
||||
):
|
||||
path = os.path.normpath(path)
|
||||
if not os.path.isdir(path):
|
||||
raise HTTPException(status_code=404, detail="Pfad nicht gefunden")
|
||||
|
||||
try:
|
||||
names = sorted(os.listdir(path), key=lambda n: n.lower())
|
||||
except PermissionError:
|
||||
raise HTTPException(status_code=403, detail="Zugriff verweigert")
|
||||
|
||||
entries = []
|
||||
for name in names:
|
||||
if name.startswith("."):
|
||||
continue
|
||||
full = os.path.join(path, name)
|
||||
try:
|
||||
is_dir = os.path.isdir(full)
|
||||
except OSError:
|
||||
continue
|
||||
entries.append({"name": name, "path": full, "isDir": is_dir})
|
||||
|
||||
parent_path = os.path.dirname(path)
|
||||
parent = parent_path if parent_path != path else None
|
||||
|
||||
return {"path": path, "parent": parent, "entries": entries}
|
||||
43
backend/app/routers/setup.py
Normal file
43
backend/app/routers/setup.py
Normal file
@@ -0,0 +1,43 @@
|
||||
import uuid
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, func
|
||||
from pydantic import BaseModel
|
||||
from ..dependencies import get_db
|
||||
from ..models.user import User
|
||||
from ..services.auth import hash_password, create_token
|
||||
|
||||
router = APIRouter(prefix="/api/setup", tags=["setup"])
|
||||
|
||||
|
||||
class SetupRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
email: str = ""
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
async def setup_status(db: AsyncSession = Depends(get_db)):
|
||||
result = await db.execute(select(func.count()).select_from(User))
|
||||
count = result.scalar()
|
||||
return {"needsSetup": count == 0}
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def run_setup(body: SetupRequest, db: AsyncSession = Depends(get_db)):
|
||||
result = await db.execute(select(func.count()).select_from(User))
|
||||
if result.scalar() > 0:
|
||||
raise HTTPException(status_code=400, detail="Setup already completed")
|
||||
|
||||
admin = User(
|
||||
id=str(uuid.uuid4()),
|
||||
username=body.username,
|
||||
email=body.email,
|
||||
password_hash=hash_password(body.password),
|
||||
is_admin=True,
|
||||
)
|
||||
db.add(admin)
|
||||
await db.flush()
|
||||
admin.token = create_token(admin.id)
|
||||
await db.commit()
|
||||
return {"success": True}
|
||||
@@ -1,10 +1,11 @@
|
||||
import React, { useEffect } from 'react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
|
||||
import { useAuthStore } from './store/authStore'
|
||||
import { usePlayerStore } from './store/playerStore'
|
||||
import Layout from './components/common/Layout'
|
||||
import AudioPlayer from './components/player/AudioPlayer'
|
||||
import Login from './pages/Login'
|
||||
import Setup from './pages/Setup'
|
||||
import Library from './pages/Library'
|
||||
import BookDetail from './pages/BookDetail'
|
||||
import PodcastDetail from './pages/PodcastDetail'
|
||||
@@ -20,8 +21,19 @@ function AppRoutes() {
|
||||
const { user, loadAuth } = useAuthStore()
|
||||
const { libraries } = useAuthStore()
|
||||
const { expanded, setExpanded } = usePlayerStore()
|
||||
const [setupNeeded, setSetupNeeded] = useState<boolean | null>(null)
|
||||
|
||||
useEffect(() => { loadAuth() }, [])
|
||||
useEffect(() => {
|
||||
fetch('/api/setup/status')
|
||||
.then((r) => r.json())
|
||||
.then((d) => setSetupNeeded(d.needsSetup ?? false))
|
||||
.catch(() => setSetupNeeded(false))
|
||||
}, [])
|
||||
|
||||
useEffect(() => { if (setupNeeded === false) loadAuth() }, [setupNeeded])
|
||||
|
||||
if (setupNeeded === null) return <div className="min-h-screen bg-background" />
|
||||
if (setupNeeded) return <Setup onComplete={() => setSetupNeeded(false)} />
|
||||
|
||||
const defaultLib = libraries?.[0]?.id
|
||||
|
||||
|
||||
103
frontend/src/components/common/FileBrowser.tsx
Normal file
103
frontend/src/components/common/FileBrowser.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import { Folder, ChevronRight, ChevronUp, X, Check, Loader2 } from 'lucide-react'
|
||||
import api from '../../api/client'
|
||||
|
||||
interface Entry { name: string; path: string; isDir: boolean }
|
||||
|
||||
interface Props {
|
||||
initialPath?: string
|
||||
onSelect: (path: string) => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export default function FileBrowser({ initialPath = '/', onSelect, onClose }: Props) {
|
||||
const [path, setPath] = useState(initialPath)
|
||||
const [entries, setEntries] = useState<Entry[]>([])
|
||||
const [parent, setParent] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const load = async (p: string) => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const r = await api.get('/api/filebrowser', { params: { path: p } })
|
||||
setPath(r.data.path)
|
||||
setParent(r.data.parent)
|
||||
setEntries(r.data.entries.filter((e: Entry) => e.isDir))
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Fehler beim Laden')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => { load(initialPath) }, [])
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4" onClick={onClose}>
|
||||
<div
|
||||
className="bg-surface border border-white/10 rounded-xl w-full max-w-lg shadow-2xl flex flex-col"
|
||||
style={{ maxHeight: '80vh' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b border-white/10 flex-shrink-0">
|
||||
<h3 className="text-sm font-semibold text-white">Ordner auswählen</h3>
|
||||
<button onClick={onClose} className="text-gray-400 hover:text-white">
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Current path */}
|
||||
<div className="px-4 py-2 bg-white/5 border-b border-white/10 flex items-center gap-2 flex-shrink-0">
|
||||
{parent && (
|
||||
<button onClick={() => load(parent)} className="text-gray-400 hover:text-white flex-shrink-0">
|
||||
<ChevronUp size={16} />
|
||||
</button>
|
||||
)}
|
||||
<p className="text-xs text-gray-300 font-mono truncate">{path}</p>
|
||||
</div>
|
||||
|
||||
{/* Entry list */}
|
||||
<div className="overflow-y-auto flex-1">
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-10">
|
||||
<Loader2 size={24} className="text-primary animate-spin" />
|
||||
</div>
|
||||
) : error ? (
|
||||
<p className="text-red-400 text-sm px-4 py-6">{error}</p>
|
||||
) : entries.length === 0 ? (
|
||||
<p className="text-gray-500 text-sm px-4 py-6">Keine Unterordner</p>
|
||||
) : (
|
||||
entries.map((e) => (
|
||||
<button
|
||||
key={e.path}
|
||||
onClick={() => load(e.path)}
|
||||
className="w-full flex items-center gap-3 px-4 py-2.5 hover:bg-white/5 text-gray-300 hover:text-white text-sm text-left transition-colors"
|
||||
>
|
||||
<Folder size={16} className="text-yellow-500 flex-shrink-0" />
|
||||
<span className="flex-1 truncate">{e.name}</span>
|
||||
<ChevronRight size={14} className="flex-shrink-0 text-gray-600" />
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex items-center justify-between px-4 py-3 border-t border-white/10 flex-shrink-0">
|
||||
<button onClick={onClose} className="text-gray-400 text-sm hover:text-white">
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { onSelect(path); onClose() }}
|
||||
className="flex items-center gap-2 bg-primary text-black px-4 py-2 rounded-lg text-sm font-medium hover:bg-primary/80"
|
||||
>
|
||||
<Check size={14} />
|
||||
Auswählen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { Users, Library, Settings, Trash2, Plus, RefreshCw, Loader2, Check, X } from 'lucide-react'
|
||||
import { Users, Library, Settings, Trash2, Plus, RefreshCw, Loader2, Check, X, FolderOpen } from 'lucide-react'
|
||||
import { getUsers, createUser, deleteUser, getSettings, updateSettings } from '../api/me'
|
||||
import { getLibraries, scanLibrary, createLibrary, deleteLibrary } from '../api/libraries'
|
||||
import FileBrowser from '../components/common/FileBrowser'
|
||||
|
||||
type Tab = 'users' | 'libraries' | 'settings'
|
||||
|
||||
@@ -119,6 +120,7 @@ function LibrariesPanel() {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [scanning, setScanning] = useState<string | null>(null)
|
||||
const [showCreate, setShowCreate] = useState(false)
|
||||
const [showBrowser, setShowBrowser] = useState(false)
|
||||
const [form, setForm] = useState({ name: '', path: '', mediaType: 'book' })
|
||||
|
||||
useEffect(() => { getLibraries().then(setLibraries).finally(() => setLoading(false)) }, [])
|
||||
@@ -160,10 +162,27 @@ function LibrariesPanel() {
|
||||
value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}
|
||||
className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:ring-1 focus:ring-primary"
|
||||
/>
|
||||
<input type="text" placeholder="Pfad (z.B. /audiofiles/hörbucher)"
|
||||
value={form.path} onChange={(e) => setForm({ ...form, path: e.target.value })}
|
||||
className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:ring-1 focus:ring-primary"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<input type="text" placeholder="Pfad (z.B. /audiofiles)"
|
||||
value={form.path} onChange={(e) => setForm({ ...form, path: e.target.value })}
|
||||
className="flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:ring-1 focus:ring-primary"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowBrowser(true)}
|
||||
className="flex items-center gap-1.5 bg-white/5 border border-white/10 px-3 py-2 rounded-lg text-sm text-gray-300 hover:text-white hover:bg-white/10"
|
||||
>
|
||||
<FolderOpen size={14} />
|
||||
Durchsuchen
|
||||
</button>
|
||||
</div>
|
||||
{showBrowser && (
|
||||
<FileBrowser
|
||||
initialPath={form.path || '/'}
|
||||
onSelect={(p) => setForm({ ...form, path: p })}
|
||||
onClose={() => setShowBrowser(false)}
|
||||
/>
|
||||
)}
|
||||
<select value={form.mediaType} onChange={(e) => setForm({ ...form, mediaType: e.target.value })}
|
||||
className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-gray-300 focus:outline-none">
|
||||
<option value="book">Hörbücher</option>
|
||||
|
||||
84
frontend/src/pages/Setup.tsx
Normal file
84
frontend/src/pages/Setup.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
import React, { useState } from 'react'
|
||||
import { BookOpen, Loader2, Eye, EyeOff } from 'lucide-react'
|
||||
import api from '../api/client'
|
||||
|
||||
interface Props {
|
||||
onComplete: () => void
|
||||
}
|
||||
|
||||
export default function Setup({ onComplete }: Props) {
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [showPwd, setShowPwd] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const submit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
await api.post('/api/setup', { username, password })
|
||||
onComplete()
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Fehler beim Anlegen')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="flex items-center justify-center gap-3 mb-3">
|
||||
<BookOpen className="text-primary" size={32} />
|
||||
<h1 className="text-3xl font-bold text-white">Audiolib</h1>
|
||||
</div>
|
||||
<p className="text-center text-gray-400 text-sm mb-8">Erster Start — Admin-Konto anlegen</p>
|
||||
|
||||
<form onSubmit={submit} className="bg-surface rounded-xl p-6 space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm text-gray-400 mb-1">Benutzername</label>
|
||||
<input
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-white placeholder-gray-500 focus:outline-none focus:ring-1 focus:ring-primary"
|
||||
placeholder="admin"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm text-gray-400 mb-1">Passwort</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showPwd ? 'text' : 'password'}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 pr-10 text-white placeholder-gray-500 focus:outline-none focus:ring-1 focus:ring-primary"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPwd(!showPwd)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-white"
|
||||
tabIndex={-1}
|
||||
>
|
||||
{showPwd ? <EyeOff size={16} /> : <Eye size={16} />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{error && <p className="text-red-400 text-sm">{error}</p>}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || !username || !password}
|
||||
className="w-full bg-primary text-black font-semibold py-2.5 rounded-lg hover:bg-primary/80 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
|
||||
>
|
||||
{loading && <Loader2 size={16} className="animate-spin" />}
|
||||
Konto anlegen
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user