Compare commits

...

15 Commits

Author SHA1 Message Date
Hördle Bot
25680a19b6 Bump version to 0.1.6.34 2025-12-14 14:24:48 +01:00
Hördle Bot
fb3e4c10dd Version-Anzeige: Neuesten Git-Tag statt Commit-Hash verwenden 2025-12-14 14:24:42 +01:00
Hördle Bot
b7293a4614 Fix: Update API route for loading cover images
- Changed the method of loading cover images to use the API route instead of directly from the filesystem.
- This aligns with the existing approach for audio playback and improves consistency across the application.
2025-12-14 14:12:45 +01:00
Hördle Bot
830e91fdff Bump version to 0.1.6.33 2025-12-14 14:11:07 +01:00
Hördle Bot
bc95af8027 Cover-Bilder über API-Route laden statt direkt aus Dateisystem 2025-12-14 14:11:02 +01:00
Hördle Bot
56461fe0bb Bump version to 0.1.6.31 2025-12-07 13:17:03 +01:00
Hördle Bot
989654f62e Fix: Waveform-Editor verwendet jetzt API-Route statt statischen Pfad
- WaveformEditor verwendet /api/audio/... statt /uploads/...
- Gleicher Pfad wie beim Abspielen aus der Liste
- Behebt Problem, dass neu hochgeladene Dateien nicht im Waveform-Editor bearbeitbar waren
2025-12-07 13:16:32 +01:00
Hördle Bot
bf9fbe37c0 Bump version to 0.1.6.30 2025-12-07 13:04:23 +01:00
Hördle Bot
c83dc7a5e5 Fix: Cache-Control-Header für Waveform-Editor API-Route hinzugefügt
- API-Route sendet jetzt explizite No-Cache-Header
- Frontend-Fetch verwendet cache: 'no-store'
- Behebt Problem, dass neu hochgeladene Dateien erst nach Container-Neustart bearbeitbar waren
2025-12-07 13:03:43 +01:00
Hördle Bot
7999d63e6d Fix: Versteckte Specials werden nicht mehr in Navigationsleiste angezeigt 2025-12-07 12:40:50 +01:00
Hördle Bot
2bf21fd75f feat: improve Gotify variable extraction in backup script
- Enhanced the loading of Gotify variables from the .env file by adding checks for existing values.
- Ensured that only non-empty and non-comment lines are processed for GOTIFY_URL and GOTIFY_APP_TOKEN.
2025-12-07 10:30:37 +01:00
Hördle Bot
e48d823c92 feat: enhance Gotify notification handling in backup script
- Added loading of environment variables from a .env file.
- Extracted Gotify configuration from docker-compose.yml if not set.
- Improved notification sending with success and error messages based on curl exit codes.
- Ensured Gotify notifications are only sent if properly configured.
2025-12-07 10:29:09 +01:00
Hördle Bot
84822e79ca feat: add Gotify notifications for Restic backup status
- Implemented a function to send notifications via Gotify for backup success, warnings, and failures.
- Notifications include details such as date and commit information.
- Added checks for Gotify configuration and fallback for JSON encoding.
2025-12-07 10:23:19 +01:00
Hördle Bot
17856ef09b Bump version to 0.1.6.28 2025-12-07 10:11:06 +01:00
Hördle Bot
fb833a7976 Fix: Waveform Editor lädt nicht für Titel ohne vollständige Song-Daten
- Filtere Songs ohne vollständige Song-Daten (song, filename) in CurateSpecialEditor
- Füge defensive Prüfungen hinzu bevor WaveformEditor gerendert wird
- Filtere unvollständige Songs bereits auf API-Ebene in curator/specials/[id]
- Verhindert Fehler wenn Songs ohne filename oder song-Objekt geladen werden
2025-12-07 10:07:43 +01:00
11 changed files with 367 additions and 19 deletions

View File

