Skip to content

Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.

Improve logo search reliability and controls and ai generation (#1126)

Jan Leon2ffcdb436f0b
diff --git a/endpoints/ai/generate_recommendations.php b/endpoints/ai/generate_recommendations.php
index 5fb3867..ac3eb4e 100644
--- a/endpoints/ai/generate_recommendations.php
+++ b/endpoints/ai/generate_recommendations.php
@@ -164,7 +164,46 @@ if (!$aiResult['success']) {
$recommendations = ai_extract_json($aiResult['content']);
+if (isset($recommendations['recommendations']) && is_array($recommendations['recommendations'])) {
+ $recommendations = $recommendations['recommendations'];
+}
+
if (is_array($recommendations)) {
+ $normalizedRecommendations = [];
+
+ foreach ($recommendations as $rec) {
+ if (!is_array($rec)) {
+ continue;
+ }
+
+ $title = $rec['title'] ?? null;
+ $description = $rec['description'] ?? null;
+ $savings = $rec['savings'] ?? '';
+
+ if (!is_scalar($title) || !is_scalar($description)
+ || ($savings !== null && !is_scalar($savings))) {
+ continue;
+ }
+
+ $title = trim((string) $title);
+ $description = trim((string) $description);
+ $savings = $savings === null ? '' : trim((string) $savings);
+
+ if ($title === '' || $description === '') {
+ continue;
+ }
+
+ $normalizedRecommendations[] = [
+ 'title' => $title,
+ 'description' => $description,
+ 'savings' => $savings,
+ ];
+ }
+
+ $recommendations = $normalizedRecommendations;
+}
+
+if (!empty($recommendations)) {
// Clear old recommendations
$stmt = $db->prepare("DELETE FROM ai_recommendations WHERE user_id = :user_id");
$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
@@ -193,9 +232,14 @@ if (is_array($recommendations)) {
exit;
}
+$jsonError = json_last_error_msg();
+ai_log_failure($aiSettings['type'] ?? '', $userId, 'invalid_completion_json', [
+ 'response_length' => strlen($aiResult['content']),
+ 'json_error' => $jsonError,
+]);
echo json_encode([
"success" => false,
- "message" => translate('error', $i18n),
- "json_error" => json_last_error_msg(),
+ "message" => translate('ai_invalid_json_response', $i18n),
+ "json_error" => $jsonError,
]);
exit;
diff --git a/endpoints/logos/search.php b/endpoints/logos/search.php
index b9d7b7e..3fb8e7d 100644
--- a/endpoints/logos/search.php
+++ b/endpoints/logos/search.php
@@ -67,6 +67,9 @@ if (isset($_GET['search'])) {
}
function fetchDDGImages($query, $vqd) {
+ // Ask DuckDuckGo specifically for transparent PNGs. The transparent
+ // colour filter alone can still return JPEG/WebP thumbnails or source
+ // images with an opaque background.
$params = http_build_query([
'l' => 'us-en',
'o' => 'json',
@@ -86,16 +89,32 @@ if (isset($_GET['search'])) {
$data = json_decode($response, true);
if (!isset($data['results']) || empty($data['results'])) return null;
- $out = [];
+ $pngResults = [];
+ $otherResults = [];
foreach ($data['results'] as $row) {
- $out[] = [
+ $result = [
'thumbnail' => $row['thumbnail'] ?? $row['image'] ?? null,
'image' => $row['image'] ?? null,
'width' => $row['width'] ?? null,
'height' => $row['height'] ?? null,
];
+
+ $imagePath = parse_url($result['image'] ?? '', PHP_URL_PATH) ?? '';
+ if (strtolower(pathinfo($imagePath, PATHINFO_EXTENSION)) === 'png') {
+ $pngResults[] = $result;
+ } else {
+ $otherResults[] = $result;
+ }
}
- return $out;
+
+ // Keep DuckDuckGo's relevance order within each group, but always put
+ // confirmed PNG source URLs first.
+ return array_merge($pngResults, $otherResults);
+ }
+
+ function searchDDGImages($query) {
+ $vqd = getVqdToken($query);
+ return $vqd ? fetchDDGImages($query, $vqd) : null;
}
function fetchBraveImages($query) {
@@ -142,7 +161,7 @@ if (isset($_GET['search'])) {
// Cache successful responses: repeat searches are common while filling the
// form, and both engines rate-limit aggressively (Brave after ~2 requests).
$cacheFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR
- . 'wallos-logo-search-' . md5($source . '|' . strtolower(urldecode($searchTerm))) . '.json';
+ . 'wallos-logo-search-v2-' . md5($source . '|' . strtolower(urldecode($searchTerm))) . '.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 3600) {
echo file_get_contents($cacheFile);
exit;
@@ -151,8 +170,23 @@ if (isset($_GET['search'])) {
$results = null;
if ($source === 'duckduckgo' || $source === 'all') {
- $vqd = getVqdToken($searchTerm);
- $results = $vqd ? fetchDDGImages($searchTerm, $vqd) : null;
+ // Prefer transparent PNG sources, but never let the stricter query
+ // break logo search entirely when DuckDuckGo rejects or limits it.
+ $pngSearchTerm = urlencode(urldecode($searchTerm) . ' filetype:png');
+ $results = searchDDGImages($pngSearchTerm);
+ if (!$results) {
+ $results = searchDDGImages($searchTerm);
+ }
+
+ if ($results) {
+ usort($results, function ($a, $b) {
+ $extension = function ($result) {
+ $path = parse_url($result['image'] ?? '', PHP_URL_PATH) ?? '';
+ return strtolower(pathinfo($path, PATHINFO_EXTENSION));
+ };
+ return ($extension($b) === 'png') <=> ($extension($a) === 'png');
+ });
+ }
}
if (!$results && ($source === 'brave' || $source === 'all')) {
diff --git a/includes/ai_client.php b/includes/ai_client.php
index ef5fe62..a734fe6 100644
--- a/includes/ai_client.php
+++ b/includes/ai_client.php
@@ -15,6 +15,179 @@ function ai_load_settings($db, $userId)
return $aiSettings ?: null;
}
+function ai_log_failure($type, $userId, $reason, $context = [])
+{
+ $details = [
+ 'provider=' . ($type ?: 'unknown'),
+ 'user_id=' . (int) $userId,
+ 'reason=' . $reason,
+ ];
+
+ foreach ($context as $key => $value) {
+ if ($value !== null && $value !== '') {
+ $details[] = $key . '=' . preg_replace('/[\r\n\s]+/', ' ', (string) $value);
+ }
+ }
+
+ error_log('[Wallos AI] ' . implode(' ', $details));
+}
+
+function ai_get_provider_error($replyData)
+{
+ if (!is_array($replyData)) {
+ return [null, null, null];
+ }
+
+ $error = $replyData['error'] ?? null;
+
+ if (is_string($error) && trim($error) !== '') {
+ return [trim($error), null, null];
+ }
+
+ if (is_array($error)) {
+ return [
+ isset($error['message']) && is_string($error['message']) ? trim($error['message']) : null,
+ $error['code'] ?? null,
+ $error['correlation_id'] ?? null,
+ ];
+ }
+
+ return [null, null, null];
+}
+
+function ai_get_text_content($content)
+{
+ if (is_string($content)) {
+ return $content;
+ }
+
+ if (!is_array($content)) {
+ return null;
+ }
+
+ $text = [];
+ foreach ($content as $part) {
+ if (is_array($part) && isset($part['text']) && is_string($part['text'])) {
+ $text[] = $part['text'];
+ }
+ }
+
+ return $text ? implode('', $text) : null;
+}
+
+function ai_decode_json_values($content)
+{
+ if (!is_string($content) || $content === '') {
+ return [];
+ }
+
+ $values = [];
+ $length = strlen($content);
+ $start = null;
+ $depth = 0;
+ $inString = false;
+ $escaped = false;
+
+ for ($index = 0; $index < $length; $index++) {
+ $character = $content[$index];
+
+ if ($start === null) {
+ if ($character === '{' || $character === '[') {
+ $start = $index;
+ $depth = 1;
+ $inString = false;
+ $escaped = false;
+ }
+ continue;
+ }
+
+ if ($inString) {
+ if ($escaped) {
+ $escaped = false;
+ } elseif ($character === '\\') {
+ $escaped = true;
+ } elseif ($character === '"') {
+ $inString = false;
+ }
+ continue;
+ }
+
+ if ($character === '"') {
+ $inString = true;
+ } elseif ($character === '{' || $character === '[') {
+ $depth++;
+ } elseif ($character === '}' || $character === ']') {
+ $depth--;
+
+ if ($depth === 0) {
+ $json = substr($content, $start, $index - $start + 1);
+ $decoded = json_decode($json, true);
+
+ if (json_last_error() === JSON_ERROR_NONE) {
+ $values[] = $decoded;
+ }
+
+ $start = null;
+ }
+ }
+ }
+
+ return $values;
+}
+
+function ai_decode_provider_response($reply)
+{
+ $decoded = json_decode($reply, true);
+ if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
+ return isset($decoded['summary']) && is_array($decoded['summary'])
+ ? $decoded['summary']
+ : $decoded;
+ }
+
+ $documents = ai_decode_json_values($reply);
+ $completion = null;
+ $fallback = null;
+ $streamedContent = '';
+
+ foreach ($documents as $document) {
+ if (!is_array($document)) {
+ continue;
+ }
+
+ $candidate = isset($document['summary']) && is_array($document['summary'])
+ ? $document['summary']
+ : $document;
+ $fallback = $candidate;
+
+ if (isset($candidate['choices'][0]['message']['content'])
+ || isset($candidate['candidates'][0]['content']['parts'][0]['text'])
+ || isset($candidate['response'])
+ || isset($candidate['error'])) {
+ $completion = $candidate;
+ }
+
+ $delta = $candidate['choices'][0]['delta']['content'] ?? null;
+ if (is_string($delta)) {
+ $streamedContent .= $delta;
+ }
+ }
+
+ if ($completion !== null) {
+ return $completion;
+ }
+
+ if ($streamedContent !== '') {
+ return [
+ 'choices' => [[
+ 'message' => ['role' => 'assistant', 'content' => $streamedContent],
+ 'finish_reason' => 'stop',
+ ]],
+ ];
+ }
+
+ return $fallback;
+}
+
/*
Validates the settings and runs one completion request against the configured provider.
Returns ["success" => true, "content" => string]
@@ -82,6 +255,7 @@ function ai_complete($aiSettings, $prompt, $db, $i18n, $userId)
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'model' => $model,
'messages' => [['role' => 'user', 'content' => $prompt]],
+ 'stream' => false,
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
@@ -127,18 +301,65 @@ function ai_complete($aiSettings, $prompt, $db, $i18n, $userId)
$reply = curl_exec($ch);
- if (curl_errno($ch)) {
- return ["success" => false, "message" => curl_error($ch)];
+ $curlErrorNumber = curl_errno($ch);
+ $curlError = $curlErrorNumber ? curl_error($ch) : '';
+ $httpCode = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
+
+ if ($curlErrorNumber) {
+ ai_log_failure($type, $userId, 'curl_error', [
+ 'curl_code' => $curlErrorNumber,
+ 'http_status' => $httpCode,
+ ]);
+ curl_close($ch);
+ return ["success" => false, "message" => $curlError];
+ }
+
+ curl_close($ch);
+
+ $replyData = ai_decode_provider_response($reply);
+
+ if (!is_array($replyData)) {
+ ai_log_failure($type, $userId, 'invalid_provider_json', [
+ 'http_status' => $httpCode,
+ 'response_length' => is_string($reply) ? strlen($reply) : 0,
+ 'json_error' => json_last_error_msg(),
+ ]);
+ return ["success" => false, "message" => translate('ai_invalid_response', $i18n)];
}
- unset($ch);
+ [$providerMessage, $providerCode, $correlationId] = ai_get_provider_error($replyData);
+
+ if (($httpCode < 200 || $httpCode >= 300) && $providerMessage === null) {
+ $fallbackMessage = $replyData['message'] ?? null;
+ $providerMessage = is_string($fallbackMessage) ? trim($fallbackMessage) : null;
+ }
+
+ if ($httpCode < 200 || $httpCode >= 300 || $providerMessage !== null) {
+ ai_log_failure($type, $userId, 'provider_error', [
+ 'http_status' => $httpCode,
+ 'provider_code' => $providerCode,
+ 'correlation_id' => $correlationId,
+ ]);
+
+ $message = translate('ai_provider_error', $i18n);
+ if ($httpCode > 0) {
+ $message .= ' (HTTP ' . $httpCode . ')';
+ }
+ if ($providerMessage !== null && $providerMessage !== '') {
+ $providerMessage = function_exists('mb_substr')
+ ? mb_substr($providerMessage, 0, 500)
+ : substr($providerMessage, 0, 500);
+ $message .= ': ' . $providerMessage;
+ }
+
+ return ["success" => false, "message" => $message];
+ }
- $replyData = json_decode($reply, true);
$content = null;
if (in_array($type, ['chatgpt', 'openrouter', 'openai-compatible'])
&& isset($replyData['choices'][0]['message']['content'])) {
- $content = $replyData['choices'][0]['message']['content'];
+ $content = ai_get_text_content($replyData['choices'][0]['message']['content']);
} elseif ($type === 'gemini'
&& isset($replyData['candidates'][0]['content']['parts'][0]['text'])) {
$content = $replyData['candidates'][0]['content']['parts'][0]['text'];
@@ -147,7 +368,11 @@ function ai_complete($aiSettings, $prompt, $db, $i18n, $userId)
}
if ($content === null) {
- return ["success" => false, "message" => translate('error', $i18n)];
+ ai_log_failure($type, $userId, 'missing_completion_content', [
+ 'http_status' => $httpCode,
+ 'finish_reason' => $replyData['choices'][0]['finish_reason'] ?? null,
+ ]);
+ return ["success" => false, "message" => translate('ai_invalid_response', $i18n)];
}
return ["success" => true, "content" => $content];
@@ -159,8 +384,22 @@ function ai_complete($aiSettings, $prompt, $db, $i18n, $userId)
*/
function ai_extract_json($content)
{
- $content = preg_replace('/^```json\s*|\s*```$/m', '', $content);
- $content = preg_replace('/^```\s*|\s*```$/m', '', $content);
+ $content = trim($content);
+ $content = preg_replace('/^```(?:json)?\s*/i', '', $content);
+ $content = preg_replace('/\s*```$/', '', $content);
+
+ $decoded = json_decode(trim($content), true);
+ if (json_last_error() === JSON_ERROR_NONE) {
+ return $decoded;
+ }
+
+ // Some compatible models add explanations or repeat the JSON array.
+ // Return the first complete JSON value instead of treating adjacent arrays as one.
+ foreach (ai_decode_json_values($content) as $value) {
+ if (is_array($value)) {
+ return $value;
+ }
+ }
- return json_decode(trim($content), true);
+ return null;
}
diff --git a/includes/i18n/de.php b/includes/i18n/de.php
index b39f626..3b91fc1 100644
--- a/includes/i18n/de.php
+++ b/includes/i18n/de.php
@@ -267,6 +267,9 @@ $i18n = [
"manually" => "Manuell",
"coming_soon" => "Demnächst",
"invalid_host" => "Ungültiger Host",
+ "ai_provider_error" => "Fehler des AI-Anbieters",
+ "ai_invalid_response" => "Der AI-Anbieter hat eine ungültige Antwort gesendet.",
+ "ai_invalid_json_response" => "Die AI-Antwort enthielt keine gültigen Empfehlungen.",
"ai_recommendations_info" => "AI Empfehlungen werden basierend auf Ihren Abonnements und Haushaltsmitgliedern generiert.",
"may_take_time" => "Je nach Anbieter, Modell und Anzahl der Abonnements kann die Generierung von Empfehlungen einige Zeit in Anspruch nehmen.",
"recommendations_visible_on_dashboard" => "Empfehlungen werden auf dem Dashboard sichtbar sein.",
diff --git a/includes/i18n/en.php b/includes/i18n/en.php
index c8c6df0..ab3c669 100644
--- a/includes/i18n/en.php
+++ b/includes/i18n/en.php
@@ -292,6 +292,9 @@ $i18n = [
"manually" => "Manually",
"coming_soon" => "Coming Soon",
"invalid_host" => "Invalid Host",
+ "ai_provider_error" => "AI provider error",
+ "ai_invalid_response" => "The AI provider returned an invalid response.",
+ "ai_invalid_json_response" => "The AI response did not contain valid recommendations.",
"ai_recommendations_info" => "AI Recommendations are generated based on your subscriptions and household members.",
"may_take_time" => "Depending on the provider, model and number of subscriptions, recommendations generation may take some time.",
"recommendations_visible_on_dashboard" => "Recommendations will be visible on the dashboard.",
diff --git a/scripts/settings.js b/scripts/settings.js
index 06e28f3..b2a3da1 100644
--- a/scripts/settings.js
+++ b/scripts/settings.js
@@ -88,11 +88,11 @@ function savePeriodBudget() {
})
.then(response => response.json())
.then(data => {
- if (data.success) {
- showSuccessMessage(data.message);
- } else {
- showErrorMessage(data.message);
- }
+ if (data.success) {
+ showSuccessMessage(data.message);
+ } else {
+ showErrorMessage(data.message || translate('unknown_error'));
+ }
})
.catch(error => {
console.error(error);
@@ -1364,7 +1364,22 @@ function runAiRecommendations() {
'X-CSRF-Token': window.csrfToken,
}
})
- .then(response => response.json())
+ .then(async response => {
+ const responseText = await response.text();
+ let data;
+
+ try {
+ data = JSON.parse(responseText);
+ } catch (error) {
+ throw new Error(`${translate('network_response_error')} (HTTP ${response.status})`);
+ }
+
+ if (!response.ok && !data.message) {
+ throw new Error(`${translate('network_response_error')} (HTTP ${response.status})`);
+ }
+
+ return data;
+ })
.then(data => {
if (data.success) {
showSuccessMessage(data.message);
@@ -1373,11 +1388,11 @@ function runAiRecommendations() {
}
})
.catch(error => {
- showErrorMessage(translate('unknown_error'));
+ showErrorMessage(error.message || translate('unknown_error'));
})
.finally(() => {
button.classList.remove("hidden");
spinner.classList.add("hidden");
});
-}
\ No newline at end of file
+}
diff --git a/scripts/subscriptions.js b/scripts/subscriptions.js
index 93157de..dada54a 100644
--- a/scripts/subscriptions.js
+++ b/scripts/subscriptions.js
@@ -329,6 +329,41 @@ function searchLogo() {
if (subscriptionForm) {
subscriptionForm.classList.add("scroll-locked");
}
+
+ const queryInput = document.querySelector("#logo-search-query");
+ queryInput.value = searchTerm;
+
+ runLogoSearch(searchTerm);
+}
+
+function submitLogoSearch() {
+ const queryInput = document.querySelector("#logo-search-query");
+ const searchTerm = queryInput.value.trim();
+ if (searchTerm === "") {
+ queryInput.focus();
+ return;
+ }
+
+ runLogoSearch(searchTerm);
+}
+
+const logoSearchQueryInput = document.querySelector("#logo-search-query");
+const logoSearchSubmitButton = document.querySelector("#logo-search-submit");
+
+if (logoSearchQueryInput && logoSearchSubmitButton) {
+ logoSearchSubmitButton.addEventListener("click", submitLogoSearch);
+ logoSearchQueryInput.addEventListener("keydown", function (event) {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ submitLogoSearch();
+ }
+ });
+}
+
+function runLogoSearch(searchTerm) {
+ const logoSearchPopup = document.querySelector("#logo-search-results");
+ const logoResults = document.querySelector("#logo-search-images");
+ const logoNav = document.querySelector("#logo-search-nav");
const logoSearchTitle = document.querySelector("#logo-search-title");
if (logoSearchTitle) {
const baseTitle = logoSearchTitle.dataset.title;
@@ -336,16 +371,17 @@ function searchLogo() {
}
// One section per source, queried in parallel and filled as each response lands
+ const encodedSearchTerm = encodeURIComponent(searchTerm);
const sources = [
- { label: 'selfh.st', url: `endpoints/logos/icon_search.php?search=${searchTerm}&source=selfhst` },
- { label: 'Dashboard Icons', url: `endpoints/logos/icon_search.php?search=${searchTerm}&source=dashboardicons` },
- { label: 'DuckDuckGo', url: `endpoints/logos/search.php?search=${searchTerm}&source=duckduckgo` },
- { label: 'Brave', url: `endpoints/logos/search.php?search=${searchTerm}&source=brave` },
+ { label: 'selfh.st', url: `endpoints/logos/icon_search.php?search=${encodedSearchTerm}&source=selfhst` },
+ { label: 'Dashboard Icons', url: `endpoints/logos/icon_search.php?search=${encodedSearchTerm}&source=dashboardicons` },
+ { label: 'DuckDuckGo', url: `endpoints/logos/search.php?search=${encodedSearchTerm}&source=duckduckgo` },
+ { label: 'Brave', url: `endpoints/logos/search.php?search=${encodedSearchTerm}&source=brave` },
];
// Google requires user-provided API credentials; the section only exists when configured
if (logoSearchPopup.dataset.googleSearch) {
- sources.unshift({ label: 'Google', url: `endpoints/logos/google_search.php?search=${searchTerm}` });
+ sources.unshift({ label: 'Google', url: `endpoints/logos/google_search.php?search=${encodedSearchTerm}` });
}
logoResults.innerHTML = "";
@@ -380,8 +416,7 @@ function searchLogo() {
logoNav.appendChild(navItem);
}
- fetch(source.url)
- .then(response => response.json())
+ fetchLogoSearchSource(source.url)
.then(data => {
if (data.results && data.results.length > 0) {
displayImageResults(data.results, resultsContainer);
@@ -399,6 +434,32 @@ function searchLogo() {
});
}
+function fetchLogoSearchSource(url, retry = true) {
+ return fetch(url, {
+ cache: "no-store",
+ headers: { "Accept": "application/json" },
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`);
+ }
+ return response.text();
+ })
+ .then(body => {
+ try {
+ return JSON.parse(body);
+ } catch (error) {
+ throw new Error("Invalid JSON response");
+ }
+ })
+ .catch(error => {
+ if (retry) {
+ return fetchLogoSearchSource(url, false);
+ }
+ throw error;
+ });
+}
+
function displayImageResults(imageSources, container) {
container.innerHTML = "";
@@ -406,7 +467,10 @@ function displayImageResults(imageSources, container) {
const img = document.createElement("img");
img.src = src.thumbnail || src.image;
img.onclick = function () {
- selectWebLogo(src.thumbnail || src.image);
+ const selectedUrl = getSupportedLogoUrl(src);
+ if (selectedUrl) {
+ selectWebLogo(selectedUrl, img.src);
+ }
};
img.onerror = function () {
this.parentNode.removeChild(this);
@@ -415,11 +479,26 @@ function displayImageResults(imageSources, container) {
});
}
-function selectWebLogo(url) {
+function getSupportedLogoUrl(source) {
+ if (source.image) {
+ try {
+ const imagePath = new URL(source.image, window.location.href).pathname.toLowerCase();
+ if (/\.(png|jpe?g|gif|webp)$/.test(imagePath)) {
+ return source.image;
+ }
+ } catch (error) {
+ // Fall through to the raster thumbnail for malformed source URLs.
+ }
+ }
+
+ return source.thumbnail || "";
+}
+
+function selectWebLogo(url, previewUrl = url) {
closeLogoSearch();
const logoPreview = document.querySelector("#form-logo");
const logoUrl = document.querySelector("#logo-url");
- logoPreview.src = url;
+ logoPreview.src = previewUrl;
logoPreview.style.display = 'block';
logoUrl.value = url;
}
diff --git a/service-worker.js b/service-worker.js
index df1d930..75f7546 100644
--- a/service-worker.js
+++ b/service-worker.js
@@ -1,6 +1,6 @@
-const STATIC_CACHE = 'static-cache-v2';
+const STATIC_CACHE = 'static-cache-v3';
const PAGES_CACHE = 'pages-cache-v1';
-const LOGOS_CACHE = 'logos-cache-v1';
+const LOGOS_CACHE = 'logos-cache-v2';
const staticAssets = [
'manifest.json',
@@ -214,18 +214,32 @@ self.addEventListener('fetch', function (event) {
const request = event.request;
const url = new URL(request.url);
- // Never intercept non-GET requests (POST, etc.)
- if (request.method !== 'GET') return;
+ // Never intercept non-GET requests (POST, etc.)
+ if (request.method !== 'GET') return;
+
+ // Search endpoints must always return their current JSON response. Falling
+ // back to a cached PHP page (especially with ignoreSearch) makes the client
+ // try to parse HTML or another query's data as JSON.
+ if (url.pathname.includes('/endpoints/logos/')) {
+ event.respondWith(fetch(request));
+ return;
+ }
- // Logo images: cache-first, populate on first load
+ // Logo images: use cache-first, but cache only successful image responses.
+ // This prevents temporary 404/HTML responses from becoming permanent
+ // broken images. Bumping LOGOS_CACHE removes previously poisoned entries.
if (url.pathname.includes('images/uploads/logos')) {
event.respondWith(
caches.match(request).then(response => {
return response || fetch(request).then(networkResponse => {
- return caches.open(LOGOS_CACHE).then(cache => {
- cache.put(request, networkResponse.clone());
- return networkResponse;
- });
+ const contentType = networkResponse.headers.get('content-type') || '';
+ if (networkResponse.ok && contentType.startsWith('image/')) {
+ return caches.open(LOGOS_CACHE).then(cache => {
+ cache.put(request, networkResponse.clone());
+ return networkResponse;
+ });
+ }
+ return networkResponse;
});
})
);
diff --git a/styles/styles.css b/styles/styles.css
index 7b611a3..4ee364d 100644
--- a/styles/styles.css
+++ b/styles/styles.css
@@ -1440,6 +1440,7 @@ input {
}
input[type="text"],
+input[type="search"],
input[type="email"],
input[type="password"],
input[type="date"],
@@ -1459,6 +1460,7 @@ select {
}
input[type="text"]:focus,
+input[type="search"]:focus,
input[type="email"]:focus,
input[type="password"]:focus,
input[type="date"]:focus,
@@ -1695,6 +1697,14 @@ textarea.thin {
max-height: 380px;
}
+.logo-search {
+ max-width: 386px;
+}
+
+.logo-search>header {
+ padding-right: 32px;
+}
+
.logo-search.is-open,
.icon-search.is-open {
display: flex;
@@ -1769,6 +1779,12 @@ textarea.thin {
display: none;
}
+.logo-search-controls {
+ width: 100%;
+ max-width: 100%;
+ flex-shrink: 0;
+}
+
.logo-search-nav {
display: flex;
flex-wrap: wrap;
@@ -1777,6 +1793,47 @@ textarea.thin {
flex-shrink: 0;
}
+.logo-search-query {
+ display: flex;
+ align-items: stretch;
+ gap: 8px;
+ width: 100%;
+ margin: 0 0 12px;
+}
+
+.logo-search-query>input {
+ width: 0;
+ min-width: 0;
+ flex-grow: 1;
+ height: 50px;
+}
+
+.logo-search-query>button {
+ width: 50px;
+ height: 50px;
+ flex-shrink: 0;
+ padding: 0;
+ border: 1px solid var(--input-border-color);
+ border-radius: 10px;
+ background-color: var(--input-background-color);
+ color: var(--text-color);
+ font-size: 16px;
+ cursor: pointer;
+ transition: color 0.15s, border-color 0.15s, background-color 0.15s, box-shadow 0.15s;
+}
+
+.logo-search-query>button:hover {
+ background-color: rgba(var(--main-color-rgb), 0.12);
+ border-color: var(--main-color);
+ color: var(--main-color);
+}
+
+.logo-search-query>button:focus-visible {
+ outline: none;
+ border-color: var(--main-color);
+ box-shadow: var(--focus-ring);
+}
+
.logo-search-nav-item {
border: 1px solid var(--input-border-color);
background-color: var(--input-background-color);
diff --git a/subscriptions.php b/subscriptions.php
index 2afb1fb..07608d6 100644
--- a/subscriptions.php
+++ b/subscriptions.php
@@ -338,7 +338,17 @@ $subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscrip
<?= translate('web_search', $i18n) ?>
</h3>
</header>
- <div id="logo-search-nav" class="logo-search-nav"></div>
+ <div class="logo-search-controls">
+ <div class="logo-search-query">
+ <input type="text" id="logo-search-query" autocomplete="off" inputmode="search"
+ placeholder="<?= translate('search_logo', $i18n) ?>"
+ aria-label="<?= translate('search_logo', $i18n) ?>">
+ <button type="button" id="logo-search-submit" title="<?= translate('search', $i18n) ?>">
+ <i class="fa-solid fa-magnifying-glass"></i>
+ </button>
+ </div>
+ <div id="logo-search-nav" class="logo-search-nav"></div>
+ </div>
<div id="logo-search-images"></div>
</div>
</div>
@@ -551,7 +561,7 @@ $subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscrip
</section>
<?php require_once 'includes/subscription_details_popup.php'; ?>
-<script src="scripts/subscriptions.js?<?= $version ?>"></script>
+<script src="scripts/subscriptions.js?<?= $version ?>&logo-search=4"></script>
<?php
if (isset($_GET['add'])) {
?>
@@ -562,4 +572,4 @@ if (isset($_GET['add'])) {
}
require_once 'includes/footer.php';
-?>
\ No newline at end of file
+?>