From 1b00c9dd272e410aa9d5342a195dda7c5ba93ddf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enes=20Yak=C4=B1=C5=9Ft=C4=B1r?= Date: Tue, 1 Dec 2026 18:42:05 +0300 Subject: [PATCH] feat(v1.8.0): Audio Studio EQ, A-B loop, smart transcripts/chapters, play queue, background import, continue shelf, command palette & portal focus rescue --- client.js | 2607 ++++++++++++++++++++++++++++++++++++++++++++++++-- main.js | 546 ++++++++++- package.json | 2 +- style.css | 736 ++++++++++++++ 4 files changed, 3768 insertions(+), 123 deletions(-) diff --git a/client.js b/client.js index e6c9ad2..a68a8e7 100644 --- a/client.js +++ b/client.js @@ -1134,10 +1134,531 @@ try { } // ============================================================================ - // 2. Audio-Only & Screen Blank Mode (NLnet Privacy & Bandwidth Shield) + // 2. Audio-Only Mode, Live Audio Studio (EQ + %300 Boost) & A-B Repeat Loop // ============================================================================ var isAudioOnlyMode = false; var wakeLockSentinel = null; + var AUDIO_STUDIO_STORAGE_KEY = 'yaktube_audio_studio_v1'; + var AUDIO_PRESETS = { + normal: { label: 'Normal', gain: 100, bass: 0, voice: 0, treble: 0, limiter: false, night: false }, + voice: { label: 'Konuşma Netliği', gain: 160, bass: -3, voice: 6.5, treble: 2, limiter: true, night: false }, + boost: { label: 'Süper Ses (%250)', gain: 250, bass: 1, voice: 3, treble: 1.5, limiter: true, night: false }, + bass: { label: 'Bas & Müzik', gain: 125, bass: 7.5, voice: 0, treble: 3, limiter: true, night: false }, + night: { label: 'Gece Dengeleyici', gain: 150, bass: -2, voice: 3.5, treble: -1, limiter: true, night: true } + }; + + function loadAudioStudioSettings() { + var def = Object.assign({ preset: 'normal' }, AUDIO_PRESETS.normal); + try { + var raw = localStorage.getItem(AUDIO_STUDIO_STORAGE_KEY); + if (!raw) return def; + var parsed = JSON.parse(raw); + return Object.assign(def, parsed || {}); + } catch (e) { + return def; + } + } + + function saveAudioStudioSettings(cfg) { + try { + localStorage.setItem(AUDIO_STUDIO_STORAGE_KEY, JSON.stringify(cfg)); + } catch (e) {} + } + + function isNonDefaultAudioConfig(cfg) { + if (!cfg) return false; + return ( + Number(cfg.gain || 100) !== 100 || + Number(cfg.bass || 0) !== 0 || + Number(cfg.voice || 0) !== 0 || + Number(cfg.treble || 0) !== 0 || + Boolean(cfg.limiter) || + Boolean(cfg.night) + ); + } + + var videoAudioGraphs = typeof WeakMap === 'function' ? new WeakMap() : null; + var activeSpectrumRaf = null; + var abLoopState = { a: null, b: null, active: false }; + + function isVideoOriginSafeForWebAudio(video) { + if (!video) return false; + var src = String(video.currentSrc || video.src || '').trim(); + if (!src || src.startsWith('blob:') || src.startsWith('/') || src.startsWith(window.location.origin)) { + return true; + } + return video.crossOrigin === 'anonymous' || video.crossOrigin === 'use-credentials'; + } + + function ensureAudioGraph(video) { + if (!video || !videoAudioGraphs) return { supported: false, reason: 'unsupported' }; + var existing = videoAudioGraphs.get(video); + if (existing) { + if (existing.ctx && existing.ctx.state === 'suspended') { + existing.ctx.resume().catch(function () {}); + } + return existing; + } + if (!isVideoOriginSafeForWebAudio(video)) { + return { supported: false, reason: 'cross-origin' }; + } + var AudioCtx = window.AudioContext || window.webkitAudioContext; + if (!AudioCtx) return { supported: false, reason: 'no-webaudio' }; + try { + var ctx = new AudioCtx(); + var source = ctx.createMediaElementSource(video); + var bassFilter = ctx.createBiquadFilter(); + bassFilter.type = 'lowshelf'; + bassFilter.frequency.value = 110; + + var voiceFilter = ctx.createBiquadFilter(); + voiceFilter.type = 'peaking'; + voiceFilter.frequency.value = 2200; + voiceFilter.Q.value = 1.1; + + var trebleFilter = ctx.createBiquadFilter(); + trebleFilter.type = 'highshelf'; + trebleFilter.frequency.value = 7500; + + var gainNode = ctx.createGain(); + var compressor = ctx.createDynamicsCompressor(); + var analyser = ctx.createAnalyser(); + analyser.fftSize = 64; + analyser.smoothingTimeConstant = 0.78; + + source.connect(bassFilter); + bassFilter.connect(voiceFilter); + voiceFilter.connect(trebleFilter); + trebleFilter.connect(gainNode); + gainNode.connect(compressor); + compressor.connect(analyser); + analyser.connect(ctx.destination); + + if (ctx.state === 'suspended') { + ctx.resume().catch(function () {}); + } + + var graph = { + supported: true, + ctx: ctx, + source: source, + bassFilter: bassFilter, + voiceFilter: voiceFilter, + trebleFilter: trebleFilter, + gainNode: gainNode, + compressor: compressor, + analyser: analyser + }; + videoAudioGraphs.set(video, graph); + return graph; + } catch (err) { + return { supported: false, reason: err && err.message ? err.message : 'error' }; + } + } + + function applyAudioStudioSettings(video, optionalCfg, forceCreate) { + var cfg = optionalCfg || loadAudioStudioSettings(); + if (!video) return { supported: false, reason: 'no-video' }; + var needsGraph = forceCreate || isNonDefaultAudioConfig(cfg) || (videoAudioGraphs && videoAudioGraphs.has(video)); + if (!needsGraph) return { supported: true, bypassed: true }; + var graph = ensureAudioGraph(video); + if (!graph || !graph.supported) return graph || { supported: false }; + + try { + var gainPct = Math.max(50, Math.min(300, Number(cfg.gain || 100))); + graph.gainNode.gain.setTargetAtTime(gainPct / 100, graph.ctx.currentTime, 0.02); + graph.bassFilter.gain.setTargetAtTime(Number(cfg.bass || 0), graph.ctx.currentTime, 0.02); + graph.voiceFilter.gain.setTargetAtTime(Number(cfg.voice || 0), graph.ctx.currentTime, 0.02); + graph.trebleFilter.gain.setTargetAtTime(Number(cfg.treble || 0), graph.ctx.currentTime, 0.02); + + if (cfg.night) { + graph.compressor.threshold.setTargetAtTime(-20, graph.ctx.currentTime, 0.02); + graph.compressor.knee.setTargetAtTime(12, graph.ctx.currentTime, 0.02); + graph.compressor.ratio.setTargetAtTime(14, graph.ctx.currentTime, 0.02); + } else if (cfg.limiter || gainPct > 105) { + graph.compressor.threshold.setTargetAtTime(-3, graph.ctx.currentTime, 0.02); + graph.compressor.knee.setTargetAtTime(6, graph.ctx.currentTime, 0.02); + graph.compressor.ratio.setTargetAtTime(12, graph.ctx.currentTime, 0.02); + } else { + graph.compressor.threshold.setTargetAtTime(0, graph.ctx.currentTime, 0.02); + graph.compressor.ratio.setTargetAtTime(1, graph.ctx.currentTime, 0.02); + } + } catch (e) {} + + var studioBarBtn = document.getElementById('yaktube-bar-studio-btn'); + if (studioBarBtn) { + studioBarBtn.classList.toggle('active', isNonDefaultAudioConfig(cfg)); + } + return graph; + } + + function stopSpectrumLoop() { + if (activeSpectrumRaf) { + cancelAnimationFrame(activeSpectrumRaf); + activeSpectrumRaf = null; + } + } + + function startSpectrumLoop(canvas, video) { + stopSpectrumLoop(); + if (!canvas || !video) return; + var ctx2d = canvas.getContext('2d'); + if (!ctx2d) return; + var graph = applyAudioStudioSettings(video, loadAudioStudioSettings(), isVideoOriginSafeForWebAudio(video)); + var analyser = graph && graph.supported ? graph.analyser : null; + var bins = analyser ? new Uint8Array(analyser.frequencyBinCount) : new Uint8Array(24); + var phase = 0; + + function drawFrame() { + if (!document.body.contains(canvas)) { + activeSpectrumRaf = null; + return; + } + var w = canvas.width; + var h = canvas.height; + ctx2d.clearRect(0, 0, w, h); + + if (document.hidden || video.paused) { + ctx2d.fillStyle = 'rgba(255, 143, 55, 0.28)'; + var idleCount = 24; + var idleW = (w - (idleCount - 1) * 4) / idleCount; + for (var k = 0; k < idleCount; k++) { + ctx2d.fillRect(k * (idleW + 4), h - 4, idleW, 4); + } + activeSpectrumRaf = requestAnimationFrame(drawFrame); + return; + } + + if (analyser) { + analyser.getByteFrequencyData(bins); + } else { + phase += 0.14; + for (var m = 0; m < bins.length; m++) { + bins[m] = Math.floor(70 + 110 * Math.abs(Math.sin(phase + m * 0.45))); + } + } + + var count = Math.min(24, bins.length); + var gap = 4; + var barW = Math.max(4, (w - (count - 1) * gap) / count); + var grad = ctx2d.createLinearGradient(0, h, 0, 0); + grad.addColorStop(0, '#ea580c'); + grad.addColorStop(0.6, '#ff8f37'); + grad.addColorStop(1, '#fde047'); + ctx2d.fillStyle = grad; + + for (var i = 0; i < count; i++) { + var v = bins[i] / 255; + var barH = Math.max(4, Math.round(v * (h - 6))); + var x = i * (barW + gap); + var y = h - barH; + if (typeof ctx2d.roundRect === 'function') { + ctx2d.beginPath(); + ctx2d.roundRect(x, y, barW, barH, 3); + ctx2d.fill(); + } else { + ctx2d.fillRect(x, y, barW, barH); + } + } + activeSpectrumRaf = requestAnimationFrame(drawFrame); + } + + activeSpectrumRaf = requestAnimationFrame(drawFrame); + } + + function openAudioStudioModal() { + var existing = document.getElementById('yaktube-audio-studio-modal'); + if (existing) { + stopSpectrumLoop(); + existing.remove(); + restoreFocusAfterModal(); + announce('Canlı Ses Stüdyosu kapatıldı.'); + return; + } + + var video = getVideoElement(); + if (!video) { + announce('Ses Stüdyosu için aktif bir video bulunamadı.'); + showQuickToast('⚠️ Aktif video bulunamadı'); + return; + } + + recordFocusBeforeModal(); + var cfg = loadAudioStudioSettings(); + var graphResult = applyAudioStudioSettings(video, cfg, isVideoOriginSafeForWebAudio(video)); + var dspSupported = Boolean(graphResult && graphResult.supported); + + var modal = document.createElement('div'); + modal.id = 'yaktube-audio-studio-modal'; + modal.className = 'yaktube-feature-modal-backdrop'; + modal.setAttribute('role', 'dialog'); + modal.setAttribute('aria-modal', 'true'); + modal.setAttribute('aria-labelledby', 'yaktube-studio-title'); + + var presetsHtml = Object.keys(AUDIO_PRESETS) + .map(function (key) { + var p = AUDIO_PRESETS[key]; + var isAct = cfg.preset === key; + return ( + '' + ); + }) + .join(''); + + modal.innerHTML = + '
' + + '
' + + '

🎛️ Canlı Ses Stüdyosu (EQ & %300 Güçlendirme)

' + + '' + + '
' + + (!dspSupported + ? '
ℹ️ Bu video dış sunucudan (Fediverse CORS korumalı) aktarıldığı için ekolayzır ve %300 ses güçlendirme güvenlik nedeniyle devre dışı bırakıldı. YakTube yerli ve YouTube videolarında tam çalışır.
' + : '') + + '' + + '
' + + presetsHtml + + '
' + + '
' + + '' + + '' + + '' + + '' + + '
' + + '' + + '
'; + + document.body.appendChild(modal); + + function closeStudio() { + stopSpectrumLoop(); + modal.remove(); + restoreFocusAfterModal(); + announce('Ses Stüdyosu kapatıldı.'); + } + + modal.querySelector('#yaktube-studio-close').addEventListener('click', closeStudio); + modal.addEventListener('click', function (e) { + if (e.target === modal) closeStudio(); + }); + + var gainEl = modal.querySelector('#yaktube-studio-gain'); + var bassEl = modal.querySelector('#yaktube-studio-bass'); + var voiceEl = modal.querySelector('#yaktube-studio-voice'); + var trebleEl = modal.querySelector('#yaktube-studio-treble'); + var nightEl = modal.querySelector('#yaktube-studio-night'); + + function syncInputsFromCfg(nextCfg) { + gainEl.value = nextCfg.gain; + bassEl.value = nextCfg.bass; + voiceEl.value = nextCfg.voice; + trebleEl.value = nextCfg.treble; + nightEl.checked = Boolean(nextCfg.night); + modal.querySelector('#yaktube-studio-gain-val').textContent = '%' + Math.round(nextCfg.gain); + modal.querySelector('#yaktube-studio-bass-val').textContent = nextCfg.bass + ' dB'; + modal.querySelector('#yaktube-studio-voice-val').textContent = nextCfg.voice + ' dB'; + modal.querySelector('#yaktube-studio-treble-val').textContent = nextCfg.treble + ' dB'; + modal.querySelectorAll('.yaktube-studio-preset-btn').forEach(function (b) { + var active = b.getAttribute('data-preset') === nextCfg.preset; + b.classList.toggle('active', active); + b.setAttribute('aria-pressed', active ? 'true' : 'false'); + }); + } + + function updateFromSliders(presetName) { + var next = { + preset: presetName || 'custom', + gain: parseFloat(gainEl.value), + bass: parseFloat(bassEl.value), + voice: parseFloat(voiceEl.value), + treble: parseFloat(trebleEl.value), + limiter: parseFloat(gainEl.value) > 105 || nightEl.checked, + night: Boolean(nightEl.checked) + }; + saveAudioStudioSettings(next); + applyAudioStudioSettings(video, next, dspSupported); + syncInputsFromCfg(next); + } + + [gainEl, bassEl, voiceEl, trebleEl].forEach(function (inp) { + inp.addEventListener('input', function () { + updateFromSliders('custom'); + }); + }); + nightEl.addEventListener('change', function () { + updateFromSliders(nightEl.checked ? 'night' : 'custom'); + announce(nightEl.checked ? 'Gece dengeleyici modu açıldı.' : 'Gece modu kapatıldı.'); + }); + + modal.querySelectorAll('.yaktube-studio-preset-btn').forEach(function (btn) { + btn.addEventListener('click', function () { + var key = btn.getAttribute('data-preset'); + var preset = AUDIO_PRESETS[key]; + if (!preset) return; + var next = Object.assign({ preset: key }, preset); + saveAudioStudioSettings(next); + applyAudioStudioSettings(video, next, dspSupported); + syncInputsFromCfg(next); + announce(preset.label + ' ses profili uygulandı. Ses gücü yüzde ' + preset.gain + '.'); + }); + }); + + modal.querySelector('#yaktube-studio-reset').addEventListener('click', function () { + var def = Object.assign({ preset: 'normal' }, AUDIO_PRESETS.normal); + saveAudioStudioSettings(def); + applyAudioStudioSettings(video, def, false); + syncInputsFromCfg(def); + announce('Ses ayarları normale sıfırlandı.'); + }); + + var specCanvas = modal.querySelector('#yaktube-studio-spectrum'); + if (specCanvas) { + startSpectrumLoop(specCanvas, video); + } + trapFocusInModal(modal); + announce('Canlı Ses Stüdyosu açıldı. Yüzde 300 ses güçlendirme ve ekolayzır hazır.'); + } + + function renderAbLoopPill() { + var pill = document.getElementById('yaktube-ab-loop-pill'); + var barBtn = document.getElementById('yaktube-bar-ab-btn'); + if (barBtn) { + if (abLoopState.active) { + barBtn.classList.add('active'); + barBtn.textContent = '🔂 A-B: ' + formatClockShort(abLoopState.a) + '-' + formatClockShort(abLoopState.b); + } else if (abLoopState.a !== null) { + barBtn.classList.add('active'); + barBtn.textContent = '🔂 A: ' + formatClockShort(abLoopState.a) + ' → B?'; + } else { + barBtn.classList.remove('active'); + barBtn.textContent = '🔂 A-B Döngü'; + } + } + if (!abLoopState.active && abLoopState.a === null) { + if (pill) pill.remove(); + return; + } + if (!pill) { + pill = document.createElement('div'); + pill.id = 'yaktube-ab-loop-pill'; + pill.className = 'yaktube-ab-loop-pill'; + pill.setAttribute('role', 'region'); + pill.setAttribute('aria-label', 'A-B Tekrar Döngüsü Durumu'); + document.body.appendChild(pill); + } + pill.innerHTML = + '🔂 ' + + (abLoopState.active + ? 'Döngü Aktif: ' + + formatClockShort(abLoopState.a) + + ' ⇄ ' + + formatClockShort(abLoopState.b) + + '' + : 'Başlangıç A: ' + formatClockShort(abLoopState.a) + ' (B için tekrar Alt+B)') + + '' + + ''; + pill.querySelector('#yaktube-ab-clear-btn').addEventListener('click', function () { + clearAbLoop(true); + }); + } + + function formatClockShort(sec) { + var s = Math.max(0, Math.floor(Number(sec || 0))); + var h = Math.floor(s / 3600); + var m = Math.floor((s % 3600) / 60); + var rem = s % 60; + if (h > 0) return h + ':' + (m < 10 ? '0' : '') + m + ':' + (rem < 10 ? '0' : '') + rem; + return m + ':' + (rem < 10 ? '0' : '') + rem; + } + + function clearAbLoop(announceClear) { + var hadAny = abLoopState.a !== null || abLoopState.active; + abLoopState.a = null; + abLoopState.b = null; + abLoopState.active = false; + renderAbLoopPill(); + if (announceClear && hadAny) { + announce('A-B tekrar döngüsü kapatıldı.'); + showQuickToast('🔂 A-B Döngüsü Kapatıldı'); + } + } + + function cycleAbLoop() { + var video = getVideoElement(); + if (!video) { + announce('A-B döngüsü için aktif video bulunamadı.'); + return; + } + if (abLoopState.a === null) { + abLoopState.a = video.currentTime || 0; + renderAbLoopPill(); + announce('A noktası işaretlendi: ' + formatTime(abLoopState.a) + '. Bitiş noktası B için tekrar Alt+B basın.'); + showQuickToast('🔂 A: ' + formatClockShort(abLoopState.a) + ' (B için tekrar bas)'); + } else if (abLoopState.b === null) { + var bPoint = video.currentTime || 0; + if (bPoint <= abLoopState.a + 0.5) { + announce('B bitiş noktası A noktasından en az 1 saniye sonra olmalıdır.'); + showQuickToast("⚠️ B noktası A'dan sonra olmalı"); + return; + } + abLoopState.b = bPoint; + abLoopState.active = true; + video.currentTime = abLoopState.a; + if (video.paused) video.play().catch(function () {}); + renderAbLoopPill(); + announce( + 'A-B döngüsü başlatıldı: ' + + formatTime(abLoopState.a) + + ' ile ' + + formatTime(abLoopState.b) + + ' arası tekrarlanıyor.' + ); + showQuickToast('🔂 Döngü: ' + formatClockShort(abLoopState.a) + ' ⇄ ' + formatClockShort(abLoopState.b)); + } else { + clearAbLoop(true); + } + } async function requestScreenWakeLock() { try { @@ -1183,10 +1704,12 @@ try { '
' + '
📻
' + '

Yalnızca Ses Modu Aktif

' + - '

Ekran pil ve veri tasarrufu için karartıldı. Arka planda çalma desteklenir.

' + - '
' + + '

Ekran pil ve veri tasarrufu için karartıldı. Arka planda çalma ve canlı spektrum desteklenir.

' + + '' + + '
' + '' + '' + + '' + '
' + '
'; @@ -1204,9 +1727,17 @@ try { } }); } + var blankStudioBtn = overlay.querySelector('#yaktube-blank-studio-btn'); + if (blankStudioBtn) { + blankStudioBtn.addEventListener('click', openAudioStudioModal); + } document.body.appendChild(overlay); } overlay.style.display = 'flex'; + var blankCanvas = overlay.querySelector('#yaktube-audio-blank-canvas'); + if (blankCanvas) { + startSpectrumLoop(blankCanvas, video); + } requestScreenWakeLock(); if (audioBtn) { audioBtn.classList.add('active'); @@ -1217,6 +1748,7 @@ try { ); showQuickToast('📻 Yalnızca Ses Modu Açık'); } else { + stopSpectrumLoop(); if (overlay) overlay.style.display = 'none'; releaseScreenWakeLock(); if (audioBtn) { @@ -1229,11 +1761,16 @@ try { } // ============================================================================ - // 3. Accessible Live Transcript Reader (NLnet WCAG 2.2 AAA Milestone) + // 3. Accessible Smart Transcript & Chapter Reader (NLnet WCAG 2.2 AAA Milestone) // ============================================================================ var liveTranscriptCues = []; var isTranscriptPanelOpen = false; + function getActiveWatchVideoSlug() { + var m = window.location.pathname.match(/\/videos\/watch\/([a-zA-Z0-9_-]+)/); + return m ? m[1] : null; + } + function extractVideoCaptions() { var video = getVideoElement(); if (!video || !video.textTracks || !video.textTracks.length) return []; @@ -1244,10 +1781,12 @@ try { if (track.cues && track.cues.length) { for (var j = 0; j < track.cues.length; j++) { var cue = track.cues[j]; + var txt = (cue.text || '').replace(/<[^>]*>/g, '').trim(); + if (!txt) continue; cuesList.push({ startTime: cue.startTime, endTime: cue.endTime, - text: (cue.text || '').replace(/<[^>]*>/g, '').trim() + text: txt }); } break; @@ -1256,6 +1795,191 @@ try { return cuesList; } + function bindTranscriptPanelContent(panel, data) { + if (!panel) return; + var chaptersWrap = panel.querySelector('#yaktube-transcript-chapters'); + var listEl = panel.querySelector('#yaktube-transcript-list'); + var metaEl = panel.querySelector('#yaktube-transcript-meta'); + var langSelectWrap = panel.querySelector('#yaktube-transcript-langs'); + var video = getVideoElement(); + var curTime = video ? video.currentTime : 0; + + var cues = (data && Array.isArray(data.cues) ? data.cues : []).map(function (c) { + return { + startTime: c.startTime !== undefined ? Number(c.startTime) : Number(c.start || 0), + endTime: c.endTime !== undefined ? Number(c.endTime) : Number(c.end || c.start || 0), + text: String(c.text || '').trim() + }; + }); + var chapters = data && Array.isArray(data.chapters) ? data.chapters : []; + + if (metaEl) { + var badgeParts = []; + if (data && data.source === 'youtube-manual') badgeParts.push('YouTube Altyazısı'); + else if (data && data.source === 'youtube-auto') badgeParts.push('YouTube Otomatik Altyazı'); + else if (data && data.source === 'peertube-caption') badgeParts.push('Sunucu Altyazısı'); + else if (data && data.source === 'html5-track') badgeParts.push('Oynatıcı Altyazısı'); + if (data && data.language) badgeParts.push('Dil: ' + data.language.toUpperCase()); + if (chapters.length > 0) badgeParts.push(chapters.length + ' Bölüm'); + if (cues.length > 0) badgeParts.push(cues.length + ' Satır'); + metaEl.textContent = badgeParts.join(' • '); + } + + if (langSelectWrap && data && Array.isArray(data.availableLanguages) && data.availableLanguages.length > 1) { + var langHtml = ''; + data.availableLanguages.slice(0, 6).forEach(function (l) { + var isSel = data.language && String(data.language).toLowerCase() === String(l.code).toLowerCase(); + langHtml += + ''; + }); + langSelectWrap.innerHTML = langHtml; + langSelectWrap.style.display = 'flex'; + langSelectWrap.querySelectorAll('.yaktube-transcript-lang-btn').forEach(function (btn) { + btn.addEventListener('click', function () { + var targetLang = btn.getAttribute('data-lang'); + loadServerTranscriptForPanel(panel, targetLang); + }); + }); + } + + if (chaptersWrap) { + if (chapters.length > 0) { + var chHtml = + '
📑 Video Bölümleri:
'; + chapters.forEach(function (ch) { + var chStart = Number(ch.start || 0); + chHtml += + ''; + }); + chHtml += '
'; + chaptersWrap.innerHTML = chHtml; + chaptersWrap.style.display = 'block'; + chaptersWrap.querySelectorAll('.yaktube-chapter-chip').forEach(function (chip) { + chip.addEventListener('click', function () { + var s = parseFloat(chip.getAttribute('data-start')); + var v = getVideoElement(); + if (v && !isNaN(s)) { + v.currentTime = s; + if (v.paused) v.play().catch(function () {}); + announce(formatTime(s) + ' bölümüne atlandı: ' + chip.textContent.trim()); + } + }); + }); + } else { + chaptersWrap.style.display = 'none'; + chaptersWrap.innerHTML = ''; + } + } + + if (!listEl) return; + liveTranscriptCues = cues; + + if (cues.length > 0) { + var listHtml = ''; + cues.forEach(function (c) { + var isActive = curTime >= c.startTime && curTime <= c.endTime; + listHtml += + '
  • ' + + '' + + escapeHtml(formatClockShort(c.startTime)) + + '' + + '' + + escapeHtml(c.text) + + '' + + '
  • '; + }); + listEl.innerHTML = listHtml; + listEl.querySelectorAll('.yaktube-transcript-item').forEach(function (item) { + function jumpToCue() { + var start = parseFloat(item.getAttribute('data-start')); + var v = getVideoElement(); + if (v && !isNaN(start)) { + v.currentTime = start; + if (v.paused) v.play().catch(function () {}); + announce( + formatTime(start) + ' konumuna gidildi: ' + item.querySelector('.yaktube-transcript-text').textContent + ); + } + } + item.addEventListener('click', jumpToCue); + item.addEventListener('keydown', function (e) { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + jumpToCue(); + } + }); + }); + } else { + listEl.innerHTML = + '
  • ' + + '

    📄 Bu video için altyazı veya transkript metni bulunamadı.

    ' + + (chapters.length > 0 + ? '

    Yukarıdaki 📑 Bölüm zaman damgalarından videonun kısımlarına doğrudan atlayabilirsiniz.

    ' + : '

    Video kaynağı veya YouTube tarafında herkese açık altyazı bulunmuyor.

    ') + + '
  • '; + } + } + + function loadServerTranscriptForPanel(panel, langCode) { + var slug = getActiveWatchVideoSlug(); + if (!slug || !panel || !document.body.contains(panel)) return; + var statusEl = panel.querySelector('#yaktube-transcript-loading'); + if (statusEl) { + statusEl.style.display = 'block'; + statusEl.textContent = '⏳ Akıllı altyazı ve zaman damgalı bölümler getiriliyor...'; + } + var querySuffix = langCode ? '?lang=' + encodeURIComponent(langCode) : ''; + fetchPluginJson('/video-transcript/' + encodeURIComponent(slug) + querySuffix) + .then(function (data) { + if (!document.body.contains(panel)) return; + if (statusEl) statusEl.style.display = 'none'; + if (data && data.ok) { + var localFallback = extractVideoCaptions(); + if ((!data.cues || data.cues.length === 0) && localFallback.length > 0) { + data.cues = localFallback; + if (!data.source || data.source === 'none' || data.source === 'description') { + data.source = 'html5-track'; + } + } + bindTranscriptPanelContent(panel, data); + var msg = + 'Transkript güncellendi: ' + + ((data.cues && data.cues.length) || 0) + + ' satır' + + (data.chapters && data.chapters.length ? ' ve ' + data.chapters.length + ' bölüm' : '') + + '.'; + announce(msg); + } + }) + .catch(function () { + if (statusEl && document.body.contains(panel)) { + statusEl.style.display = 'none'; + } + }); + } + function openTranscriptPanel() { var existing = document.getElementById('yaktube-transcript-panel'); if (existing) { @@ -1270,60 +1994,30 @@ try { isTranscriptPanelOpen = true; var cues = extractVideoCaptions(); - var video = getVideoElement(); - var curTime = video ? video.currentTime : 0; var panel = document.createElement('div'); panel.id = 'yaktube-transcript-panel'; panel.className = 'yaktube-transcript-panel'; panel.setAttribute('role', 'region'); - panel.setAttribute('aria-label', 'Video Transkript ve Canlı Metin İnceleyici'); - - var listHtml = ''; - if (cues && cues.length) { - liveTranscriptCues = cues; - cues.forEach(function (c, idx) { - var isActive = curTime >= c.startTime && curTime <= c.endTime; - listHtml += - '
  • ' + - '' + - formatTime(c.startTime) + - '' + - '' + - c.text + - '' + - '
  • '; - }); - } else { - listHtml = - '
    ' + - '

    📄 Bu video için otomatik altyazı veya transkript henüz hazır değil.

    ' + - '

    Video oynatıcısındaki Altyazı (CC) butonunu açarak dili seçebilirsiniz.

    ' + - '
    '; - } + panel.setAttribute('aria-label', 'Video Transkript ve Bölümler Paneli'); panel.innerHTML = '
    ' + - '
    ' + + '
    ' + '📜' + - '

    Video Transkripti

    ' + + '

    Akıllı Transkript & Bölümler

    ' + + '' + '
    ' + - '
    ' + + '
    ' + '' + - '' + + '' + + '' + '
    ' + '
    ' + - '
      ' + - listHtml + - '
    '; + '' + + '' + + '' + + '
      '; var closeBtn = panel.querySelector('#yaktube-transcript-close'); if (closeBtn) { @@ -1331,29 +2025,35 @@ try { panel.remove(); isTranscriptPanelOpen = false; restoreFocusAfterModal(); + announce('Transkript paneli kapatıldı.'); }); } - // Click on cue to jump video - panel.querySelectorAll('.yaktube-transcript-item').forEach(function (item) { - function jumpToCue() { - var start = parseFloat(item.getAttribute('data-start')); - var v = getVideoElement(); - if (v && !isNaN(start)) { - v.currentTime = start; - if (v.paused) v.play(); - announce( - formatTime(start) + ' konumuna gidildi: ' + item.querySelector('.yaktube-transcript-text').textContent - ); + var copyBtn = panel.querySelector('#yaktube-transcript-copy'); + if (copyBtn) { + copyBtn.addEventListener('click', function () { + if (!liveTranscriptCues || !liveTranscriptCues.length) { + showQuickToast('⚠️ Kopyalanacak transkript yok'); + return; } - } - item.addEventListener('click', jumpToCue); - item.addEventListener('keydown', function (e) { - if (e.key === 'Enter' || e.key === ' ') { - e.preventDefault(); - jumpToCue(); + var plain = liveTranscriptCues + .map(function (c) { + return '[' + formatClockShort(c.startTime) + '] ' + c.text; + }) + .join('\n'); + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(plain).then(function () { + showQuickToast('📋 Transkript panoya kopyalandı (' + liveTranscriptCues.length + ' satır)'); + announce('Transkript panoya kopyalandı.'); + }); } }); + } + + bindTranscriptPanelContent(panel, { + source: cues.length ? 'html5-track' : 'none', + cues: cues, + chapters: [] }); // Live search in transcript @@ -1362,7 +2062,8 @@ try { searchInp.addEventListener('input', function (e) { var query = (e.target.value || '').toLowerCase().trim(); panel.querySelectorAll('.yaktube-transcript-item').forEach(function (item) { - var txt = (item.querySelector('.yaktube-transcript-text').textContent || '').toLowerCase(); + var txtEl = item.querySelector('.yaktube-transcript-text'); + var txt = ((txtEl && txtEl.textContent) || '').toLowerCase(); item.style.display = txt.includes(query) ? 'flex' : 'none'; }); }); @@ -1377,12 +2078,321 @@ try { document.body.appendChild(panel); } + loadServerTranscriptForPanel(panel, ''); trapFocusInModal(panel); announce( - 'Transkript paneli açıldı. ' + (cues.length ? cues.length + ' satır metin bulundu.' : 'Altyazı bulunamadı.') + 'Akıllı transkript ve bölümler paneli açıldı. ' + + (cues.length ? cues.length + ' satır hazır, YouTube kaynakları da taranıyor.' : 'Veriler getiriliyor.') ); } + // ============================================================================ + // 3b. Persistent Personal Playback Queue (Alt+R / + Sıraya Ekle) + // ============================================================================ + var PLAY_QUEUE_STORAGE_KEY = 'yaktube_play_queue_v1'; + + function makeQueueKey(item) { + if (!item) return ''; + if (item.uuid) return 'uuid:' + item.uuid; + if (item.id && !String(item.id).startsWith('local')) return 'yt:' + item.id; + if (item.localUrl) return 'url:' + item.localUrl; + if (item.url) return 'url:' + item.url; + return 'title:' + (item.title || ''); + } + + function loadPlayQueue() { + try { + var raw = localStorage.getItem(PLAY_QUEUE_STORAGE_KEY); + var arr = raw ? JSON.parse(raw) : []; + return Array.isArray(arr) ? arr : []; + } catch (e) { + return []; + } + } + + function savePlayQueue(list) { + try { + localStorage.setItem(PLAY_QUEUE_STORAGE_KEY, JSON.stringify(Array.isArray(list) ? list : [])); + } catch (e) {} + syncQueueCountersUI(); + } + + function syncQueueCountersUI() { + var list = loadPlayQueue(); + var count = list.length; + var barBtn = document.getElementById('yaktube-bar-queue-btn'); + if (barBtn) { + barBtn.textContent = count > 0 ? '📋 Sıra (' + count + ')' : '📋 Sıra'; + barBtn.classList.toggle('active', count > 0); + } + var miniBtn = document.getElementById('yaktube-floating-queue-btn'); + if (count > 0) { + if (!miniBtn) { + miniBtn = document.createElement('button'); + miniBtn.id = 'yaktube-floating-queue-btn'; + miniBtn.type = 'button'; + miniBtn.className = 'yaktube-floating-queue-btn'; + miniBtn.setAttribute('aria-label', 'Çalma sırasını aç (Alt+R)'); + miniBtn.addEventListener('click', openPlayQueueDrawer); + document.body.appendChild(miniBtn); + } + miniBtn.textContent = '📋 Çalma Sırası (' + count + ')'; + } else if (miniBtn) { + miniBtn.remove(); + } + } + + function addToPlayQueue(rawItem) { + if (!rawItem) return false; + var item = { + key: makeQueueKey(rawItem), + id: rawItem.id || '', + uuid: rawItem.uuid || '', + title: rawItem.title || 'Adsız Video', + channel: rawItem.channel || getInstanceName(), + durationFormatted: rawItem.durationFormatted || '', + localUrl: rawItem.localUrl || '', + url: rawItem.url || '', + thumbnail: rawItem.thumbnail || '/client/assets/images/default-thumbnail.jpg', + isLive: Boolean(rawItem.isLive) + }; + if (!item.key) return false; + var queue = loadPlayQueue(); + var already = queue.some(function (q) { + return q.key === item.key; + }); + if (already) { + showQuickToast('ℹ️ Bu video zaten çalma sıranızda'); + announce(item.title + ' zaten çalma sıranızda bulunuyor.'); + return false; + } + queue.push(item); + savePlayQueue(queue); + showQuickToast('➕ Sıraya Eklendi (' + queue.length + '): ' + item.title); + announce(item.title + ' çalma sırasına eklendi. Sırada ' + queue.length + ' video var.'); + return true; + } + + function getNextQueueItem(consume) { + var queue = loadPlayQueue(); + if (!queue.length) return null; + var curSlug = getActiveWatchVideoSlug(); + var idx = 0; + if (curSlug) { + var foundIdx = queue.findIndex(function (q) { + var slugMatch = (q.uuid && q.uuid === curSlug) || (q.localUrl && q.localUrl.indexOf(curSlug) !== -1); + return !slugMatch; + }); + if (foundIdx === -1) return null; + idx = foundIdx; + } + var picked = queue[idx]; + if (consume && picked) { + queue.splice(idx, 1); + savePlayQueue(queue); + } + return picked; + } + + function playSpecificQueueItem(item, indexToRemove) { + if (!item) return false; + if (typeof indexToRemove === 'number') { + var q = loadPlayQueue(); + if (indexToRemove >= 0 && indexToRemove < q.length) { + q.splice(indexToRemove, 1); + savePlayQueue(q); + } + } + var targetLocal = item.localUrl || (item.uuid ? '/videos/watch/' + item.uuid : ''); + if (targetLocal) { + announce('Çalma sırasından oynatılıyor: ' + item.title); + showQuickToast('▶️ Sıradan: ' + item.title); + currentActiveVideoKey = null; + window.location.href = targetLocal; + return true; + } + if (item.url) { + announce("Çalma sırasındaki video YakTube'a aktarılıp oynatılıyor: " + item.title); + var dummyBtn = document.createElement('button'); + handleImport(item.url, dummyBtn, item.title); + return true; + } + return false; + } + + function openPlayQueueDrawer() { + var existing = document.getElementById('yaktube-queue-drawer'); + if (existing) { + existing.remove(); + restoreFocusAfterModal(); + announce('Çalma sırası çekmecesi kapatıldı.'); + return; + } + + recordFocusBeforeModal(); + var modal = document.createElement('div'); + modal.id = 'yaktube-queue-drawer'; + modal.className = 'yaktube-feature-modal-backdrop'; + modal.setAttribute('role', 'dialog'); + modal.setAttribute('aria-modal', 'true'); + modal.setAttribute('aria-labelledby', 'yaktube-queue-title'); + + function renderDrawer() { + var queue = loadPlayQueue(); + var bodyHtml = ''; + if (!queue.length) { + bodyHtml = + '
      ' + + '
      📋
      ' + + '

      Çalma sıranız şu an boş

      ' + + '

      Arama sonuçlarındaki veya önerilen videolardaki + Sıraya Ekle butonuna basarak arka arkaya oynatılacak kendi listenizi oluşturabilirsiniz.

      ' + + '
      '; + } else { + bodyHtml = '
        '; + queue.forEach(function (q, idx) { + bodyHtml += + '
      1. ' + + '' + + (idx + 1) + + '' + + '' + + '
        ' + + '
        ' + + escapeHtml(q.title) + + '
        ' + + '
        ' + + escapeHtml(q.channel || '') + + (q.durationFormatted ? ' • ' + escapeHtml(q.durationFormatted) : '') + + (q.localUrl || q.uuid ? ' • ✅ Hazır' : ' • 📥 İndirilecek') + + '
        ' + + '
        ' + + '
        ' + + '' + + (idx > 0 + ? '' + : '') + + (idx < queue.length - 1 + ? '' + : '') + + '' + + '
        ' + + '
      2. '; + }); + bodyHtml += '
      '; + } + + modal.innerHTML = + '
      ' + + '
      ' + + '

      📋 Kişisel Çalma Sırası (' + + queue.length + + ')

      ' + + '' + + '
      ' + + '
      ' + + bodyHtml + + '
      ' + + '' + + '
      '; + + modal.querySelector('#yaktube-queue-close').addEventListener('click', closeQueue); + modal.querySelector('#yaktube-queue-play-next').addEventListener('click', function () { + var q = loadPlayQueue(); + if (q.length) { + closeQueue(); + playSpecificQueueItem(q[0], 0); + } + }); + modal.querySelector('#yaktube-queue-clear').addEventListener('click', function () { + savePlayQueue([]); + renderDrawer(); + announce('Çalma sırası tamamen temizlendi.'); + }); + modal.querySelectorAll('.yaktube-queue-play-one').forEach(function (b) { + b.addEventListener('click', function () { + var idx = parseInt(b.getAttribute('data-idx'), 10); + var q = loadPlayQueue(); + if (q[idx]) { + closeQueue(); + playSpecificQueueItem(q[idx], idx); + } + }); + }); + modal.querySelectorAll('.yaktube-queue-up').forEach(function (b) { + b.addEventListener('click', function () { + var idx = parseInt(b.getAttribute('data-idx'), 10); + var q = loadPlayQueue(); + if (idx > 0 && idx < q.length) { + var tmp = q[idx - 1]; + q[idx - 1] = q[idx]; + q[idx] = tmp; + savePlayQueue(q); + renderDrawer(); + announce('Video bir üst sıraya taşındı.'); + } + }); + }); + modal.querySelectorAll('.yaktube-queue-down').forEach(function (b) { + b.addEventListener('click', function () { + var idx = parseInt(b.getAttribute('data-idx'), 10); + var q = loadPlayQueue(); + if (idx >= 0 && idx < q.length - 1) { + var tmp = q[idx + 1]; + q[idx + 1] = q[idx]; + q[idx] = tmp; + savePlayQueue(q); + renderDrawer(); + announce('Video bir alt sıraya taşındı.'); + } + }); + }); + modal.querySelectorAll('.yaktube-queue-del').forEach(function (b) { + b.addEventListener('click', function () { + var idx = parseInt(b.getAttribute('data-idx'), 10); + var q = loadPlayQueue(); + var removed = q.splice(idx, 1)[0]; + savePlayQueue(q); + renderDrawer(); + announce((removed ? removed.title : 'Video') + ' sıradan çıkarıldı.'); + }); + }); + } + + function closeQueue() { + modal.remove(); + restoreFocusAfterModal(); + announce('Çalma sırası kapatıldı.'); + } + + modal.addEventListener('click', function (e) { + if (e.target === modal) closeQueue(); + }); + + document.body.appendChild(modal); + renderDrawer(); + trapFocusInModal(modal); + announce('Kişisel çalma sırası penceresi açıldı.'); + } + // Sync transcript highlight with current video time setInterval(function () { if (!isTranscriptPanelOpen) return; @@ -1393,17 +2403,20 @@ try { if (!panel) return; var items = panel.querySelectorAll('.yaktube-transcript-item'); + var bestItem = null; items.forEach(function (item) { var start = parseFloat(item.getAttribute('data-start')); - var isActive = Math.abs(curTime - start) < 3; - if (isActive && !item.classList.contains('active')) { - items.forEach(function (i) { - i.classList.remove('active'); - }); - item.classList.add('active'); + if (!isNaN(start) && start <= curTime + 0.5) { + bestItem = item; } }); - }, 1500); + if (bestItem && !bestItem.classList.contains('active')) { + items.forEach(function (i) { + i.classList.remove('active'); + }); + bestItem.classList.add('active'); + } + }, 1200); // ============================================================================ // 4. Fediverse Clean Share & Timestamp Generator (Privacy First) @@ -1581,8 +2594,12 @@ try { 'Alt + M veya MSesi Kapat / Aç (Mute)' + 'Alt + T veya TSinema / Tiyatro Modu' + 'Alt + I veya IHızlı Video Bilgisi & İstatistikler' + - 'Alt + C📜 Canlı Video Transkript Panelini Aç / Kapat' + - 'Alt + O📻 Yalnızca Ses & Ekran Karartma Modu' + + 'Alt + C📜 Akıllı Transkript & Bölümler Paneli' + + 'Alt + E🎛️ Canlı Ses Stüdyosu (EQ & %300 Güç)' + + 'Alt + B🔂 A-B Tekrar Döngüsü (İşaretle / Kapat)' + + 'Alt + R📋 Kişisel Çalma Sırası (Kuyruk)' + + 'Alt + G veya Ctrl + Shift + K⌘ Hızlı Komut Paleti' + + 'Alt + O📻 Yalnızca Ses & Ekran Karartma Modu' + 'F6 / Shift + F6🎯 Mantıksal Bölge Gezinmesi (Landmarks)' + 'Alt + U⏱️ Uyku Zamanlayıcısı (Sleep Timer)' + 'Alt + Q📱 Telefonda Devam Et (QR Kod)' + @@ -2874,7 +3891,10 @@ try { '' + '' + '' + - '' + + '' + + '' + + '' + + '' + '' + ''; @@ -2961,6 +3981,31 @@ try { }); } + var studioBtn = bar.querySelector('#yaktube-bar-studio-btn'); + if (studioBtn) { + if (isNonDefaultAudioConfig(loadAudioStudioSettings())) { + studioBtn.classList.add('active'); + } + studioBtn.addEventListener('click', function () { + openAudioStudioModal(); + }); + } + + var abBtn = bar.querySelector('#yaktube-bar-ab-btn'); + if (abBtn) { + abBtn.addEventListener('click', function () { + cycleAbLoop(); + }); + } + + var queueBarBtn = bar.querySelector('#yaktube-bar-queue-btn'); + if (queueBarBtn) { + queueBarBtn.addEventListener('click', function () { + openPlayQueueDrawer(); + }); + syncQueueCountersUI(); + } + var transcriptBtn = bar.querySelector('#yaktube-bar-transcript-btn'); if (transcriptBtn) { transcriptBtn.addEventListener('click', function () { @@ -2989,6 +4034,43 @@ try { announce('Kota uyarısı penceresi kapatıldı.'); return; } + var studioModal = document.getElementById('yaktube-audio-studio-modal'); + if (studioModal) { + stopSpectrumLoop(); + studioModal.remove(); + restoreFocusAfterModal(); + announce('Ses Stüdyosu kapatıldı.'); + return; + } + var queueDrawer = document.getElementById('yaktube-queue-drawer'); + if (queueDrawer) { + queueDrawer.remove(); + restoreFocusAfterModal(); + announce('Çalma sırası penceresi kapatıldı.'); + return; + } + var cmdPalette = document.getElementById('yaktube-command-palette'); + if (cmdPalette) { + cmdPalette.remove(); + restoreFocusAfterModal(); + announce('Hızlı komut paleti kapatıldı.'); + return; + } + var cockpitModal = document.getElementById('yaktube-server-cockpit-modal'); + if (cockpitModal) { + cockpitModal.remove(); + restoreFocusAfterModal(); + announce('Sistem kokpiti kapatıldı.'); + return; + } + var trPanel = document.getElementById('yaktube-transcript-panel'); + if (trPanel) { + trPanel.remove(); + isTranscriptPanelOpen = false; + restoreFocusAfterModal(); + announce('Transkript paneli kapatıldı.'); + return; + } var sleepModal = document.getElementById('yaktube-sleep-modal'); if (sleepModal) { sleepModal.remove(); @@ -3059,10 +4141,20 @@ try { } } - // Search Open: Alt+S, Ctrl+K or '/' key (Turkish Q Shift+7) + // Command Palette: Alt+G or Ctrl+Shift+K + if ( + (e.altKey && (e.key === 'g' || e.key === 'G')) || + (e.ctrlKey && e.shiftKey && (e.key === 'k' || e.key === 'K')) + ) { + e.preventDefault(); + openCommandPalette(); + return; + } + + // Search Open: Alt+S, Ctrl+K (without Shift) or '/' key (Turkish Q Shift+7) if ( ((e.altKey && (e.key === 's' || e.key === 'S')) || - (e.ctrlKey && (e.key === 'k' || e.key === 'K')) || + (e.ctrlKey && !e.shiftKey && (e.key === 'k' || e.key === 'K')) || e.key === '/') && !isInputFocused() ) { @@ -3092,6 +4184,27 @@ try { return; } + // Live Audio Studio (EQ & %300 Boost): Alt+E + if (e.altKey && (e.key === 'e' || e.key === 'E') && !isInputFocused()) { + e.preventDefault(); + openAudioStudioModal(); + return; + } + + // A-B Repeat Loop: Alt+B + if (e.altKey && (e.key === 'b' || e.key === 'B') && !isInputFocused()) { + e.preventDefault(); + cycleAbLoop(); + return; + } + + // Personal Play Queue Drawer: Alt+R + if (e.altKey && (e.key === 'r' || e.key === 'R') && !isInputFocused()) { + e.preventDefault(); + openPlayQueueDrawer(); + return; + } + // Voice Search Open: Alt+V or Shift+V if ( ((e.altKey && (e.key === 'v' || e.key === 'V')) || (e.shiftKey && (e.key === 'v' || e.key === 'V'))) && @@ -3360,7 +4473,88 @@ try { } } - function showModal(title, desc) { + var bgImportMinimized = false; + var activeBgImportState = null; + + function updateBackgroundImportPill(state) { + activeBgImportState = state; + var pill = document.getElementById('yaktube-bg-import-pill'); + if (!state || (!bgImportMinimized && state.status !== 'ready')) { + if (pill) pill.remove(); + return; + } + if (!pill) { + pill = document.createElement('div'); + pill.id = 'yaktube-bg-import-pill'; + pill.className = 'yaktube-bg-import-pill'; + pill.setAttribute('role', 'status'); + pill.setAttribute('aria-live', 'polite'); + document.body.appendChild(pill); + } + var safeTitle = escapeHtml(state.title || 'Video'); + if (state.status === 'ready' && state.watchUrl) { + pill.classList.add('ready'); + pill.innerHTML = + '
      ✅ ' + + safeTitle + + ' izlemeye hazır!
      ' + + '
      ' + + '▶️ Şimdi İzle' + + '' + + '' + + '
      '; + pill.querySelector('#yaktube-bg-import-queue-btn').addEventListener('click', function () { + addToPlayQueue({ + uuid: state.uuid || '', + title: state.title || 'Hazır Video', + channel: getInstanceName(), + localUrl: state.watchUrl, + url: state.watchUrl + }); + bgImportMinimized = false; + pill.remove(); + }); + pill.querySelector('#yaktube-bg-import-dismiss-btn').addEventListener('click', function () { + bgImportMinimized = false; + pill.remove(); + }); + } else if (state.status === 'failed') { + pill.classList.remove('ready'); + pill.innerHTML = + '
      ⚠️ ' + + safeTitle + + ' aktarılamadı.
      ' + + ''; + pill.querySelector('#yaktube-bg-import-dismiss-btn').addEventListener('click', function () { + bgImportMinimized = false; + pill.remove(); + }); + } else { + pill.classList.remove('ready'); + pill.innerHTML = + '
      📥 ' + + safeTitle + + ' — ' + + escapeHtml(state.progressLabel || 'Arka planda indiriliyor...') + + '
      ' + + '
      ' + + '' + + '
      '; + pill.querySelector('#yaktube-bg-import-expand-btn').addEventListener('click', function () { + bgImportMinimized = false; + pill.remove(); + showModal(state.modalTitle || '📥 Video İndiriliyor...', state.modalDesc || 'Hazırlanıyor...', { + allowMinimize: true, + videoTitle: state.title + }); + }); + } + } + + function showModal(title, desc, options) { + var opts = options || {}; var overlay = document.getElementById('yaktube-import-modal'); if (!overlay) { overlay = document.createElement('div'); @@ -3378,16 +4572,44 @@ try { '

      ' + (desc || 'Seçtiğiniz video D: diskinize aktarılıyor...') + '

      ' + + '' + '
      '; document.body.appendChild(overlay); + var minBtn = overlay.querySelector('#yaktube-modal-minimize-btn'); + if (minBtn) { + minBtn.addEventListener('click', function () { + bgImportMinimized = true; + overlay.style.display = 'none'; + restoreFocusAfterModal(); + updateBackgroundImportPill( + activeBgImportState || { + status: 'progress', + title: opts.videoTitle || 'Video', + progressLabel: 'İndiriliyor...' + } + ); + announce('İndirme arka plana alındı. Hazır olduğunda size haber verilecek.'); + showQuickToast('⏬ İndirme arka plana alındı'); + }); + } } else { var titleElem = document.getElementById('yaktube-modal-title'); var descElem = document.getElementById('yaktube-modal-desc'); if (titleElem) titleElem.innerText = title; if (descElem) descElem.innerText = desc; - overlay.style.display = 'flex'; + if (!bgImportMinimized) { + overlay.style.display = 'flex'; + } + } + var minWrap = document.getElementById('yaktube-modal-min-wrap'); + if (minWrap) { + minWrap.style.display = opts.allowMinimize ? 'flex' : 'none'; + } + if (!bgImportMinimized) { + announce((title || '') + '. ' + (desc || ''), true); } - announce((title || '') + '. ' + (desc || ''), true); } function hideModal() { @@ -4270,11 +5492,23 @@ try { return; } + bgImportMinimized = false; + activeBgImportState = { + status: 'progress', + title: videoTitle || 'Video', + modalTitle: '[1/2] 📥 Video İndiriliyor...', + modalDesc: + (videoTitle ? '"' + videoTitle + '" ' : 'Video ') + + "YouTube'dan sunucunuza aktarılıyor. Lütfen bekleyin...", + progressLabel: 'Başlatılıyor...' + }; + recordFocusBeforeModal(); btn.disabled = true; btn.innerHTML = '⏳ Aktarılıyor...'; showModal( '[1/2] 📥 Video İndiriliyor...', - (videoTitle ? '"' + videoTitle + '" ' : 'Video ') + "YouTube'dan sunucunuza aktarılıyor. Lütfen bekleyin..." + (videoTitle ? '"' + videoTitle + '" ' : 'Video ') + "YouTube'dan sunucunuza aktarılıyor. Lütfen bekleyin...", + { allowMinimize: true, videoTitle: videoTitle } ); var headers = { 'Content-Type': 'application/json' }; @@ -4350,23 +5584,61 @@ try { .then(function (sData) { isRequestInFlight = false; if (sData.isImporting) { - showModal( - '[1/2] 📥 Video İndiriliyor...', - 'Video yüksek hızla sunucuya indiriliyor (' + Math.round(attempts * 1.5) + ' sn)...' - ); + var impSec = Math.round(attempts * 1.5); + updateBackgroundImportPill({ + status: 'progress', + title: videoTitle || 'Video', + modalTitle: '[1/2] 📥 Video İndiriliyor...', + modalDesc: 'Video yüksek hızla sunucuya indiriliyor (' + impSec + ' sn)...', + progressLabel: 'İndiriliyor (' + impSec + ' sn)' + }); + if (!bgImportMinimized) { + showModal( + '[1/2] 📥 Video İndiriliyor...', + 'Video yüksek hızla sunucuya indiriliyor (' + impSec + ' sn)...', + { allowMinimize: true, videoTitle: videoTitle } + ); + } } else if (sData.isTranscoding) { - showModal( - '[2/2] ⚙️ Oynatıcı Hazırlanıyor...', - 'Video işleniyor ve yüksek kalite akış hazırlanıyor...' - ); + updateBackgroundImportPill({ + status: 'progress', + title: videoTitle || 'Video', + modalTitle: '[2/2] ⚙️ Oynatıcı Hazırlanıyor...', + modalDesc: 'Video işleniyor ve yüksek kalite akış hazırlanıyor...', + progressLabel: 'İşleniyor...' + }); + if (!bgImportMinimized) { + showModal( + '[2/2] ⚙️ Oynatıcı Hazırlanıyor...', + 'Video işleniyor ve yüksek kalite akış hazırlanıyor...', + { allowMinimize: true, videoTitle: videoTitle } + ); + } } if (sData.isPublished) { clearInterval(pollInterval); - showModal('🎉 Video Hazır!', 'Video kütüphanenize eklendi. Oynatıcı açılıyor...'); - setTimeout(function () { - window.location.href = '/videos/watch/' + (sData.uuid || videoUuid); - }, 400); + var targetWatchUrl = '/videos/watch/' + (sData.uuid || videoUuid); + if (bgImportMinimized) { + btn.disabled = false; + btn.innerHTML = '✅ Hazır'; + updateBackgroundImportPill({ + status: 'ready', + uuid: sData.uuid || videoUuid, + title: videoTitle || sData.name || 'Video', + watchUrl: targetWatchUrl + }); + announce( + (videoTitle || 'Video') + + ' hazır! Ekranın sağ altındaki Şimdi İzle veya Sıraya Ekle butonunu kullanabilirsiniz.', + true + ); + } else { + showModal('🎉 Video Hazır!', 'Video kütüphanenize eklendi. Oynatıcı açılıyor...'); + setTimeout(function () { + window.location.href = targetWatchUrl; + }, 400); + } } else if (sData.isFailed) { clearInterval(pollInterval); btn.disabled = false; @@ -4374,7 +5646,11 @@ try { var failMsg = sData.errorMessage || "Bu video şu anda YouTube'dan aktarılamadı. Lütfen tekrar deneyin veya başka bir video seçin."; - showModal('⚠️ Video Aktarma Hatası', failMsg); + if (bgImportMinimized) { + updateBackgroundImportPill({ status: 'failed', title: videoTitle || 'Video' }); + } else { + showModal('⚠️ Video Aktarma Hatası', failMsg); + } announce(failMsg, true); } }) @@ -4655,6 +5931,28 @@ try { ' kanalı, Süre: ' + durationText; + var ytQueueBtn = !isLive + ? '' + : ''; + ytCardsHtml += '
      ' + actionButton + + ytQueueBtn + + '
      ' + '
      ' + '
      '; }); @@ -4733,7 +6034,7 @@ try { '">' + '' + + '" style="text-decoration:none; color:inherit;">' + '
      ' + '' + - '
      ' + + '' + '✅ ' + escapeHtml(getInstanceName()) + "'da Mevcut" + @@ -4759,12 +6063,32 @@ try { ' • ' + escapeHtml(lViews) + '
      ' + - '
      ' + - '
      ▶️ ' + - escapeHtml(getInstanceName()) + - "'dan Hemen İzle
      " + - '' + '
      ' + + '
      ' + + '▶️ ' + + escapeHtml(getInstanceName()) + + "'dan İzle" + + '' + + '
      ' + + '' + ''; }); @@ -4826,6 +6150,24 @@ try { handleImport(videoUrl, e.currentTarget, videoTitle); }); }); + + targetContainer.querySelectorAll('.yaktube-queue-add-btn').forEach(function (qBtn) { + qBtn.addEventListener('click', function (e) { + e.preventDefault(); + e.stopPropagation(); + var b = e.currentTarget; + addToPlayQueue({ + id: b.getAttribute('data-id') || '', + uuid: b.getAttribute('data-uuid') || '', + url: b.getAttribute('data-url') || '', + localUrl: b.getAttribute('data-local-url') || '', + title: b.getAttribute('data-title') || '', + channel: b.getAttribute('data-channel') || '', + durationFormatted: b.getAttribute('data-dur') || '', + thumbnail: b.getAttribute('data-thumb') || '' + }); + }); + }); } renderAll(); @@ -5669,6 +7011,25 @@ try { openFullSearchModal('', true); }); } + + // 4. Quick Command Palette Trigger Button (⌘ Komutlar) + var cmdBtn = outerWrap.querySelector('.yaktube-cmd-palette-trigger-btn'); + if (!cmdBtn) { + cmdBtn = document.createElement('button'); + cmdBtn.type = 'button'; + cmdBtn.className = 'yaktube-cmd-palette-trigger-btn'; + cmdBtn.setAttribute('aria-label', 'Hızlı Komut Paleti (Alt+G veya Ctrl+Shift+K)'); + cmdBtn.setAttribute('title', 'Hızlı Komut Paleti (Alt+G)'); + cmdBtn.innerHTML = '⌘'; + + outerWrap.appendChild(cmdBtn); + + cmdBtn.addEventListener('click', function (e) { + e.preventDefault(); + e.stopPropagation(); + openCommandPalette(); + }); + } } function injectSearchEnhancements() { @@ -6097,6 +7458,10 @@ try { function playFirstSmartRecommendation(triggerSource) { clearUpNextOverlay(); + var queuedNext = getNextQueueItem(true); + if (queuedNext) { + return playSpecificQueueItem(queuedNext); + } var nextItem = getFirstSmartRecommendation(); if (!nextItem) { announce('Henüz sıradaki öneri hazır değil.'); @@ -6438,7 +7803,28 @@ try { escapeHtml(item.channel || '') + '' + '' + + '
      ' + actionButton + + '' + + '
      ' + '' + ''; }); @@ -6603,6 +7989,24 @@ try { currentActiveVideoKey = null; }); }); + + container.querySelectorAll('.yaktube-queue-add-btn').forEach(function (qBtn) { + qBtn.addEventListener('click', function (e) { + e.preventDefault(); + e.stopPropagation(); + var b = e.currentTarget; + addToPlayQueue({ + id: b.getAttribute('data-id') || '', + uuid: b.getAttribute('data-uuid') || '', + url: b.getAttribute('data-url') || '', + localUrl: b.getAttribute('data-local-url') || '', + title: b.getAttribute('data-title') || '', + channel: b.getAttribute('data-channel') || '', + durationFormatted: b.getAttribute('data-dur') || '', + thumbnail: b.getAttribute('data-thumb') || '' + }); + }); + }); } function updatePrefetchBadgeInPlace(status) { @@ -6809,10 +8213,25 @@ try { function showPostVideoUpNextOverlay() { clearUpNextOverlay(); - if (!cachedRelatedResults || cachedRelatedResults.length === 0) return; + var queuedPreview = getNextQueueItem(false); + if (!queuedPreview && (!cachedRelatedResults || cachedRelatedResults.length === 0)) return; - // Always pick the very first unwatched recommendation (#1 in Smart Recommendations) - var nextItem = getFirstSmartRecommendation(); + // Priority: Personal Queue first, then #1 Smart Recommendation + var nextItem = queuedPreview + ? { + title: queuedPreview.title, + channel: queuedPreview.channel, + reasonBadge: '📋 Kişisel Çalma Sıranız', + thumbnail: queuedPreview.thumbnail, + url: queuedPreview.url, + isDownloaded: Boolean(queuedPreview.localUrl || queuedPreview.uuid), + localVideo: queuedPreview.localUrl + ? { url: queuedPreview.localUrl, uuid: queuedPreview.uuid } + : queuedPreview.uuid + ? { url: '/videos/watch/' + queuedPreview.uuid, uuid: queuedPreview.uuid } + : null + } + : getFirstSmartRecommendation(); if (!nextItem) return; var isReadyLocal = !!(nextItem.isDownloaded && nextItem.localVideo && nextItem.localVideo.url); @@ -7542,11 +8961,17 @@ try { videoState.lastPlayTime = Date.now(); clearUpNextOverlay(); updateMediaSessionMetadata(video); + try { + applyAudioStudioSettings(video, loadAudioStudioSettings(), false); + } catch (e) {} }); video.addEventListener('ended', function () { videoState.hasPlayed = false; videoState.explicitlyPausedByClick = true; + try { + recordContinueWatchingProgress(video, true); + } catch (e) {} try { showPostVideoUpNextOverlay(); } catch (e) {} @@ -7554,6 +8979,17 @@ try { video.addEventListener('timeupdate', function () { updateMediaSessionPosition(video); + if ( + abLoopState.active && + abLoopState.a !== null && + abLoopState.b !== null && + video.currentTime >= abLoopState.b + ) { + video.currentTime = abLoopState.a; + } + try { + recordContinueWatchingProgress(video, false); + } catch (e) {} try { checkSmartPrefetchOnTimeUpdate(video); } catch (e) {} @@ -7671,13 +9107,963 @@ try { } catch (e) {} } - // 10. Unified Debounced MutationObserver & Reactive SPA Engine (v1.5.0) + // ============================================================================ + // 10. Continue Watching Shelf, Command Palette, Admin Cockpit & Portal Focus Rescue + // ============================================================================ + var CONTINUE_WATCHING_KEY = 'yaktube_continue_watching_v1'; + var lastContinueSaveTs = 0; + var cachedUserRoleId = null; + var roleFetchAttempted = false; + + function checkCurrentUserRoleOnce() { + if (roleFetchAttempted) return Promise.resolve(cachedUserRoleId); + var token = null; + try { + token = localStorage.getItem('access_token'); + } catch (e) {} + if (!token) return Promise.resolve(null); + roleFetchAttempted = true; + return fetch('/api/v1/users/me', { + headers: { Authorization: 'Bearer ' + token } + }) + .then(function (r) { + return r.ok ? r.json() : null; + }) + .then(function (u) { + if (u && u.role && typeof u.role.id === 'number') { + cachedUserRoleId = u.role.id; + } + return cachedUserRoleId; + }) + .catch(function () { + return null; + }); + } + try { + checkCurrentUserRoleOnce(); + } catch (e) {} + + function loadContinueWatchingList() { + try { + var raw = localStorage.getItem(CONTINUE_WATCHING_KEY); + var arr = raw ? JSON.parse(raw) : []; + return Array.isArray(arr) ? arr : []; + } catch (e) { + return []; + } + } + + function saveContinueWatchingList(list) { + try { + localStorage.setItem(CONTINUE_WATCHING_KEY, JSON.stringify((list || []).slice(0, 12))); + } catch (e) {} + } + + function recordContinueWatchingProgress(video, isEnded) { + if (!video || !isWatchUrl() || isEmbedUrl()) return; + var slug = getActiveWatchVideoSlug(); + if (!slug) return; + + var now = Date.now(); + if (!isEnded && now - lastContinueSaveTs < 4000) return; + + var dur = Number(video.duration || 0); + var cur = Number(video.currentTime || 0); + if (!isFinite(dur) || dur < 30) return; + + lastContinueSaveTs = now; + var ratio = cur / dur; + var list = loadContinueWatchingList(); + + if (isEnded || ratio >= 0.94) { + var pruned = list.filter(function (item) { + return item.slug !== slug; + }); + if (pruned.length !== list.length) { + saveContinueWatchingList(pruned); + } + return; + } + + if (cur < 5) return; + + var titleEl = document.querySelector('h1.video-title, my-video-watch h1, .video-name, .title'); + var title = (titleEl && titleEl.textContent.trim()) || document.title.replace(/\s*[-|]\s*YakTube.*$/i, '').trim(); + if (!title) title = 'YakTube Videosu'; + + var chEl = document.querySelector('.video-info-channel-name, .channel-name, .actor-name'); + var channel = (chEl && chEl.textContent.trim()) || getInstanceName(); + + var thumbMeta = document.querySelector('meta[property="og:image"]'); + var thumbnail = video.poster || (thumbMeta && thumbMeta.content) || '/client/assets/images/default-thumbnail.jpg'; + + var entry = { + slug: slug, + url: '/videos/watch/' + slug, + startTime: Math.floor(cur), + duration: Math.floor(dur), + pct: Math.min(99, Math.max(2, Math.round(ratio * 100))), + title: title, + channel: channel, + thumbnail: thumbnail, + updatedAt: now + }; + + var next = [entry].concat( + list.filter(function (x) { + return x.slug !== slug; + }) + ); + saveContinueWatchingList(next); + } + + function isHomeContinueShelfUrl() { + var p = (window.location.pathname || '').toLowerCase(); + if (p.indexOf('/search') === 0 || p.indexOf('/videos/watch') === 0 || p.indexOf('/w/') === 0) { + return false; + } + return ( + p === '/' || + p === '' || + p.indexOf('/videos/overview') === 0 || + p.indexOf('/videos/trending') === 0 || + p.indexOf('/videos/recently-added') === 0 || + p.indexOf('/videos/local') === 0 + ); + } + + function injectContinueWatchingShelf() { + if (!isHomeContinueShelfUrl()) { + var stray = document.getElementById('yaktube-continue-watching-shelf'); + if (stray) stray.remove(); + return; + } + + var items = loadContinueWatchingList(); + if (!items.length) { + var existingEmpty = document.getElementById('yaktube-continue-watching-shelf'); + if (existingEmpty) existingEmpty.remove(); + return; + } + + var chipsBar = document.getElementById('yaktube-category-chips-bar'); + var anchorTarget = + chipsBar || + document.querySelector('my-video-filters-header, my-videos-list, my-video-overview, .main-col, main'); + if (!anchorTarget) return; + + var sig = items + .slice(0, 6) + .map(function (it) { + return it.slug + ':' + it.startTime; + }) + .join('|'); + + var shelf = document.getElementById('yaktube-continue-watching-shelf'); + if (shelf) { + var curSig = shelf.getAttribute('data-render-sig'); + if (chipsBar && shelf.previousElementSibling !== chipsBar && chipsBar.parentElement) { + chipsBar.insertAdjacentElement('afterend', shelf); + } + if (curSig === sig) return; + } else { + shelf = document.createElement('section'); + shelf.id = 'yaktube-continue-watching-shelf'; + shelf.className = 'yaktube-continue-shelf'; + shelf.setAttribute('aria-label', 'Kaldığın Yerden Devam Et'); + if (chipsBar && chipsBar.parentElement) { + chipsBar.insertAdjacentElement('afterend', shelf); + } else if (anchorTarget.parentElement) { + anchorTarget.parentElement.insertBefore(shelf, anchorTarget); + } + } + + shelf.setAttribute('data-render-sig', sig); + var visibleItems = items.slice(0, 6); + var cardsHtml = visibleItems + .map(function (it) { + var resumeUrl = it.url + '?start=' + it.startTime + 's'; + var remaining = Math.max(0, (it.duration || 0) - (it.startTime || 0)); + return ( + '
      ' + + '' + + '' + + '⏯️ ' + + escapeHtml(formatClockShort(it.startTime)) + + ' / ' + + escapeHtml(formatClockShort(it.duration)) + + '' + + '
      ' + + '
      ' + + '
      ' + + '' + + escapeHtml(it.title) + + '' + + '
      ' + + escapeHtml(it.channel || getInstanceName()) + + '
      ' + + '
      ' + + '▶️ Devam Et' + + '' + + '' + + '
      ' + + '
      ' + + '
      ' + ); + }) + .join(''); + + shelf.innerHTML = + '
      ' + + '

      ⏯️ Kaldığın Yerden Devam Et

      ' + + '' + + '
      ' + + '
      ' + + cardsHtml + + '
      '; + + var clearAllBtn = shelf.querySelector('#yaktube-cw-clear-all'); + if (clearAllBtn) { + clearAllBtn.addEventListener('click', function () { + saveContinueWatchingList([]); + shelf.remove(); + announce('Kaldığın yerden devam et rafı temizlendi.'); + }); + } + + shelf.querySelectorAll('.yaktube-cw-remove-btn').forEach(function (btn) { + btn.addEventListener('click', function () { + var targetSlug = btn.getAttribute('data-slug'); + var next = loadContinueWatchingList().filter(function (x) { + return x.slug !== targetSlug; + }); + saveContinueWatchingList(next); + injectContinueWatchingShelf(); + announce('Kayıt kaldırıldı.'); + }); + }); + + shelf.querySelectorAll('.yaktube-cw-queue-btn').forEach(function (btn) { + btn.addEventListener('click', function () { + var targetSlug = btn.getAttribute('data-slug'); + var found = loadContinueWatchingList().find(function (x) { + return x.slug === targetSlug; + }); + if (found) { + addToPlayQueue({ + uuid: found.slug, + localUrl: found.url + '?start=' + found.startTime + 's', + url: found.url, + title: found.title, + channel: found.channel, + durationFormatted: formatClockShort(found.duration), + thumbnail: found.thumbnail + }); + } + }); + }); + } + + function openServerCockpitModal() { + var existing = document.getElementById('yaktube-server-cockpit-modal'); + if (existing) { + existing.remove(); + restoreFocusAfterModal(); + announce('Yönetici sistem kokpiti kapatıldı.'); + return; + } + + var token = null; + try { + token = localStorage.getItem('access_token'); + } catch (e) {} + + recordFocusBeforeModal(); + var modal = document.createElement('div'); + modal.id = 'yaktube-server-cockpit-modal'; + modal.className = 'yaktube-feature-modal-backdrop'; + modal.setAttribute('role', 'dialog'); + modal.setAttribute('aria-modal', 'true'); + modal.setAttribute('aria-labelledby', 'yaktube-cockpit-title'); + + modal.innerHTML = + '
      ' + + '
      ' + + '

      🚀 YakTube Yönetici Sistem Kokpiti

      ' + + '' + + '
      ' + + '
      ⏳ Sunucu verileri alınıyor...
      ' + + '
      '; + + document.body.appendChild(modal); + + function closeCockpit() { + modal.remove(); + restoreFocusAfterModal(); + announce('Sistem kokpiti kapatıldı.'); + } + + modal.querySelector('#yaktube-cockpit-close').addEventListener('click', closeCockpit); + modal.addEventListener('click', function (e) { + if (e.target === modal) closeCockpit(); + }); + + function formatUptimeTR(sec) { + var s = Math.max(0, Math.floor(Number(sec || 0))); + var d = Math.floor(s / 86400); + var h = Math.floor((s % 86400) / 3600); + var m = Math.floor((s % 3600) / 60); + return (d > 0 ? d + 'g ' : '') + h + 's ' + m + 'dk'; + } + + function loadCockpitData() { + var bodyEl = modal.querySelector('#yaktube-cockpit-body'); + if (!bodyEl) return; + var hdrs = token ? { Authorization: 'Bearer ' + token } : {}; + fetch('/plugins/yaktube-server/router/server-cockpit', { headers: hdrs }) + .then(function (r) { + return r.json(); + }) + .then(function (data) { + if (!document.body.contains(modal)) return; + if (!data || !data.ok) { + bodyEl.innerHTML = + '
      ⚠️ ' + + escapeHtml((data && data.error) || 'Kokpit verisi alınamadı (Yönetici oturumu gerekli).') + + '
      '; + return; + } + var stDisk = data.disks && data.disks.storage; + var cache = data.cache || {}; + var vids = data.videos || {}; + var imps = data.imports || {}; + var proc = data.process || {}; + + var issuesHtml = ''; + if (Array.isArray(data.recentIssues) && data.recentIssues.length) { + issuesHtml = + '
      📋 Aktif / Son İşlemler & Durumlar
      ' + + ''; + } + + bodyEl.innerHTML = + '
      ' + + '
      ' + + '
      💾 Medya Diski
      ' + + '
      ' + + (stDisk ? stDisk.freeGB + ' GB Boş' : 'Bilinmiyor') + + '
      ' + + '
      ' + + (stDisk ? stDisk.totalGB + ' GB Toplam (%' + stDisk.usedPct + ' dolu)' : '') + + '
      ' + + '
      ' + + '
      ' + + '
      🎬 Yerel Kütüphane
      ' + + '
      ' + + (vids.publishedLocal || 0) + + ' Video
      ' + + '
      ' + + (vids.totalHoursLocal || 0) + + ' saat • +' + + (vids.remoteVideos || 0) + + ' Fediverse
      ' + + '
      ' + + '
      ' + + '
      ⚙️ İşlem Kuyruğu
      ' + + '
      ' + + ((vids.transcoding || 0) + (vids.importing || 0)) + + ' Aktif
      ' + + '
      ' + + (imps.processing || 0) + + ' indirme • ' + + (vids.transcoding || 0) + + ' transcode
      ' + + '
      ' + + '
      ' + + '
      🧹 Fediverse & Transkript Önbelleği
      ' + + '
      ' + + (cache.totalSizeMB || 0) + + ' MB
      ' + + '
      ' + + (cache.totalFiles || 0) + + ' dosya • ' + + (cache.transcriptCacheCount || 0) + + ' transkript
      ' + + '
      ' + + '
      ' + + '
      🖥️ Sunucu Süreci
      ' + + '
      ' + + (proc.rssMB || 0) + + ' MB RAM
      ' + + '
      Çalışma: ' + + formatUptimeTR(proc.uptimeSeconds) + + ' • ' + + escapeHtml(proc.nodeVersion || '') + + '
      ' + + '
      ' + + '
      ' + + issuesHtml + + '
      ' + + '' + + '' + + '' + + '
      '; + + bodyEl.querySelector('#yaktube-cockpit-refresh').addEventListener('click', function () { + loadCockpitData(); + announce('Sistem kokpiti yenilendi.'); + }); + bodyEl.querySelector('#yaktube-cockpit-clean-cache').addEventListener('click', function (ev) { + var b = ev.currentTarget; + b.disabled = true; + fetch('/plugins/yaktube-server/router/clean-cache', { + method: 'POST', + headers: Object.assign({ 'Content-Type': 'application/json' }, hdrs), + body: JSON.stringify({ forceAll: true }) + }) + .then(function (r) { + return r.json(); + }) + .then(function (res) { + showQuickToast( + '🧹 ' + (res.deletedCount || 0) + ' önbellek dosyası temizlendi (' + (res.freedMB || 0) + ' MB)' + ); + announce((res.deletedCount || 0) + ' önbellek dosyası temizlendi.'); + loadCockpitData(); + }) + .catch(function () { + b.disabled = false; + }); + }); + bodyEl.querySelector('#yaktube-cockpit-clean-failed').addEventListener('click', function (ev) { + var b = ev.currentTarget; + b.disabled = true; + fetch('/plugins/yaktube-server/router/cleanup-failed-imports', { + method: 'POST', + headers: Object.assign({ 'Content-Type': 'application/json' }, hdrs), + body: '{}' + }) + .then(function (r) { + return r.json(); + }) + .then(function (res) { + showQuickToast('🗑️ ' + (res.message || 'Temizlendi')); + announce(res.message || 'Kalıntılar temizlendi.'); + loadCockpitData(); + }) + .catch(function () { + b.disabled = false; + }); + }); + }) + .catch(function () { + if (bodyEl) bodyEl.innerHTML = '
      ⚠️ Sunucuya ulaşılamadı.
      '; + }); + } + + loadCockpitData(); + trapFocusInModal(modal); + announce('YakTube yönetici sistem kokpiti açıldı.'); + } + + function openCommandPalette() { + var existing = document.getElementById('yaktube-command-palette'); + if (existing) { + existing.remove(); + restoreFocusAfterModal(); + announce('Hızlı komut paleti kapatıldı.'); + return; + } + + recordFocusBeforeModal(); + var onWatch = isWatchUrl(); + var commands = []; + + if (onWatch) { + commands.push( + { + id: 'studio', + label: '🎛️ Canlı Ses Stüdyosu (EQ & %300 Güç)', + hint: 'Alt+E', + run: openAudioStudioModal + }, + { + id: 'ab', + label: '🔂 A-B Tekrar Döngüsü İşaretle / Kapat', + hint: 'Alt+B', + run: cycleAbLoop + }, + { + id: 'transcript', + label: '📜 Akıllı Transkript & Bölümler Paneli', + hint: 'Alt+C', + run: openTranscriptPanel + }, + { + id: 'audio-only', + label: '📻 Yalnızca Ses & Ekran Karartma Modu', + hint: 'Alt+O', + run: toggleAudioOnlyMode + }, + { + id: 'next', + label: '⏭️ Sıradaki Videoyu Oynat', + hint: 'Shift+N', + run: function () { + playFirstSmartRecommendation('cmd-palette'); + } + }, + { + id: 'share', + label: '🔗 Zaman Damgalı Temiz Paylaşım', + hint: 'Alt+S', + run: openCleanShareModal + }, + { + id: 'qr', + label: '📱 Telefonda Devam Et (QR Kod)', + hint: 'Alt+Q', + run: openPhoneTransferModal + }, + { + id: 'sleep', + label: '⏱️ Uyku Zamanlayıcısı', + hint: 'Alt+U', + run: openSleepTimerModal + }, + { + id: 'info', + label: '📊 Video Bilgisi ve İstatistikler', + hint: 'Alt+I', + run: showQuickVideoInfo + } + ); + } + + commands.push( + { + id: 'queue', + label: '📋 Kişisel Çalma Sırası (' + loadPlayQueue().length + ' video)', + hint: 'Alt+R', + run: openPlayQueueDrawer + }, + { + id: 'search', + label: '🔍 Canlı YouTube & YakTube Araması', + hint: 'Ctrl+K veya /', + run: function () { + openFullSearchModal('', false); + } + }, + { + id: 'voice', + label: '🎙️ Sesli Arama Başlat', + hint: 'Shift+V', + run: function () { + openFullSearchModal('', true); + } + }, + { + id: 'home', + label: '🏠 Ana Sayfa (Keşfet)', + hint: 'Sayfa', + run: function () { + window.location.href = '/videos/overview'; + } + }, + { + id: 'trending', + label: '🔥 Popüler Videolar', + hint: 'Sayfa', + run: function () { + window.location.href = '/videos/trending'; + } + }, + { + id: 'recent', + label: '🆕 Son Eklenen Videolar', + hint: 'Sayfa', + run: function () { + window.location.href = '/videos/recently-added'; + } + }, + { + id: 'subs', + label: '📺 Aboneliklerim / Kitaplığım', + hint: 'Sayfa', + run: function () { + window.location.href = '/my-library/subscriptions'; + } + }, + { + id: 'shortcuts', + label: '⌨️ Klavye Kısayolları Kılavuzu', + hint: 'Alt+H / F1', + run: toggleShortcutsModal + } + ); + + if (cachedUserRoleId === 0) { + commands.push({ + id: 'cockpit', + label: '🚀 Yönetici Sistem Kokpiti & Bakım', + hint: 'Yönetici', + run: openServerCockpitModal + }); + } + + var modal = document.createElement('div'); + modal.id = 'yaktube-command-palette'; + modal.className = 'yaktube-feature-modal-backdrop'; + modal.setAttribute('role', 'dialog'); + modal.setAttribute('aria-modal', 'true'); + modal.setAttribute('aria-labelledby', 'yaktube-cmd-heading'); + + modal.innerHTML = + '
      ' + + '
      ' + + '

      ⌘ YakTube Hızlı Komut Paleti

      ' + + '' + + '
      ' + + '' + + '' + + '
      '; + + document.body.appendChild(modal); + + var inp = modal.querySelector('#yaktube-cmd-input'); + var listEl = modal.querySelector('#yaktube-cmd-list'); + var filtered = commands.slice(); + var selectedIdx = 0; + + function closePalette() { + modal.remove(); + restoreFocusAfterModal(); + } + + function executeCommand(cmd) { + if (!cmd) return; + modal.remove(); + setTimeout(function () { + cmd.run(); + }, 20); + } + + function renderCommands() { + if (!filtered.length) { + listEl.innerHTML = '
    • Eşleşen komut bulunamadı.
    • '; + return; + } + listEl.innerHTML = filtered + .map(function (c, i) { + return ( + '
    • ' + + '' + + escapeHtml(c.label) + + '' + + '' + + escapeHtml(c.hint) + + '' + + '
    • ' + ); + }) + .join(''); + inp.setAttribute('aria-activedescendant', 'yaktube-cmd-opt-' + selectedIdx); + listEl.querySelectorAll('.yaktube-cmd-item').forEach(function (el) { + el.addEventListener('click', function () { + var idx = parseInt(el.getAttribute('data-idx'), 10); + executeCommand(filtered[idx]); + }); + }); + } + + modal.querySelector('#yaktube-cmd-close').addEventListener('click', closePalette); + modal.addEventListener('click', function (e) { + if (e.target === modal) closePalette(); + }); + + inp.addEventListener('input', function () { + var q = (inp.value || '').toLocaleLowerCase('tr').trim(); + filtered = q + ? commands.filter(function (c) { + return c.label.toLocaleLowerCase('tr').indexOf(q) !== -1; + }) + : commands.slice(); + selectedIdx = 0; + renderCommands(); + }); + + inp.addEventListener('keydown', function (e) { + if (e.key === 'ArrowDown') { + e.preventDefault(); + if (filtered.length) { + selectedIdx = (selectedIdx + 1) % filtered.length; + renderCommands(); + var sel = document.getElementById('yaktube-cmd-opt-' + selectedIdx); + if (sel) sel.scrollIntoView({ block: 'nearest' }); + } + } else if (e.key === 'ArrowUp') { + e.preventDefault(); + if (filtered.length) { + selectedIdx = (selectedIdx - 1 + filtered.length) % filtered.length; + renderCommands(); + var selUp = document.getElementById('yaktube-cmd-opt-' + selectedIdx); + if (selUp) selUp.scrollIntoView({ block: 'nearest' }); + } + } else if (e.key === 'Enter') { + e.preventDefault(); + executeCommand(filtered[selectedIdx]); + } + }); + + renderCommands(); + setTimeout(function () { + inp.focus(); + }, 30); + announce('Hızlı komut paleti açıldı. ' + commands.length + ' komut hazır.'); + } + + // PeerTube Portal / Bottom-of-Body Popover / Dropdown Automatic Focus Rescue Engine + var portalRescueInitialized = false; + function initPortalFocusRescue() { + if (portalRescueInitialized || typeof MutationObserver !== 'function') return; + portalRescueInitialized = true; + + var lastTriggerEl = null; + var lastTriggerTime = 0; + var activePortalEntry = null; + var rescuedSet = typeof WeakSet === 'function' ? new WeakSet() : null; + var pendingTimer = null; + + var PORTAL_SELECTOR = + 'ngb-popover-window, ngb-modal-window, .cdk-overlay-pane, .dropdown-menu.show, .popover.show, [role="menu"], [role="dialog"], [role="listbox"]'; + + function isYakTubeElement(el) { + if (!el || !el.nodeType || el.nodeType !== 1) return false; + if (el.id && el.id.indexOf('yaktube-') === 0) return true; + return Boolean(el.closest && el.closest('[id^="yaktube-"]')); + } + + function isIgnoredPassiveOverlay(el) { + if (!el || !el.matches) return true; + return el.matches('ngb-tooltip-window, .toast, .toast-container, [role="alert"], [role="status"], .alert'); + } + + function isElementVisibleForFocus(el) { + if (!el || !document.body.contains(el)) return false; + if (el.disabled || el.getAttribute('aria-hidden') === 'true') return false; + var st = window.getComputedStyle(el); + if (st.display === 'none' || st.visibility === 'hidden') return false; + var rect = el.getBoundingClientRect(); + return rect.width > 0 && rect.height > 0; + } + + function findFirstPortalFocusTarget(portal) { + var candidates = portal.querySelectorAll( + '[autofocus], input:not([type="hidden"]):not([disabled]), select:not([disabled]), textarea:not([disabled]), [role="menuitem"]:not([disabled]), [role="option"]:not([disabled]), button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])' + ); + for (var i = 0; i < candidates.length; i++) { + if (isElementVisibleForFocus(candidates[i])) return candidates[i]; + } + return null; + } + + function rescuePortalFocus(portal) { + if (!portal || isYakTubeElement(portal) || isIgnoredPassiveOverlay(portal)) return; + if (rescuedSet && rescuedSet.has(portal)) return; + if (!isElementVisibleForFocus(portal)) return; + if (portal.contains(document.activeElement)) return; + if (Date.now() - lastTriggerTime > 1500) return; + + var target = findFirstPortalFocusTarget(portal); + if (!target) { + if (!portal.hasAttribute('tabindex')) { + portal.setAttribute('tabindex', '-1'); + } + target = portal; + } + + if (rescuedSet) rescuedSet.add(portal); + activePortalEntry = { + portal: portal, + trigger: lastTriggerEl && document.body.contains(lastTriggerEl) ? lastTriggerEl : null + }; + + try { + target.focus({ preventScroll: false }); + } catch (e) { + try { + target.focus(); + } catch (e2) {} + } + + var headingEl = portal.querySelector('h1, h2, h3, h4, .popover-header, .modal-title'); + var labelTxt = + (headingEl && headingEl.textContent.trim()) || portal.getAttribute('aria-label') || 'Açılır menü'; + announce(labelTxt + ' açıldı.'); + } + + function captureTrigger(e) { + var t = e.target; + if (!t || !t.closest || isYakTubeElement(t)) return; + var interactive = t.closest( + 'button, [role="button"], a, [aria-haspopup], [ngbDropdownToggle], [aria-expanded], summary, .action-button, .more-button' + ); + if (interactive) { + lastTriggerEl = interactive; + lastTriggerTime = Date.now(); + } + } + + document.addEventListener('pointerdown', captureTrigger, true); + document.addEventListener( + 'keydown', + function (e) { + if (e.key === 'Enter' || e.key === ' ') { + captureTrigger(e); + } + }, + true + ); + + var portalObserver = new MutationObserver(function (mutations) { + if (activePortalEntry) { + var pStillOpen = + document.body.contains(activePortalEntry.portal) && isElementVisibleForFocus(activePortalEntry.portal); + if (!pStillOpen) { + if (rescuedSet) rescuedSet.delete(activePortalEntry.portal); + var trig = activePortalEntry.trigger; + activePortalEntry = null; + if ( + trig && + document.body.contains(trig) && + (!document.activeElement || document.activeElement === document.body) + ) { + try { + trig.focus(); + } catch (e) {} + } + } + } + + if (Date.now() - lastTriggerTime > 1500) return; + + var candidatePortal = null; + for (var i = 0; i < mutations.length; i++) { + var m = mutations[i]; + if (m.type === 'childList' && m.addedNodes && m.addedNodes.length) { + for (var j = 0; j < m.addedNodes.length; j++) { + var n = m.addedNodes[j]; + if (!n || n.nodeType !== 1 || isYakTubeElement(n)) continue; + if (n.matches && n.matches(PORTAL_SELECTOR)) { + candidatePortal = n; + } else if (n.querySelector) { + var inner = n.querySelector(PORTAL_SELECTOR); + if (inner && !isYakTubeElement(inner)) candidatePortal = inner; + } + } + } else if (m.type === 'attributes' && m.target && m.target.nodeType === 1 && !isYakTubeElement(m.target)) { + if (m.target.matches && m.target.matches(PORTAL_SELECTOR)) { + candidatePortal = m.target; + } else if (m.attributeName === 'aria-expanded' && m.target.getAttribute('aria-expanded') === 'true') { + var ctrlId = m.target.getAttribute('aria-controls'); + if (ctrlId) { + var ctrlEl = document.getElementById(ctrlId); + if (ctrlEl && !isYakTubeElement(ctrlEl)) candidatePortal = ctrlEl; + } + if (!candidatePortal && m.target.parentElement) { + var sibMenu = m.target.parentElement.querySelector('.dropdown-menu.show, [role="menu"]'); + if (sibMenu && !isYakTubeElement(sibMenu)) candidatePortal = sibMenu; + } + } + } + } + + if (candidatePortal) { + if (pendingTimer) clearTimeout(pendingTimer); + pendingTimer = setTimeout(function () { + pendingTimer = null; + rescuePortalFocus(candidatePortal); + }, 45); + } + }); + + if (document.body) { + portalObserver.observe(document.body, { + childList: true, + attributes: true, + attributeFilter: ['class', 'aria-expanded', 'hidden'], + subtree: true + }); + } + } + + // 10b. Unified Debounced MutationObserver & Reactive SPA Engine (v1.5.0) var unifiedTimer = null; function runUnifiedCycle(isNav) { try { if (checkPendingPostLoginRedirect()) return; } catch (e) {} + try { + checkCurrentUserRoleOnce(); + } catch (e) {} + + try { + initPortalFocusRescue(); + } catch (e) {} + try { autoFixDOM(); } catch (e) {} @@ -7699,6 +10085,10 @@ try { injectCategoryChipsBar(); } catch (e) {} + try { + injectContinueWatchingShelf(); + } catch (e) {} + try { injectSkipToCategoriesLink(); } catch (e) {} @@ -7719,6 +10109,10 @@ try { checkAndInjectWatchPageComments(); } catch (e) {} + try { + syncQueueCountersUI(); + } catch (e) {} + try { injectPWAInstallButton(); } catch (e) {} @@ -7751,6 +10145,9 @@ try { // SPA Navigation Handler function onLocationChange() { currentActiveVideoKey = null; + try { + clearAbLoop(false); + } catch (e) {} scheduleUnifiedCycle(true); setTimeout(function () { scheduleUnifiedCycle(false, 0); diff --git a/main.js b/main.js index 0d486ad..1632c23 100644 --- a/main.js +++ b/main.js @@ -2999,6 +2999,286 @@ async function register({ registerHook, getRouter, registerSetting, settingsMana const videoOriginCache = new Map(); const VIDEO_ORIGIN_CACHE_TTL_MS = 10 * 60 * 1000; + const transcriptMemoryCache = new Map(); + const inFlightTranscriptRequests = new Map(); + const TRANSCRIPT_OK_TTL_MS = 12 * 60 * 60 * 1000; + const TRANSCRIPT_EMPTY_TTL_MS = 10 * 60 * 1000; + + function resolveTranscriptStorageRoot() { + try { + if ( + peertubeHelpers && + peertubeHelpers.plugin && + typeof peertubeHelpers.plugin.getDataDirectoryPath === 'function' + ) { + const dataDir = peertubeHelpers.plugin.getDataDirectoryPath(); + const candidate = path.resolve(dataDir, '..', '..', '..'); + if (fs.existsSync(candidate)) return candidate; + } + } catch (e) {} + if (fs.existsSync('D:\\yaktube_storage')) return 'D:\\yaktube_storage'; + return process.cwd(); + } + + function extractYouTubeIdFromText(str) { + if (!str || typeof str !== 'string') return null; + const match = + str.match(/[?&]v=([a-zA-Z0-9_-]{11})/) || + str.match(/youtu\.be\/([a-zA-Z0-9_-]{11})/) || + str.match(/shorts\/([a-zA-Z0-9_-]{11})/) || + str.match(/embed\/([a-zA-Z0-9_-]{11})/); + return match ? match[1] : null; + } + + function extractYouTubeIdFromRow(row) { + if (!row) return null; + return extractYouTubeIdFromText(row.targetUrl) || extractYouTubeIdFromText(row.description); + } + + function fetchRemoteTextWithLimit(targetUrl, timeoutMs = 9000, maxRedirects = 4, maxBytes = 4 * 1024 * 1024) { + return new Promise((resolve, reject) => { + if (maxRedirects <= 0) return reject(new Error('Too many redirects')); + let parsed; + try { + parsed = new URL(targetUrl); + } catch (e) { + return reject(e); + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + return reject(new Error('Unsupported protocol')); + } + const lib = parsed.protocol === 'https:' ? https : http; + const req = lib.get( + targetUrl, + { + timeout: timeoutMs, + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0.0.0 Safari/537.36', + Accept: 'application/json, text/vtt, text/plain, */*' + } + }, + res => { + if ([301, 302, 307, 308].includes(res.statusCode) && res.headers.location) { + res.resume(); + const nextUrl = new URL(res.headers.location, targetUrl).toString(); + return resolve(fetchRemoteTextWithLimit(nextUrl, timeoutMs, maxRedirects - 1, maxBytes)); + } + if (res.statusCode !== 200) { + res.resume(); + return reject(new Error('HTTP ' + res.statusCode)); + } + const chunks = []; + let received = 0; + res.on('data', chunk => { + received += chunk.length; + if (received > maxBytes) { + req.destroy(new Error('Response too large')); + return; + } + chunks.push(chunk); + }); + res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); + res.on('error', reject); + } + ); + req.on('timeout', () => req.destroy(new Error('Timeout'))); + req.on('error', reject); + }); + } + + function parseTimeTokenToSeconds(token) { + if (!token || typeof token !== 'string') return NaN; + const parts = token.trim().replace(',', '.').split(':'); + if (parts.length === 2) { + const m = parseInt(parts[0], 10); + const s = parseFloat(parts[1]); + if (isNaN(m) || isNaN(s)) return NaN; + return m * 60 + s; + } + if (parts.length === 3) { + const h = parseInt(parts[0], 10); + const m = parseInt(parts[1], 10); + const s = parseFloat(parts[2]); + if (isNaN(h) || isNaN(m) || isNaN(s)) return NaN; + return h * 3600 + m * 60 + s; + } + return NaN; + } + + function decodeSubtitleEntities(str) { + return String(str || '') + .replace(/<\d{2}:\d{2}(?::\d{2})?\.\d+>/g, '') + .replace(/<\/?[^>]+(>|$)/g, ' ') + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'|'/g, "'") + .replace(/ /g, ' ') + .replace(/\s+/g, ' ') + .trim(); + } + + function parseChaptersFromDescription(description, maxDurationSec) { + if (!description || typeof description !== 'string') return []; + const lines = description.split(/\r?\n/); + const seenStarts = new Set(); + const chapters = []; + for (const rawLine of lines) { + const line = rawLine.trim(); + if (!line || line.length > 220) continue; + const mPrefix = line.match(/^[\[\(\*•\-–—\s]*((?:\d{1,2}:)?\d{1,2}:\d{2})[\]\)\*:\-\s–—]+(.+)$/); + const mSuffix = !mPrefix ? line.match(/^(.+?)[\s\-\–—:\(\[]+((?:\d{1,2}:)?\d{1,2}:\d{2})[\)\]\s]*$/) : null; + const timeStr = mPrefix ? mPrefix[1] : mSuffix ? mSuffix[2] : null; + let title = mPrefix ? mPrefix[2] : mSuffix ? mSuffix[1] : ''; + if (!timeStr) continue; + const startSec = Math.floor(parseTimeTokenToSeconds(timeStr)); + if (isNaN(startSec) || startSec < 0) continue; + if (maxDurationSec > 0 && startSec > maxDurationSec + 5) continue; + title = title.replace(/^[\-\–—:\s•]+|[\-\–—:\s•]+$/g, '').trim(); + if (!title || title.length < 2) continue; + if (seenStarts.has(startSec)) continue; + seenStarts.add(startSec); + chapters.push({ title, start: startSec }); + } + chapters.sort((a, b) => a.start - b.start); + return chapters.length >= 2 ? chapters : []; + } + + function parseJson3Subtitles(rawText) { + const parsed = JSON.parse(rawText); + const events = Array.isArray(parsed && parsed.events) ? parsed.events : []; + const cues = []; + for (const ev of events) { + if (!ev || !Array.isArray(ev.segs)) continue; + const text = ev.segs + .map(s => (s && s.utf8 ? s.utf8 : '')) + .join('') + .replace(/\n+/g, ' '); + const clean = decodeSubtitleEntities(text); + if (!clean || clean === '[Müzik]' || clean === '[Music]') { + if (!clean) continue; + } + const start = Number(((ev.tStartMs || 0) / 1000).toFixed(2)); + const dur = ev.dDurationMs ? ev.dDurationMs / 1000 : 3; + const end = Number((start + Math.max(0.5, dur)).toFixed(2)); + if ( + cues.length > 0 && + cues[cues.length - 1].text === clean && + Math.abs(start - cues[cues.length - 1].start) < 2 + ) { + cues[cues.length - 1].end = Math.max(cues[cues.length - 1].end, end); + continue; + } + cues.push({ start, end, text: clean }); + } + return cues; + } + + function parseVttOrSrtSubtitles(rawText) { + const normalized = String(rawText || '') + .replace(/^\uFEFF/, '') + .replace(/\r\n/g, '\n') + .replace(/\r/g, '\n'); + const blocks = normalized.split(/\n{2,}/); + const cues = []; + for (const block of blocks) { + const lines = block + .split('\n') + .map(l => l.trim()) + .filter(Boolean); + if (!lines.length) continue; + if (/^(WEBVTT|Kind:|Language:|NOTE\b|STYLE\b)/i.test(lines[0])) continue; + const timeIdx = lines.findIndex(l => l.includes('-->')); + if (timeIdx === -1) continue; + const parts = lines[timeIdx].split('-->'); + if (parts.length < 2) continue; + const start = parseTimeTokenToSeconds(parts[0].trim().split(/\s+/)[0]); + const end = parseTimeTokenToSeconds(parts[1].trim().split(/\s+/)[0]); + if (isNaN(start)) continue; + const rawBody = lines.slice(timeIdx + 1).join(' '); + const clean = decodeSubtitleEntities(rawBody); + if (!clean) continue; + const safeStart = Number(start.toFixed(2)); + const safeEnd = Number((!isNaN(end) && end > start ? end : start + 3).toFixed(2)); + if (cues.length > 0 && cues[cues.length - 1].text === clean) { + cues[cues.length - 1].end = Math.max(cues[cues.length - 1].end, safeEnd); + continue; + } + cues.push({ start: safeStart, end: safeEnd, text: clean }); + } + return cues; + } + + function parseSubtitlePayload(rawText) { + if (!rawText || typeof rawText !== 'string') return []; + const trimmed = rawText.trim(); + if (!trimmed) return []; + if (trimmed.startsWith('{')) { + try { + return parseJson3Subtitles(trimmed); + } catch (e) {} + } + return parseVttOrSrtSubtitles(trimmed); + } + + function pickPreferredCaptionTrack(ytInfo, preferredLang, videoLang) { + const manual = ytInfo && ytInfo.subtitles && typeof ytInfo.subtitles === 'object' ? ytInfo.subtitles : {}; + const auto = + ytInfo && ytInfo.automatic_captions && typeof ytInfo.automatic_captions === 'object' + ? ytInfo.automatic_captions + : {}; + const availableLanguages = []; + const collectLangs = (mapObj, isAuto) => { + for (const code of Object.keys(mapObj)) { + if (!code || code === 'live_chat') continue; + const tracks = mapObj[code]; + if (!Array.isArray(tracks) || tracks.length === 0) continue; + availableLanguages.push({ + code, + name: tracks[0].name || code, + auto: isAuto + }); + } + }; + collectLangs(manual, false); + collectLangs(auto, true); + + const priorityLangs = []; + for (const candidate of [preferredLang, 'tr', videoLang, 'en', 'en-US', 'en-GB']) { + const c = candidate ? String(candidate).trim().toLowerCase() : ''; + if (c && !priorityLangs.includes(c)) priorityLangs.push(c); + } + + const pickFormat = tracks => { + for (const ext of ['json3', 'vtt', 'srt']) { + const hit = tracks.find(t => t && t.ext === ext && t.url); + if (hit) return hit; + } + return tracks.find(t => t && t.url) || null; + }; + + const pickFromMap = (mapObj, isAuto) => { + const keys = Object.keys(mapObj).filter( + k => k && k !== 'live_chat' && Array.isArray(mapObj[k]) && mapObj[k].length + ); + if (keys.length === 0) return null; + for (const p of priorityLangs) { + const exact = keys.find(k => k.toLowerCase() === p) || keys.find(k => k.toLowerCase().startsWith(p + '-')); + if (exact) { + const track = pickFormat(mapObj[exact]); + if (track) return { code: exact, isAuto, track }; + } + } + // Also match *-orig auto-captions (video's native language) or first available + const origKey = keys.find(k => k.endsWith('-orig')) || keys[0]; + const fallbackTrack = pickFormat(mapObj[origKey]); + return fallbackTrack ? { code: origKey, isAuto, track: fallbackTrack } : null; + }; + + const chosen = pickFromMap(manual, false) || pickFromMap(auto, true); + return { chosen, availableLanguages: availableLanguages.slice(0, 12) }; + } router.get('/video-origin/:uuid', async (req, res) => { if (isCrawlerBotRequest(req)) { @@ -3042,23 +3322,7 @@ async function register({ registerHook, getRouter, registerSetting, settingsMana } const row = rows[0]; - let youtubeId = null; - - if (row.targetUrl) { - const match = - row.targetUrl.match(/[?&]v=([^&]+)/) || - row.targetUrl.match(/youtu\.be\/([^?]+)/) || - row.targetUrl.match(/shorts\/([^?]+)/); - if (match) youtubeId = match[1]; - } - - if (!youtubeId && row.description) { - const match = - row.description.match(/youtube\.com\/watch\?v=([a-zA-Z0-9_-]{11})/) || - row.description.match(/youtu\.be\/([a-zA-Z0-9_-]{11})/) || - row.description.match(/shorts\/([a-zA-Z0-9_-]{11})/); - if (match) youtubeId = match[1]; - } + const youtubeId = extractYouTubeIdFromRow(row); const payload = { ok: true, @@ -3076,6 +3340,254 @@ async function register({ registerHook, getRouter, registerSetting, settingsMana } }); + // 6b. Akıllı Transkript & Bölüm (Chapters) Çekici + router.get('/video-transcript/:uuid', async (req, res) => { + if (isCrawlerBotRequest(req)) { + return res.json({ ok: false, botIgnored: true, cues: [], chapters: [] }); + } + const rawParam = (req.params.uuid || '').trim(); + if (!rawParam) return res.status(400).json({ ok: false, error: 'UUID required' }); + const resolvedUuid = shortToUuid(rawParam); + const reqLang = String(req.query.lang || '') + .trim() + .toLowerCase(); + const forceRefresh = req.query.refresh === '1' || req.query.refresh === 'true'; + const queryYtId = + req.query.youtubeId && /^[a-zA-Z0-9_-]{11}$/.test(String(req.query.youtubeId).trim()) + ? String(req.query.youtubeId).trim() + : null; + const cacheKey = `${resolvedUuid}__${reqLang || 'auto'}__${queryYtId || 'db'}`; + + if (!forceRefresh) { + const memHit = transcriptMemoryCache.get(cacheKey); + if (memHit) { + const ttl = memHit.hasContent ? TRANSCRIPT_OK_TTL_MS : TRANSCRIPT_EMPTY_TTL_MS; + if (Date.now() - memHit.time < ttl) { + return res.json(memHit.payload); + } + } + } + + const storageRoot = resolveTranscriptStorageRoot(); + const transcriptCacheDir = path.join(storageRoot, 'cache', 'transcripts'); + const diskCachePath = path.join( + transcriptCacheDir, + `${resolvedUuid.replace(/[^a-zA-Z0-9_-]/g, '_')}_${reqLang || 'auto'}.json` + ); + + if (!forceRefresh && fs.existsSync(diskCachePath)) { + try { + const st = await fs.promises.stat(diskCachePath); + if (Date.now() - st.mtimeMs < 7 * 24 * 60 * 60 * 1000) { + const diskPayload = JSON.parse(await fs.promises.readFile(diskCachePath, 'utf8')); + if (diskPayload && diskPayload.ok) { + transcriptMemoryCache.set(cacheKey, { + time: Date.now(), + hasContent: + (diskPayload.cues && diskPayload.cues.length > 0) || + (diskPayload.chapters && diskPayload.chapters.length > 0), + payload: diskPayload + }); + return res.json(diskPayload); + } + } + } catch (e) {} + } + + if (inFlightTranscriptRequests.has(cacheKey)) { + try { + const shared = await inFlightTranscriptRequests.get(cacheKey); + return res.json(shared); + } catch (err) { + return res.status(500).json({ ok: false, error: err.message }); + } + } + + const workPromise = (async () => { + let row = null; + if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(resolvedUuid)) { + const rows = await dbQuery( + `SELECT v.id, v.uuid, v.name, v.description, v.duration, v.language, vi."targetUrl" + FROM "video" v + LEFT JOIN "videoImport" vi ON vi."videoId" = v.id + WHERE v.uuid = $1::uuid + LIMIT 1`, + [resolvedUuid] + ); + if (rows[0]) row = rows[0]; + } else if (/^\d+$/.test(rawParam)) { + const rows = await dbQuery( + `SELECT v.id, v.uuid, v.name, v.description, v.duration, v.language, vi."targetUrl" + FROM "video" v + LEFT JOIN "videoImport" vi ON vi."videoId" = v.id + WHERE v.id = $1::int + LIMIT 1`, + [parseInt(rawParam, 10)] + ); + if (rows[0]) row = rows[0]; + } + + if (!row && !queryYtId) { + return { ok: false, error: 'Video not found', cues: [], chapters: [] }; + } + + let cues = []; + let chapters = row ? parseChaptersFromDescription(row.description, Number(row.duration || 0)) : []; + let language = row && row.language ? row.language : null; + let languageName = language || ''; + let isAutoGenerated = false; + let source = chapters.length > 0 ? 'description' : 'none'; + let availableLanguages = []; + const youtubeId = queryYtId || extractYouTubeIdFromRow(row); + + // 1. Try local/remote PeerTube videoCaption rows if not requesting a different language + if (row && row.id) { + try { + const capRows = await dbQuery( + `SELECT id, language, filename, "fileUrl", "automaticallyGenerated" + FROM "videoCaption" + WHERE "videoId" = $1 + ORDER BY CASE WHEN language = $2 THEN 0 WHEN language = 'tr' THEN 1 WHEN language = 'en' THEN 2 ELSE 3 END, "automaticallyGenerated" ASC, id ASC + LIMIT 6`, + [row.id, reqLang || 'tr'] + ); + for (const cap of capRows) { + availableLanguages.push({ + code: cap.language, + name: cap.language, + auto: Boolean(cap.automaticallyGenerated) + }); + } + const matchedCap = reqLang + ? capRows.find(c => String(c.language || '').toLowerCase() === reqLang) + : capRows[0]; + if (matchedCap) { + let capText = ''; + const localCapPath = matchedCap.filename + ? path.join(storageRoot, 'captions', path.basename(matchedCap.filename)) + : ''; + const cachedCapPath = matchedCap.filename + ? path.join(storageRoot, 'cache', 'video-captions', path.basename(matchedCap.filename)) + : ''; + if (localCapPath && fs.existsSync(localCapPath)) { + capText = await fs.promises.readFile(localCapPath, 'utf8'); + } else if (cachedCapPath && fs.existsSync(cachedCapPath)) { + capText = await fs.promises.readFile(cachedCapPath, 'utf8'); + } else if (matchedCap.fileUrl) { + capText = await fetchRemoteTextWithLimit(matchedCap.fileUrl, 7000); + } + const parsedLocalCues = parseSubtitlePayload(capText); + if (parsedLocalCues.length > 0) { + cues = parsedLocalCues; + language = matchedCap.language; + languageName = matchedCap.language; + isAutoGenerated = Boolean(matchedCap.automaticallyGenerated); + source = 'peertube-caption'; + } + } + } catch (capErr) {} + } + + // 2. Fallback to live YouTube subtitle & chapter extraction via yt-dlp when cues or chapters are still needed + if (youtubeId && (cues.length === 0 || chapters.length === 0 || reqLang)) { + try { + const ytdlpPath = resolveYtDlpPath(logger, customYtDlpPath, peertubeHelpers); + const ytUrl = `https://www.youtube.com/watch?v=${youtubeId}`; + const rawJsonStr = await new Promise((resolve, reject) => { + execFile( + ytdlpPath, + ['--dump-single-json', '--skip-download', '--no-warnings', '--socket-timeout', '8', ytUrl], + { maxBuffer: 14 * 1024 * 1024, timeout: 15000 }, + (err, stdout) => { + if (err || !stdout) return reject(err || new Error('Empty yt-dlp output')); + resolve(stdout); + } + ); + }); + const startIdx = rawJsonStr.indexOf('{'); + const endIdx = rawJsonStr.lastIndexOf('}'); + if (startIdx !== -1 && endIdx !== -1) { + const ytInfo = JSON.parse(rawJsonStr.substring(startIdx, endIdx + 1)); + if (Array.isArray(ytInfo.chapters) && ytInfo.chapters.length > 0) { + chapters = ytInfo.chapters + .filter(c => c && c.title && c.start_time !== undefined) + .map(c => ({ + title: String(c.title).trim(), + start: Math.max(0, Math.floor(Number(c.start_time || 0))), + end: c.end_time !== undefined ? Math.floor(Number(c.end_time)) : null + })); + } else if (chapters.length === 0 && ytInfo.description) { + chapters = parseChaptersFromDescription(ytInfo.description, Number(ytInfo.duration || 0)); + } + + if (cues.length === 0 || reqLang) { + const picked = pickPreferredCaptionTrack(ytInfo, reqLang, row && row.language); + if (picked.availableLanguages.length > 0) { + availableLanguages = picked.availableLanguages; + } + if (picked.chosen && picked.chosen.track && picked.chosen.track.url) { + const subText = await fetchRemoteTextWithLimit(picked.chosen.track.url, 9000); + const ytCues = parseSubtitlePayload(subText); + if (ytCues.length > 0) { + cues = ytCues; + language = picked.chosen.code; + languageName = (picked.chosen.track && picked.chosen.track.name) || picked.chosen.code; + isAutoGenerated = picked.chosen.isAuto; + source = picked.chosen.isAuto ? 'youtube-auto' : 'youtube-manual'; + } + } + } + } + } catch (ytErr) { + if (logger) { + logger.warn(`[YakTube Transcript] Extract warning for ${resolvedUuid}: ${ytErr.message}`); + } + } + } + + const payload = { + ok: true, + uuid: (row && row.uuid) || resolvedUuid, + title: (row && row.name) || '', + youtubeId: youtubeId || null, + language, + languageName, + isAutoGenerated, + source, + cues, + chapters, + availableLanguages + }; + + const hasContent = cues.length > 0 || chapters.length > 0; + if (transcriptMemoryCache.size > 400) transcriptMemoryCache.clear(); + transcriptMemoryCache.set(cacheKey, { + time: Date.now(), + hasContent, + payload + }); + + if (hasContent) { + try { + await fs.promises.mkdir(transcriptCacheDir, { recursive: true }); + await fs.promises.writeFile(diskCachePath, JSON.stringify(payload), 'utf8'); + } catch (diskErr) {} + } + + return payload; + })().finally(() => { + inFlightTranscriptRequests.delete(cacheKey); + }); + + inFlightTranscriptRequests.set(cacheKey, workPromise); + try { + const result = await workPromise; + return res.json(result); + } catch (err) { + return res.status(500).json({ ok: false, error: err.message, cues: [], chapters: [] }); + } + }); + // 7. YouTube Original Comments Route router.get('/youtube-comments', async (req, res) => { const videoId = (req.query.id || req.query.v || '').trim(); diff --git a/package.json b/package.json index adb0f3b..42e4901 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "peertube-plugin-yaktube-ondemand", - "version": "1.7.18", + "version": "1.8.0", "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", diff --git a/style.css b/style.css index 999edf5..9267573 100644 --- a/style.css +++ b/style.css @@ -1946,3 +1946,739 @@ label[for='auto-play-video'], visibility: hidden !important; pointer-events: none !important; } + +/* ============================================================================ + 5. Live Audio Studio, Spectrum & A-B Loop (v1.8.0) + ============================================================================ */ +.yaktube-studio-modal { + max-width: 520px !important; + width: 94vw !important; + background: #141824 !important; + color: #f8fafc !important; + border: 1px solid rgba(255, 143, 55, 0.35) !important; + border-radius: 16px !important; + padding: 20px !important; + box-shadow: 0 20px 50px rgba(0, 0, 0, 0.75) !important; +} + +.yaktube-studio-spectrum { + display: block; + width: 100%; + max-width: 100%; + height: 64px; + border-radius: 10px; + background: rgba(15, 23, 42, 0.85); + border: 1px solid rgba(255, 255, 255, 0.08); + margin: 10px 0 14px 0; +} + +.yaktube-studio-warn { + background: rgba(59, 130, 246, 0.16); + border: 1px solid rgba(96, 165, 250, 0.45); + color: #bfdbfe; + border-radius: 10px; + padding: 10px 12px; + font-size: 13px; + margin-bottom: 10px; +} + +.yaktube-studio-presets { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-bottom: 14px; +} + +.yaktube-studio-preset-btn { + background: #1e293b; + color: #e2e8f0; + border: 1px solid rgba(255, 255, 255, 0.14); + border-radius: 999px; + padding: 6px 12px; + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: all 0.15s ease; +} + +.yaktube-studio-preset-btn:hover, +.yaktube-studio-preset-btn:focus-visible { + border-color: #ff8f37; + outline: 2px solid #ff8f37; + outline-offset: 2px; +} + +.yaktube-studio-preset-btn.active { + background: linear-gradient(135deg, #ff8f37 0%, #ea580c 100%); + color: #0b0f19; + font-weight: 800; + border-color: #ff8f37; +} + +.yaktube-studio-sliders { + display: flex; + flex-direction: column; + gap: 10px; + margin-bottom: 14px; +} + +.yaktube-studio-row { + display: flex; + flex-direction: column; + gap: 4px; + font-size: 13px; + color: #cbd5e1; +} + +.yaktube-studio-row span { + display: flex; + justify-content: space-between; + align-items: center; +} + +.yaktube-studio-row input[type='range'] { + width: 100%; + accent-color: #ff8f37; + cursor: pointer; +} + +.yaktube-studio-footer { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + flex-wrap: wrap; + border-top: 1px solid rgba(255, 255, 255, 0.1); + padding-top: 12px; +} + +.yaktube-studio-check { + display: flex; + align-items: center; + gap: 8px; + font-size: 13px; + color: #e2e8f0; + cursor: pointer; +} + +.yaktube-ab-loop-pill { + position: fixed; + bottom: 20px; + left: 20px; + z-index: 99990; + display: flex; + align-items: center; + gap: 10px; + background: rgba(15, 23, 42, 0.96); + color: #f8fafc; + border: 1.5px solid #ff8f37; + border-radius: 999px; + padding: 8px 14px; + font-size: 13px; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.6); +} + +.yaktube-ab-clear-btn { + background: rgba(255, 143, 55, 0.18); + color: #ff8f37; + border: 1px solid rgba(255, 143, 55, 0.5); + border-radius: 999px; + padding: 3px 10px; + font-size: 12px; + font-weight: 700; + cursor: pointer; +} + +/* ============================================================================ + 6. Smart Transcript Chapters, Playback Queue & Background Import (v1.8.0) + ============================================================================ */ +.yaktube-transcript-langs, +.yaktube-transcript-chapters { + padding: 10px 14px; + border-bottom: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(15, 23, 42, 0.5); +} + +.yaktube-transcript-langs { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.yaktube-transcript-lang-btn { + background: #1e293b; + color: #cbd5e1; + border: 1px solid rgba(255, 255, 255, 0.14); + border-radius: 999px; + padding: 4px 10px; + font-size: 12px; + cursor: pointer; +} + +.yaktube-transcript-lang-btn.active { + background: #ff8f37; + color: #0b0f19; + font-weight: 700; + border-color: #ff8f37; +} + +.yaktube-chapters-title { + font-size: 12px; + font-weight: 700; + color: #ff8f37; + margin-bottom: 8px; +} + +.yaktube-chapters-row { + display: flex; + flex-wrap: wrap; + gap: 8px; + max-height: 120px; + overflow-y: auto; +} + +.yaktube-chapter-chip { + background: rgba(30, 41, 59, 0.9); + color: #f1f5f9; + border: 1px solid rgba(255, 143, 55, 0.3); + border-radius: 8px; + padding: 5px 10px; + font-size: 12px; + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 6px; +} + +.yaktube-chapter-chip:hover, +.yaktube-chapter-chip:focus-visible { + background: rgba(255, 143, 55, 0.22); + border-color: #ff8f37; + outline: 2px solid #ff8f37; +} + +.yaktube-chapter-time { + font-family: monospace; + color: #ff8f37; + font-weight: 700; +} + +.yaktube-transcript-loading { + padding: 10px 14px; + font-size: 13px; + color: #93c5fd; + background: rgba(59, 130, 246, 0.1); +} + +.yaktube-card-actions { + display: flex; + align-items: stretch; + gap: 6px; + margin-top: 8px; + flex-wrap: wrap; +} + +.yaktube-card-actions > .yaktube-import-btn, +.yaktube-card-actions > .yaktube-play-btn { + flex: 1 1 auto; + margin-top: 0 !important; +} + +.yaktube-queue-add-btn { + background: rgba(30, 41, 59, 0.95); + color: #fde68a; + border: 1px solid rgba(255, 143, 55, 0.45); + border-radius: 8px; + padding: 6px 10px; + font-size: 12px; + font-weight: 700; + cursor: pointer; + transition: all 0.15s ease; +} + +.yaktube-queue-add-btn:hover, +.yaktube-queue-add-btn:focus-visible { + background: #ff8f37; + color: #0b0f19; + outline: 2px solid #ff8f37; + outline-offset: 2px; +} + +.yaktube-floating-queue-btn { + position: fixed; + bottom: 20px; + right: 20px; + z-index: 99985; + background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); + color: #ff8f37; + border: 1.5px solid #ff8f37; + border-radius: 999px; + padding: 10px 16px; + font-size: 13px; + font-weight: 800; + cursor: pointer; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.55); +} + +.yaktube-floating-queue-btn:focus-visible { + outline: 3px solid #fff; + outline-offset: 2px; +} + +.yaktube-queue-modal { + max-width: 580px !important; + width: 95vw !important; + background: #141824 !important; + color: #f8fafc !important; + border: 1px solid rgba(255, 143, 55, 0.35) !important; + border-radius: 16px !important; + padding: 20px !important; +} + +.yaktube-queue-scroll { + max-height: 55vh; + overflow-y: auto; + margin: 10px 0 14px 0; +} + +.yaktube-queue-list { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 8px; +} + +.yaktube-queue-item { + display: flex; + align-items: center; + gap: 10px; + background: rgba(30, 41, 59, 0.72); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 10px; + padding: 8px 10px; +} + +.yaktube-queue-num { + width: 24px; + height: 24px; + border-radius: 50%; + background: rgba(255, 143, 55, 0.2); + color: #ff8f37; + display: inline-flex; + align-items: center; + justify-content: center; + font-weight: 800; + font-size: 12px; + flex-shrink: 0; +} + +.yaktube-queue-thumb { + width: 68px; + height: 40px; + object-fit: cover; + border-radius: 6px; + flex-shrink: 0; +} + +.yaktube-queue-meta { + flex: 1 1 auto; + min-width: 0; +} + +.yaktube-queue-item-title { + font-size: 13px; + font-weight: 700; + color: #f8fafc; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.yaktube-queue-item-sub { + font-size: 11px; + color: #94a3b8; + margin-top: 2px; +} + +.yaktube-queue-item-actions { + display: flex; + gap: 4px; + flex-shrink: 0; +} + +.yaktube-queue-act-btn { + background: #0f172a; + color: #f8fafc; + border: 1px solid rgba(255, 255, 255, 0.14); + border-radius: 6px; + padding: 4px 7px; + cursor: pointer; + font-size: 12px; +} + +.yaktube-queue-act-btn:hover, +.yaktube-queue-act-btn:focus-visible { + border-color: #ff8f37; + outline: 2px solid #ff8f37; +} + +.yaktube-bg-import-pill { + position: fixed; + bottom: 70px; + right: 20px; + z-index: 99992; + max-width: 360px; + background: rgba(15, 23, 42, 0.97); + color: #f8fafc; + border: 1.5px solid #38bdf8; + border-radius: 12px; + padding: 12px 14px; + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.7); + display: flex; + flex-direction: column; + gap: 8px; +} + +.yaktube-bg-import-pill.ready { + border-color: #10b981; +} + +.yaktube-bg-import-text { + font-size: 13px; + line-height: 1.4; +} + +.yaktube-bg-import-actions { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + +.yaktube-bg-import-go-btn { + background: #10b981; + color: #052e16; + text-decoration: none; + padding: 5px 12px; + border-radius: 8px; + font-weight: 800; + font-size: 12px; +} + +.yaktube-bg-import-sub-btn, +.yaktube-bg-import-close-btn { + background: #1e293b; + color: #e2e8f0; + border: 1px solid rgba(255, 255, 255, 0.16); + border-radius: 8px; + padding: 5px 10px; + font-size: 12px; + cursor: pointer; +} + +/* ============================================================================ + 7. Continue Watching Shelf, Command Palette & Admin Server Cockpit (v1.8.0) + ============================================================================ */ +.yaktube-cmd-palette-trigger-btn { + width: 34px; + height: 34px; + border-radius: 50%; + background: rgba(30, 41, 59, 0.9); + color: #ff8f37; + border: 1px solid rgba(255, 143, 55, 0.45); + font-weight: 800; + font-size: 14px; + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + margin-left: 4px; +} + +.yaktube-cmd-palette-trigger-btn:hover, +.yaktube-cmd-palette-trigger-btn:focus-visible { + background: #ff8f37; + color: #0b0f19; + outline: 2px solid #ff8f37; + outline-offset: 2px; +} + +.yaktube-continue-shelf { + margin: 14px 0 22px 0; + padding: 16px; + background: linear-gradient(135deg, rgba(15, 23, 42, 0.92) 0%, rgba(30, 41, 59, 0.85) 100%); + border: 1px solid rgba(255, 143, 55, 0.28); + border-radius: 16px; +} + +.yaktube-continue-header { + display: flex; + justify-content: space-between; + align-items: center; + gap: 10px; + margin-bottom: 12px; + flex-wrap: wrap; +} + +.yaktube-continue-header h3 { + margin: 0; + font-size: 16px; + font-weight: 800; + color: #ff8f37; +} + +.yaktube-continue-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); + gap: 12px; +} + +.yaktube-continue-card { + background: rgba(15, 23, 42, 0.85); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 12px; + overflow: hidden; + display: flex; + flex-direction: column; +} + +.yaktube-continue-thumb-link { + position: relative; + display: block; + aspect-ratio: 16 / 9; + background: #020617; + overflow: hidden; +} + +.yaktube-continue-thumb-link img { + width: 100%; + height: 100%; + object-fit: cover; +} + +.yaktube-continue-badge { + position: absolute; + bottom: 8px; + right: 8px; + background: rgba(2, 6, 23, 0.88); + color: #fde68a; + font-size: 11px; + font-weight: 700; + padding: 2px 7px; + border-radius: 6px; +} + +.yaktube-continue-progress { + position: absolute; + bottom: 0; + left: 0; + right: 0; + height: 4px; + background: rgba(255, 255, 255, 0.2); +} + +.yaktube-continue-progress > div { + height: 100%; + background: linear-gradient(90deg, #ff8f37, #ea580c); +} + +.yaktube-continue-body { + padding: 10px 12px; + display: flex; + flex-direction: column; + gap: 6px; + flex: 1 1 auto; +} + +.yaktube-continue-title { + color: #f8fafc; + text-decoration: none; + font-size: 13px; + font-weight: 700; + line-height: 1.35; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +.yaktube-continue-sub { + font-size: 11px; + color: #94a3b8; +} + +.yaktube-continue-actions { + display: flex; + align-items: center; + gap: 6px; + margin-top: auto; +} + +.yaktube-continue-resume-btn { + flex: 1 1 auto; + text-align: center; + background: linear-gradient(135deg, #ff8f37 0%, #ea580c 100%); + color: #0b0f19 !important; + text-decoration: none !important; + font-weight: 800; + font-size: 12px; + padding: 6px 10px; + border-radius: 8px; +} + +.yaktube-cw-remove-btn { + background: #1e293b; + color: #cbd5e1; + border: 1px solid rgba(255, 255, 255, 0.14); + border-radius: 8px; + padding: 6px 8px; + font-size: 12px; + cursor: pointer; +} + +.yaktube-cmd-modal { + max-width: 580px !important; + width: 95vw !important; + background: #0f172a !important; + color: #f8fafc !important; + border: 1.5px solid #ff8f37 !important; + border-radius: 16px !important; + padding: 18px !important; +} + +.yaktube-cmd-input { + width: 100%; + box-sizing: border-box; + margin: 10px 0 12px 0; + padding: 10px 14px; + border-radius: 10px; + border: 1px solid rgba(255, 143, 55, 0.5); + background: #1e293b; + color: #fff; + font-size: 14px; +} + +.yaktube-cmd-input:focus { + outline: 2px solid #ff8f37; +} + +.yaktube-cmd-list { + list-style: none; + margin: 0; + padding: 0; + max-height: 50vh; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 6px; +} + +.yaktube-cmd-item { + display: flex; + justify-content: space-between; + align-items: center; + gap: 10px; + padding: 10px 12px; + border-radius: 10px; + background: rgba(30, 41, 59, 0.65); + cursor: pointer; + font-size: 13px; + font-weight: 600; +} + +.yaktube-cmd-item:hover, +.yaktube-cmd-item.selected { + background: rgba(255, 143, 55, 0.24); + outline: 2px solid #ff8f37; +} + +.yaktube-cmd-empty { + text-align: center; + padding: 20px; + color: #94a3b8; +} + +.yaktube-cockpit-modal { + max-width: 720px !important; + width: 96vw !important; + background: #0f172a !important; + color: #f8fafc !important; + border: 1.5px solid rgba(56, 189, 248, 0.55) !important; + border-radius: 16px !important; + padding: 20px !important; +} + +.yaktube-cockpit-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); + gap: 10px; + text-align: left; + margin-bottom: 16px; +} + +.yaktube-cockpit-card { + background: rgba(30, 41, 59, 0.82); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 12px; + padding: 12px; +} + +.yaktube-cockpit-label { + font-size: 12px; + color: #94a3b8; + margin-bottom: 4px; +} + +.yaktube-cockpit-val { + font-size: 18px; + font-weight: 800; + color: #ff8f37; +} + +.yaktube-cockpit-sub { + font-size: 11px; + color: #cbd5e1; + margin-top: 3px; +} + +.yaktube-cockpit-section-title { + text-align: left; + font-size: 13px; + font-weight: 700; + color: #38bdf8; + margin: 8px 0 6px 0; +} + +.yaktube-cockpit-issues { + list-style: none; + margin: 0 0 14px 0; + padding: 0; + max-height: 150px; + overflow-y: auto; + text-align: left; + display: flex; + flex-direction: column; + gap: 6px; +} + +.yaktube-cockpit-issues li { + background: rgba(30, 41, 59, 0.6); + padding: 7px 10px; + border-radius: 8px; + font-size: 12px; + display: flex; + flex-direction: column; + gap: 2px; +} + +.yaktube-cockpit-actions { + display: flex; + gap: 10px; + flex-wrap: wrap; + justify-content: flex-end; + border-top: 1px solid rgba(255, 255, 255, 0.1); + padding-top: 12px; +}