@@ -27,7 +27,9 @@ COPY . .
RUN if [ -n "$APP_VERSION" ]; then \ RUN if [ -n "$APP_VERSION" ]; then \
echo "$APP_VERSION" > /tmp/version.txt; \ echo "$APP_VERSION" > /tmp/version.txt; \
else \ else \
(git describe --tags --always 2>/dev/null || \ (git describe --tags --exact-match 2>/dev/null || \
git describe --tags --abbrev=0 2>/dev/null || \
git tag --sort=-version:refname | head -1 2>/dev/null || \
(grep -o '"version": "[^"]*"' package.json 2>/dev/null | cut -d'"' -f4 | sed 's/^/v/') || \ (grep -o '"version": "[^"]*"' package.json 2>/dev/null | cut -d'"' -f4 | sed 's/^/v/') || \
echo "dev") > /tmp/version.txt; \ echo "dev") > /tmp/version.txt; \
fi && \ fi && \

View File

@@ -73,7 +73,9 @@ export default async function GenrePage({ params }: PageProps) {
// Sort // Sort
genres.sort((a, b) => getLocalizedValue(a.name, locale).localeCompare(getLocalizedValue(b.name, locale))); genres.sort((a, b) => getLocalizedValue(a.name, locale).localeCompare(getLocalizedValue(b.name, locale)));
const specials = await prisma.special.findMany(); const specials = await prisma.special.findMany({
where: { hidden: false },
});
specials.sort((a, b) => getLocalizedValue(a.name, locale).localeCompare(getLocalizedValue(b.name, locale))); specials.sort((a, b) => getLocalizedValue(a.name, locale).localeCompare(getLocalizedValue(b.name, locale)));
const now = new Date(); const now = new Date();

View File

@@ -0,0 +1,95 @@
import { NextRequest, NextResponse } from 'next/server';
import { stat } from 'fs/promises';
import { createReadStream } from 'fs';
import path from 'path';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ filename: string }> }
) {
try {
const { filename } = await params;
// Security: Prevent path traversal attacks
// Allow alphanumeric, hyphens, underscores, and dots for image filenames
// Support common image formats: jpg, jpeg, png, gif, webp
const safeFilenamePattern = /^[a-zA-Z0-9_\-\.]+\.(jpg|jpeg|png|gif|webp)$/i;
if (!safeFilenamePattern.test(filename)) {
return new NextResponse('Invalid filename', { status: 400 });
}
// Additional check: ensure no path separators
if (filename.includes('/') || filename.includes('\\') || filename.includes('..')) {
return new NextResponse('Invalid filename', { status: 400 });
}
const filePath = path.join(process.cwd(), 'public/uploads/covers', filename);
// Security: Verify the resolved path is still within covers directory
const coversDir = path.join(process.cwd(), 'public/uploads/covers');
const resolvedPath = path.resolve(filePath);
if (!resolvedPath.startsWith(coversDir)) {
return new NextResponse('Forbidden', { status: 403 });
}
const stats = await stat(filePath);
const fileSize = stats.size;
// Determine content type based on file extension
const ext = filename.toLowerCase().split('.').pop();
const contentTypeMap: Record<string, string> = {
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'png': 'image/png',
'gif': 'image/gif',
'webp': 'image/webp',
};
const contentType = contentTypeMap[ext || ''] || 'image/jpeg';
const stream = createReadStream(filePath);
// Convert Node stream to Web stream
const readable = new ReadableStream({
start(controller) {
let isClosed = false;
stream.on('data', (chunk: any) => {
if (isClosed) return;
try {
controller.enqueue(chunk);
} catch (e) {
isClosed = true;
stream.destroy();
}
});
stream.on('end', () => {
if (isClosed) return;
isClosed = true;
controller.close();
});
stream.on('error', (err: any) => {
if (isClosed) return;
isClosed = true;
controller.error(err);
});
},
cancel() {
stream.destroy();
}
});
return new NextResponse(readable, {
status: 200,
headers: {
'Content-Length': fileSize.toString(),
'Content-Type': contentType,
'Cache-Control': 'public, max-age=3600, must-revalidate',
},
});
} catch (error) {
console.error('Error serving cover image:', error);
return new NextResponse('Internal Server Error', { status: 500 });
}
}

View File

@@ -1,9 +1,14 @@
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client'; import { PrismaClient } from '@prisma/client';
import { requireStaffAuth } from '@/lib/auth'; import { requireStaffAuth } from '@/lib/auth';
import { access } from 'fs/promises';
import path from 'path';
const prisma = new PrismaClient(); const prisma = new PrismaClient();
// Mark route as dynamic to prevent caching
export const dynamic = 'force-dynamic';
export async function GET( export async function GET(
request: NextRequest, request: NextRequest,
{ params }: { params: Promise<{ id: string }> } { params }: { params: Promise<{ id: string }> }
@@ -52,7 +57,41 @@ export async function GET(
return NextResponse.json({ error: 'Special not found' }, { status: 404 }); return NextResponse.json({ error: 'Special not found' }, { status: 404 });
} }
return NextResponse.json(special); // Filtere Songs ohne vollständige Song-Daten und prüfe Datei-Existenz
// Dies verhindert Fehler im Frontend, wenn Songs gelöscht wurden, Daten fehlen
// oder Dateien noch nicht im Container verfügbar sind (Volume Mount Delay)
const uploadsDir = path.join(process.cwd(), 'public/uploads');
const filteredSongs = await Promise.all(
special.songs
.filter(ss => ss.song && ss.song.filename)
.map(async (ss) => {
const filePath = path.join(uploadsDir, ss.song.filename);
try {
// Prüfe ob Datei existiert und zugänglich ist
await access(filePath);
return ss;
} catch (error) {
// Datei existiert nicht oder ist nicht zugänglich
console.warn(`[API] Song file not available: ${ss.song.filename} (may be syncing)`);
return null;
}
})
);
// Entferne null-Werte (Songs ohne verfügbare Dateien)
const availableSongs = filteredSongs.filter((ss): ss is typeof special.songs[0] => ss !== null);
return NextResponse.json({
...special,
songs: availableSongs,
}, {
headers: {
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
'Pragma': 'no-cache',
'Expires': '0',
},
});
} }

View File

