From b40267b7dafa0bbc2da987f9ba6082cbd5f231a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enes=20Yak=C4=B1=C5=9Ft=C4=B1r?= Date: Thu, 19 Nov 2026 20:30:22 +0300 Subject: [PATCH] fix(search): remove legacy custom JS collision, dedupe yt-dlp searches, raise timeout to 30s, and auto-restore search DOM (v1.7.17) --- client.js | 750 ++++++++++++++++++++++++++++----------------------- main.js | 50 ++-- package.json | 2 +- 3 files changed, 442 insertions(+), 360 deletions(-) diff --git a/client.js b/client.js index d7f2c55..672244f 100644 --- a/client.js +++ b/client.js @@ -4465,26 +4465,400 @@ try { var container = document.getElementById('yaktube-ondemand-container'); var nativeResults = searchMount.querySelector('.search-result'); + function ensureSearchContainerMounted() { + var curSearchMount = document.querySelector('my-search, my-search-results') || searchMount; + var curNative = curSearchMount ? curSearchMount.querySelector('.search-result') : null; + var el = document.getElementById('yaktube-ondemand-container'); + if (!el) { + el = document.createElement('div'); + el.id = 'yaktube-ondemand-container'; + el.className = 'yaktube-ondemand-section'; + el.setAttribute('role', 'region'); + el.setAttribute('aria-label', 'Canlı YouTube ve ' + getInstanceName() + ' Arama Sonuçları'); + } + if (curSearchMount && el.parentElement !== curSearchMount) { + curSearchMount.insertBefore(el, curNative || curSearchMount.firstChild); + } + return el; + } + + function renderSearchOutcome(ytData, localData, activeContainer) { + var targetContainer = activeContainer || ensureSearchContainerMounted(); + ytData = ytData || {}; + localData = localData || {}; + + if (typeof ytData.guestImportLimit === 'number') { + cachedGuestImportLimit = ytData.guestImportLimit; + } + + if (ytData && ytData.blocked) { + var safetyMsg = + ytData.message || + 'Bu arama terimi veya içerik, Çocuk ve Aile Güvenliği (Child & Family Safety) politikaları gereğince filtrelenmiştir.'; + targetContainer.innerHTML = + '
' + + '
' + + '🛡️ Çocuk ve Aile Güvenliği Koruması' + + '

Arama Filtrelendi

' + + '

' + + escapeHtml(safetyMsg) + + '

' + + '
' + + '
'; + announce(safetyMsg, true); + return; + } + + var rawYtResults = ytData.results || []; + var uniqueYtResults = []; + var seenIds = {}; + + rawYtResults.forEach(function (item) { + if (item && item.id && !seenIds[item.id] && item.title) { + seenIds[item.id] = true; + uniqueYtResults.push(item); + } + }); + + var ytCount = uniqueYtResults.length; + var localResults = localData.data || []; + var localTotal = typeof localData.total === 'number' ? localData.total : localResults.length; + + if (ytCount === 0 && localResults.length === 0) { + var emptyTitle = ytData.searchError + ? 'YouTube bağlantısı geçici olarak zaman aşımına uğradı' + : '"' + escapeHtml(query) + '" için Sonuç Bulunamadı'; + var retryHtml = ytData.searchError + ? '
' + : ''; + targetContainer.innerHTML = + '
' + + '
' + + '⚡ Canlı YouTube & Web Arama' + + '

' + + emptyTitle + + '

' + + '
' + + '' + + '
' + + retryHtml; + var rBtn = document.getElementById('yaktube-retry-search-btn'); + if (rBtn) { + rBtn.addEventListener('click', function () { + window.__yaktube_last_search_snapshot__ = null; + lastQuery = null; + checkAndInjectSearchResults(); + }); + } + var scBtn = document.getElementById('yaktube-open-shortcuts'); + if (scBtn) scBtn.addEventListener('click', toggleShortcutsModal); + announce( + ytData.searchError + ? 'YouTube bağlantısı geçici olarak yanıt vermedi.' + : query + ' için eşleşen video bulunamadı.' + ); + return; + } + + var visibleYtCount = Math.min(12, ytCount); + + function renderAll() { + var ytHeaderHtml = ''; + var ytCardsHtml = ''; + var ytLoadMoreHtml = ''; + + if (ytCount > 0) { + var countText = ytCount === 1 ? '1 Video Bulundu' : ytCount + ' Video Bulundu'; + ytHeaderHtml = + '
' + + '
' + + '⚡ Canlı YouTube & Web Arama' + + '

"' + + escapeHtml(query) + + '" için ' + + countText + + '

' + + '
' + + '' + + '
'; + + var visibleResults = uniqueYtResults.slice(0, visibleYtCount); + visibleResults.forEach(function (item) { + if (item && item.title && item.channel) { + saveVideoChannelMeta( + item.title, + item.channel, + item.id || '', + (item.localVideo && item.localVideo.uuid) || '' + ); + } + var isLocal = !!item.isDownloaded; + var isLive = !!item.isLive; + + var statusBadge = ''; + if (isLive) { + statusBadge = + '🔴 CANLI YAYIN'; + } else if (isLocal) { + statusBadge = + '✅ ' + + escapeHtml(getInstanceName()) + + "'da Mevcut"; + } + + var actionButton = ''; + if (isLive) { + actionButton = + ''; + } else if (isLocal && item.localVideo && item.localVideo.url) { + actionButton = + '▶️ ' + + escapeHtml(getInstanceName()) + + "'dan İzle"; + } else { + actionButton = + '"; + } + + var durationText = isLive ? 'CANLI' : item.durationFormatted || formatClockTime(item.duration); + var cardLabel = + item.title + + (isLive ? ' (Canlı Yayın)' : isLocal ? ' (' + getInstanceName() + ' kütüphanenizde mevcut)' : '') + + ', ' + + item.channel + + ' kanalı, Süre: ' + + durationText; + + ytCardsHtml += + '
' + + '
' + + '' +
+                escapeHtml(item.title) +
+                '' + + '' + + escapeHtml(durationText) + + '' + + '
' + + '
' + + '
' + + statusBadge + + '

' + + escapeHtml(item.title) + + '

' + + '
' + + escapeHtml(item.channel) + + '
' + + '
' + + actionButton + + '
' + + '
'; + }); + + if (visibleYtCount < ytCount) { + ytLoadMoreHtml = + '
' + + '' + + '
'; + } + } + + var localShelfHtml = ''; + if (localResults.length > 0) { + var localCardsHtml = ''; + localResults.forEach(function (lItem) { + var lThumb = + lItem.thumbnailPath || + (lItem.thumbnails && lItem.thumbnails[0] + ? lItem.thumbnails[0].fileUrl + : '/client/assets/images/default-thumbnail.jpg'); + var lDuration = formatClockTime(lItem.duration); + var lChannel = + (lItem.channel && (lItem.channel.displayName || lItem.channel.name)) || + (lItem.account && (lItem.account.displayName || lItem.account.name)) || + getInstanceName(); + var lWatchUrl = lItem.url || '/videos/watch/' + (lItem.shortUUID || lItem.uuid); + var lViews = (lItem.views || 0) + ' görüntüleme'; + var lLabel = + lItem.name + + ', ' + + lChannel + + ', ' + + getInstanceName() + + ' yerel sunucusunda mevcut, Süre: ' + + lDuration; + + localCardsHtml += + '
' + + '' + + '
' + + '' +
+                escapeHtml(lItem.name) +
+                '' + + '' + + escapeHtml(lDuration) + + '' + + '
' + + '
' + + '
' + + '✅ ' + + escapeHtml(getInstanceName()) + + "'da Mevcut" + + '

' + + escapeHtml(lItem.name) + + '

' + + '
' + + escapeHtml(lChannel) + + ' • ' + + escapeHtml(lViews) + + '
' + + '
' + + '
▶️ ' + + escapeHtml(getInstanceName()) + + "'dan Hemen İzle
" + + '
' + + '
' + + '
'; + }); + + localShelfHtml = + '
' + + '
' + + '
' + + '✅ Yerel Kütüphane' + + '

"' + + escapeHtml(query) + + '" için ' + + escapeHtml(getInstanceName()) + + ' Sunucusunda ' + + localTotal + + ' Video Bulundu

' + + '
' + + 'Doğrudan sunucumuzda barındırılan, yüksek hızlı ve anında izlenebilen videolar' + + '
' + + '
' + + localCardsHtml + + '
' + + '
'; + } + + targetContainer.innerHTML = + ytHeaderHtml + + (ytCount > 0 ? '
' + ytCardsHtml + '
' : '') + + ytLoadMoreHtml + + localShelfHtml; + + var sBtn = document.getElementById('yaktube-open-shortcuts'); + if (sBtn) { + sBtn.addEventListener('click', toggleShortcutsModal); + } + + var loadMoreBtn = document.getElementById('yaktube-load-more-btn'); + if (loadMoreBtn) { + loadMoreBtn.addEventListener('click', function () { + visibleYtCount = Math.min(visibleYtCount + 6, ytCount); + renderAll(); + announce(visibleYtCount + ' adet video gösteriliyor.'); + }); + } + + targetContainer.querySelectorAll('.yaktube-live-btn').forEach(function (btn) { + btn.addEventListener('click', function (e) { + var liveUrl = e.currentTarget.getAttribute('data-url'); + var liveTitle = e.currentTarget.getAttribute('data-title'); + handleLiveStream(liveUrl, liveTitle); + }); + }); + + targetContainer.querySelectorAll('.yaktube-import-btn').forEach(function (btn) { + btn.addEventListener('click', function (e) { + var videoUrl = e.currentTarget.getAttribute('data-url'); + var videoTitle = e.currentTarget.getAttribute('data-title'); + handleImport(videoUrl, e.currentTarget, videoTitle); + }); + }); + } + + renderAll(); + } + if (queryKey === lastQueryKey) { - if (container && container.parentElement !== searchMount) { - searchMount.insertBefore(container, nativeResults || searchMount.firstChild); + if (container) { + if (container.parentElement !== searchMount) { + searchMount.insertBefore(container, nativeResults || searchMount.firstChild); + } + ensureFediverseBridge(query, currentSearchTarget); + return; + } + // If Angular re-rendered and wiped #yaktube-ondemand-container, restore instantly! + if (!isSearching) { + var snap = window.__yaktube_last_search_snapshot__; + if (snap && snap.key === queryKey) { + var restoredContainer = ensureSearchContainerMounted(); + renderSearchOutcome(snap.ytData, snap.localData, restoredContainer); + ensureFediverseBridge(query, currentSearchTarget); + return; + } + lastQuery = null; + lastSearchTarget = null; + } else { + container = ensureSearchContainerMounted(); + ensureFediverseBridge(query, currentSearchTarget); + return; } - ensureFediverseBridge(query, currentSearchTarget); - return; } lastQuery = query; lastSearchTarget = currentSearchTarget; - - if (!container) { - container = document.createElement('div'); - container.id = 'yaktube-ondemand-container'; - container.className = 'yaktube-ondemand-section'; - container.setAttribute('role', 'region'); - container.setAttribute('aria-label', 'Canlı YouTube ve ' + getInstanceName() + ' Arama Sonuçları'); - searchMount.insertBefore(container, nativeResults || searchMount.firstChild); - } else if (container.parentElement !== searchMount) { - searchMount.insertBefore(container, nativeResults || searchMount.firstChild); - } + container = ensureSearchContainerMounted(); container.innerHTML = '
' + @@ -4525,359 +4899,49 @@ try { Promise.all([ fetchPluginJson('/youtube-search?q=' + encodeURIComponent(query), fetchOpts).catch(function (err) { - if (err && err.name === 'AbortError') return { results: [] }; + if (err && err.name === 'AbortError') return { results: [], aborted: true }; console.warn('[YakTube] YouTube search fetch error:', err); - return { results: [] }; + return { results: [], searchError: true }; }), fetch('/api/v1/search/videos?search=' + encodeURIComponent(query) + '&isLocal=true&count=12', fetchOpts) .then(function (res) { return res.json(); }) .catch(function (err) { - if (err && err.name === 'AbortError') return { total: 0, data: [] }; + if (err && err.name === 'AbortError') return { total: 0, data: [], aborted: true }; console.warn('[YakTube] Local videos search fetch error:', err); return { total: 0, data: [] }; }) ]) .then(function (responses) { + if (abortCtrl && abortCtrl.signal && abortCtrl.signal.aborted) return; var ytData = responses[0] || {}; var localData = responses[1] || {}; - if (typeof ytData.guestImportLimit === 'number') { - cachedGuestImportLimit = ytData.guestImportLimit; - } + if (ytData.aborted || localData.aborted) return; - if (ytData && ytData.blocked) { - var safetyMsg = - ytData.message || - 'Bu arama terimi veya içerik, Çocuk ve Aile Güvenliği (Child & Family Safety) politikaları gereğince filtrelenmiştir.'; - container.innerHTML = - '
' + - '
' + - '🛡️ Çocuk ve Aile Güvenliği Koruması' + - '

Arama Filtrelendi

' + - '

' + - escapeHtml(safetyMsg) + - '

' + - '
' + - '
'; - announce(safetyMsg, true); - return; - } - - var rawYtResults = ytData.results || []; - var uniqueYtResults = []; - var seenIds = {}; - - rawYtResults.forEach(function (item) { - if (item && item.id && !seenIds[item.id] && item.title) { - seenIds[item.id] = true; - uniqueYtResults.push(item); - } - }); - - var ytCount = uniqueYtResults.length; - var localResults = localData.data || []; - var localTotal = typeof localData.total === 'number' ? localData.total : localResults.length; - - if (ytCount === 0 && localResults.length === 0) { - container.innerHTML = - '
' + - '
' + - '⚡ Canlı YouTube & Web Arama' + - '

"' + - escapeHtml(query) + - '" için Sonuç Bulunamadı

' + - '
' + - '' + - '
'; - announce(query + ' için YouTube veya yerel sunucuda eşleşen video bulunamadı.'); - } else { - var visibleYtCount = Math.min(12, ytCount); - - function renderAll() { - // 1. YouTube Section - var ytHeaderHtml = ''; - var ytCardsHtml = ''; - var ytLoadMoreHtml = ''; - - if (ytCount > 0) { - var countText = ytCount === 1 ? '1 Video Bulundu' : ytCount + ' Video Bulundu'; - ytHeaderHtml = - '
' + - '
' + - '⚡ Canlı YouTube & Web Arama' + - '

"' + - escapeHtml(query) + - '" için ' + - countText + - '

' + - '
' + - '' + - '
'; - - var visibleResults = uniqueYtResults.slice(0, visibleYtCount); - visibleResults.forEach(function (item) { - if (item && item.title && item.channel) { - saveVideoChannelMeta( - item.title, - item.channel, - item.id || '', - (item.localVideo && item.localVideo.uuid) || '' - ); - } - var isLocal = !!item.isDownloaded; - var isLive = !!item.isLive; - - var statusBadge = ''; - if (isLive) { - statusBadge = - '🔴 CANLI YAYIN'; - } else if (isLocal) { - statusBadge = - '✅ ' + - escapeHtml(getInstanceName()) + - "'da Mevcut"; - } - - var actionButton = ''; - if (isLive) { - actionButton = - ''; - } else if (isLocal && item.localVideo && item.localVideo.url) { - actionButton = - '▶️ ' + - escapeHtml(getInstanceName()) + - "'dan İzle"; - } else { - actionButton = - '"; - } - - var durationText = isLive ? 'CANLI' : item.durationFormatted || formatClockTime(item.duration); - var cardLabel = - item.title + - (isLive ? ' (Canlı Yayın)' : isLocal ? ' (' + getInstanceName() + ' kütüphanenizde mevcut)' : '') + - ', ' + - item.channel + - ' kanalı, Süre: ' + - durationText; - - ytCardsHtml += - '
' + - '
' + - '' +
-                    escapeHtml(item.title) +
-                    '' + - '' + - escapeHtml(durationText) + - '' + - '
' + - '
' + - '
' + - statusBadge + - '

' + - escapeHtml(item.title) + - '

' + - '
' + - escapeHtml(item.channel) + - '
' + - '
' + - actionButton + - '
' + - '
'; - }); - - if (visibleYtCount < ytCount) { - ytLoadMoreHtml = - '
' + - '' + - '
'; - } - } - - // 2. Local Videos Shelf - var localShelfHtml = ''; - if (localResults.length > 0) { - var localCardsHtml = ''; - localResults.forEach(function (lItem) { - var lThumb = - lItem.thumbnailPath || - (lItem.thumbnails && lItem.thumbnails[0] - ? lItem.thumbnails[0].fileUrl - : '/client/assets/images/default-thumbnail.jpg'); - var lDuration = formatClockTime(lItem.duration); - var lChannel = - (lItem.channel && (lItem.channel.displayName || lItem.channel.name)) || - (lItem.account && (lItem.account.displayName || lItem.account.name)) || - getInstanceName(); - var lWatchUrl = lItem.url || '/videos/watch/' + (lItem.shortUUID || lItem.uuid); - var lViews = (lItem.views || 0) + ' görüntüleme'; - var lLabel = - lItem.name + - ', ' + - lChannel + - ', ' + - getInstanceName() + - ' yerel sunucusunda mevcut, Süre: ' + - lDuration; - - localCardsHtml += - ''; - }); - - localShelfHtml = - '
' + - '
' + - '
' + - '✅ Yerel Kütüphane' + - '

"' + - escapeHtml(query) + - '" için ' + - escapeHtml(getInstanceName()) + - ' Sunucusunda ' + - localTotal + - ' Video Bulundu

' + - '
' + - 'Doğrudan sunucumuzda barındırılan, yüksek hızlı ve anında izlenebilen videolar' + - '
' + - '
' + - localCardsHtml + - '
' + - '
'; - } - - container.innerHTML = - ytHeaderHtml + - (ytCount > 0 ? '
' + ytCardsHtml + '
' : '') + - ytLoadMoreHtml + - localShelfHtml; - - var sBtn = document.getElementById('yaktube-open-shortcuts'); - if (sBtn) { - sBtn.addEventListener('click', toggleShortcutsModal); - } - - var loadMoreBtn = document.getElementById('yaktube-load-more-btn'); - if (loadMoreBtn) { - loadMoreBtn.addEventListener('click', function () { - visibleYtCount = Math.min(visibleYtCount + 6, ytCount); - renderAll(); - announce(visibleYtCount + ' adet video gösteriliyor.'); - }); - } - - container.querySelectorAll('.yaktube-live-btn').forEach(function (btn) { - btn.addEventListener('click', function (e) { - var liveUrl = e.currentTarget.getAttribute('data-url'); - var liveTitle = e.currentTarget.getAttribute('data-title'); - handleLiveStream(liveUrl, liveTitle); - }); - }); - - container.querySelectorAll('.yaktube-import-btn').forEach(function (btn) { - btn.addEventListener('click', function (e) { - var videoUrl = e.currentTarget.getAttribute('data-url'); - var videoTitle = e.currentTarget.getAttribute('data-title'); - handleImport(videoUrl, e.currentTarget, videoTitle); - }); - }); - } - - renderAll(); + window.__yaktube_last_search_snapshot__ = { key: queryKey, ytData: ytData, localData: localData }; + var activeContainer = ensureSearchContainerMounted(); + renderSearchOutcome(ytData, localData, activeContainer); + var ytLen = (ytData.results && ytData.results.length) || 0; + var localTotal = typeof localData.total === 'number' ? localData.total : (localData.data || []).length; + if (ytLen > 0 || localTotal > 0) { var announceMsg = '"' + query + '" için arama sonuçları listelendi: '; if (localTotal > 0) { announceMsg += localTotal + ' adet yerel ' + getInstanceName() + ' videosu, '; } - if (ytCount > 0) { - announceMsg += ytCount + ' adet YouTube sonucu ve '; + if (ytLen > 0) { + announceMsg += ytLen + ' adet YouTube sonucu ve '; } announceMsg += 'Fediverse sonuçları hazır.'; announce(announceMsg); } }) .catch(function (err) { + if (abortCtrl && abortCtrl.signal && abortCtrl.signal.aborted) return; console.error('[YakTube] Search fetch error:', err); - container.innerHTML = + var activeContainer = ensureSearchContainerMounted(); + activeContainer.innerHTML = '
' + '
' + '⚡ Canlı YouTube & Web Arama' + @@ -4887,7 +4951,9 @@ try { announce('Arama sırasında bir bağlantı sorunu oluştu.'); }) .finally(function () { - isSearching = false; + if (!abortCtrl || !abortCtrl.signal || !abortCtrl.signal.aborted) { + isSearching = false; + } ensureFediverseBridge(query, currentSearchTarget); }); } diff --git a/main.js b/main.js index 9b29b55..0d486ad 100644 --- a/main.js +++ b/main.js @@ -1483,24 +1483,30 @@ async function register({ registerHook, getRouter, registerSetting, settingsMana return res.json(result); }); - // Reusable YouTube Raw Search Helper (with Cache & SafeSearch) + const inFlightYouTubeSearches = new Map(); + + // Reusable YouTube Raw Search Helper (with Cache, In-Flight Dedupe & SafeSearch) function searchYouTubeRaw(query, maxCount = 24) { - return new Promise((resolve, reject) => { - const cleanQ = (query || '').trim(); - if (!cleanQ || cleanQ.length < 2) return resolve({ results: [], cached: false }); - if (safeSearchEnabled && isContentBlocked(cleanQ, blockedKeywordsList)) { - return resolve({ results: [], cached: false, blocked: true }); - } + const cleanQ = (query || '').trim(); + if (!cleanQ || cleanQ.length < 2) return Promise.resolve({ results: [], cached: false }); + if (safeSearchEnabled && isContentBlocked(cleanQ, blockedKeywordsList)) { + return Promise.resolve({ results: [], cached: false, blocked: true }); + } - const cacheKey = `${cleanQ.toLocaleLowerCase('tr')}__${maxCount}`; - const cached = getCached(cacheKey) || (maxCount <= 24 ? getCached(cleanQ) : null); - if (cached) { - const filteredCached = safeSearchEnabled - ? cached.filter(e => !isContentBlocked(e.title, blockedKeywordsList)) - : cached; - return resolve({ results: filteredCached.slice(0, maxCount), cached: true }); - } + const cacheKey = `${cleanQ.toLocaleLowerCase('tr')}__${maxCount}`; + const cached = getCached(cacheKey) || (maxCount <= 24 ? getCached(cleanQ) : null); + if (cached) { + const filteredCached = safeSearchEnabled + ? cached.filter(e => !isContentBlocked(e.title, blockedKeywordsList)) + : cached; + return Promise.resolve({ results: filteredCached.slice(0, maxCount), cached: true }); + } + if (inFlightYouTubeSearches.has(cacheKey)) { + return inFlightYouTubeSearches.get(cacheKey); + } + + const p = new Promise((resolve, reject) => { const ytdlpPath = resolveYtDlpPath(logger, customYtDlpPath, peertubeHelpers); const args = [ `ytsearch${maxCount}:${cleanQ}`, @@ -1510,8 +1516,13 @@ async function register({ registerHook, getRouter, registerSetting, settingsMana '--no-warnings' ]; - execFile(ytdlpPath, args, { maxBuffer: 10 * 1024 * 1024, timeout: 15000 }, (error, stdout) => { + execFile(ytdlpPath, args, { maxBuffer: 10 * 1024 * 1024, timeout: 30000 }, (error, stdout, stderr) => { if (error) { + if (logger) { + logger.warn( + `[YakTube Search] yt-dlp search error for "${cleanQ}": ${error.message} ${stderr || ''}`.trim() + ); + } return reject(error); } try { @@ -1562,7 +1573,12 @@ async function register({ registerHook, getRouter, registerSetting, settingsMana return reject(parseErr); } }); + }).finally(() => { + inFlightYouTubeSearches.delete(cacheKey); }); + + inFlightYouTubeSearches.set(cacheKey, p); + return p; } function isCrawlerBotRequest(req) { @@ -1639,7 +1655,7 @@ async function register({ registerHook, getRouter, registerSetting, settingsMana return res.json({ results: enrichedResults, cached, guestImportLimit }); } catch (err) { if (logger) logger.error('YouTube search error: ' + err.message); - return res.status(500).json({ error: 'Search failed', details: err.message }); + return res.json({ results: [], searchError: true, errorDetails: err.message, guestImportLimit }); } } diff --git a/package.json b/package.json index 8e8ed4f..45d9159 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "peertube-plugin-yaktube-ondemand", - "version": "1.7.16", + "version": "1.7.17", "description": "Accessible On-Demand YouTube Import, Live Streams, Smart Recommendations, Sleep Timer, Touch Gestures, Voice Assistant & A11y Engine for PeerTube", "main": "main.js", "library": "./main.js",