import { http, HttpError } from '@/lib/http'; /** * Schnittstelle der Mediathek (App\Http\Controllers\MediaController). * Einträge: { id, path, url, thumb_url, name, alt, caption, tags, width, height, size, mime, missing, uploader, usage_count, created_at } */ export const BASE = '/redaktion/mediathek'; function xsrfToken() { const match = document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]*)/); return match ? decodeURIComponent(match[1]) : ''; } /** * Datei mit Fortschrittsanzeige hochladen (fetch kennt keinen Upload-Fortschritt). * * @returns {Promise} JSON-Antwort */ export function uploadWithProgress(url, file, { field = 'image', onProgress } = {}) { return new Promise((resolve, reject) => { const body = new FormData(); body.append(field, file); const xhr = new XMLHttpRequest(); xhr.open('POST', url); xhr.setRequestHeader('Accept', 'application/json'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('X-XSRF-TOKEN', xsrfToken()); xhr.withCredentials = true; xhr.upload.onprogress = (event) => event.lengthComputable && onProgress?.(event.loaded / event.total); xhr.onerror = () => reject(new HttpError(0, { message: 'Keine Verbindung. Bitte erneut versuchen.' })); xhr.onload = () => { let data = null; try { data = JSON.parse(xhr.responseText); } catch { data = null; } if (xhr.status >= 200 && xhr.status < 300) { resolve(data); } else { if (xhr.status === 413) data = { message: 'Die Datei ist zu groß.' }; reject(new HttpError(xhr.status, data)); } }; xhr.send(body); }); } function query(params) { const search = new URLSearchParams(); for (const [key, value] of Object.entries(params)) { if (Array.isArray(value)) { value.forEach((item) => search.append(`${key}[]`, item)); } else if (value !== null && value !== undefined && value !== '' && value !== false) { search.append(key, value); } } const string = search.toString(); return string ? `?${string}` : ''; } export const mediaApi = { list: (params = {}) => http.get(`${BASE}/liste${query(params)}`), show: (id) => http.get(`${BASE}/${id}`), update: (id, data) => http.put(`${BASE}/${id}`, data), remove: (id) => http.delete(`${BASE}/${id}`), bulkRemove: (ids, onlyUnused = false) => http.post(`${BASE}/loeschen`, { ids, only_unused: onlyUnused }), rebuild: () => http.post(`${BASE}/neu-einlesen`), /** @returns {Promise} Eintrag der Mediathek */ upload: (file, onProgress) => uploadWithProgress(BASE, file, { onProgress }).then((data) => data.media), replace: (id, file, onProgress) => uploadWithProgress(`${BASE}/${id}/ersetzen`, file, { onProgress }).then((data) => data.media), downloadUrl: (id) => `${BASE}/${id}/original`, }; /** Auswahl, wie sie Editoren zurückbekommen. */ export const toSelection = (item) => ({ id: item.id, path: item.path, url: item.url, alt: item.alt ?? '', caption: item.caption ?? '', width: item.width, height: item.height }); const PATH_PATTERN = /^[A-Za-z0-9_-][A-Za-z0-9/_.-]*\.(webp|jpe?g|png|gif)$/i; /** * Bildpfade in beliebigen Daten (Pagebuilder-JSON, HTML mit src="/uploads/…") – * für den Filter „Hier verwendet“ der Bildauswahl. * * @returns {string[]} */ export function collectImagePaths(value, found = new Set()) { if (typeof value === 'string') { if (PATH_PATTERN.test(value) && !value.includes('..')) { found.add(value); } else if (value.includes(' collectImagePaths(entry, found)); } else if (value && typeof value === 'object') { Object.values(value).forEach((entry) => collectImagePaths(entry, found)); } return [...found]; } export const ACCEPT ='image/jpeg,image/png,image/webp,image/gif'; export function formatBytes(bytes) { if (!bytes) return '–'; if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1).replace('.', ',')} MB`; return `${Math.max(1, Math.round(bytes / 1024))} KB`; } export function mimeLabel(mime) { return { 'image/webp': 'WebP', 'image/jpeg': 'JPEG', 'image/png': 'PNG', 'image/gif': 'GIF' }[mime] ?? (mime || '–'); }