@@ -1615,7 +1615,7 @@ export default function CuratorPageClient() {
</div> </div>
)} )}
<div style={{ overflowX: 'auto' }}> <div style={{ overflowX: 'auto', position: 'relative' }}>
<table <table
style={{ style={{
width: '100%', width: '100%',
@@ -1686,7 +1686,17 @@ export default function CuratorPageClient() {
{t('columnRating')} {sortField === 'averageRating' && (sortDirection === 'asc' ? '↑' : '↓')} {t('columnRating')} {sortField === 'averageRating' && (sortDirection === 'asc' ? '↑' : '↓')}
</th> </th>
<th style={{ padding: '0.5rem' }}>{t('columnExcludeGlobal')}</th> <th style={{ padding: '0.5rem' }}>{t('columnExcludeGlobal')}</th>
<th style={{ padding: '0.5rem' }}>{t('columnActions')}</th> <th
style={{
padding: '0.5rem',
position: 'sticky',
right: 0,
backgroundColor: 'white',
zIndex: 10,
}}
>
{t('columnActions')}
</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -1701,12 +1711,13 @@ export default function CuratorPageClient() {
const isSelected = selectedSongIds.has(song.id); const isSelected = selectedSongIds.has(song.id);
const rowBackgroundColor = isSelected ? '#eff6ff' : 'white';
return ( return (
<tr <tr
key={song.id} key={song.id}
style={{ style={{
borderBottom: '1px solid #f3f4f6', borderBottom: '1px solid #f3f4f6',
backgroundColor: isSelected ? '#eff6ff' : 'transparent', backgroundColor: rowBackgroundColor,
}} }}
> >
<td style={{ padding: '0.5rem' }}> <td style={{ padding: '0.5rem' }}>
@@ -1810,7 +1821,7 @@ export default function CuratorPageClient() {
}} }}
> >
<img <img
src={`/uploads/covers/${song.coverImage}`} src={`/api/covers/${song.coverImage}`}
alt={`Cover für ${song.title}`} alt={`Cover für ${song.title}`}
style={{ style={{
width: '200px', width: '200px',
@@ -2010,6 +2021,10 @@ export default function CuratorPageClient() {
style={{ style={{
padding: '0.5rem', padding: '0.5rem',
whiteSpace: 'nowrap', whiteSpace: 'nowrap',
position: 'sticky',
right: 0,
backgroundColor: rowBackgroundColor,
zIndex: 10,
}} }}
> >
{isEditing ? ( {isEditing ? (
@@ -2025,6 +2040,7 @@ export default function CuratorPageClient() {
border: 'none', border: 'none',
borderRadius: '0.25rem', borderRadius: '0.25rem',
cursor: 'pointer', cursor: 'pointer',
whiteSpace: 'nowrap',
}} }}
> >
💾 💾
@@ -2038,6 +2054,7 @@ export default function CuratorPageClient() {
border: 'none', border: 'none',
borderRadius: '0.25rem', borderRadius: '0.25rem',
cursor: 'pointer', cursor: 'pointer',
whiteSpace: 'nowrap',
}} }}
> >

View File

@@ -32,6 +32,7 @@ export default function CuratorSpecialEditorPage() {
} }
const res = await fetch(`/api/curator/specials/${specialId}`, { const res = await fetch(`/api/curator/specials/${specialId}`, {
headers: getCuratorAuthHeaders(), headers: getCuratorAuthHeaders(),
cache: 'no-store',
}); });
if (res.status === 403) { if (res.status === 403) {
setError(t('specialForbidden')); setError(t('specialForbidden'));

View File

@@ -62,11 +62,14 @@ export default function CurateSpecialEditor({
saveChangesLabel = '💾 Save Changes', saveChangesLabel = '💾 Save Changes',
savedLabel = '✓ Saved', savedLabel = '✓ Saved',
}: CurateSpecialEditorProps) { }: CurateSpecialEditorProps) {
// Filtere Songs ohne vollständige Song-Daten (song, song.filename)
const validSongs = special.songs.filter(ss => ss.song && ss.song.filename);
const [selectedSongId, setSelectedSongId] = useState<number | null>( const [selectedSongId, setSelectedSongId] = useState<number | null>(
special.songs.length > 0 ? special.songs[0].songId : null validSongs.length > 0 ? validSongs[0].songId : null
); );
const [pendingStartTime, setPendingStartTime] = useState<number | null>( const [pendingStartTime, setPendingStartTime] = useState<number | null>(
special.songs.length > 0 ? special.songs[0].startTime : null validSongs.length > 0 ? validSongs[0].startTime : null
); );
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false); const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@@ -77,7 +80,7 @@ export default function CurateSpecialEditor({
const unlockSteps = JSON.parse(special.unlockSteps); const unlockSteps = JSON.parse(special.unlockSteps);
const totalDuration = unlockSteps[unlockSteps.length - 1]; const totalDuration = unlockSteps[unlockSteps.length - 1];
const selectedSpecialSong = special.songs.find(ss => ss.songId === selectedSongId) ?? null; const selectedSpecialSong = validSongs.find(ss => ss.songId === selectedSongId) ?? null;
const handleStartTimeChange = (newStartTime: number) => { const handleStartTimeChange = (newStartTime: number) => {
setPendingStartTime(newStartTime); setPendingStartTime(newStartTime);
@@ -111,7 +114,7 @@ export default function CurateSpecialEditor({
</p> </p>
</div> </div>
{special.songs.length === 0 ? ( {validSongs.length === 0 ? (
<div style={{ padding: '2rem', background: '#f3f4f6', borderRadius: '0.5rem', textAlign: 'center' }}> <div style={{ padding: '2rem', background: '#f3f4f6', borderRadius: '0.5rem', textAlign: 'center' }}>
<p>{noSongsHint}</p> <p>{noSongsHint}</p>
<p style={{ fontSize: '0.875rem', color: '#666', marginTop: '0.5rem' }}> <p style={{ fontSize: '0.875rem', color: '#666', marginTop: '0.5rem' }}>
@@ -125,7 +128,7 @@ export default function CurateSpecialEditor({
Select Song to Curate Select Song to Curate
</h2> </h2>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))', gap: '1rem' }}> <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))', gap: '1rem' }}>
{special.songs.map(ss => ( {validSongs.map(ss => (
<div <div
key={ss.songId} key={ss.songId}
onClick={() => { onClick={() => {
@@ -152,7 +155,7 @@ export default function CurateSpecialEditor({
</div> </div>
</div> </div>
{selectedSpecialSong && ( {selectedSpecialSong && selectedSpecialSong.song && selectedSpecialSong.song.filename ? (
<div> <div>
<h2 style={{ fontSize: '1.25rem', fontWeight: 'bold', marginBottom: '1rem' }}> <h2 style={{ fontSize: '1.25rem', fontWeight: 'bold', marginBottom: '1rem' }}>
Curate: {selectedSpecialSong.song.title} Curate: {selectedSpecialSong.song.title}
@@ -181,7 +184,7 @@ export default function CurateSpecialEditor({
</button> </button>
</div> </div>
<WaveformEditor <WaveformEditor
audioUrl={`/uploads/${selectedSpecialSong.song.filename}`} audioUrl={`/api/audio/${selectedSpecialSong.song.filename}`}
startTime={pendingStartTime ?? selectedSpecialSong.startTime} startTime={pendingStartTime ?? selectedSpecialSong.startTime}
duration={totalDuration} duration={totalDuration}
unlockSteps={unlockSteps} unlockSteps={unlockSteps}
@@ -189,7 +192,13 @@ export default function CurateSpecialEditor({
/> />
</div> </div>
</div> </div>
)} ) : selectedSpecialSong ? (
<div style={{ padding: '2rem', background: '#fee2e2', borderRadius: '0.5rem', textAlign: 'center' }}>
<p style={{ color: '#991b1b', fontWeight: 'bold' }}>
Fehler: Song-Daten unvollständig. Bitte wählen Sie einen anderen Song.
</p>
</div>
) : null}
</div> </div>
)} )}
</div> </div>

88
docs/TESTING.md Normal file
View File

@@ -0,0 +1,88 @@
# Integration Testing
Hördle uses [Playwright](https://playwright.dev/) for end-to-end (E2E) integration testing. These tests ensure that critical flows like gameplay, authentication, and admin management function correctly across different browsers.
## Prerequisites
Ensure you have the Playwright browsers installed:
```bash
npx playwright install
```
## Running Tests
### Headless Mode (CI/CLI)
To run all tests in headless mode (Chromium, Firefox, WebKit):
```bash
npm run test:e2e
```
### UI Mode (Interactive)
To run tests with a UI to inspect traces and watch execution:
```bash
npm run test:e2e:ui
```
### Specific Test File
To run a specific test file:
```bash
npx playwright test tests/gameplay.spec.ts
```
### Specific Project (Browser)
To run tests only on a specific browser (e.g., Chromium):
```bash
npx playwright test --project=chromium
```
## Configuration
The Playwright configuration is located in `playwright.config.ts`. It sets up the base URL (default: `http://localhost:3000`) and the web server command to start the app if it's not running.
### Environment Variables
* **`ADMIN_PASSWORD`**: The tests assume the admin password is `'admin123'`.
* In `app/api/admin/login/route.ts`, the login logic has been enhanced to check if `ADMIN_PASSWORD` is a bcrypt hash (starts with `$2b$`) or plain text.
* For local testing, you can set `ADMIN_PASSWORD="admin123"` in your `.env` or `.env.local` (though the default fallback in the code also handles this).
* **Curator Credentials**: The mock Curator login page (`app/[locale]/curator/page.tsx`) mocks validation for testing.
* Username: `elpatron`
* Password: `example_password`
## Test Structure
Tests are located in the `tests/` directory:
* **`auth.spec.ts`**: Verifies public access and admin login flows.
* **`admin.spec.ts`**: Checks the Admin Dashboard, including access protection and visibility of sections (Dashboard, Daily Puzzles, etc.).
* **`curator.spec.ts`**: Verifies the Curator login form and authentication flows (valid/invalid credentials).
* **`gameplay.spec.ts`**: Tests the core game loop: loading the game, playing audio, interaction with the prompt, and submitting a guess.
## Troubleshooting & Known Issues
### Next.js Development Overlay (`nextjs-portal`)
In development mode (`npm run dev`), Next.js injects an overlay (`<nextjs-portal>`) for hot reloading feedback. This overlay can sometimes intercept clicks intended for UI elements, causing tests to fail with "element is not clickable" or timeout errors.
**Solution:**
We inject a CSS style in the `beforeEach` hook of our tests to hide this overlay:
```typescript
test.beforeEach(async ({ page }) => {
await page.addStyleTag({ content: 'nextjs-portal, #nextjs-dev-overlay, [data-nextjs-dev-overlay] { display: none !important; }' });
});
```
### WebKit (Safari) Stability
WebKit can be slower or more sensitive to timing in some environments. If tests fail on WebKit but pass on other browsers:
1. Try increasing the timeout in `playwright.config.ts`.
2. Use `await page.waitForTimeout(500)` or specific assertions like `await expect(page).toHaveURL(...)` to allow for transition times, as implemented in `tests/admin.spec.ts`.

View File

@@ -1,6 +1,6 @@
{ {
"name": "hoerdle", "name": "hoerdle",
"version": "0.1.6.27", "version": "0.1.6.34",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",

View File

@@ -9,6 +9,79 @@ if [ -f "$HOME/.restic-env" ]; then
. "$HOME/.restic-env" . "$HOME/.restic-env"
fi fi
# Extract Gotify variables from .env file if not set (ignore comments and empty lines)
if [ -z "$GOTIFY_URL" ] && [ -f ".env" ]; then
GOTIFY_URL=$(grep -v '^#' .env | grep -v '^$' | grep '^GOTIFY_URL=' | head -1 | cut -d'=' -f2- | tr -d '"' | tr -d "'" | xargs || echo "")
fi
if [ -z "$GOTIFY_APP_TOKEN" ] && [ -f ".env" ]; then
GOTIFY_APP_TOKEN=$(grep -v '^#' .env | grep -v '^$' | grep '^GOTIFY_APP_TOKEN=' | head -1 | cut -d'=' -f2- | tr -d '"' | tr -d "'" | xargs || echo "")
fi
# Extract Gotify variables from docker-compose.yml if not set
if [ -z "$GOTIFY_URL" ] && [ -f "docker-compose.yml" ]; then
GOTIFY_URL=$(grep -oP 'GOTIFY_URL=\K[^\s]+' docker-compose.yml | head -1 | tr -d '"' | tr -d "'" || echo "")
fi
if [ -z "$GOTIFY_APP_TOKEN" ] && [ -f "docker-compose.yml" ]; then
GOTIFY_APP_TOKEN=$(grep -oP 'GOTIFY_APP_TOKEN=\K[^\s]+' docker-compose.yml | head -1 | tr -d '"' | tr -d "'" || echo "")
fi
# Function to send Gotify notification
send_gotify_notification() {
local title="$1"
local message="$2"
local priority="${3:-5}"
# Check if Gotify is configured
if [ -z "$GOTIFY_URL" ] || [ -z "$GOTIFY_APP_TOKEN" ]; then
echo "⚠️ Gotify not configured (GOTIFY_URL or GOTIFY_APP_TOKEN not set), skipping notification"
return 0
fi
echo "📢 Sending Gotify notification..."
# Send notification (fire and forget, don't fail on error)
# Use jq if available for proper JSON encoding, otherwise use simple approach
if command -v jq >/dev/null 2>&1; then
local json_payload
json_payload=$(jq -n \
--arg title "$title" \
--arg message "$message" \
--argjson priority "$priority" \
'{title: $title, message: $message, priority: $priority}')
local curl_exit_code=0
curl -sSf -X POST "${GOTIFY_URL}/message?token=${GOTIFY_APP_TOKEN}" \
-H "Content-Type: application/json" \
-d "$json_payload" \
>/dev/null 2>&1 || curl_exit_code=$?
if [ $curl_exit_code -eq 0 ]; then
echo "✅ Gotify notification sent successfully"
else
echo "⚠️ Failed to send Gotify notification (curl exit code: $curl_exit_code)"
fi
else
# Fallback: simple JSON encoding (replace " with \" and newlines with \n)
local escaped_title escaped_message
escaped_title=$(echo "$title" | sed 's/"/\\"/g')
escaped_message=$(echo "$message" | sed 's/"/\\"/g' | sed ':a;N;$!ba;s/\n/\\n/g')
local curl_exit_code=0
curl -sSf -X POST "${GOTIFY_URL}/message?token=${GOTIFY_APP_TOKEN}" \
-H "Content-Type: application/json" \
-d "{\"title\":\"${escaped_title}\",\"message\":\"${escaped_message}\",\"priority\":${priority}}" \
>/dev/null 2>&1 || curl_exit_code=$?
if [ $curl_exit_code -eq 0 ]; then
echo "✅ Gotify notification sent successfully"
else
echo "⚠️ Failed to send Gotify notification (curl exit code: $curl_exit_code)"
fi
fi
}
echo "💾 Creating Restic backup..." echo "💾 Creating Restic backup..."
if ! command -v restic >/dev/null 2>&1; then if ! command -v restic >/dev/null 2>&1; then
@@ -71,12 +144,32 @@ restic -r "$RESTIC_REPO" backup \
if [ $RESTIC_EXIT_CODE -eq 0 ]; then if [ $RESTIC_EXIT_CODE -eq 0 ]; then
echo "✅ Restic backup completed successfully" echo "✅ Restic backup completed successfully"
# Send success notification
send_gotify_notification \
"Hördle Backup: Erfolgreich" \
"Restic Backup wurde erfolgreich abgeschlossen.\nDatum: ${CURRENT_DATE}\nCommit: ${CURRENT_COMMIT_SHORT}" \
5
exit 0 exit 0
elif [ $RESTIC_EXIT_CODE -eq 3 ]; then elif [ $RESTIC_EXIT_CODE -eq 3 ]; then
echo "⚠️ Restic backup completed with warnings (some files could not be read), continuing..." echo "⚠️ Restic backup completed with warnings (some files could not be read), continuing..."
# Send warning notification
send_gotify_notification \
"Hördle Backup: Mit Warnungen" \
"Restic Backup wurde mit Warnungen abgeschlossen (einige Dateien konnten nicht gelesen werden).\nDatum: ${CURRENT_DATE}\nCommit: ${CURRENT_COMMIT_SHORT}" \
7
exit 0 exit 0
else else
echo "⚠️ Restic backup failed (exit code: $RESTIC_EXIT_CODE), continuing deployment..." echo "⚠️ Restic backup failed (exit code: $RESTIC_EXIT_CODE), continuing deployment..."
# Send error notification
send_gotify_notification \
"Hördle Backup: Fehlgeschlagen" \
"Restic Backup ist fehlgeschlagen (Exit Code: ${RESTIC_EXIT_CODE}).\nDatum: ${CURRENT_DATE}\nCommit: ${CURRENT_COMMIT_SHORT}" \
9
exit 0 exit 0
fi fi

View File

@@ -63,8 +63,10 @@ fi
./scripts/backup-restic.sh ./scripts/backup-restic.sh
# Nur neueste Version holen (shallow fetch), vollständiges Repo ist im Deployment nicht nötig # Nur neueste Version holen (shallow fetch), vollständiges Repo ist im Deployment nicht nötig
echo "📥 Fetching latest commit (shallow clone) from git..." # Wichtig: Tags müssen vollständig geholt werden für Version-Anzeige
git fetch --prune --tags --depth=1 origin master echo "📥 Fetching latest commit and all tags from git..."
git fetch --prune --tags origin master
git fetch --tags origin
git reset --hard origin/master git reset --hard origin/master
# Prüfe und erstelle/repariere Netzwerk falls nötig # Prüfe und erstelle/repariere Netzwerk falls nötig