Compare commits
20 Commits
33f8080aa8
...
v0.1.5.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2fa8aa0042 | ||
|
|
8ecf430bf5 | ||
|
|
71abb7c322 | ||
|
|
b730c6637a | ||
|
|
6e93529bc3 | ||
|
|
990e1927e9 | ||
|
|
d7fee047c2 | ||
|
|
28d14ff099 | ||
|
|
b1493b44bf | ||
|
|
b8a803b76e | ||
|
|
e2bdf0fc88 | ||
|
|
2cb9af8d2b | ||
|
|
d6ad01b00e | ||
|
|
693817b18c | ||
|
|
41336e3af3 | ||
|
|
d7ec691469 | ||
|
|
5e1700712e | ||
|
|
f691384a34 | ||
|
|
f0d75c591a | ||
|
|
1f34d5813e |
@@ -786,7 +786,16 @@ export default function AdminPage({ params }: { params: { locale: string } }) {
|
|||||||
|
|
||||||
const handleSaveCurator = async (e: React.FormEvent) => {
|
const handleSaveCurator = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!curatorUsername.trim()) return;
|
if (!curatorUsername.trim()) {
|
||||||
|
alert('Bitte einen Benutzernamen eingeben.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Beim Anlegen eines neuen Kurators ist ein Passwort Pflicht.
|
||||||
|
if (!editingCuratorId && !curatorPassword.trim()) {
|
||||||
|
alert('Für neue Kuratoren muss ein Passwort gesetzt werden.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const payload: any = {
|
const payload: any = {
|
||||||
username: curatorUsername.trim(),
|
username: curatorUsername.trim(),
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import CuratorPageInner from '../../curator/page';
|
|||||||
|
|
||||||
export default function CuratorPage() {
|
export default function CuratorPage() {
|
||||||
// Wrapper für die lokalisierte Route /[locale]/curator
|
// Wrapper für die lokalisierte Route /[locale]/curator
|
||||||
|
// Hinweis: Pfad '../../curator/page' zeigt von 'app/[locale]/curator' korrekt auf 'app/curator/page'.
|
||||||
return <CuratorPageInner />;
|
return <CuratorPageInner />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import { PrismaClient } from '@prisma/client';
|
import { PrismaClient, Prisma } from '@prisma/client';
|
||||||
import bcrypt from 'bcryptjs';
|
import bcrypt from 'bcryptjs';
|
||||||
import { requireAdminAuth } from '@/lib/auth';
|
import { requireAdminAuth } from '@/lib/auth';
|
||||||
|
|
||||||
@@ -69,6 +69,15 @@ export async function POST(request: NextRequest) {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error creating curator:', error);
|
console.error('Error creating curator:', error);
|
||||||
|
|
||||||
|
// Handle unique username constraint violation explicitly
|
||||||
|
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'A curator with this username already exists.' },
|
||||||
|
{ status: 409 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -153,6 +162,15 @@ export async function PUT(request: NextRequest) {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error updating curator:', error);
|
console.error('Error updating curator:', error);
|
||||||
|
|
||||||
|
// Handle unique username constraint violation explicitly for updates
|
||||||
|
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'A curator with this username already exists.' },
|
||||||
|
{ status: 409 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
21
app/api/public-songs/route.ts
Normal file
21
app/api/public-songs/route.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
// Öffentliche, schreibgeschützte Song-Liste für das Spiel (GuessInput etc.).
|
||||||
|
// Kein Auth, nur Lesen der nötigsten Felder.
|
||||||
|
export async function GET() {
|
||||||
|
const songs = await prisma.song.findMany({
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
title: true,
|
||||||
|
artist: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(songs);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -30,7 +30,19 @@ function curatorCanEditSong(context: StaffContext, song: any, assignments: { gen
|
|||||||
if (context.role === 'admin') return true;
|
if (context.role === 'admin') return true;
|
||||||
|
|
||||||
const songGenreIds = (song.genres || []).map((g: any) => g.id);
|
const songGenreIds = (song.genres || []).map((g: any) => g.id);
|
||||||
const songSpecialIds = (song.specials || []).map((s: any) => s.specialId ?? s.id);
|
// `song.specials` kann je nach Context entweder ein Array von
|
||||||
|
// - `Special` (mit `id`)
|
||||||
|
// - `SpecialSong` (mit `specialId`)
|
||||||
|
// - `SpecialSong` (mit Relation `special.id`)
|
||||||
|
// sein. Wir normalisieren hier auf reine Zahlen-IDs.
|
||||||
|
const songSpecialIds = (song.specials || [])
|
||||||
|
.map((s: any) => {
|
||||||
|
if (s?.id != null) return s.id;
|
||||||
|
if (s?.specialId != null) return s.specialId;
|
||||||
|
if (s?.special?.id != null) return s.special.id;
|
||||||
|
return undefined;
|
||||||
|
})
|
||||||
|
.filter((id: any): id is number => typeof id === 'number');
|
||||||
|
|
||||||
// Songs ohne Genres/Specials sind für Kuratoren generell editierbar
|
// Songs ohne Genres/Specials sind für Kuratoren generell editierbar
|
||||||
if (songGenreIds.length === 0 && songSpecialIds.length === 0) {
|
if (songGenreIds.length === 0 && songSpecialIds.length === 0) {
|
||||||
@@ -47,7 +59,14 @@ function curatorCanDeleteSong(context: StaffContext, song: any, assignments: { g
|
|||||||
if (context.role === 'admin') return true;
|
if (context.role === 'admin') return true;
|
||||||
|
|
||||||
const songGenreIds = (song.genres || []).map((g: any) => g.id);
|
const songGenreIds = (song.genres || []).map((g: any) => g.id);
|
||||||
const songSpecialIds = (song.specials || []).map((s: any) => s.specialId ?? s.id);
|
const songSpecialIds = (song.specials || [])
|
||||||
|
.map((s: any) => {
|
||||||
|
if (s?.id != null) return s.id;
|
||||||
|
if (s?.specialId != null) return s.specialId;
|
||||||
|
if (s?.special?.id != null) return s.special.id;
|
||||||
|
return undefined;
|
||||||
|
})
|
||||||
|
.filter((id: any): id is number => typeof id === 'number');
|
||||||
|
|
||||||
const allGenresAllowed = songGenreIds.every((id: number) => assignments.genreIds.has(id));
|
const allGenresAllowed = songGenreIds.every((id: number) => assignments.genreIds.has(id));
|
||||||
const allSpecialsAllowed = songSpecialIds.every((id: number) => assignments.specialIds.has(id));
|
const allSpecialsAllowed = songSpecialIds.every((id: number) => assignments.specialIds.has(id));
|
||||||
@@ -59,7 +78,11 @@ function curatorCanDeleteSong(context: StaffContext, song: any, assignments: { g
|
|||||||
export const runtime = 'nodejs';
|
export const runtime = 'nodejs';
|
||||||
export const maxDuration = 60; // 60 seconds timeout for uploads
|
export const maxDuration = 60; // 60 seconds timeout for uploads
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET(request: NextRequest) {
|
||||||
|
// Alle Zugriffe auf die Songliste erfordern Staff-Auth (Admin oder Kurator)
|
||||||
|
const { error, context } = await requireStaffAuth(request);
|
||||||
|
if (error || !context) return error!;
|
||||||
|
|
||||||
const songs = await prisma.song.findMany({
|
const songs = await prisma.song.findMany({
|
||||||
orderBy: { createdAt: 'desc' },
|
orderBy: { createdAt: 'desc' },
|
||||||
include: {
|
include: {
|
||||||
@@ -73,8 +96,33 @@ export async function GET() {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let visibleSongs = songs;
|
||||||
|
|
||||||
|
if (context.role === 'curator') {
|
||||||
|
const assignments = await getCuratorAssignments(context.curator.id);
|
||||||
|
|
||||||
|
visibleSongs = songs.filter(song => {
|
||||||
|
const songGenreIds = song.genres.map(g => g.id);
|
||||||
|
// `song.specials` ist hier ein Array von SpecialSong mit Relation `special`.
|
||||||
|
// Es kann theoretisch verwaiste Einträge ohne `special` geben → defensiv optional chainen.
|
||||||
|
const songSpecialIds = song.specials
|
||||||
|
.map(ss => ss.special?.id)
|
||||||
|
.filter((id): id is number => typeof id === 'number');
|
||||||
|
|
||||||
|
// Songs ohne Genres/Specials sind immer sichtbar
|
||||||
|
if (songGenreIds.length === 0 && songSpecialIds.length === 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasGenre = songGenreIds.some(id => assignments.genreIds.has(id));
|
||||||
|
const hasSpecial = songSpecialIds.some(id => assignments.specialIds.has(id));
|
||||||
|
|
||||||
|
return hasGenre || hasSpecial;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Map to include activation count and flatten specials
|
// Map to include activation count and flatten specials
|
||||||
const songsWithActivations = songs.map(song => ({
|
const songsWithActivations = visibleSongs.map(song => ({
|
||||||
id: song.id,
|
id: song.id,
|
||||||
title: song.title,
|
title: song.title,
|
||||||
artist: song.artist,
|
artist: song.artist,
|
||||||
@@ -85,7 +133,10 @@ export async function GET() {
|
|||||||
activations: song.puzzles.length,
|
activations: song.puzzles.length,
|
||||||
puzzles: song.puzzles,
|
puzzles: song.puzzles,
|
||||||
genres: song.genres,
|
genres: song.genres,
|
||||||
specials: song.specials.map(ss => ss.special),
|
// Nur Specials mit existierender Relation durchreichen, um undefinierte Einträge zu vermeiden.
|
||||||
|
specials: song.specials
|
||||||
|
.map(ss => ss.special)
|
||||||
|
.filter((s): s is any => !!s),
|
||||||
averageRating: song.averageRating,
|
averageRating: song.averageRating,
|
||||||
ratingCount: song.ratingCount,
|
ratingCount: song.ratingCount,
|
||||||
excludeFromGlobal: song.excludeFromGlobal,
|
excludeFromGlobal: song.excludeFromGlobal,
|
||||||
@@ -411,57 +462,62 @@ export async function PUT(request: Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (effectiveGenreIds && effectiveGenreIds.length > 0) {
|
// Wenn effectiveGenreIds definiert ist, auch leere Arrays übernehmen (löscht alle Zuordnungen).
|
||||||
|
if (effectiveGenreIds !== undefined) {
|
||||||
data.genres = {
|
data.genres = {
|
||||||
set: effectiveGenreIds.map((gId: number) => ({ id: gId }))
|
set: effectiveGenreIds.map((gId: number) => ({ id: gId }))
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle SpecialSong relations separately
|
// Execute all database write operations in a transaction to ensure consistency
|
||||||
if (effectiveSpecialIds !== undefined) {
|
const updatedSong = await prisma.$transaction(async (tx) => {
|
||||||
// First, get current special assignments
|
// Handle SpecialSong relations separately
|
||||||
const currentSpecials = await prisma.specialSong.findMany({
|
if (effectiveSpecialIds !== undefined) {
|
||||||
where: { songId: Number(id) }
|
// First, get current special assignments (within transaction)
|
||||||
});
|
const currentSpecials = await tx.specialSong.findMany({
|
||||||
|
where: { songId: Number(id) }
|
||||||
const currentSpecialIds = currentSpecials.map(ss => ss.specialId);
|
|
||||||
const newSpecialIds = effectiveSpecialIds as number[];
|
|
||||||
|
|
||||||
// Delete removed specials
|
|
||||||
const toDelete = currentSpecialIds.filter(sid => !newSpecialIds.includes(sid));
|
|
||||||
if (toDelete.length > 0) {
|
|
||||||
await prisma.specialSong.deleteMany({
|
|
||||||
where: {
|
|
||||||
songId: Number(id),
|
|
||||||
specialId: { in: toDelete }
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// Add new specials
|
const currentSpecialIds = currentSpecials.map(ss => ss.specialId);
|
||||||
const toAdd = newSpecialIds.filter(sid => !currentSpecialIds.includes(sid));
|
const newSpecialIds = effectiveSpecialIds as number[];
|
||||||
if (toAdd.length > 0) {
|
|
||||||
await prisma.specialSong.createMany({
|
|
||||||
data: toAdd.map(specialId => ({
|
|
||||||
songId: Number(id),
|
|
||||||
specialId,
|
|
||||||
startTime: 0
|
|
||||||
}))
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatedSong = await prisma.song.update({
|
// Delete removed specials
|
||||||
where: { id: Number(id) },
|
const toDelete = currentSpecialIds.filter(sid => !newSpecialIds.includes(sid));
|
||||||
data,
|
if (toDelete.length > 0) {
|
||||||
include: {
|
await tx.specialSong.deleteMany({
|
||||||
genres: true,
|
where: {
|
||||||
specials: {
|
songId: Number(id),
|
||||||
include: {
|
specialId: { in: toDelete }
|
||||||
special: true
|
}
|
||||||
}
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add new specials
|
||||||
|
const toAdd = newSpecialIds.filter(sid => !currentSpecialIds.includes(sid));
|
||||||
|
if (toAdd.length > 0) {
|
||||||
|
await tx.specialSong.createMany({
|
||||||
|
data: toAdd.map(specialId => ({
|
||||||
|
songId: Number(id),
|
||||||
|
specialId,
|
||||||
|
startTime: 0
|
||||||
|
}))
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Update song (this also handles genre relations via Prisma's set operation)
|
||||||
|
return await tx.song.update({
|
||||||
|
where: { id: Number(id) },
|
||||||
|
data,
|
||||||
|
include: {
|
||||||
|
genres: true,
|
||||||
|
specials: {
|
||||||
|
include: {
|
||||||
|
special: true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json(updatedSong);
|
return NextResponse.json(updatedSong);
|
||||||
@@ -507,7 +563,7 @@ export async function DELETE(request: Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete file
|
// Delete files first (outside transaction, as file system operations can't be rolled back)
|
||||||
const filePath = path.join(process.cwd(), 'public/uploads', song.filename);
|
const filePath = path.join(process.cwd(), 'public/uploads', song.filename);
|
||||||
try {
|
try {
|
||||||
await unlink(filePath);
|
await unlink(filePath);
|
||||||
@@ -526,9 +582,11 @@ export async function DELETE(request: Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete from database (will cascade delete related puzzles)
|
// Delete from database in transaction (will cascade delete related puzzles, SpecialSong, etc.)
|
||||||
await prisma.song.delete({
|
await prisma.$transaction(async (tx) => {
|
||||||
where: { id: Number(id) },
|
await tx.song.delete({
|
||||||
|
where: { id: Number(id) },
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json({ success: true });
|
return NextResponse.json({ success: true });
|
||||||
|
|||||||
1333
app/curator/CuratorPageClient.tsx
Normal file
1333
app/curator/CuratorPageClient.tsx
Normal file
File diff suppressed because it is too large
Load Diff
1325
app/curator/page.tsx
1325
app/curator/page.tsx
File diff suppressed because it is too large
Load Diff
@@ -391,6 +391,13 @@ export default function Game({ dailyPuzzle, genre = null, isSpecial = false, max
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Aktuelle Attempt-Anzeige:
|
||||||
|
// - Während des Spiels: nächster Versuch = guesses.length + 1
|
||||||
|
// - Nach Spielende (gelöst oder verloren): letzter Versuch = guesses.length
|
||||||
|
const currentAttempt = (gameState.isSolved || gameState.isFailed)
|
||||||
|
? gameState.guesses.length
|
||||||
|
: gameState.guesses.length + 1;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="container">
|
<div className="container">
|
||||||
<header className="header">
|
<header className="header">
|
||||||
@@ -403,7 +410,7 @@ export default function Game({ dailyPuzzle, genre = null, isSpecial = false, max
|
|||||||
<main className="game-board">
|
<main className="game-board">
|
||||||
<div style={{ borderBottom: '1px solid #e5e7eb', paddingBottom: '1rem' }}>
|
<div style={{ borderBottom: '1px solid #e5e7eb', paddingBottom: '1rem' }}>
|
||||||
<div id="tour-status" className="status-bar">
|
<div id="tour-status" className="status-bar">
|
||||||
<span>{t('attempt')} {gameState.guesses.length + 1} / {maxAttempts}</span>
|
<span>{t('attempt')} {currentAttempt} / {maxAttempts}</span>
|
||||||
<span>{unlockedSeconds}s {t('unlocked')}</span>
|
<span>{unlockedSeconds}s {t('unlocked')}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -512,14 +519,20 @@ export default function Game({ dailyPuzzle, genre = null, isSpecial = false, max
|
|||||||
</audio>
|
</audio>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div style={{ marginBottom: '1rem' }}>
|
<div style={{ marginBottom: '1.25rem' }}>
|
||||||
<StarRating onRate={handleRatingSubmit} hasRated={hasRated} />
|
<StarRating onRate={handleRatingSubmit} hasRated={hasRated} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div style={{ marginBottom: '1.25rem', textAlign: 'center' }}>
|
||||||
|
<p style={{ fontSize: '0.85rem', color: 'var(--muted-foreground)', marginBottom: '0.5rem' }}>
|
||||||
|
{t('shareExplanation')}
|
||||||
|
</p>
|
||||||
|
<button onClick={handleShare} className="btn-primary">
|
||||||
|
{shareText}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
{statistics && <Statistics statistics={statistics} />}
|
{statistics && <Statistics statistics={statistics} />}
|
||||||
<button onClick={handleShare} className="btn-primary" style={{ marginTop: '1rem' }}>
|
|
||||||
{shareText}
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -22,9 +22,25 @@ export default function GuessInput({ onGuess, disabled }: GuessInputProps) {
|
|||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetch('/api/songs')
|
fetch('/api/public-songs')
|
||||||
.then(res => res.json())
|
.then(res => {
|
||||||
.then(data => setSongs(data));
|
if (!res.ok) {
|
||||||
|
throw new Error(`Failed to load songs: ${res.status}`);
|
||||||
|
}
|
||||||
|
return res.json();
|
||||||
|
})
|
||||||
|
.then(data => {
|
||||||
|
if (Array.isArray(data)) {
|
||||||
|
setSongs(data);
|
||||||
|
} else {
|
||||||
|
console.error('Unexpected songs payload in GuessInput:', data);
|
||||||
|
setSongs([]);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
console.error('Error loading songs for GuessInput:', err);
|
||||||
|
setSongs([]);
|
||||||
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -49,13 +49,15 @@ export async function getOrCreateDailyPuzzle(genre: Genre | null = null) {
|
|||||||
// Calculate total weight
|
// Calculate total weight
|
||||||
const totalWeight = weightedSongs.reduce((sum, item) => sum + item.weight, 0);
|
const totalWeight = weightedSongs.reduce((sum, item) => sum + item.weight, 0);
|
||||||
|
|
||||||
// Pick a random song based on weights
|
// Pick a random song based on weights using cumulative weights
|
||||||
|
// This ensures proper distribution and handles edge cases
|
||||||
let random = Math.random() * totalWeight;
|
let random = Math.random() * totalWeight;
|
||||||
let selectedSong = weightedSongs[0].song;
|
let selectedSong = weightedSongs[weightedSongs.length - 1].song; // Fallback to last song
|
||||||
|
|
||||||
|
let cumulativeWeight = 0;
|
||||||
for (const item of weightedSongs) {
|
for (const item of weightedSongs) {
|
||||||
random -= item.weight;
|
cumulativeWeight += item.weight;
|
||||||
if (random <= 0) {
|
if (random <= cumulativeWeight) {
|
||||||
selectedSong = item.song;
|
selectedSong = item.song;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -156,11 +158,13 @@ export async function getOrCreateSpecialPuzzle(special: Special) {
|
|||||||
|
|
||||||
const totalWeight = weightedSongs.reduce((sum, item) => sum + item.weight, 0);
|
const totalWeight = weightedSongs.reduce((sum, item) => sum + item.weight, 0);
|
||||||
let random = Math.random() * totalWeight;
|
let random = Math.random() * totalWeight;
|
||||||
let selectedSpecialSong = weightedSongs[0].specialSong;
|
let selectedSpecialSong = weightedSongs[weightedSongs.length - 1].specialSong; // Fallback to last song
|
||||||
|
|
||||||
|
// Pick a random song based on weights using cumulative weights
|
||||||
|
let cumulativeWeight = 0;
|
||||||
for (const item of weightedSongs) {
|
for (const item of weightedSongs) {
|
||||||
random -= item.weight;
|
cumulativeWeight += item.weight;
|
||||||
if (random <= 0) {
|
if (random <= cumulativeWeight) {
|
||||||
selectedSpecialSong = item.specialSong;
|
selectedSpecialSong = item.specialSong;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,7 @@
|
|||||||
"comeBackTomorrow": "Komm morgen zurück für ein neues Lied.",
|
"comeBackTomorrow": "Komm morgen zurück für ein neues Lied.",
|
||||||
"theSongWas": "Das Lied war:",
|
"theSongWas": "Das Lied war:",
|
||||||
"score": "Punkte",
|
"score": "Punkte",
|
||||||
|
"shareExplanation": "Teile dein Ergebnis mit Freund:innen – so hilfst du, Hördle bekannter zu machen.",
|
||||||
"scoreBreakdown": "Punkteaufschlüsselung",
|
"scoreBreakdown": "Punkteaufschlüsselung",
|
||||||
"albumCover": "Album-Cover",
|
"albumCover": "Album-Cover",
|
||||||
"released": "Veröffentlicht",
|
"released": "Veröffentlicht",
|
||||||
|
|||||||
@@ -41,6 +41,7 @@
|
|||||||
"comeBackTomorrow": "Come back tomorrow for a new song.",
|
"comeBackTomorrow": "Come back tomorrow for a new song.",
|
||||||
"theSongWas": "The song was:",
|
"theSongWas": "The song was:",
|
||||||
"score": "Score",
|
"score": "Score",
|
||||||
|
"shareExplanation": "Share your result with friends – your support helps Hördle grow.",
|
||||||
"scoreBreakdown": "Score Breakdown",
|
"scoreBreakdown": "Score Breakdown",
|
||||||
"albumCover": "Album Cover",
|
"albumCover": "Album Cover",
|
||||||
"released": "Released",
|
"released": "Released",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "hoerdle",
|
"name": "hoerdle",
|
||||||
"version": "0.1.4.11",
|
"version": "0.1.5.2",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
echo "🚀 Starting optimized deployment..."
|
echo "🚀 Starting optimized deployment with full rollback support..."
|
||||||
|
|
||||||
# Backup database
|
# Backup database (per Deployment, inkl. Metadaten für Rollback)
|
||||||
echo "💾 Creating database backup..."
|
echo "💾 Creating database backup for this deployment..."
|
||||||
|
|
||||||
# Try to find database path from docker-compose.yml or .env
|
# Try to find database path from docker-compose.yml or .env
|
||||||
DB_PATH=""
|
DB_PATH=""
|
||||||
@@ -26,16 +26,29 @@ if [ -n "$DB_PATH" ]; then
|
|||||||
# Convert container path to host path if needed
|
# Convert container path to host path if needed
|
||||||
# /app/data/prod.db -> ./data/prod.db
|
# /app/data/prod.db -> ./data/prod.db
|
||||||
DB_PATH=$(echo "$DB_PATH" | sed 's|/app/|./|')
|
DB_PATH=$(echo "$DB_PATH" | sed 's|/app/|./|')
|
||||||
|
|
||||||
if [ -f "$DB_PATH" ]; then
|
if [ -f "$DB_PATH" ]; then
|
||||||
# Create backups directory
|
# Create backups directory
|
||||||
mkdir -p ./backups
|
mkdir -p ./backups
|
||||||
|
|
||||||
# Create timestamped backup
|
# Create timestamped backup
|
||||||
BACKUP_FILE="./backups/$(basename "$DB_PATH" .db)_$(date +%Y%m%d_%H%M%S).db"
|
DEPLOY_TS="$(date +%Y%m%d_%H%M%S)"
|
||||||
|
BACKUP_FILE="./backups/$(basename "$DB_PATH" .db)_${DEPLOY_TS}.db"
|
||||||
cp "$DB_PATH" "$BACKUP_FILE"
|
cp "$DB_PATH" "$BACKUP_FILE"
|
||||||
echo "✅ Database backed up to: $BACKUP_FILE"
|
echo "✅ Database backed up to: $BACKUP_FILE"
|
||||||
|
|
||||||
|
# Store metadata for restore (Timestamp, DB-Path, Git-Commit)
|
||||||
|
CURRENT_COMMIT="$(git rev-parse HEAD || echo 'unknown')"
|
||||||
|
{
|
||||||
|
echo "timestamp=${DEPLOY_TS}"
|
||||||
|
echo "db_path=${DB_PATH}"
|
||||||
|
echo "backup_file=${BACKUP_FILE}"
|
||||||
|
echo "git_commit=${CURRENT_COMMIT}"
|
||||||
|
} > "./backups/last_deploy.meta"
|
||||||
|
|
||||||
|
# Append to history manifest (eine Zeile pro Deployment)
|
||||||
|
echo "${DEPLOY_TS}|${DB_PATH}|${BACKUP_FILE}|${CURRENT_COMMIT}" >> "./backups/deploy_history.log"
|
||||||
|
|
||||||
# Keep only last 10 backups
|
# Keep only last 10 backups
|
||||||
ls -t ./backups/*.db | tail -n +11 | xargs -r rm
|
ls -t ./backups/*.db | tail -n +11 | xargs -r rm
|
||||||
echo "🧹 Cleaned old backups (keeping last 10)"
|
echo "🧹 Cleaned old backups (keeping last 10)"
|
||||||
@@ -46,13 +59,10 @@ else
|
|||||||
echo "⚠️ Could not determine database path from config files"
|
echo "⚠️ Could not determine database path from config files"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Pull latest changes
|
# Nur neueste Version holen (shallow fetch), vollständiges Repo ist im Deployment nicht nötig
|
||||||
echo "📥 Pulling latest changes from git..."
|
echo "📥 Fetching latest commit (shallow clone) from git..."
|
||||||
git pull
|
git fetch --prune --tags --depth=1 origin master
|
||||||
|
git reset --hard origin/master
|
||||||
# Fetch all tags
|
|
||||||
echo "🏷️ Fetching git tags..."
|
|
||||||
git fetch --tags
|
|
||||||
|
|
||||||
# Prüfe und erstelle/repariere Netzwerk falls nötig
|
# Prüfe und erstelle/repariere Netzwerk falls nötig
|
||||||
echo "🌐 Prüfe Docker-Netzwerk..."
|
echo "🌐 Prüfe Docker-Netzwerk..."
|
||||||
|
|||||||
93
scripts/restore.sh
Normal file
93
scripts/restore.sh
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
echo "🧯 Hördle restore script – Rollback auf früheres Datenbank-Backup"
|
||||||
|
|
||||||
|
# Hilfsfunktion für Fehlerausgabe
|
||||||
|
die() {
|
||||||
|
echo "❌ $1" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# Backup-Verzeichnis
|
||||||
|
BACKUP_DIR="./backups"
|
||||||
|
|
||||||
|
if [ ! -d "$BACKUP_DIR" ]; then
|
||||||
|
die "Kein Backup-Verzeichnis gefunden (${BACKUP_DIR}). Es scheint noch kein Deployment-Backup erstellt worden zu sein."
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Argument: gewünschter Backup-Timestamp oder 'latest'
|
||||||
|
TARGET="$1"
|
||||||
|
|
||||||
|
if [ -z "$TARGET" ]; then
|
||||||
|
echo "⚙️ Nutzung:"
|
||||||
|
echo " ./scripts/restore.sh latest # neuestes Backup zurückspielen"
|
||||||
|
echo " ./scripts/restore.sh 20250101_120000 # bestimmtes Backup (Timestamp aus Dateiname)"
|
||||||
|
echo ""
|
||||||
|
echo "Verfügbare Backups:"
|
||||||
|
ls -1 "${BACKUP_DIR}"/*.db 2>/dev/null || echo " (keine .db-Backups gefunden)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# DB-Pfad wie in deploy.sh bestimmen
|
||||||
|
DB_PATH=""
|
||||||
|
|
||||||
|
if [ -f "docker-compose.yml" ]; then
|
||||||
|
DB_PATH=$(grep -oP 'DATABASE_URL=file:\K[^\s]+' docker-compose.yml | head -1)
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -z "$DB_PATH" ] && [ -f ".env" ]; then
|
||||||
|
DB_PATH=$(grep -oP '^DATABASE_URL=file:\K.+' .env | head -1)
|
||||||
|
fi
|
||||||
|
|
||||||
|
DB_PATH=$(echo "$DB_PATH" | tr -d '"' | tr -d "'")
|
||||||
|
|
||||||
|
if [ -z "$DB_PATH" ]; then
|
||||||
|
die "Konnte den Datenbank-Pfad aus docker-compose.yml oder .env nicht ermitteln."
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Containerpfad zu Hostpfad umbauen (/app/... -> ./...)
|
||||||
|
DB_PATH=$(echo "$DB_PATH" | sed 's|/app/|./|')
|
||||||
|
|
||||||
|
echo "📁 Ziel-Datenbank-Datei: $DB_PATH"
|
||||||
|
|
||||||
|
# Backup-Datei bestimmen
|
||||||
|
if [ "$TARGET" = "latest" ]; then
|
||||||
|
BACKUP_FILE=$(ls -t "${BACKUP_DIR}"/*.db 2>/dev/null | head -1 || true)
|
||||||
|
[ -z "$BACKUP_FILE" ] && die "Kein Backup gefunden."
|
||||||
|
else
|
||||||
|
# Versuchen, exakten Dateinamen zu finden
|
||||||
|
if [ -f "${BACKUP_DIR}/${TARGET}" ]; then
|
||||||
|
BACKUP_FILE="${BACKUP_DIR}/${TARGET}"
|
||||||
|
else
|
||||||
|
# Versuchen, anhand des Timestamps ein Backup zu finden
|
||||||
|
BACKUP_FILE=$(ls "${BACKUP_DIR}"/*"${TARGET}"*.db 2>/dev/null | head -1 || true)
|
||||||
|
fi
|
||||||
|
|
||||||
|
[ -z "$BACKUP_FILE" ] && die "Kein Backup für '${TARGET}' gefunden."
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "⏪ Verwende Backup-Datei: $BACKUP_FILE"
|
||||||
|
|
||||||
|
if [ ! -f "$BACKUP_FILE" ]; then
|
||||||
|
die "Backup-Datei existiert nicht: $BACKUP_FILE"
|
||||||
|
fi
|
||||||
|
|
||||||
|
read -p "❗ Dies überschreibt die aktuelle Datenbank-Datei. Fortfahren? [y/N] " CONFIRM
|
||||||
|
if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
|
||||||
|
echo "Abgebrochen."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "📦 Kopiere Backup nach: $DB_PATH"
|
||||||
|
cp "$BACKUP_FILE" "$DB_PATH"
|
||||||
|
|
||||||
|
echo "🔄 Starte Docker-Container neu..."
|
||||||
|
docker compose restart hoerdle
|
||||||
|
|
||||||
|
echo "✅ Restore abgeschlossen."
|
||||||
|
echo "ℹ️ Hinweis: Der Code-Stand (Git-Commit) ist nicht automatisch zurückgedreht."
|
||||||
|
echo " Falls du auch die App-Version zurückrollen möchtest, checke lokal den passenden Commit/Tag aus"
|
||||||
|
echo " und führe anschließend wieder ./scripts/deploy.sh aus."
|
||||||
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user