Perf: 9 Performance-Fixes — SW by-v1072
Backend: - DB: 3 neue Indizes (forum_posts thread+user, routes user) — Forum/Routen-Queries - Caching: cache.py (TTL-Cache ohne neue Dependency) für 5 statische Listen (training_exercises, pflege_tipps, wiki_stats, wiki_gruppen, help_articles) - diary.py + breeder_photos.py: Bildverarbeitung (ffmpeg/PIL/EXIF) per run_in_executor → blockiert Event-Loop nicht mehr - scheduler.py: 11 kollidierende Jobs auf 5-Min-Intervalle gestaggert, coalesce=True - social.py: ORDER BY RANDOM() ohne LIMIT in 2 Stellen gefixt - alerts.py: Haversine-Loop bekommt SQL-Bounding-Box-Vorfilter Frontend: - sw.js: Tile-Cache mit LRU-Eviction (max 500 Einträge) - admin.js: Event-Listener-Leak — Tab-Klicks per Delegation statt N Listener - api.js: compressImage() Helper — Client-seitiges Resize auf max 2000px (HEIC/Videos/<500KB unverändert), integriert in 8 Upload-Stellen (diary, dog-profile×2, walks, poison, lost, health×2) Bump APP_VER 1071 → 1072 (sw.js, app.js, main.py, index.html)
This commit is contained in:
parent
3abf974d29
commit
c03884cb81
23 changed files with 461 additions and 120 deletions
|
|
@ -101,9 +101,9 @@
|
|||
</script>
|
||||
|
||||
<!-- CSS: Reihenfolge ist wichtig — ?v= zwingt Browser zur Neuladung -->
|
||||
<link rel="stylesheet" href="/css/design-system.css?v=1071">
|
||||
<link rel="stylesheet" href="/css/layout.css?v=1071">
|
||||
<link rel="stylesheet" href="/css/components.css?v=1071">
|
||||
<link rel="stylesheet" href="/css/design-system.css?v=1072">
|
||||
<link rel="stylesheet" href="/css/layout.css?v=1072">
|
||||
<link rel="stylesheet" href="/css/components.css?v=1072">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
|
|
@ -616,10 +616,10 @@
|
|||
<div id="modal-container"></div>
|
||||
|
||||
<!-- JS: Reihenfolge ist wichtig — erst Basis, dann Features -->
|
||||
<script src="/js/api.js?v=1071"></script>
|
||||
<script src="/js/ui.js?v=1071"></script>
|
||||
<script src="/js/app.js?v=1071"></script>
|
||||
<script src="/js/worlds.js?v=1071"></script>
|
||||
<script src="/js/api.js?v=1072"></script>
|
||||
<script src="/js/ui.js?v=1072"></script>
|
||||
<script src="/js/app.js?v=1072"></script>
|
||||
<script src="/js/worlds.js?v=1072"></script>
|
||||
|
||||
<!-- Feature-Seiten werden lazy geladen -->
|
||||
|
||||
|
|
|
|||
|
|
@ -814,9 +814,57 @@ const API = (() => {
|
|||
} catch {}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------
|
||||
// BILD-KOMPRESSION (Client-Side vor Upload)
|
||||
// ----------------------------------------------------------
|
||||
// iPhone-Fotos sind 4-12 MB — vor Upload auf max. 2000px / JPEG q=0.85
|
||||
// skalieren. HEIC/HEIF unverändert lassen (Browser-Canvas kann sie nicht
|
||||
// decoden, Backend hat eigene HEIC-Konvertierung). Nicht-Bilder unverändert.
|
||||
async function compressImage(file, maxSize = 2000, quality = 0.85) {
|
||||
try {
|
||||
if (!file || !(file instanceof File || file instanceof Blob)) return file;
|
||||
const type = (file.type || '').toLowerCase();
|
||||
if (!type.startsWith('image/')) return file;
|
||||
if (type === 'image/heic' || type === 'image/heif') return file;
|
||||
if (type === 'image/gif') return file; // GIF-Animation nicht kaputt skalieren
|
||||
if (file.size < 500_000) return file; // <500KB: lohnt sich nicht
|
||||
|
||||
const img = await createImageBitmap(file);
|
||||
try {
|
||||
const longest = Math.max(img.width, img.height);
|
||||
const scale = Math.min(1, maxSize / longest);
|
||||
// Nur skalieren wenn Bild wirklich größer ist; bei scale=1 trotzdem als JPEG
|
||||
// neu kodieren — spart bei iPhone-Originalen oft trotzdem viel (EXIF, weniger Qualität).
|
||||
const w = Math.round(img.width * scale);
|
||||
const h = Math.round(img.height * scale);
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = w; canvas.height = h;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return file;
|
||||
ctx.drawImage(img, 0, 0, w, h);
|
||||
|
||||
const blob = await new Promise(res => canvas.toBlob(res, 'image/jpeg', quality));
|
||||
if (!blob || blob.size >= file.size) return file; // Kompression hat nichts gebracht
|
||||
|
||||
const newName = (file.name || 'photo.jpg').replace(/\.(heic|heif|png|webp|jpeg|jpg)$/i, '.jpg');
|
||||
const finalName = /\.jpe?g$/i.test(newName) ? newName : (newName + '.jpg');
|
||||
return new File([blob], finalName, { type: 'image/jpeg', lastModified: Date.now() });
|
||||
} finally {
|
||||
// ImageBitmap-Ressourcen freigeben (wo unterstützt)
|
||||
if (typeof img.close === 'function') img.close();
|
||||
}
|
||||
} catch {
|
||||
// Bei jedem Fehler (z.B. createImageBitmap auf HEIC) — original zurück
|
||||
return file;
|
||||
}
|
||||
}
|
||||
// Auch global verfügbar, damit Seiten-Module ihn direkt nutzen können
|
||||
if (typeof window !== 'undefined') window.compressImage = compressImage;
|
||||
|
||||
// Öffentliche API
|
||||
return {
|
||||
get, post, put, patch, del, upload, swCacheDelete,
|
||||
get, post, put, patch, del, upload, swCacheDelete, compressImage,
|
||||
auth, dogs, diary, health, tieraerzte, healthDocs, poison,
|
||||
places, routes, walks, events, sitting, forum, lost, knigge, weather, push,
|
||||
friends, chat, webcal, importData, sharing, widget, notifications, services, ratings, sittingAccess, training, notes,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
Router, State-Management, Navigation, Initialisierung.
|
||||
============================================================ */
|
||||
|
||||
const APP_VER = '1071'; // ← bei jedem Deploy mit Frontend-Änderungen erhöhen
|
||||
const APP_VER = '1072'; // ← bei jedem Deploy mit Frontend-Änderungen erhöhen
|
||||
const APP_VERSION = '1.6.0'; // ← semantische Version, wird bei make release gesetzt
|
||||
const IS_STAGING = location.hostname === 'staging.banyaro.app';
|
||||
// Cache-Bust-Parameter nach Update-Reload sofort entfernen.
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ window.Page_admin = (() => {
|
|||
let _container = null;
|
||||
let _appState = null;
|
||||
let _tab = 'uebersicht';
|
||||
let _delegationAttached = null; // WeakRef-Ersatz: zuletzt mit Delegation versehener Container
|
||||
|
||||
const TABS = [
|
||||
{ id: 'uebersicht', label: 'Übersicht', icon: 'house-line' },
|
||||
|
|
@ -71,20 +72,43 @@ window.Page_admin = (() => {
|
|||
|
||||
_container.querySelector('#adm-tabs')
|
||||
?.style.setProperty('--adm-tab-cols', Math.ceil(TABS.length / 2));
|
||||
_container.querySelectorAll('#adm-tabs .by-tab').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
_tab = btn.dataset.tab;
|
||||
_container.querySelectorAll('#adm-tabs .by-tab').forEach(b =>
|
||||
b.classList.toggle('active', b.dataset.tab === _tab)
|
||||
);
|
||||
_renderTab();
|
||||
});
|
||||
});
|
||||
|
||||
// Event-Delegation: Listener EINMAL pro Container-Instanz setzen
|
||||
// (innerHTML überschreibt zwar das DOM, aber bei jedem init() würden ohne
|
||||
// Flag erneut N=18 Tab-Listener akkumuliert werden)
|
||||
if (_delegationAttached !== _container) {
|
||||
_container.addEventListener('click', _onContainerClick);
|
||||
_delegationAttached = _container;
|
||||
}
|
||||
|
||||
_renderActionItems();
|
||||
_renderTab();
|
||||
}
|
||||
|
||||
// Delegation-Handler für Tab-Buttons + Action-Item-Buttons
|
||||
function _onContainerClick(e) {
|
||||
// Tab-Button (#adm-tabs .by-tab)
|
||||
const tabBtn = e.target.closest('#adm-tabs .by-tab');
|
||||
if (tabBtn && _container.contains(tabBtn)) {
|
||||
_tab = tabBtn.dataset.tab;
|
||||
_container.querySelectorAll('#adm-tabs .by-tab').forEach(b =>
|
||||
b.classList.toggle('active', b.dataset.tab === _tab)
|
||||
);
|
||||
_renderTab();
|
||||
return;
|
||||
}
|
||||
// Action-Item-Button ([data-action-tab])
|
||||
const actionBtn = e.target.closest('[data-action-tab]');
|
||||
if (actionBtn && _container.contains(actionBtn)) {
|
||||
_tab = actionBtn.dataset.actionTab;
|
||||
_container.querySelectorAll('#adm-tabs .by-tab').forEach(b =>
|
||||
b.classList.toggle('active', b.dataset.tab === _tab)
|
||||
);
|
||||
_renderTab();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
async function _renderActionItems() {
|
||||
const el = _container.querySelector('#adm-action-items');
|
||||
if (!el) return;
|
||||
|
|
@ -134,15 +158,7 @@ window.Page_admin = (() => {
|
|||
</span>
|
||||
</div>`;
|
||||
|
||||
el.querySelectorAll('[data-action-tab]').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
_tab = btn.dataset.actionTab;
|
||||
_container.querySelectorAll('#adm-tabs .by-tab').forEach(b =>
|
||||
b.classList.toggle('active', b.dataset.tab === _tab)
|
||||
);
|
||||
_renderTab();
|
||||
});
|
||||
});
|
||||
// Klicks auf [data-action-tab] werden zentral via _onContainerClick (Delegation) behandelt
|
||||
}
|
||||
|
||||
async function _renderTab() {
|
||||
|
|
|
|||
|
|
@ -1728,8 +1728,10 @@ window.Page_diary = (() => {
|
|||
if (saveBtn) saveBtn.textContent = `0 von ${total} hochgeladen…`;
|
||||
|
||||
const results = await Promise.all(_newFiles.map(async file => {
|
||||
// Bild-Kompression vor Upload (HEIC/Video/<500KB werden unverändert durchgereicht)
|
||||
const toUpload = await API.compressImage(file);
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('file', toUpload);
|
||||
try {
|
||||
const m = await API.diary.uploadMedia(_appState.activeDog.id, entryId, formData);
|
||||
if (saveBtn) saveBtn.textContent = `${++done} von ${total} hochgeladen…`;
|
||||
|
|
|
|||
|
|
@ -762,8 +762,10 @@ window.Page_dog_profile = (() => {
|
|||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
try {
|
||||
// Client-Side-Kompression vor Upload (HEIC bleibt unverändert)
|
||||
const toUpload = await API.compressImage(file);
|
||||
const fd = new FormData();
|
||||
fd.append('file', file);
|
||||
fd.append('file', toUpload);
|
||||
const result = await API.dogs.uploadPhoto(dog.id, fd);
|
||||
// Position zurücksetzen
|
||||
await API.dogs.updatePhotoPosition(dog.id, 1.0, 0.0, 0.0);
|
||||
|
|
@ -1384,8 +1386,10 @@ window.Page_dog_profile = (() => {
|
|||
// Foto hochladen wenn gewählt
|
||||
if (fotoFile) {
|
||||
try {
|
||||
// Client-Side-Kompression vor Upload
|
||||
const toUpload = await API.compressImage(fotoFile);
|
||||
const fd = new FormData();
|
||||
fd.append('file', fotoFile);
|
||||
fd.append('file', toUpload);
|
||||
const result = await API.dogs.uploadPhoto(saved.id, fd);
|
||||
saved.foto_url = result.foto_url;
|
||||
_appState.activeDog = { ...saved };
|
||||
|
|
|
|||
|
|
@ -1263,8 +1263,9 @@ window.Page_health = (() => {
|
|||
if (!saved.media_items) saved.media_items = [];
|
||||
for (const f of files) {
|
||||
try {
|
||||
const toUpload = await API.compressImage(f);
|
||||
const fd = new FormData();
|
||||
fd.append('file', f);
|
||||
fd.append('file', toUpload);
|
||||
const res = await API.health.uploadMedia(dogId, saved.id, fd);
|
||||
saved.media_items.push({ id: res.id, url: res.url, media_type: res.media_type });
|
||||
// Rückwärtskompatibilität: erste Datei auch als datei_url sichern
|
||||
|
|
@ -2739,6 +2740,8 @@ window.Page_health = (() => {
|
|||
}
|
||||
|
||||
await UI.asyncButton(btn, async () => {
|
||||
// Client-Side-Kompression nur wenn Bild (PDFs etc. unverändert durchgereicht)
|
||||
const toUpload = await API.compressImage(file);
|
||||
const formData = new FormData();
|
||||
formData.append('dog_id', String(dog.id));
|
||||
formData.append('typ', fd.typ);
|
||||
|
|
@ -2746,7 +2749,7 @@ window.Page_health = (() => {
|
|||
formData.append('beschreibung', fd.beschreibung || '');
|
||||
formData.append('datum', fd.datum || '');
|
||||
if (fd.vet_id) formData.append('vet_id', fd.vet_id);
|
||||
formData.append('file', file);
|
||||
formData.append('file', toUpload);
|
||||
|
||||
try {
|
||||
const doc = await API.healthDocs.upload(formData);
|
||||
|
|
|
|||
|
|
@ -772,8 +772,9 @@ window.Page_lost = (() => {
|
|||
// Foto hochladen
|
||||
if (photoInput?.files[0]) {
|
||||
try {
|
||||
const toUpload = await API.compressImage(photoInput.files[0]);
|
||||
const formData = new FormData();
|
||||
formData.append('file', photoInput.files[0]);
|
||||
formData.append('file', toUpload);
|
||||
const media = await API.lost.uploadFoto(created.id, formData);
|
||||
created.foto_url = media.foto_url;
|
||||
} catch {
|
||||
|
|
|
|||
|
|
@ -552,8 +552,9 @@ window.Page_poison = (() => {
|
|||
// Foto hochladen
|
||||
if (photoInput?.files[0]) {
|
||||
try {
|
||||
const toUpload = await API.compressImage(photoInput.files[0]);
|
||||
const formData = new FormData();
|
||||
formData.append('file', photoInput.files[0]);
|
||||
formData.append('file', toUpload);
|
||||
const media = await API.poison.uploadPhoto(created.id, formData);
|
||||
created.foto_url = media.foto_url;
|
||||
} catch {
|
||||
|
|
|
|||
|
|
@ -628,8 +628,10 @@ window.Page_walks = (() => {
|
|||
document.getElementById('wd-photo-input')?.addEventListener('change', async function() {
|
||||
if (!this.files.length) return;
|
||||
const file = this.files[0];
|
||||
// Client-Side-Kompression vor Upload (HEIC bleibt unverändert)
|
||||
const toUpload = await API.compressImage(file);
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('file', toUpload);
|
||||
try {
|
||||
const photo = await API.walks.uploadPhoto(walk.id, formData);
|
||||
const grid = document.getElementById('wd-photos-grid');
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
============================================================ */
|
||||
|
||||
// ← EINZIGE Stelle für die Version — STATIC_ASSETS und CACHE_VERSION leiten sich ab
|
||||
const VER = '1071';
|
||||
const VER = '1072';
|
||||
const CACHE_VERSION = `by-v${VER}`;
|
||||
const CACHE_STATIC = `${CACHE_VERSION}-static`;
|
||||
const CACHE_TILES = 'ban-yaro-tiles-v1'; // bleibt über SW-Updates erhalten
|
||||
|
|
@ -132,6 +132,26 @@ function _isMediaUpload(request) {
|
|||
return (request.headers.get('Content-Type') || '').includes('multipart');
|
||||
}
|
||||
|
||||
// Tile-Cache LRU: Eviction wenn zu viele Tiles drin sind
|
||||
// cache.keys() liefert Insertion-Order — daher löschen wir vom Anfang.
|
||||
// Bei jedem Tile-Add: trimTileCache() im Hintergrund (kein await vor respondWith).
|
||||
const _TILE_MAX_ENTRIES = 500;
|
||||
let _tileTrimRunning = false;
|
||||
async function trimTileCache(maxEntries = _TILE_MAX_ENTRIES) {
|
||||
if (_tileTrimRunning) return; // gleichzeitige Trims verhindern
|
||||
_tileTrimRunning = true;
|
||||
try {
|
||||
const cache = await caches.open(CACHE_TILES);
|
||||
const keys = await cache.keys();
|
||||
if (keys.length > maxEntries) {
|
||||
const toDelete = keys.slice(0, keys.length - maxEntries);
|
||||
await Promise.all(toDelete.map(k => cache.delete(k)));
|
||||
}
|
||||
} catch {} finally {
|
||||
_tileTrimRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Welche GET-API-Endpoints sollen gecacht werden?
|
||||
const _CACHEABLE_GET = [
|
||||
/^\/api\/dogs(\/\d+)?$/,
|
||||
|
|
@ -315,14 +335,18 @@ self.addEventListener('fetch', event => {
|
|||
return;
|
||||
}
|
||||
|
||||
// OSM-Kartenkacheln: eigener persistenter Cache
|
||||
// OSM-Kartenkacheln: eigener persistenter Cache (Cache-First mit LRU-Eviction)
|
||||
if (url.hostname.endsWith('tile.openstreetmap.org')) {
|
||||
event.respondWith(
|
||||
caches.open(CACHE_TILES).then(cache =>
|
||||
cache.match(event.request).then(cached => {
|
||||
if (cached) return cached;
|
||||
return fetch(event.request).then(response => {
|
||||
if (response.ok) cache.put(event.request, response.clone());
|
||||
if (response.ok) {
|
||||
cache.put(event.request, response.clone())
|
||||
.then(() => trimTileCache()) // im Hintergrund — blockiert respondWith nicht
|
||||
.catch(() => {});
|
||||
}
|
||||
return response;
|
||||
});
|
||||
})
|
||||
|
|
@ -435,6 +459,7 @@ self.addEventListener('message', event => {
|
|||
function fetchBatch() {
|
||||
if (queue.length === 0) {
|
||||
source?.postMessage({ type: 'CACHE_TILES_PROGRESS', done: total, total });
|
||||
trimTileCache(); // nach Bulk-Vorausladen einmal trimmen
|
||||
return;
|
||||
}
|
||||
const batch = queue.splice(0, 8);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue