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 (
+ '' +
+ p.label +
+ ' '
+ );
+ })
+ .join('');
+
+ modal.innerHTML =
+ '
';
+
+ 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)') +
+ ' ' +
+ '✕ Kapat ';
+ 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.
' +
+ '
' +
+ '
' +
'🎬 Görüntüyü Aç (Alt+O) ' +
'⏯️ Oynat / Duraklat (Boşluk) ' +
+ '🎛️ Ses Stüdyosu ' +
'
' +
'
';
@@ -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 +=
+ '
' +
+ escapeHtml(l.name || l.code) +
+ (l.auto ? ' (Oto)' : '') +
+ ' ';
+ });
+ 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 +=
+ '' +
+ '' +
+ escapeHtml(formatClockShort(chStart)) +
+ ' ' +
+ escapeHtml(ch.title) +
+ ' ';
+ });
+ 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 =
'' +
'
';
});
@@ -4733,7 +6034,7 @@ try {
'">' +
'' +
+ '" style="text-decoration:none; color:inherit;">' +
'' +
'
' +
- '
' +
- '
' +
- '▶️ ' +
- escapeHtml(getInstanceName()) +
- "'dan Hemen İ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 +
+ '➕ Sıra ' +
+ '
' +
'' +
'';
});
@@ -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()) +
+ '
' +
+ '
' +
+ '
' +
+ ' '
+ );
+ })
+ .join('');
+
+ shelf.innerHTML =
+ '' +
+ '' +
+ 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 =
+ '' +
+ '' +
+ '
⏳ 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
' +
+ '' +
+ data.recentIssues
+ .map(function (it) {
+ var lbl = it.state === 2 ? '⚙️ İşleniyor' : it.state === 3 ? '📥 İndiriliyor' : '⚠️ Hata';
+ return (
+ '' +
+ lbl +
+ ' ' +
+ escapeHtml(it.name || '') +
+ ' ' +
+ (it.importError
+ ? '' +
+ escapeHtml(String(it.importError).slice(0, 70)) +
+ ' '
+ : '') +
+ ' '
+ );
+ })
+ .join('') +
+ ' ';
+ }
+
+ 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 +
+ '' +
+ '🔄 Yenile ' +
+ '🧹 Uzak Önbelleği Temizle ' +
+ ' 0 ? '' : 'disabled') +
+ '>🗑️ Hatalı Kalıntıları Sil (' +
+ (data.cleanableFailedCount || 0) +
+ ') ' +
+ '
';
+
+ 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 =
+ '' +
+ '' +
+ '
' +
+ '
' +
+ '
';
+
+ 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;
+}