Git Komut Rehberi & Terminal Asistanı
Sıfırdan Yeni Bir Depo Başlatın:
Mevcut Bir Git Deposu veya Klasörü Gönderin:
Hataları Geri Alma, İptal & Temizlik:
Son commit'i geri al (yapılan değişiklikleri korur):
git reset --soft HEAD~1
Yapılan yerel değişiklikleri iptal et (çalışma ağacını temizler):
git restore .
Takip edilmeyen gereksiz dosyaları sil:
git clean -fd
Değişiklikleri geçici sakla ve geri getir (stash):
git stash git stash pop
Dal (Branch) ve Sürüm Etiketleri:
Yeni dal aç ve geçiş yap:
git checkout -b yeni-ozellik git push -u origin yeni-ozellik
Sürüm etiketi (tag) oluştur ve gönder:
git tag -a v1.0.0 -m "Sürüm 1.0.0" git push origin --tags
10281 lines
425 KiB
JavaScript
10281 lines
425 KiB
JavaScript
var cachedYakNetSsoEnabled = null;
|
||
// 100% Incompatible Browser Suppression & Error Guardian
|
||
// CRITICAL: PeerTube's Angular app (my-app ngOnInit) relies on document.getElementById('incompatible-browser')
|
||
// to exist so it can do .className += " browser-ok" before calling this.loadUser()!
|
||
// Removing it from DOM causes a null pointer crash that breaks user session initialization!
|
||
if (typeof window !== 'undefined') {
|
||
try {
|
||
window.displayIncompatibleBrowser = function () {};
|
||
var neuterIncompatible = function () {
|
||
var el = document.getElementById('incompatible-browser');
|
||
if (el) {
|
||
if (!el.classList.contains('browser-ok')) {
|
||
el.classList.add('browser-ok');
|
||
}
|
||
el.style.setProperty('display', 'none', 'important');
|
||
el.style.setProperty('visibility', 'hidden', 'important');
|
||
el.style.setProperty('height', '0px', 'important');
|
||
el.style.setProperty('width', '0px', 'important');
|
||
el.style.setProperty('opacity', '0', 'important');
|
||
el.style.setProperty('pointer-events', 'none', 'important');
|
||
} else {
|
||
try {
|
||
var dummy = document.createElement('div');
|
||
dummy.id = 'incompatible-browser';
|
||
dummy.className = 'browser-ok';
|
||
dummy.style.display = 'none';
|
||
(document.body || document.documentElement).appendChild(dummy);
|
||
} catch (e) {}
|
||
}
|
||
};
|
||
neuterIncompatible();
|
||
if (document.readyState === 'loading') {
|
||
document.addEventListener('DOMContentLoaded', neuterIncompatible);
|
||
}
|
||
var neuterInterval = setInterval(neuterIncompatible, 1000);
|
||
setTimeout(function () {
|
||
clearInterval(neuterInterval);
|
||
}, 5000);
|
||
} catch (e) {}
|
||
}
|
||
|
||
// Immediate URL rewrite: redirect legacy /search/videos to /search
|
||
if (typeof window !== 'undefined' && window.location) {
|
||
if (window.location.pathname === '/search/videos' || window.location.pathname.startsWith('/search/videos/')) {
|
||
var targetSearch = window.location.search || '';
|
||
window.location.replace('/search' + targetSearch);
|
||
}
|
||
}
|
||
try {
|
||
(function () {
|
||
if (window.__YAKTUBE_ENGINE_LOADED__) return;
|
||
window.__YAKTUBE_ENGINE_LOADED__ = true;
|
||
try {
|
||
localStorage.setItem('hide-mobile-msg', 'true');
|
||
sessionStorage.setItem('hide-mobile-msg', 'true');
|
||
} catch (e) {}
|
||
console.log('[YakTube] YakNet SSO, Custom Branding, A11y & On-Demand Engine Active');
|
||
|
||
// Global Suppression of role="application" on Video Elements (W3C WAI-ARIA Screen Reader Compliance)
|
||
try {
|
||
if (
|
||
typeof HTMLVideoElement !== 'undefined' &&
|
||
HTMLVideoElement.prototype &&
|
||
!HTMLVideoElement.prototype._yaktubeA11yHooked
|
||
) {
|
||
HTMLVideoElement.prototype._yaktubeA11yHooked = true;
|
||
var origVideoSetAttribute = HTMLVideoElement.prototype.setAttribute;
|
||
HTMLVideoElement.prototype.setAttribute = function (name, val) {
|
||
if (String(name).toLowerCase() === 'role' && String(val).toLowerCase() === 'application') {
|
||
return; // 100% suppress role="application" on video tags
|
||
}
|
||
return origVideoSetAttribute.apply(this, arguments);
|
||
};
|
||
}
|
||
} catch (e) {}
|
||
|
||
// Ensure Fediverse Global Search (SepiaSearch) is default in PeertubeServerConfig
|
||
try {
|
||
if (
|
||
window.PeertubeServerConfig &&
|
||
window.PeertubeServerConfig.search &&
|
||
window.PeertubeServerConfig.search.searchIndex
|
||
) {
|
||
window.PeertubeServerConfig.search.searchIndex.isDefaultSearch = true;
|
||
}
|
||
} catch (e) {}
|
||
|
||
// Dynamic Instance Name Helper
|
||
function getInstanceName() {
|
||
if (
|
||
window.PeertubeServerConfig &&
|
||
window.PeertubeServerConfig.instance &&
|
||
window.PeertubeServerConfig.instance.name
|
||
) {
|
||
return window.PeertubeServerConfig.instance.name;
|
||
}
|
||
var metaSite = document.querySelector('meta[property="og:site_name"]');
|
||
if (metaSite && metaSite.content) return metaSite.content;
|
||
var brandEl = document.querySelector('.header-left .brand-name, .instance-name, a.brand');
|
||
if (brandEl && brandEl.textContent) return brandEl.textContent.trim();
|
||
return 'YakTube';
|
||
}
|
||
|
||
// 1. Screen Reader Live Announcer (W3C WCAG 2.2 AAA Compliant Auto-Clearing Engine)
|
||
function applySrOnlyStyles(el) {
|
||
el.className = 'yaktube-sr-only';
|
||
el.style.position = 'absolute';
|
||
el.style.width = '1px';
|
||
el.style.height = '1px';
|
||
el.style.padding = '0';
|
||
el.style.margin = '-1px';
|
||
el.style.overflow = 'hidden';
|
||
el.style.clip = 'rect(0, 0, 0, 0)';
|
||
el.style.whiteSpace = 'nowrap';
|
||
el.style.border = '0';
|
||
}
|
||
|
||
function getLiveRegion(assertive) {
|
||
var id = assertive ? 'yaktube-a11y-live-assertive' : 'yaktube-a11y-live-region';
|
||
var region = document.getElementById(id);
|
||
if (!region || !document.body.contains(region)) {
|
||
region = document.createElement('div');
|
||
region.id = id;
|
||
region.setAttribute('aria-live', assertive ? 'assertive' : 'polite');
|
||
region.setAttribute('aria-atomic', 'true');
|
||
region.setAttribute('aria-relevant', 'additions text');
|
||
applySrOnlyStyles(region);
|
||
document.body.appendChild(region);
|
||
}
|
||
return region;
|
||
}
|
||
|
||
function announce(text, assertive) {
|
||
if (!text || !String(text).trim()) return;
|
||
var strText = String(text).trim();
|
||
var region = getLiveRegion(assertive);
|
||
|
||
if (region._setTimer) {
|
||
clearTimeout(region._setTimer);
|
||
region._setTimer = null;
|
||
}
|
||
if (region._clearTimer) {
|
||
clearTimeout(region._clearTimer);
|
||
region._clearTimer = null;
|
||
}
|
||
|
||
// Screen reader mutation trigger: clear first so repeat announcements are re-announced
|
||
region.textContent = '';
|
||
|
||
region._setTimer = setTimeout(function () {
|
||
region.textContent = strText;
|
||
|
||
// Seslendirme yapıldıktan veya ekran okuyucu kuyruğuna alındıktan sonra
|
||
// sayfanın en altında ya da sanal imleç gezintisinde eski metin kalmaması için
|
||
// DOM'daki duyuru metnini temizle (Metin uzunluğuna göre 3 ile 7 saniye arası)
|
||
var clearDelay = Math.min(7000, Math.max(3000, strText.length * 50));
|
||
region._clearTimer = setTimeout(function () {
|
||
if (region && document.body.contains(region)) {
|
||
region.textContent = '';
|
||
}
|
||
region._clearTimer = null;
|
||
}, clearDelay);
|
||
region._setTimer = null;
|
||
}, 50);
|
||
}
|
||
|
||
// Load official YakNet Web Component definition
|
||
if (
|
||
typeof customElements !== 'undefined' &&
|
||
!customElements.get('yaknet-account') &&
|
||
!document.getElementById('yaknet-account-script')
|
||
) {
|
||
var s = document.createElement('script');
|
||
s.id = 'yaknet-account-script';
|
||
s.src = 'https://cdnjs.yakhub.com.tr/ajax/libs/yaknet-account/latest/yaknet-account.js';
|
||
s.async = true;
|
||
document.head.appendChild(s);
|
||
}
|
||
|
||
// Intercept and sanitize YakNet Account Web Component popup menu (v1.5.12)
|
||
function hookYakNetAccountComponent() {
|
||
if (typeof customElements === 'undefined') return;
|
||
customElements
|
||
.whenDefined('yaknet-account')
|
||
.then(function () {
|
||
var YakNetAccount = customElements.get('yaknet-account');
|
||
if (!YakNetAccount || !YakNetAccount.prototype || YakNetAccount.prototype._yaktubeSanitizerHooked) return;
|
||
YakNetAccount.prototype._yaktubeSanitizerHooked = true;
|
||
var originalRender = YakNetAccount.prototype.render;
|
||
if (typeof originalRender === 'function') {
|
||
YakNetAccount.prototype.render = function () {
|
||
originalRender.call(this);
|
||
try {
|
||
if (this.shadowRoot) {
|
||
var isOfficial = isOfficialYakTubeServer();
|
||
|
||
// 1. In YakTube: Suppress redundant/recursive link to YakTube inside services list
|
||
var selfLinks = this.shadowRoot.querySelectorAll(
|
||
'a[href*="yaktube.yakhub.com.tr"], .yn-app-card.yn-current, a[aria-label="YakTube"]'
|
||
);
|
||
selfLinks.forEach(function (a) {
|
||
a.style.display = 'none';
|
||
});
|
||
|
||
// 2. In third-party PeerTube instances: Suppress entire external services grid & 9-dot launcher to avoid community backlash
|
||
if (!isOfficial) {
|
||
// Hide 9-dot apps button
|
||
var appsBtn = this.shadowRoot.querySelector('#appsTriggerBtn, .yn-apps-btn');
|
||
if (appsBtn) appsBtn.style.display = 'none';
|
||
|
||
// Hide apps popover
|
||
var appsPopover = this.shadowRoot.querySelector('#yn-apps-popover, .yn-apps-popover');
|
||
if (appsPopover) appsPopover.style.display = 'none';
|
||
|
||
// Legacy selectors for backwards compatibility
|
||
var appsGrid = this.shadowRoot.querySelector('.yn-apps-grid, .yn-apps-grid-3col');
|
||
if (appsGrid) appsGrid.style.display = 'none';
|
||
var sectionTitle = this.shadowRoot.querySelector(
|
||
'#yn-services-label, .yn-section-title, .yn-apps-footer'
|
||
);
|
||
if (sectionTitle) sectionTitle.style.display = 'none';
|
||
}
|
||
|
||
// 3. Ensure Logout Button Hook is attached whenever account menu renders
|
||
var shadowLogoutBtn =
|
||
this.shadowRoot.getElementById('logoutBtn') ||
|
||
this.shadowRoot.querySelector('.yn-logout-btn') ||
|
||
this.shadowRoot.querySelector('button[title*="Çıkış"], button[aria-label*="Çıkış"]');
|
||
if (shadowLogoutBtn && !shadowLogoutBtn.hasAttribute('data-yaktube-hooked')) {
|
||
shadowLogoutBtn.setAttribute('data-yaktube-hooked', 'true');
|
||
shadowLogoutBtn.addEventListener(
|
||
'click',
|
||
function (ev) {
|
||
ev.preventDefault();
|
||
ev.stopPropagation();
|
||
performUnifiedLogout();
|
||
},
|
||
true
|
||
);
|
||
}
|
||
}
|
||
} catch (e) {}
|
||
};
|
||
}
|
||
})
|
||
.catch(function () {});
|
||
}
|
||
hookYakNetAccountComponent();
|
||
|
||
// Silent background SSO Probe Engine
|
||
function initSilentSSOProbe() {
|
||
var token = localStorage.getItem('access_token');
|
||
var isManualLogout = sessionStorage.getItem('yaknet_manual_logout');
|
||
if (
|
||
token ||
|
||
isManualLogout ||
|
||
window.location.search.includes('local=true') ||
|
||
window.location.search.includes('externalAuthError') ||
|
||
window.location.pathname.includes('/login')
|
||
) {
|
||
return;
|
||
}
|
||
|
||
var iframeId = 'yaknet-sso-iframe-instance';
|
||
if (!document.getElementById(iframeId)) {
|
||
var iframe = document.createElement('iframe');
|
||
iframe.id = iframeId;
|
||
iframe.src = 'https://developer-console.yakhub.com.tr/sdk/sso-frame';
|
||
iframe.title = 'YakNet Oturum Kontrolü';
|
||
iframe.setAttribute('aria-hidden', 'true');
|
||
iframe.tabIndex = -1;
|
||
iframe.style.cssText =
|
||
'display:none!important;width:0!important;height:0!important;border:0!important;position:absolute!important;pointer-events:none!important;';
|
||
document.body.appendChild(iframe);
|
||
}
|
||
}
|
||
if (document.readyState === 'loading') {
|
||
document.addEventListener('DOMContentLoaded', initSilentSSOProbe);
|
||
} else {
|
||
initSilentSSOProbe();
|
||
}
|
||
|
||
function saveReturnUrlBeforeLogin() {
|
||
try {
|
||
var currentPath = window.location.pathname + window.location.search + window.location.hash;
|
||
if (currentPath && !window.location.pathname.includes('/login')) {
|
||
localStorage.setItem('yaktube_return_url', currentPath);
|
||
localStorage.setItem('yaktube_return_url_time', String(Date.now()));
|
||
sessionStorage.setItem('yaktube_return_url', currentPath);
|
||
sessionStorage.setItem('redirect-url-after-login', currentPath);
|
||
}
|
||
} catch (e) {}
|
||
}
|
||
|
||
function checkPendingPostLoginRedirect() {
|
||
try {
|
||
if (window.location.pathname.includes('/login')) return false;
|
||
var token = localStorage.getItem('access_token');
|
||
if (!token) return false;
|
||
var savedUrl =
|
||
localStorage.getItem('yaktube_return_url') ||
|
||
sessionStorage.getItem('yaktube_return_url') ||
|
||
sessionStorage.getItem('redirect-url-after-login');
|
||
if (!savedUrl) return false;
|
||
var savedTime = parseInt(localStorage.getItem('yaktube_return_url_time') || '0', 10);
|
||
localStorage.removeItem('yaktube_return_url');
|
||
localStorage.removeItem('yaktube_return_url_time');
|
||
sessionStorage.removeItem('yaktube_return_url');
|
||
sessionStorage.removeItem('redirect-url-after-login');
|
||
if (savedTime && Date.now() - savedTime > 15 * 60 * 1000) return false;
|
||
var currentFull = window.location.pathname + window.location.search + window.location.hash;
|
||
if (
|
||
typeof savedUrl === 'string' &&
|
||
savedUrl.startsWith('/') &&
|
||
!savedUrl.startsWith('//') &&
|
||
!savedUrl.startsWith('/login') &&
|
||
savedUrl !== currentFull
|
||
) {
|
||
window.location.replace(savedUrl);
|
||
return true;
|
||
}
|
||
} catch (e) {}
|
||
return false;
|
||
}
|
||
|
||
checkPendingPostLoginRedirect();
|
||
|
||
function triggerYakNetOAuth() {
|
||
saveReturnUrlBeforeLogin();
|
||
sessionStorage.removeItem('yaknet_manual_logout');
|
||
var callbackUrl = 'https://yaktube.yakhub.com.tr/plugins/peertube-plugin-auth-yaknet/router/auth-callback';
|
||
window.location.href =
|
||
'https://developer-console.yakhub.com.tr/oauth/authorize?client_id=01a03c41-f758-721e-b927-619bffde5c23&redirect_uri=' +
|
||
encodeURIComponent(callbackUrl) +
|
||
'&response_type=code&scope=';
|
||
}
|
||
|
||
// Handle direct postMessage from YakNet SSO frame
|
||
window.addEventListener('message', function (ev) {
|
||
if (ev.data && ev.data.type === 'YAKNET_SSO_STATUS') {
|
||
if (ev.data.authenticated && ev.data.user) {
|
||
var token = localStorage.getItem('access_token');
|
||
if (
|
||
!token &&
|
||
!window.location.search.includes('local=true') &&
|
||
!window.location.search.includes('externalAuthError')
|
||
) {
|
||
sessionStorage.removeItem('yaknet_manual_logout');
|
||
console.log('[YakTube] Live YakNet session detected via SSO frame! Connecting...', ev.data.user);
|
||
triggerYakNetOAuth();
|
||
}
|
||
} else if (ev.data.authenticated === false) {
|
||
var hasToken = localStorage.getItem('access_token') || localStorage.getItem('username');
|
||
if (hasToken) {
|
||
console.log('[YakTube] YakNet session ended elsewhere. Clearing YakTube...');
|
||
clearYakTubeAuthSession();
|
||
window.location.reload();
|
||
}
|
||
}
|
||
}
|
||
});
|
||
|
||
// Global listener for YakNet SSO broadcast from developer-console.yakhub.com.tr
|
||
window.addEventListener('yaknet-auth', function (e) {
|
||
if (e.detail && e.detail.authenticated && e.detail.user) {
|
||
var token = localStorage.getItem('access_token');
|
||
if (
|
||
!token &&
|
||
!window.location.search.includes('local=true') &&
|
||
!window.location.search.includes('externalAuthError')
|
||
) {
|
||
sessionStorage.removeItem('yaknet_manual_logout');
|
||
console.log('[YakTube] Initiating automatic single-sign-on handshake for:', e.detail.user);
|
||
triggerYakNetOAuth();
|
||
}
|
||
} else if (e.detail && e.detail.authenticated === false) {
|
||
var hasToken = localStorage.getItem('access_token') || localStorage.getItem('username');
|
||
if (hasToken) {
|
||
clearYakTubeAuthSession();
|
||
window.location.reload();
|
||
}
|
||
}
|
||
});
|
||
|
||
// Clear YakTube auth session and cloud search cache safely
|
||
function clearYakTubeAuthSession() {
|
||
try {
|
||
localStorage.removeItem('access_token');
|
||
localStorage.removeItem('refresh_token');
|
||
localStorage.removeItem('token_type');
|
||
localStorage.removeItem('id');
|
||
localStorage.removeItem('username');
|
||
localStorage.removeItem('displayName');
|
||
localStorage.removeItem('email');
|
||
localStorage.removeItem('role');
|
||
localStorage.removeItem('yaktube_recent_searches');
|
||
sessionStorage.clear();
|
||
} catch (e) {}
|
||
}
|
||
|
||
// Unified single sign-out for YakTube and YakNet
|
||
function performUnifiedLogout() {
|
||
clearYakTubeAuthSession();
|
||
try {
|
||
sessionStorage.setItem('yaknet_manual_logout', 'true');
|
||
} catch (err) {}
|
||
window.location.replace(
|
||
'https://developer-console.yakhub.com.tr/sdk/logout?redirect_uri=' +
|
||
encodeURIComponent('https://yaktube.yakhub.com.tr')
|
||
);
|
||
}
|
||
|
||
document.addEventListener(
|
||
'click',
|
||
function (e) {
|
||
var el = e.target;
|
||
if (el && el.closest) {
|
||
var isLogout = el.closest(
|
||
'a[href*="logout"], button[title*="Log out"], button[title*="Çıkış"], .logout-button, [class*="logout"], [aria-label*="Çıkış"], [aria-label*="Log out"]'
|
||
);
|
||
if (isLogout) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
performUnifiedLogout();
|
||
return;
|
||
}
|
||
var isLogin = el.closest(
|
||
'my-login-link, .login-button, a[href*="/login"]:not(#yaktube-show-admin-login), a[aria-label*="Giriş"], a[title*="Giriş"], a[title*="login"], a[aria-label*="login"], .yaknet-sso-login-btn'
|
||
);
|
||
if (isLogin && !window.location.search.includes('local=true')) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
sessionStorage.removeItem('yaknet_manual_logout');
|
||
triggerYakNetOAuth();
|
||
return;
|
||
}
|
||
}
|
||
},
|
||
true
|
||
);
|
||
|
||
// 2.3 Dedicated Local Admin Login Modal (Alt+A)
|
||
function openLocalAdminLoginModal() {
|
||
var existingModal = document.getElementById('yaktube-admin-login-modal');
|
||
if (existingModal) {
|
||
existingModal.style.display = 'flex';
|
||
var uInput = existingModal.querySelector('#yaktube-admin-username');
|
||
if (uInput) uInput.focus();
|
||
return;
|
||
}
|
||
|
||
var modal = document.createElement('div');
|
||
modal.id = 'yaktube-admin-login-modal';
|
||
modal.className = 'yaktube-modal-overlay';
|
||
modal.setAttribute('role', 'dialog');
|
||
modal.setAttribute('aria-modal', 'true');
|
||
modal.setAttribute('aria-labelledby', 'yaktube-admin-modal-title');
|
||
|
||
modal.innerHTML =
|
||
'<div class="yaktube-modal-card" style="max-width: 420px; background:#181824; border:1px solid rgba(255,143,55,0.4); border-radius:18px; padding:26px; color:#fff; box-shadow:0 16px 40px rgba(0,0,0,0.8); text-align:left;">' +
|
||
'<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:18px;">' +
|
||
'<h3 id="yaktube-admin-modal-title" style="margin:0; font-size:18px; color:#ff8f37;">⚙️ Sunucu Yöneticisi Girişi</h3>' +
|
||
'<button id="yaktube-admin-modal-close" class="yaktube-voice-modal-close-btn" aria-label="Kapat">✕</button>' +
|
||
'</div>' +
|
||
'<p style="font-size:13px; color:#aaa; margin-bottom:16px;">Yerel yönetici (admin) kullanıcı adı ve şifrenizle giriş yaparak PeerTube yönetim paneline erişebilirsiniz.</p>' +
|
||
'<form id="yaktube-admin-direct-form" style="display:flex; flex-direction:column; gap:12px;">' +
|
||
'<div style="display:flex; flex-direction:column; gap:4px;">' +
|
||
'<label for="yaktube-admin-username" style="font-size:13px; font-weight:600; color:#ddd;">Kullanıcı Adı veya E-posta:</label>' +
|
||
'<input type="text" id="yaktube-admin-username" required style="background:#22222e; border:1px solid #444; border-radius:8px; padding:10px 12px; color:#fff; font-size:14px; outline:none;" />' +
|
||
'</div>' +
|
||
'<div style="display:flex; flex-direction:column; gap:4px;">' +
|
||
'<label for="yaktube-admin-password" style="font-size:13px; font-weight:600; color:#ddd;">Şifre:</label>' +
|
||
'<input type="password" id="yaktube-admin-password" required style="background:#22222e; border:1px solid #444; border-radius:8px; padding:10px 12px; color:#fff; font-size:14px; outline:none;" />' +
|
||
'</div>' +
|
||
'<div id="yaktube-admin-login-error" style="color:#ef4444; font-size:13px; display:none; margin-top:4px;"></div>' +
|
||
'<button type="submit" id="yaktube-admin-login-submit" style="background:linear-gradient(135deg, #ff8f37 0%, #ff5e3a 100%); color:#fff; border:none; border-radius:8px; padding:12px; font-weight:700; font-size:14px; cursor:pointer; margin-top:6px;">Yönetici Olarak Giriş Yap</button>' +
|
||
'</form>' +
|
||
'</div>';
|
||
|
||
document.body.appendChild(modal);
|
||
|
||
modal.querySelector('#yaktube-admin-modal-close').addEventListener('click', function () {
|
||
modal.style.display = 'none';
|
||
});
|
||
modal.addEventListener('click', function (e) {
|
||
if (e.target === modal) modal.style.display = 'none';
|
||
});
|
||
|
||
var form = modal.querySelector('#yaktube-admin-direct-form');
|
||
var errEl = modal.querySelector('#yaktube-admin-login-error');
|
||
var uInput = modal.querySelector('#yaktube-admin-username');
|
||
var pInput = modal.querySelector('#yaktube-admin-password');
|
||
var sBtn = modal.querySelector('#yaktube-admin-login-submit');
|
||
|
||
uInput.focus();
|
||
|
||
form.addEventListener('submit', async function (ev) {
|
||
ev.preventDefault();
|
||
errEl.style.display = 'none';
|
||
sBtn.disabled = true;
|
||
sBtn.innerText = 'Giriş Yapılıyor...';
|
||
|
||
try {
|
||
var clientRes = await fetch('/api/v1/oauth-clients/local');
|
||
var clientData = await clientRes.json();
|
||
|
||
var bodyParams = new URLSearchParams({
|
||
client_id: clientData.client_id,
|
||
client_secret: clientData.client_secret,
|
||
grant_type: 'password',
|
||
username: uInput.value.trim(),
|
||
password: pInput.value
|
||
});
|
||
|
||
var tokenRes = await fetch('/api/v1/users/token', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||
body: bodyParams.toString()
|
||
});
|
||
|
||
var tokenData = await tokenRes.json();
|
||
if (!tokenRes.ok || !tokenData.access_token) {
|
||
throw new Error(tokenData.error_description || tokenData.error || 'Kullanıcı adı veya şifre hatalı.');
|
||
}
|
||
|
||
// Store tokens
|
||
localStorage.setItem('access_token', tokenData.access_token);
|
||
localStorage.setItem('refresh_token', tokenData.refresh_token);
|
||
localStorage.setItem('token_type', tokenData.token_type || 'Bearer');
|
||
localStorage.setItem('username', uInput.value.trim());
|
||
|
||
// Get user details
|
||
var meRes = await fetch('/api/v1/users/me', {
|
||
headers: { Authorization: 'Bearer ' + tokenData.access_token }
|
||
});
|
||
if (meRes.ok) {
|
||
var meData = await meRes.json();
|
||
localStorage.setItem('email', meData.email || '');
|
||
localStorage.setItem('displayName', meData.displayName || meData.username || '');
|
||
}
|
||
|
||
announce('Yönetici girişi başarılı! Yönetim paneline yönlendiriliyorsunuz.', true);
|
||
window.location.href = '/admin';
|
||
} catch (err) {
|
||
errEl.innerText = err.message;
|
||
errEl.style.display = 'block';
|
||
sBtn.disabled = false;
|
||
sBtn.innerText = 'Yönetici Olarak Giriş Yap';
|
||
}
|
||
});
|
||
}
|
||
|
||
// 2. YakNet SSO Header & Login Flow
|
||
function injectYakNetSSO() {
|
||
// 2.1 Header: Place YakNet Account widget in top-right .buttons-container
|
||
var headerRight =
|
||
document.querySelector('my-header .buttons-container') ||
|
||
document.querySelector('.buttons-container') ||
|
||
document.querySelector('my-header .header-right') ||
|
||
document.querySelector('my-header .user-menu') ||
|
||
document.querySelector('my-header .action-buttons') ||
|
||
document.querySelector('.header-right') ||
|
||
document.querySelector('header .right');
|
||
|
||
var token = localStorage.getItem('access_token');
|
||
var uName = localStorage.getItem('username');
|
||
var uEmail = localStorage.getItem('email');
|
||
var displayName = localStorage.getItem('displayName') || uName || '';
|
||
var emailStr = uEmail || '';
|
||
var isAuth = !!token && !!uName;
|
||
|
||
if (headerRight) {
|
||
var liveWidget = headerRight.querySelector('#yaknet-header-account-widget');
|
||
|
||
if (isAuth) {
|
||
// 1. AUTHENTICATED: Add class to body & Hide ALL native login links completely
|
||
document.body.classList.add('yaktube-user-logged-in');
|
||
document
|
||
.querySelectorAll('my-login-link, a[href*="/login"], .login-button, [class*="login-link"]')
|
||
.forEach(function (btn) {
|
||
btn.style.setProperty('display', 'none', 'important');
|
||
btn.setAttribute('aria-hidden', 'true');
|
||
btn.setAttribute('tabindex', '-1');
|
||
});
|
||
|
||
if (!isYakNetSsoEnabled()) {
|
||
if (liveWidget) liveWidget.remove();
|
||
return;
|
||
}
|
||
if (!liveWidget && isOfficialYakTubeServer()) {
|
||
var widgetWrap = document.createElement('div');
|
||
widgetWrap.id = 'yaknet-header-account-widget';
|
||
widgetWrap.className = 'yaknet-header-widget';
|
||
widgetWrap.style.display = 'inline-flex';
|
||
widgetWrap.style.alignItems = 'center';
|
||
widgetWrap.style.marginRight = '8px';
|
||
|
||
widgetWrap.innerHTML =
|
||
'<yaknet-account ' +
|
||
'client-id="01a03c41-f758-721e-b927-619bffde5c23" ' +
|
||
'redirect-uri="https://yaktube.yakhub.com.tr/plugins/peertube-plugin-auth-yaknet/router/auth-callback" ' +
|
||
'base-url="https://developer-console.yakhub.com.tr" ' +
|
||
'login-url="/login" ' +
|
||
'authenticated="true" ' +
|
||
'hide-service="yaktube" ' +
|
||
'user-name="' +
|
||
displayName.replace(/"/g, '"') +
|
||
'" ' +
|
||
'user-email="' +
|
||
emailStr.replace(/"/g, '"') +
|
||
'" ' +
|
||
'theme="dark">' +
|
||
'</yaknet-account>';
|
||
|
||
var targetSibling =
|
||
headerRight.querySelector('my-user-menu') ||
|
||
headerRight.querySelector('.user-menu') ||
|
||
headerRight.querySelector('.settings-button') ||
|
||
headerRight.querySelector('my-user-notifications') ||
|
||
headerRight.querySelector('my-notification-bell');
|
||
|
||
if (targetSibling && targetSibling.parentElement === headerRight) {
|
||
headerRight.insertBefore(widgetWrap, targetSibling);
|
||
} else {
|
||
headerRight.prepend(widgetWrap);
|
||
}
|
||
} else if (liveWidget) {
|
||
if (!isOfficialYakTubeServer()) {
|
||
liveWidget.remove();
|
||
} else {
|
||
var el = liveWidget.querySelector('yaknet-account');
|
||
if (el) {
|
||
if (
|
||
el.getAttribute('authenticated') !== 'true' ||
|
||
el.getAttribute('user-name') !== displayName ||
|
||
el.getAttribute('hide-service') !== 'yaktube'
|
||
) {
|
||
el.setAttribute('authenticated', 'true');
|
||
el.setAttribute('user-name', displayName);
|
||
el.setAttribute('user-email', emailStr);
|
||
el.setAttribute('hide-service', 'yaktube');
|
||
if (typeof el.syncStateFromAttributes === 'function') {
|
||
el.syncStateFromAttributes();
|
||
el.render();
|
||
}
|
||
}
|
||
|
||
if (el.shadowRoot) {
|
||
// Direct DOM safety: remove self-link on polling cycle too
|
||
var selfLinks = el.shadowRoot.querySelectorAll(
|
||
'a[href*="yaktube.yakhub.com.tr"], .yn-app-card.yn-current, a[aria-label="YakTube"]'
|
||
);
|
||
selfLinks.forEach(function (a) {
|
||
a.style.display = 'none';
|
||
});
|
||
|
||
var shadowLogoutBtn =
|
||
el.shadowRoot.getElementById('logoutBtn') ||
|
||
el.shadowRoot.querySelector('.yn-logout-btn') ||
|
||
el.shadowRoot.querySelector('button[title*="Çıkış"], button[aria-label*="Çıkış"]');
|
||
if (shadowLogoutBtn && !shadowLogoutBtn.hasAttribute('data-yaktube-hooked')) {
|
||
shadowLogoutBtn.setAttribute('data-yaktube-hooked', 'true');
|
||
shadowLogoutBtn.addEventListener(
|
||
'click',
|
||
function (ev) {
|
||
ev.preventDefault();
|
||
ev.stopPropagation();
|
||
performUnifiedLogout();
|
||
},
|
||
true
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
} else {
|
||
// 2. GUEST / NOT LOGGED IN:
|
||
document.body.classList.remove('yaktube-user-logged-in');
|
||
if (liveWidget) {
|
||
liveWidget.remove();
|
||
}
|
||
|
||
document
|
||
.querySelectorAll('my-login-link, a[href*="/login"], .login-button, [class*="login-link"]')
|
||
.forEach(function (btn) {
|
||
btn.style.display = '';
|
||
btn.removeAttribute('aria-hidden');
|
||
btn.removeAttribute('tabindex');
|
||
|
||
var loginAnchor = btn.tagName.toLowerCase() === 'a' ? btn : btn.querySelector('a');
|
||
if (loginAnchor && isYakNetSsoEnabled()) {
|
||
loginAnchor.setAttribute('aria-label', 'YakNet ile Giriş Yap');
|
||
loginAnchor.setAttribute('title', 'YakNet ile Giriş Yap');
|
||
var spanText = loginAnchor.querySelector('span');
|
||
if (spanText) {
|
||
spanText.textContent = 'YakNet ile Giriş Yap';
|
||
} else {
|
||
loginAnchor.textContent = 'YakNet ile Giriş Yap';
|
||
}
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
// 2.2 Login Modal / Page
|
||
var loginCard =
|
||
document.querySelector('my-login') ||
|
||
document.querySelector('.login-page') ||
|
||
document.querySelector('.login-container') ||
|
||
document.querySelector('form.login') ||
|
||
document.querySelector('form[action*="login"]') ||
|
||
document.querySelector('my-login-modal');
|
||
|
||
if (loginCard && isYakNetSsoEnabled() && !document.getElementById('yaknet-login-section')) {
|
||
var isLocalLogin = window.location.search.includes('local=true') || window.location.pathname.includes('/admin');
|
||
|
||
var ssoBox = document.createElement('div');
|
||
ssoBox.id = 'yaknet-login-section';
|
||
ssoBox.className = 'yaknet-login-banner';
|
||
ssoBox.innerHTML =
|
||
'<div style="font-size: 19px; font-weight: 700; color: #ff8f37; margin-bottom: 6px;">YakNet ile YakTube\'a Katılın</div>' +
|
||
'<p style="font-size: 13px; color: #94a3b8; margin-bottom: 16px; line-height: 1.45;">' +
|
||
'YouTube gibi tek bir YakNet hesabıyla güvenle giriş yapabilir, kendi video ve müzik kanallarınızı oluşturabilirsiniz.' +
|
||
'</p>' +
|
||
'<a href="https://developer-console.yakhub.com.tr/oauth/authorize?client_id=01a03c41-f758-721e-b927-619bffde5c23&redirect_uri=https%3A%2F%2Fyaktube.yakhub.com.tr%2Fplugins%2Fpeertube-plugin-auth-yaknet%2Frouter%2Fauth-callback&response_type=code&scope=" class="yaknet-sso-login-btn" aria-label="YakNet Hesabınız ile Tek Tıkla Giriş Yapın">' +
|
||
'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>' +
|
||
'<span>YakNet ile Giriş Yap</span>' +
|
||
'</a>' +
|
||
'<div style="margin-top: 14px; font-size: 13px; color: #94a3b8;">' +
|
||
'YakNet hesabınız yok mu? <a href="https://developer-console.yakhub.com.tr/register" target="_blank" rel="noopener noreferrer" style="color: #ff8f37; font-weight: 600; text-decoration: underline;">YakNet Hesabı Oluştur</a>' +
|
||
'</div>' +
|
||
'<div style="margin-top: 14px; padding-top: 12px; border-top: 1px solid rgba(255,255,255,0.08); font-size: 11.5px; color: #64748b; line-height: 1.45;">' +
|
||
'Giriş yaparak <a href="/about/instance" target="_blank" style="color: #94a3b8; text-decoration: underline;">Kullanım Koşulları</a>\'nı ve <a href="/about/instance" target="_blank" style="color: #94a3b8; text-decoration: underline;">Gizlilik Politikası</a>\'nı kabul etmiş sayılırsınız.' +
|
||
'</div>' +
|
||
'<div class="yaktube-admin-login-link" style="margin-top: 14px;">' +
|
||
(isLocalLogin
|
||
? '<span>⚙️ Yönetici (Local Admin) Giriş Modu Aktif</span>'
|
||
: '<a href="#" id="yaktube-show-admin-login">⚙️ Sunucu Yöneticisi Girişi</a>') +
|
||
'</div>';
|
||
|
||
var formFirstChild = loginCard.firstElementChild;
|
||
if (formFirstChild) {
|
||
loginCard.insertBefore(ssoBox, formFirstChild);
|
||
} else {
|
||
loginCard.appendChild(ssoBox);
|
||
}
|
||
|
||
var registerLinks = document.querySelectorAll('a[href*="/signup"], a[href*="/register"]');
|
||
registerLinks.forEach(function (l) {
|
||
l.href = 'https://developer-console.yakhub.com.tr/register';
|
||
l.innerText = 'YakNet Hesabı Oluştur';
|
||
});
|
||
|
||
var formInputs = loginCard.querySelector('.form-group, .inputs, form') || loginCard.querySelector('input');
|
||
var containerToHide = formInputs ? formInputs.closest('form') || formInputs.parentElement : null;
|
||
|
||
if (containerToHide && !isLocalLogin) {
|
||
var subElements = Array.from(loginCard.children).filter(function (el) {
|
||
return (
|
||
el.id !== 'yaknet-login-section' &&
|
||
!el.classList.contains('title') &&
|
||
!el.classList.contains('page-title')
|
||
);
|
||
});
|
||
|
||
subElements.forEach(function (el) {
|
||
el.style.display = 'none';
|
||
});
|
||
|
||
var showAdminBtn = document.getElementById('yaktube-show-admin-login');
|
||
if (showAdminBtn) {
|
||
showAdminBtn.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
openLocalAdminLoginModal();
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 3. Intelligent Branding & A11y DOM Auto-Fixer
|
||
function autoFixDOM() {
|
||
enhanceVideoPlayerAccessibility();
|
||
injectAccessiblePlayerBar();
|
||
|
||
// Check if on 403 / unauthorized page and provide admin login button
|
||
var notAuthorizedEl = document.querySelector('my-not-found, .not-found, .forbidden, my-forbidden, .error-page');
|
||
if (notAuthorizedEl && !document.getElementById('yaktube-403-admin-btn')) {
|
||
var btn403 = document.createElement('div');
|
||
btn403.id = 'yaktube-403-admin-btn';
|
||
btn403.style.margin = '20px auto';
|
||
btn403.style.textAlign = 'center';
|
||
btn403.innerHTML =
|
||
'<button style="background:linear-gradient(135deg, #ff8f37 0%, #ff5e3a 100%); color:#fff; border:none; padding:12px 24px; border-radius:10px; font-weight:700; cursor:pointer; font-size:15px;">🔑 Sunucu Yöneticisi Olarak Giriş Yap (Alt+A)</button>';
|
||
btn403.querySelector('button').addEventListener('click', openLocalAdminLoginModal);
|
||
notAuthorizedEl.appendChild(btn403);
|
||
}
|
||
|
||
injectYakNetSSO();
|
||
|
||
// Check auth status for login button rendering
|
||
var tokenVal = localStorage.getItem('access_token');
|
||
var userVal = localStorage.getItem('username');
|
||
var isAlreadyAuth = !!tokenVal && !!userVal;
|
||
|
||
if (!isAlreadyAuth) {
|
||
// Replace all login buttons labels and titles ONLY for guests
|
||
document
|
||
.querySelectorAll(
|
||
'my-login-link, a[href*="/login"], a[title*="Giriş sayfasına git"], [aria-label*="Giriş sayfasına git"]'
|
||
)
|
||
.forEach(function (el) {
|
||
if (el.getAttribute('title') && el.getAttribute('title').includes('Giriş sayfasına git')) {
|
||
el.setAttribute('title', 'YakNet ile Giriş Yap');
|
||
}
|
||
if (el.getAttribute('aria-label') && el.getAttribute('aria-label').includes('Giriş sayfasına git')) {
|
||
el.setAttribute('aria-label', 'YakNet ile Giriş Yap');
|
||
}
|
||
var anchor = el.tagName.toLowerCase() === 'a' ? el : el.querySelector('a');
|
||
if (anchor) {
|
||
anchor.setAttribute('title', 'YakNet ile Giriş Yap');
|
||
anchor.setAttribute('aria-label', 'YakNet ile Giriş Yap');
|
||
var spans = anchor.querySelectorAll('span');
|
||
spans.forEach(function (s) {
|
||
if (
|
||
s.textContent.includes('Giriş sayfasına git') ||
|
||
s.textContent.trim() === 'Giriş' ||
|
||
s.textContent.trim() === 'Giriş yap'
|
||
) {
|
||
s.textContent = 'YakNet ile Giriş Yap';
|
||
}
|
||
});
|
||
}
|
||
});
|
||
}
|
||
|
||
// Aggressively remove generic Framasoft Open-in-App / Play Store banners
|
||
document
|
||
.querySelectorAll(
|
||
'.mobile-msg, [class*="mobile-msg"], button[title*="Bu mesajı kapat"], button[aria-label*="Bu mesajı kapat"]'
|
||
)
|
||
.forEach(function (m) {
|
||
m.remove();
|
||
});
|
||
var genericAppBanners = document.querySelectorAll(
|
||
'my-open-app, my-client-app-banner, .open-app-container, .app-banner, [class*="open-app"], [class*="open-in-app"], .mobile-app-banner, my-open-in-app, .app-promotion, a[href*="play.google.com/store/apps/details?id=app.joinpeertube"], a[href*="f-droid.org"]'
|
||
);
|
||
genericAppBanners.forEach(function (banner) {
|
||
banner.setAttribute('aria-hidden', 'true');
|
||
banner.setAttribute('tabindex', '-1');
|
||
if (banner.parentElement) {
|
||
try {
|
||
banner.remove();
|
||
} catch (e) {
|
||
banner.style.display = 'none';
|
||
}
|
||
}
|
||
});
|
||
|
||
// Replace leftover PeerTube branding in visible UI texts
|
||
var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false);
|
||
var node;
|
||
while ((node = walker.nextNode())) {
|
||
var val = node.nodeValue;
|
||
if (val && (val.includes('PeerTube') || val.includes('Peertube'))) {
|
||
var parentTag = node.parentElement ? node.parentElement.tagName : '';
|
||
var parentElem = node.parentElement;
|
||
if (
|
||
parentElem &&
|
||
(parentElem.closest('#yaktube-ondemand-container') ||
|
||
parentElem.closest('#yaktube-live-watch-container') ||
|
||
parentElem.tagName === 'SCRIPT' ||
|
||
parentElem.tagName === 'STYLE')
|
||
) {
|
||
continue;
|
||
}
|
||
if (true) {
|
||
node.nodeValue = val
|
||
.replace(/PeerTube hakkında/gi, 'YakTube Hakkında')
|
||
.replace(/PeerTube'a katılın/gi, "YakTube'a Katılın")
|
||
.replace(/PeerTube örneği/gi, 'YakTube Sunucusu')
|
||
.replace(/PeerTube/g, 'YakTube')
|
||
.replace(/Giriş sayfasına git/gi, 'YakNet ile Giriş Yap');
|
||
}
|
||
}
|
||
}
|
||
|
||
// Semantic Headings (H3 for video titles, H2 for sections)
|
||
document
|
||
.querySelectorAll('.video-miniature, my-video-miniature, .video-card, .yaktube-card, [class*="miniature"]')
|
||
.forEach(function (card) {
|
||
var titleElement = card.querySelector(
|
||
'.video-miniature-name, .video-name, .yaktube-video-name, a[title], .title'
|
||
);
|
||
if (titleElement) {
|
||
if (!['H1', 'H2', 'H3', 'H4', 'H5', 'H6'].includes(titleElement.tagName)) {
|
||
titleElement.setAttribute('role', 'heading');
|
||
titleElement.setAttribute('aria-level', '3');
|
||
}
|
||
}
|
||
});
|
||
|
||
document
|
||
.querySelectorAll('.section-title, .sub-header, .videos-header, .page-header, .yaktube-title-h3')
|
||
.forEach(function (sec) {
|
||
if (!['H1', 'H2'].includes(sec.tagName)) {
|
||
sec.setAttribute('role', 'heading');
|
||
sec.setAttribute('aria-level', '2');
|
||
}
|
||
});
|
||
|
||
// Make native PeerTube comment authors accessible as H3 headings for screen readers
|
||
document
|
||
.querySelectorAll('my-video-comment, .video-comment, my-video-comment-thread, .comment, .comment-thread')
|
||
.forEach(function (commentEl) {
|
||
var authorEl = commentEl.querySelector(
|
||
'.display-name, .actor-name, .comment-author, a.actor-link, .video-comment-header-left a, .video-comment-header-left span'
|
||
);
|
||
if (
|
||
authorEl &&
|
||
!['H1', 'H2', 'H3', 'H4', 'H5', 'H6'].includes(authorEl.tagName) &&
|
||
!authorEl.getAttribute('role')
|
||
) {
|
||
authorEl.setAttribute('role', 'heading');
|
||
authorEl.setAttribute('aria-level', '3');
|
||
}
|
||
});
|
||
|
||
// Auto-fix unlabeled buttons
|
||
document.querySelectorAll('button:not([data-a11y-fixed])').forEach(function (btn) {
|
||
btn.setAttribute('data-a11y-fixed', 'true');
|
||
var text = (btn.textContent || '').trim();
|
||
var hasAria = btn.getAttribute('aria-label') || btn.getAttribute('title');
|
||
|
||
if (!text && !hasAria) {
|
||
var html = btn.innerHTML.toLowerCase();
|
||
var className = (btn.className || '').toLowerCase();
|
||
var icon = btn.querySelector('my-global-icon, i, svg, [class*="icon-"]');
|
||
var iconName = icon ? icon.className || icon.getAttribute('name') || '' : '';
|
||
|
||
if (html.includes('search') || className.includes('search') || iconName.includes('search')) {
|
||
btn.setAttribute('aria-label', 'Ara');
|
||
} else if (html.includes('bell') || className.includes('notification') || iconName.includes('bell')) {
|
||
btn.setAttribute('aria-label', 'Bildirimler');
|
||
} else if (html.includes('cog') || html.includes('setting') || className.includes('setting')) {
|
||
btn.setAttribute('aria-label', 'Ayarlar');
|
||
} else if (
|
||
html.includes('menu') ||
|
||
html.includes('bars') ||
|
||
className.includes('burger') ||
|
||
className.includes('menu')
|
||
) {
|
||
btn.setAttribute('aria-label', 'Ana Gezinme Menüsü');
|
||
} else if (html.includes('play') || className.includes('play')) {
|
||
btn.setAttribute('aria-label', 'Oynat');
|
||
} else if (html.includes('pause') || className.includes('pause')) {
|
||
btn.setAttribute('aria-label', 'Duraklat');
|
||
} else if (html.includes('volume') || html.includes('mute') || className.includes('volume')) {
|
||
btn.setAttribute('aria-label', 'Ses Kontrolü');
|
||
} else if (html.includes('fullscreen') || className.includes('fullscreen')) {
|
||
btn.setAttribute('aria-label', 'Tam Ekran');
|
||
} else if (
|
||
html.includes('ellipsis') ||
|
||
html.includes('more') ||
|
||
className.includes('more') ||
|
||
className.includes('action')
|
||
) {
|
||
btn.setAttribute('aria-label', 'Diğer İşlemler ve Seçenekler');
|
||
} else if (html.includes('trash') || html.includes('delete') || className.includes('delete')) {
|
||
btn.setAttribute('aria-label', 'Sil');
|
||
} else if (html.includes('edit') || className.includes('edit')) {
|
||
btn.setAttribute('aria-label', 'Düzenle');
|
||
} else if (html.includes('share') || className.includes('share')) {
|
||
btn.setAttribute('aria-label', 'Paylaş');
|
||
} else if (html.includes('thumb-up') || html.includes('like') || className.includes('like')) {
|
||
btn.setAttribute('aria-label', 'Beğen');
|
||
} else if (html.includes('thumb-down') || html.includes('dislike') || className.includes('dislike')) {
|
||
btn.setAttribute('aria-label', 'Beğenme');
|
||
} else if (html.includes('filter') || className.includes('filter')) {
|
||
btn.setAttribute('aria-label', 'Filtreler');
|
||
} else if (html.includes('close') || html.includes('times') || className.includes('close')) {
|
||
btn.setAttribute('aria-label', 'Kapat');
|
||
} else if (btn.closest('.vjs-control-bar')) {
|
||
btn.setAttribute('aria-label', 'Oynatıcı Düğmesi');
|
||
} else {
|
||
var parent = btn.parentElement;
|
||
if (parent && parent.title) {
|
||
btn.setAttribute('aria-label', parent.title);
|
||
} else {
|
||
btn.setAttribute('aria-label', 'Düğme');
|
||
}
|
||
}
|
||
}
|
||
});
|
||
|
||
// Auto-fix unlabeled images
|
||
document.querySelectorAll('img:not([data-a11y-fixed])').forEach(function (img) {
|
||
img.setAttribute('data-a11y-fixed', 'true');
|
||
var alt = img.getAttribute('alt');
|
||
if (!alt || alt.trim() === '') {
|
||
var card = img.closest('.video-miniature, .video-card, .yaktube-card, [class*="miniature"]');
|
||
if (card) {
|
||
var titleEl = card.querySelector(
|
||
'.video-miniature-name, .video-name, .yaktube-video-name, h3, h4, a[title]'
|
||
);
|
||
var titleText = titleEl ? (titleEl.textContent || titleEl.getAttribute('title') || '').trim() : '';
|
||
if (titleText) {
|
||
img.setAttribute('alt', titleText + ' video kapağı');
|
||
return;
|
||
}
|
||
}
|
||
|
||
var avatarContainer = img.closest('.actor-avatar, .channel-avatar, .avatar, [class*="avatar"]');
|
||
if (avatarContainer) {
|
||
var nameEl = avatarContainer.parentElement
|
||
? avatarContainer.parentElement.querySelector('.name, .actor-name, .channel-name')
|
||
: null;
|
||
var nameText = nameEl ? (nameEl.textContent || '').trim() : '';
|
||
img.setAttribute('alt', (nameText ? nameText + ' ' : '') + 'Profil Resmi');
|
||
return;
|
||
}
|
||
|
||
var parentLink = img.closest('a');
|
||
if (parentLink && parentLink.textContent && parentLink.textContent.trim().length > 0) {
|
||
img.setAttribute('alt', '');
|
||
return;
|
||
}
|
||
|
||
if (img.src && (img.src.includes('logo') || img.className.includes('logo'))) {
|
||
img.setAttribute('alt', getInstanceName());
|
||
return;
|
||
}
|
||
|
||
if (parentLink && parentLink.getAttribute('title')) {
|
||
img.setAttribute('alt', parentLink.getAttribute('title'));
|
||
} else {
|
||
img.setAttribute('alt', 'Görsel');
|
||
}
|
||
}
|
||
});
|
||
|
||
// Auto-fix unlabeled links
|
||
document.querySelectorAll('a:not([data-a11y-fixed])').forEach(function (a) {
|
||
a.setAttribute('data-a11y-fixed', 'true');
|
||
var text = (a.textContent || '').trim();
|
||
var hasAria = a.getAttribute('aria-label') || a.getAttribute('title');
|
||
if (!text && !hasAria) {
|
||
var img = a.querySelector('img');
|
||
if (img && img.alt) {
|
||
a.setAttribute('aria-label', img.alt);
|
||
} else if (a.href) {
|
||
if (a.href.includes('/videos/watch/')) {
|
||
a.setAttribute('aria-label', 'Videoyu İzle');
|
||
} else if (a.href.includes('/video-channels/')) {
|
||
a.setAttribute('aria-label', 'Kanal Sayfasına Git');
|
||
} else if (a.href.includes('/accounts/')) {
|
||
a.setAttribute('aria-label', 'Hesap Profiline Git');
|
||
} else if (a.href.includes('/videos/search')) {
|
||
a.setAttribute('aria-label', 'Arama Sayfası');
|
||
} else {
|
||
a.setAttribute('aria-label', 'Bağlantı');
|
||
}
|
||
}
|
||
}
|
||
});
|
||
|
||
// Auto-fix search inputs
|
||
document.querySelectorAll('input:not([data-a11y-fixed])').forEach(function (inp) {
|
||
inp.setAttribute('data-a11y-fixed', 'true');
|
||
if (!inp.getAttribute('aria-label') && !inp.getAttribute('placeholder') && !(inp.labels && inp.labels.length)) {
|
||
var type = (inp.getAttribute('type') || 'text').toLowerCase();
|
||
if (type === 'search') {
|
||
inp.setAttribute('aria-label', getInstanceName() + ' Video Arama');
|
||
} else if (type === 'checkbox') {
|
||
inp.setAttribute('aria-label', 'Seçim Kutusu');
|
||
} else if (type === 'password') {
|
||
inp.setAttribute('aria-label', 'Şifre');
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
// 3. Screen-Reader & Turkish Q Optimized Shortcuts & Player Bar (v1.4.1)
|
||
// YakTube NLnet WCAG 2.2 AAA & Privacy Suite Modules
|
||
|
||
// ============================================================================
|
||
// 1. WCAG 2.2 AAA Focus Trap & Modal Management
|
||
// ============================================================================
|
||
var lastActiveElementBeforeModal = null;
|
||
|
||
function trapFocusInModal(modalEl) {
|
||
if (!modalEl) return;
|
||
var focusableElements = modalEl.querySelectorAll(
|
||
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
|
||
);
|
||
if (!focusableElements.length) return;
|
||
var firstFocusable = focusableElements[0];
|
||
var lastFocusable = focusableElements[focusableElements.length - 1];
|
||
|
||
function handleKeydown(e) {
|
||
if (e.key !== 'Tab') return;
|
||
if (e.shiftKey) {
|
||
if (document.activeElement === firstFocusable) {
|
||
e.preventDefault();
|
||
lastFocusable.focus();
|
||
}
|
||
} else {
|
||
if (document.activeElement === lastFocusable) {
|
||
e.preventDefault();
|
||
firstFocusable.focus();
|
||
}
|
||
}
|
||
}
|
||
|
||
modalEl.removeEventListener('keydown', modalEl._trapHandler);
|
||
modalEl._trapHandler = handleKeydown;
|
||
modalEl.addEventListener('keydown', handleKeydown);
|
||
setTimeout(function () {
|
||
firstFocusable.focus();
|
||
}, 50);
|
||
}
|
||
|
||
function recordFocusBeforeModal() {
|
||
lastActiveElementBeforeModal = document.activeElement;
|
||
}
|
||
|
||
function restoreFocusAfterModal() {
|
||
if (lastActiveElementBeforeModal && typeof lastActiveElementBeforeModal.focus === 'function') {
|
||
try {
|
||
lastActiveElementBeforeModal.focus();
|
||
} catch (e) {}
|
||
}
|
||
}
|
||
|
||
// ============================================================================
|
||
// 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 (
|
||
'<button type="button" class="yaktube-studio-preset-btn ' +
|
||
(isAct ? 'active' : '') +
|
||
'" data-preset="' +
|
||
key +
|
||
'" aria-pressed="' +
|
||
(isAct ? 'true' : 'false') +
|
||
'">' +
|
||
p.label +
|
||
'</button>'
|
||
);
|
||
})
|
||
.join('');
|
||
|
||
modal.innerHTML =
|
||
'<div class="yaktube-feature-modal yaktube-studio-modal">' +
|
||
'<div class="yaktube-feature-modal-header">' +
|
||
'<h3 id="yaktube-studio-title">🎛️ Canlı Ses Stüdyosu (EQ & %300 Güçlendirme)</h3>' +
|
||
'<button type="button" id="yaktube-studio-close" class="yaktube-voice-modal-close-btn" aria-label="Ses Stüdyosunu kapat">✕</button>' +
|
||
'</div>' +
|
||
(!dspSupported
|
||
? '<div class="yaktube-studio-warn" role="status">ℹ️ 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.</div>'
|
||
: '') +
|
||
'<canvas id="yaktube-studio-spectrum" width="440" height="68" class="yaktube-studio-spectrum" aria-label="Canlı ses frekans görselleştiricisi"></canvas>' +
|
||
'<div class="yaktube-studio-presets" role="group" aria-label="Hazır ses profilleri">' +
|
||
presetsHtml +
|
||
'</div>' +
|
||
'<div class="yaktube-studio-sliders">' +
|
||
'<label class="yaktube-studio-row"><span>🔊 Ses Gücü: <strong id="yaktube-studio-gain-val">%' +
|
||
Math.round(cfg.gain || 100) +
|
||
'</strong></span>' +
|
||
'<input id="yaktube-studio-gain" type="range" min="50" max="300" step="5" value="' +
|
||
Math.round(cfg.gain || 100) +
|
||
'" aria-label="Ses gücü yüzde" ' +
|
||
(dspSupported ? '' : 'disabled') +
|
||
' /></label>' +
|
||
'<label class="yaktube-studio-row"><span>🥁 Bas (110 Hz): <strong id="yaktube-studio-bass-val">' +
|
||
Number(cfg.bass || 0) +
|
||
' dB</strong></span>' +
|
||
'<input id="yaktube-studio-bass" type="range" min="-12" max="12" step="0.5" value="' +
|
||
Number(cfg.bass || 0) +
|
||
'" aria-label="Bas seviyesi desibel" ' +
|
||
(dspSupported ? '' : 'disabled') +
|
||
' /></label>' +
|
||
'<label class="yaktube-studio-row"><span>🗣️ Konuşma Netliği (2.2 kHz): <strong id="yaktube-studio-voice-val">' +
|
||
Number(cfg.voice || 0) +
|
||
' dB</strong></span>' +
|
||
'<input id="yaktube-studio-voice" type="range" min="-12" max="12" step="0.5" value="' +
|
||
Number(cfg.voice || 0) +
|
||
'" aria-label="Konuşma netliği desibel" ' +
|
||
(dspSupported ? '' : 'disabled') +
|
||
' /></label>' +
|
||
'<label class="yaktube-studio-row"><span>✨ Tiz (7.5 kHz): <strong id="yaktube-studio-treble-val">' +
|
||
Number(cfg.treble || 0) +
|
||
' dB</strong></span>' +
|
||
'<input id="yaktube-studio-treble" type="range" min="-12" max="12" step="0.5" value="' +
|
||
Number(cfg.treble || 0) +
|
||
'" aria-label="Tiz seviyesi desibel" ' +
|
||
(dspSupported ? '' : 'disabled') +
|
||
' /></label>' +
|
||
'</div>' +
|
||
'<div class="yaktube-studio-footer">' +
|
||
'<label class="yaktube-studio-check"><input type="checkbox" id="yaktube-studio-night" ' +
|
||
(cfg.night ? 'checked ' : '') +
|
||
(dspSupported ? '' : 'disabled') +
|
||
'/> Gece Modu (Yüksek sesleri yumuşat, fısıltıları yükselt)</label>' +
|
||
'<button type="button" id="yaktube-studio-reset" class="yaktube-audio-action-btn">↺ Sıfırla</button>' +
|
||
'</div>' +
|
||
'</div>';
|
||
|
||
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 =
|
||
'<span>🔂 ' +
|
||
(abLoopState.active
|
||
? 'Döngü Aktif: <b>' +
|
||
formatClockShort(abLoopState.a) +
|
||
'</b> ⇄ <b>' +
|
||
formatClockShort(abLoopState.b) +
|
||
'</b>'
|
||
: 'Başlangıç A: <b>' + formatClockShort(abLoopState.a) + '</b> (B için tekrar Alt+B)') +
|
||
'</span>' +
|
||
'<button type="button" id="yaktube-ab-clear-btn" class="yaktube-ab-clear-btn" aria-label="A-B döngüsünü iptal et">✕ Kapat</button>';
|
||
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 {
|
||
if ('wakeLock' in navigator) {
|
||
wakeLockSentinel = await navigator.wakeLock.request('screen');
|
||
wakeLockSentinel.addEventListener('release', function () {
|
||
wakeLockSentinel = null;
|
||
});
|
||
}
|
||
} catch (err) {
|
||
console.warn('[YakTube] WakeLock error:', err);
|
||
}
|
||
}
|
||
|
||
function releaseScreenWakeLock() {
|
||
if (wakeLockSentinel) {
|
||
wakeLockSentinel.release().catch(function () {});
|
||
wakeLockSentinel = null;
|
||
}
|
||
}
|
||
|
||
function toggleAudioOnlyMode() {
|
||
var video = getVideoElement();
|
||
if (!video) {
|
||
announce('Aktif video bulunamadı.');
|
||
return;
|
||
}
|
||
|
||
isAudioOnlyMode = !isAudioOnlyMode;
|
||
document.body.classList.toggle('yaktube-audio-only-active', isAudioOnlyMode);
|
||
|
||
var overlay = document.getElementById('yaktube-audio-blank-overlay');
|
||
var audioBtn = document.getElementById('yaktube-bar-audio-btn');
|
||
|
||
if (isAudioOnlyMode) {
|
||
if (!overlay) {
|
||
overlay = document.createElement('div');
|
||
overlay.id = 'yaktube-audio-blank-overlay';
|
||
overlay.className = 'yaktube-audio-blank-overlay';
|
||
overlay.setAttribute('role', 'region');
|
||
overlay.setAttribute('aria-label', 'Yalnızca Ses ve Ekran Karartma Modu');
|
||
overlay.innerHTML =
|
||
'<div class="yaktube-audio-blank-content">' +
|
||
'<div style="font-size:48px; margin-bottom:12px;">📻</div>' +
|
||
'<h3 style="margin:0 0 8px 0; font-size:20px; font-weight:700; color:#ff8f37;">Yalnızca Ses Modu Aktif</h3>' +
|
||
'<p style="margin:0 0 12px 0; font-size:14px; color:#aaa; max-width:380px;">Ekran pil ve veri tasarrufu için karartıldı. Arka planda çalma ve canlı spektrum desteklenir.</p>' +
|
||
'<canvas id="yaktube-audio-blank-canvas" width="360" height="58" class="yaktube-studio-spectrum" aria-label="Canlı ses dalgası"></canvas>' +
|
||
'<div style="display:flex; gap:12px; justify-content:center; flex-wrap:wrap; margin-top:14px;">' +
|
||
'<button id="yaktube-exit-audio-btn" class="yaktube-audio-action-btn" aria-label="Görüntüyü Aç ve Ses Modundan Çık">🎬 Görüntüyü Aç (Alt+O)</button>' +
|
||
'<button id="yaktube-toggle-play-audio-btn" class="yaktube-audio-action-btn" aria-label="Oynat veya Duraklat">⏯️ Oynat / Duraklat (Boşluk)</button>' +
|
||
'<button id="yaktube-blank-studio-btn" class="yaktube-audio-action-btn" aria-label="Canlı Ses Stüdyosunu Aç (Alt+E)">🎛️ Ses Stüdyosu</button>' +
|
||
'</div>' +
|
||
'</div>';
|
||
|
||
var exitBtn = overlay.querySelector('#yaktube-exit-audio-btn');
|
||
if (exitBtn) {
|
||
exitBtn.addEventListener('click', toggleAudioOnlyMode);
|
||
}
|
||
var togglePlayBtn = overlay.querySelector('#yaktube-toggle-play-audio-btn');
|
||
if (togglePlayBtn) {
|
||
togglePlayBtn.addEventListener('click', function () {
|
||
var v = getVideoElement();
|
||
if (v) {
|
||
if (v.paused) v.play();
|
||
else v.pause();
|
||
}
|
||
});
|
||
}
|
||
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');
|
||
audioBtn.setAttribute('aria-pressed', 'true');
|
||
}
|
||
announce(
|
||
'Yalnızca ses modu açıldı. Ekran karartıldı, pil ve veri tasarrufu aktif. Çıkmak için Alt+O tuşuna basın.'
|
||
);
|
||
showQuickToast('📻 Yalnızca Ses Modu Açık');
|
||
} else {
|
||
stopSpectrumLoop();
|
||
if (overlay) overlay.style.display = 'none';
|
||
releaseScreenWakeLock();
|
||
if (audioBtn) {
|
||
audioBtn.classList.remove('active');
|
||
audioBtn.setAttribute('aria-pressed', 'false');
|
||
}
|
||
announce('Yalnızca ses modu kapatıldı. Görüntü normale döndü.');
|
||
showQuickToast('🎬 Normal Görüntü Modu');
|
||
}
|
||
}
|
||
|
||
// ============================================================================
|
||
// 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 [];
|
||
|
||
var cuesList = [];
|
||
for (var i = 0; i < video.textTracks.length; i++) {
|
||
var track = video.textTracks[i];
|
||
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: txt
|
||
});
|
||
}
|
||
break;
|
||
}
|
||
}
|
||
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 +=
|
||
'<button type="button" class="yaktube-transcript-lang-btn ' +
|
||
(isSel ? 'active' : '') +
|
||
'" data-lang="' +
|
||
escapeHtml(l.code) +
|
||
'">' +
|
||
escapeHtml(l.name || l.code) +
|
||
(l.auto ? ' (Oto)' : '') +
|
||
'</button>';
|
||
});
|
||
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 =
|
||
'<div class="yaktube-chapters-title">📑 Video Bölümleri:</div><div class="yaktube-chapters-row">';
|
||
chapters.forEach(function (ch) {
|
||
var chStart = Number(ch.start || 0);
|
||
chHtml +=
|
||
'<button type="button" class="yaktube-chapter-chip" data-start="' +
|
||
chStart +
|
||
'" aria-label="Bölüm ' +
|
||
escapeHtml(formatClockShort(chStart) + ' ' + ch.title) +
|
||
'">' +
|
||
'<span class="yaktube-chapter-time">' +
|
||
escapeHtml(formatClockShort(chStart)) +
|
||
'</span> ' +
|
||
escapeHtml(ch.title) +
|
||
'</button>';
|
||
});
|
||
chHtml += '</div>';
|
||
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 +=
|
||
'<li class="yaktube-transcript-item ' +
|
||
(isActive ? 'active' : '') +
|
||
'" data-start="' +
|
||
c.startTime +
|
||
'" tabindex="0" role="button" aria-label="' +
|
||
escapeHtml(formatClockShort(c.startTime) + ': ' + c.text) +
|
||
'">' +
|
||
'<span class="yaktube-transcript-time">' +
|
||
escapeHtml(formatClockShort(c.startTime)) +
|
||
'</span>' +
|
||
'<span class="yaktube-transcript-text">' +
|
||
escapeHtml(c.text) +
|
||
'</span>' +
|
||
'</li>';
|
||
});
|
||
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 =
|
||
'<li class="yaktube-transcript-empty" style="padding:20px; text-align:center; color:#94a3b8; list-style:none;">' +
|
||
'<p style="font-size:14px; margin:0 0 6px 0;">📄 Bu video için altyazı veya transkript metni bulunamadı.</p>' +
|
||
(chapters.length > 0
|
||
? '<p style="font-size:12px; color:#ff8f37; margin:0;">Yukarıdaki 📑 Bölüm zaman damgalarından videonun kısımlarına doğrudan atlayabilirsiniz.</p>'
|
||
: '<p style="font-size:12px; color:#64748b; margin:0;">Video kaynağı veya YouTube tarafında herkese açık altyazı bulunmuyor.</p>') +
|
||
'</li>';
|
||
}
|
||
}
|
||
|
||
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) {
|
||
existing.remove();
|
||
isTranscriptPanelOpen = false;
|
||
restoreFocusAfterModal();
|
||
announce('Transkript paneli kapatıldı.');
|
||
return;
|
||
}
|
||
|
||
recordFocusBeforeModal();
|
||
isTranscriptPanelOpen = true;
|
||
|
||
var cues = extractVideoCaptions();
|
||
|
||
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 Bölümler Paneli');
|
||
|
||
panel.innerHTML =
|
||
'<div class="yaktube-transcript-header">' +
|
||
'<div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap;">' +
|
||
'<span style="font-size:18px;">📜</span>' +
|
||
'<h3 style="margin:0; font-size:16px; font-weight:700; color:#ff8f37;">Akıllı Transkript & Bölümler</h3>' +
|
||
'<span id="yaktube-transcript-meta" style="font-size:12px; color:#94a3b8;"></span>' +
|
||
'</div>' +
|
||
'<div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap;">' +
|
||
'<input type="text" id="yaktube-transcript-search" class="yaktube-transcript-search" placeholder="Transkriptte ara..." aria-label="Transkript içinde kelime ara" />' +
|
||
'<button type="button" id="yaktube-transcript-copy" class="yaktube-audio-action-btn" style="padding:6px 10px; font-size:12px;" aria-label="Tüm transkripti panoya kopyala">📋 Kopyala</button>' +
|
||
'<button type="button" id="yaktube-transcript-close" class="yaktube-voice-modal-close-btn" aria-label="Transkript panelini kapat">✕</button>' +
|
||
'</div>' +
|
||
'</div>' +
|
||
'<div id="yaktube-transcript-langs" class="yaktube-transcript-langs" style="display:none;"></div>' +
|
||
'<div id="yaktube-transcript-chapters" class="yaktube-transcript-chapters" style="display:none;"></div>' +
|
||
'<div id="yaktube-transcript-loading" class="yaktube-transcript-loading" style="display:none;"></div>' +
|
||
'<ul id="yaktube-transcript-list" class="yaktube-transcript-list" role="list"></ul>';
|
||
|
||
var closeBtn = panel.querySelector('#yaktube-transcript-close');
|
||
if (closeBtn) {
|
||
closeBtn.addEventListener('click', function () {
|
||
panel.remove();
|
||
isTranscriptPanelOpen = false;
|
||
restoreFocusAfterModal();
|
||
announce('Transkript paneli kapatıldı.');
|
||
});
|
||
}
|
||
|
||
var copyBtn = panel.querySelector('#yaktube-transcript-copy');
|
||
if (copyBtn) {
|
||
copyBtn.addEventListener('click', function () {
|
||
if (!liveTranscriptCues || !liveTranscriptCues.length) {
|
||
showQuickToast('⚠️ Kopyalanacak transkript yok');
|
||
return;
|
||
}
|
||
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
|
||
var searchInp = panel.querySelector('#yaktube-transcript-search');
|
||
if (searchInp) {
|
||
searchInp.addEventListener('input', function (e) {
|
||
var query = (e.target.value || '').toLowerCase().trim();
|
||
panel.querySelectorAll('.yaktube-transcript-item').forEach(function (item) {
|
||
var txtEl = item.querySelector('.yaktube-transcript-text');
|
||
var txt = ((txtEl && txtEl.textContent) || '').toLowerCase();
|
||
item.style.display = txt.includes(query) ? 'flex' : 'none';
|
||
});
|
||
});
|
||
}
|
||
|
||
var targetWrap = document.querySelector(
|
||
'#video-wrapper, #videojs-wrapper, .player-container, my-video-watch .player'
|
||
);
|
||
if (targetWrap && targetWrap.parentNode) {
|
||
targetWrap.parentNode.insertBefore(panel, targetWrap.nextSibling);
|
||
} else {
|
||
document.body.appendChild(panel);
|
||
}
|
||
|
||
loadServerTranscriptForPanel(panel, '');
|
||
trapFocusInModal(panel);
|
||
announce(
|
||
'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 =
|
||
'<div style="padding:28px 16px; text-align:center; color:#94a3b8;">' +
|
||
'<div style="font-size:34px; margin-bottom:8px;">📋</div>' +
|
||
'<p style="margin:0 0 6px 0; font-size:15px; color:#e2e8f0; font-weight:700;">Çalma sıranız şu an boş</p>' +
|
||
'<p style="margin:0; font-size:13px;">Arama sonuçlarındaki veya önerilen videolardaki <b>+ Sıraya Ekle</b> butonuna basarak arka arkaya oynatılacak kendi listenizi oluşturabilirsiniz.</p>' +
|
||
'</div>';
|
||
} else {
|
||
bodyHtml = '<ol class="yaktube-queue-list">';
|
||
queue.forEach(function (q, idx) {
|
||
bodyHtml +=
|
||
'<li class="yaktube-queue-item">' +
|
||
'<span class="yaktube-queue-num">' +
|
||
(idx + 1) +
|
||
'</span>' +
|
||
'<img src="' +
|
||
escapeHtml(q.thumbnail || '/client/assets/images/default-thumbnail.jpg') +
|
||
'" alt="" class="yaktube-queue-thumb" onerror="this.src=\'/client/assets/images/default-thumbnail.jpg\'" />' +
|
||
'<div class="yaktube-queue-meta">' +
|
||
'<div class="yaktube-queue-item-title">' +
|
||
escapeHtml(q.title) +
|
||
'</div>' +
|
||
'<div class="yaktube-queue-item-sub">' +
|
||
escapeHtml(q.channel || '') +
|
||
(q.durationFormatted ? ' • ' + escapeHtml(q.durationFormatted) : '') +
|
||
(q.localUrl || q.uuid ? ' • ✅ Hazır' : ' • 📥 İndirilecek') +
|
||
'</div>' +
|
||
'</div>' +
|
||
'<div class="yaktube-queue-item-actions">' +
|
||
'<button type="button" class="yaktube-queue-act-btn yaktube-queue-play-one" data-idx="' +
|
||
idx +
|
||
'" aria-label="Sıradaki ' +
|
||
escapeHtml(q.title) +
|
||
' videosunu hemen oynat">▶️</button>' +
|
||
(idx > 0
|
||
? '<button type="button" class="yaktube-queue-act-btn yaktube-queue-up" data-idx="' +
|
||
idx +
|
||
'" aria-label="Yukarı taşı">⬆️</button>'
|
||
: '') +
|
||
(idx < queue.length - 1
|
||
? '<button type="button" class="yaktube-queue-act-btn yaktube-queue-down" data-idx="' +
|
||
idx +
|
||
'" aria-label="Aşağı taşı">⬇️</button>'
|
||
: '') +
|
||
'<button type="button" class="yaktube-queue-act-btn yaktube-queue-del" data-idx="' +
|
||
idx +
|
||
'" aria-label="Sıradan çıkar">🗑️</button>' +
|
||
'</div>' +
|
||
'</li>';
|
||
});
|
||
bodyHtml += '</ol>';
|
||
}
|
||
|
||
modal.innerHTML =
|
||
'<div class="yaktube-feature-modal yaktube-queue-modal">' +
|
||
'<div class="yaktube-feature-modal-header">' +
|
||
'<h3 id="yaktube-queue-title">📋 Kişisel Çalma Sırası (' +
|
||
queue.length +
|
||
')</h3>' +
|
||
'<button type="button" id="yaktube-queue-close" class="yaktube-voice-modal-close-btn" aria-label="Çalma sırasını kapat">✕</button>' +
|
||
'</div>' +
|
||
'<div class="yaktube-queue-scroll">' +
|
||
bodyHtml +
|
||
'</div>' +
|
||
'<div class="yaktube-studio-footer">' +
|
||
'<button type="button" id="yaktube-queue-play-next" class="yaktube-audio-action-btn" ' +
|
||
(queue.length ? '' : 'disabled') +
|
||
'>⏭️ İlkini Hemen Oynat</button>' +
|
||
'<button type="button" id="yaktube-queue-clear" class="yaktube-audio-action-btn" ' +
|
||
(queue.length ? '' : 'disabled') +
|
||
'>🧹 Listeyi Temizle</button>' +
|
||
'</div>' +
|
||
'</div>';
|
||
|
||
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;
|
||
var video = getVideoElement();
|
||
if (!video) return;
|
||
var curTime = video.currentTime;
|
||
var panel = document.getElementById('yaktube-transcript-panel');
|
||
if (!panel) return;
|
||
|
||
var items = panel.querySelectorAll('.yaktube-transcript-item');
|
||
var bestItem = null;
|
||
items.forEach(function (item) {
|
||
var start = parseFloat(item.getAttribute('data-start'));
|
||
if (!isNaN(start) && start <= curTime + 0.5) {
|
||
bestItem = item;
|
||
}
|
||
});
|
||
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)
|
||
// ============================================================================
|
||
function openCleanShareModal() {
|
||
var existing = document.getElementById('yaktube-clean-share-modal');
|
||
if (existing) existing.remove();
|
||
|
||
recordFocusBeforeModal();
|
||
|
||
var video = getVideoElement();
|
||
var curSec = video ? Math.floor(video.currentTime) : 0;
|
||
var cleanUrl = window.location.origin + window.location.pathname;
|
||
var timestampUrl = cleanUrl + '?start=' + curSec + 's';
|
||
|
||
var titleEl = document.querySelector('h1.video-title, my-video-watch h1, .video-name, .title');
|
||
var videoTitle = titleEl ? titleEl.textContent.trim() : document.title;
|
||
|
||
var modal = document.createElement('div');
|
||
modal.id = 'yaktube-clean-share-modal';
|
||
modal.className = 'yaktube-feature-modal-backdrop';
|
||
modal.setAttribute('role', 'dialog');
|
||
modal.setAttribute('aria-modal', 'true');
|
||
modal.setAttribute('aria-labelledby', 'yaktube-share-title');
|
||
|
||
modal.innerHTML =
|
||
'<div class="yaktube-modal-card" style="max-width:480px; background:#181824; border:1px solid rgba(255,143,55,0.4); border-radius:18px; padding:24px; color:#fff; box-shadow:0 16px 40px rgba(0,0,0,0.8);">' +
|
||
'<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:16px;">' +
|
||
'<h3 id="yaktube-share-title" style="margin:0; font-size:18px; color:#ff8f37;">🔗 Temiz ve Federe Paylaşım</h3>' +
|
||
'<button id="yaktube-share-close" class="yaktube-voice-modal-close-btn" aria-label="Kapat">✕</button>' +
|
||
'</div>' +
|
||
'<p style="font-size:13px; color:#aaa; margin-bottom:16px;">Tüm reklam ve izleyici parametrelerinden arındırılmış temiz YakTube bağlantısı:</p>' +
|
||
'<div style="display:flex; flex-direction:column; gap:12px;">' +
|
||
'<div style="display:flex; align-items:center; gap:8px;">' +
|
||
'<input type="checkbox" id="yaktube-share-timestamp-chk" style="width:18px; height:18px; accent-color:#ff8f37; cursor:pointer;" />' +
|
||
'<label for="yaktube-share-timestamp-chk" style="font-size:14px; cursor:pointer;">Şu anki zamandan başlat (<b>' +
|
||
formatTime(curSec) +
|
||
'</b>)</label>' +
|
||
'</div>' +
|
||
'<div style="display:flex; gap:8px;">' +
|
||
'<input type="text" id="yaktube-share-url-inp" value="' +
|
||
cleanUrl +
|
||
'" readonly style="flex:1; background:#22222e; border:1px solid #444; border-radius:8px; padding:10px 12px; color:#fff; font-size:13px;" aria-label="Paylaşım Bağlantısı" />' +
|
||
'<button id="yaktube-copy-share-btn" class="yaktube-play-btn" style="padding:10px 16px; white-space:nowrap;" aria-label="Bağlantıyı Panoya Kopyala">📋 Kopyala</button>' +
|
||
'</div>' +
|
||
'<div style="margin-top:8px; display:flex; gap:8px; flex-wrap:wrap;">' +
|
||
'<a id="yaktube-mastodon-share" target="_blank" rel="noopener noreferrer" class="yaktube-player-action-btn" style="text-decoration:none; display:inline-flex; align-items:center; gap:6px;">🐘 Mastodon / Fediverse</a>' +
|
||
'<a id="yaktube-whatsapp-share" target="_blank" rel="noopener noreferrer" class="yaktube-player-action-btn" style="text-decoration:none; display:inline-flex; align-items:center; gap:6px;">💬 WhatsApp</a>' +
|
||
'</div>' +
|
||
'</div>' +
|
||
'</div>';
|
||
|
||
var closeBtn = modal.querySelector('#yaktube-share-close');
|
||
if (closeBtn) {
|
||
closeBtn.addEventListener('click', function () {
|
||
modal.remove();
|
||
restoreFocusAfterModal();
|
||
});
|
||
}
|
||
|
||
var chk = modal.querySelector('#yaktube-share-timestamp-chk');
|
||
var inp = modal.querySelector('#yaktube-share-url-inp');
|
||
var mastodonLink = modal.querySelector('#yaktube-mastodon-share');
|
||
var waLink = modal.querySelector('#yaktube-whatsapp-share');
|
||
|
||
function updateShareLinks() {
|
||
var finalUrl = chk.checked ? timestampUrl : cleanUrl;
|
||
inp.value = finalUrl;
|
||
var shareText = encodeURIComponent(videoTitle + ' - YakTube: ' + finalUrl);
|
||
if (mastodonLink) mastodonLink.href = 'https://mastodonshare.com/?text=' + shareText;
|
||
if (waLink) waLink.href = 'https://api.whatsapp.com/send?text=' + shareText;
|
||
}
|
||
chk.addEventListener('change', updateShareLinks);
|
||
updateShareLinks();
|
||
|
||
modal.querySelector('#yaktube-copy-share-btn').addEventListener('click', function () {
|
||
inp.select();
|
||
navigator.clipboard
|
||
.writeText(inp.value)
|
||
.then(function () {
|
||
announce('Temiz paylaşım bağlantısı panoya kopyalandı.');
|
||
showQuickToast('📋 Bağlantı Kopyalandı!');
|
||
})
|
||
.catch(function () {
|
||
document.execCommand('copy');
|
||
announce('Temiz paylaşım bağlantısı kopyalandı.');
|
||
});
|
||
});
|
||
|
||
document.body.appendChild(modal);
|
||
trapFocusInModal(modal);
|
||
announce('Paylaşım penceresi açıldı. Kapatmak için Escape tuşuna basın.');
|
||
}
|
||
|
||
// ============================================================================
|
||
// 5. F6 Landmark Cycle Navigation (WCAG 2.2 AAA Quick Switch)
|
||
// ============================================================================
|
||
var landmarkIndex = 0;
|
||
function cycleLandmarks(reverse) {
|
||
var landmarks = [
|
||
{ name: 'Başlık ve Ana Arama', selector: 'header, my-header, #yaktube-search-input' },
|
||
{ name: 'Kategori Çipleri', selector: '#yaktube-home-categories, .yaktube-categories-bar' },
|
||
{ name: 'Video Oynatıcı Alanı', selector: '#videojs-wrapper, .video-js, #video-wrapper' },
|
||
{ name: 'Video Araç Çubuğu', selector: '#yaktube-player-action-bar' },
|
||
{ name: 'Video Açıklaması ve Bilgiler', selector: 'my-video-watch-description, .video-info, .video-bottom' },
|
||
{ name: 'Yorumlar ve Tartışmalar', selector: 'my-video-comments, .comments' },
|
||
{ name: 'Önerilen Videolar', selector: 'my-video-watch-related, .related-videos, #yaktube-ondemand-container' }
|
||
];
|
||
|
||
var validLandmarks = landmarks
|
||
.map(function (item) {
|
||
return { name: item.name, el: document.querySelector(item.selector) };
|
||
})
|
||
.filter(function (item) {
|
||
return !!item.el && item.el.offsetParent !== null;
|
||
});
|
||
|
||
if (!validLandmarks.length) {
|
||
announce('Sayfada gezinilebilir alan bulunamadı.');
|
||
return;
|
||
}
|
||
|
||
if (reverse) {
|
||
landmarkIndex = (landmarkIndex - 1 + validLandmarks.length) % validLandmarks.length;
|
||
} else {
|
||
landmarkIndex = (landmarkIndex + 1) % validLandmarks.length;
|
||
}
|
||
|
||
var target = validLandmarks[landmarkIndex];
|
||
if (target && target.el) {
|
||
target.el.setAttribute('tabindex', '-1');
|
||
target.el.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||
target.el.focus();
|
||
announce('Bölgeye atlandı: ' + target.name);
|
||
showQuickToast('🎯 ' + target.name);
|
||
}
|
||
}
|
||
|
||
function toggleShortcutsModal() {
|
||
var modal = document.getElementById('yaktube-shortcuts-dialog');
|
||
if (modal) {
|
||
if (modal.style.display === 'none' || !modal.style.display) {
|
||
modal.style.display = 'flex';
|
||
announce('Klavye kısayolları yardım penceresi açıldı. Kapatmak için Escape tuşuna basın.');
|
||
var closeBtn = document.getElementById('yaktube-shortcuts-close');
|
||
if (closeBtn) closeBtn.focus();
|
||
trapFocusInModal(modal);
|
||
} else {
|
||
modal.style.display = 'none';
|
||
announce('Yardım penceresi kapatıldı.');
|
||
}
|
||
} else {
|
||
modal = document.createElement('div');
|
||
modal.id = 'yaktube-shortcuts-dialog';
|
||
modal.className = 'yaktube-modal-overlay';
|
||
modal.setAttribute('role', 'dialog');
|
||
modal.setAttribute('aria-modal', 'true');
|
||
modal.setAttribute('aria-labelledby', 'yaktube-shortcuts-title');
|
||
modal.innerHTML =
|
||
'<div class="yaktube-modal-card" style="max-width: 600px; background:#1e1e24; border-radius:18px; padding:24px; color:#fff; box-shadow:0 16px 40px rgba(0,0,0,0.8);">' +
|
||
'<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:16px;">' +
|
||
'<h3 id="yaktube-shortcuts-title" style="margin:0; font-size:18px; color:#ff8f37;">⌨️ Klavye Kısayolları (Ekran Okuyucu Uyumlu)</h3>' +
|
||
'<button id="yaktube-shortcuts-close" class="yaktube-voice-modal-close-btn" aria-label="Kapat">✕</button>' +
|
||
'</div>' +
|
||
'<div style="font-size:12px; color:#aaa; margin-bottom:14px;">💡 <b>Ekran Okuyucu Notu:</b> Sanal imleç (Browse mode) açıkken kısayolları <b>Alt</b> tuşuyla birlikte kullanabilir veya video oynatıcı butonlarından faydalanabilirsiniz.</div>' +
|
||
'<table class="yaktube-shortcuts-table" style="width:100%; border-collapse:collapse; font-size:13px;">' +
|
||
'<thead><tr style="border-bottom:1px solid rgba(255,255,255,0.1); text-align:left; color:#aaa;"><th style="padding:6px 0;">Kısayol (Evrensel / Tek Tuş)</th><th style="padding:6px 0;">İşlev</th></tr></thead>' +
|
||
'<tbody>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + P</span> veya <span class="yaktube-kbd">Shift + P</span></td><td>🎬 Video Oynatıcıya Odaklan (Atla)</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + K</span> veya <span class="yaktube-kbd">Space</span></td><td>Oynat / Duraklat</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Shift + N</span></td><td>Sonraki Videoya Geç</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + J</span> veya <span class="yaktube-kbd">J</span></td><td>10 saniye geri sar</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + L</span> veya <span class="yaktube-kbd">L</span></td><td>10 saniye ileri sar</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + Yukarı / Aşağı</span></td><td>Sesi %5 artır / azalt</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + M</span> veya <span class="yaktube-kbd">M</span></td><td>Sesi Kapat / Aç (Mute)</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + T</span> veya <span class="yaktube-kbd">T</span></td><td>Sinema / Tiyatro Modu</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + I</span> veya <span class="yaktube-kbd">I</span></td><td>Hızlı Video Bilgisi & İstatistikler</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + C</span></td><td>📜 Akıllı Transkript & Bölümler Paneli</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + E</span></td><td>🎛️ Canlı Ses Stüdyosu (EQ & %300 Güç)</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + B</span></td><td>🔂 A-B Tekrar Döngüsü (İşaretle / Kapat)</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + R</span></td><td>📋 Kişisel Çalma Sırası (Kuyruk)</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + G</span> veya <span class="yaktube-kbd">Ctrl + Shift + K</span></td><td>⌘ Hızlı Komut Paleti</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + O</span></td><td>📻 Yalnızca Ses & Ekran Karartma Modu</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">F6</span> / <span class="yaktube-kbd">Shift + F6</span></td><td>🎯 Mantıksal Bölge Gezinmesi (Landmarks)</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + U</span></td><td>⏱️ Uyku Zamanlayıcısı (Sleep Timer)</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + Q</span></td><td>📱 Telefonda Devam Et (QR Kod)</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + .</span> / <span class="yaktube-kbd">Alt + ,</span></td><td>Oynatma hızını artır / azalt</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + S</span> veya <span class="yaktube-kbd">/</span> (Shift+7)</td><td>Arama penceresini aç</td></tr>' +
|
||
'<tr style="border-bottom:1px solid rgba(255,255,255,0.05);"><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + V</span> veya <span class="yaktube-kbd">Shift + V</span></td><td>Sesli aramayı başlat</td></tr>' +
|
||
'<tr><td style="padding:8px 0;"><span class="yaktube-kbd">Alt + H</span> veya <span class="yaktube-kbd">F1</span> veya <span class="yaktube-kbd">?</span></td><td>Bu kılavuzu aç / kapat</td></tr>' +
|
||
'</tbody>' +
|
||
'</table>' +
|
||
'</div>';
|
||
document.body.appendChild(modal);
|
||
|
||
var closeBtn = modal.querySelector('#yaktube-shortcuts-close');
|
||
if (closeBtn) {
|
||
closeBtn.addEventListener('click', function () {
|
||
modal.style.display = 'none';
|
||
});
|
||
}
|
||
modal.addEventListener('click', function (e) {
|
||
if (e.target === modal) modal.style.display = 'none';
|
||
});
|
||
|
||
announce('Klavye kısayolları yardım penceresi açıldı. Kapatmak için Escape tuşuna basın.');
|
||
}
|
||
}
|
||
|
||
function isInputFocused() {
|
||
var el = document.activeElement;
|
||
if (!el) return false;
|
||
var tag = el.tagName ? el.tagName.toUpperCase() : '';
|
||
return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || el.isContentEditable;
|
||
}
|
||
|
||
function getVideoElement() {
|
||
// 1. Direct video tag in DOM
|
||
var v = document.querySelector('video');
|
||
if (v) return v;
|
||
|
||
// 2. Video inside iframes (e.g. embed player)
|
||
var iframes = document.querySelectorAll('iframe');
|
||
for (var i = 0; i < iframes.length; i++) {
|
||
try {
|
||
var doc = iframes[i].contentDocument || (iframes[i].contentWindow && iframes[i].contentWindow.document);
|
||
if (doc) {
|
||
var iv = doc.querySelector('video');
|
||
if (iv) return iv;
|
||
}
|
||
} catch (e) {}
|
||
}
|
||
return null;
|
||
}
|
||
window.getVideoElement = getVideoElement;
|
||
|
||
function formatTime(seconds) {
|
||
if (isNaN(seconds) || seconds < 0) return '0 saniye';
|
||
var mins = Math.floor(seconds / 60);
|
||
var secs = Math.floor(seconds % 60);
|
||
if (mins === 0) return secs + ' saniye';
|
||
return mins + ' dakika ' + secs + ' saniye';
|
||
}
|
||
|
||
function showQuickVideoInfo() {
|
||
var video = getVideoElement();
|
||
if (!video) {
|
||
announce('Şu anda aktif oynatılan bir video bulunmuyor.');
|
||
return;
|
||
}
|
||
|
||
var titleEl = document.querySelector('h1.video-title, .video-name, my-video-watch h1, .title');
|
||
var title = titleEl ? titleEl.textContent.trim() : 'Video';
|
||
var curTime = formatTime(video.currentTime);
|
||
var totalTime = formatTime(video.duration || 0);
|
||
var remaining = formatTime((video.duration || 0) - video.currentTime);
|
||
var speed = (video.playbackRate || 1) + 'x';
|
||
var volume = Math.round((video.volume || 1) * 100) + '%';
|
||
var quality = video.videoHeight ? video.videoHeight + 'p' : 'Otomatik';
|
||
|
||
// Visual Toast
|
||
var existingToast = document.querySelector('.yaktube-video-info-toast');
|
||
if (existingToast) existingToast.remove();
|
||
|
||
var toast = document.createElement('div');
|
||
toast.className = 'yaktube-video-info-toast';
|
||
toast.innerHTML =
|
||
'<div class="yaktube-info-toast-title">📊 Video Bilgisi & Durum</div>' +
|
||
'<div class="yaktube-info-toast-row"><span>Başlık:</span> <b>' +
|
||
(title.length > 28 ? title.substring(0, 28) + '...' : title) +
|
||
'</b></div>' +
|
||
'<div class="yaktube-info-toast-row"><span>Konum / Süre:</span> <b>' +
|
||
curTime +
|
||
' / ' +
|
||
totalTime +
|
||
'</b></div>' +
|
||
'<div class="yaktube-info-toast-row"><span>Kalan Süre:</span> <b>' +
|
||
remaining +
|
||
'</b></div>' +
|
||
'<div class="yaktube-info-toast-row"><span>Çözünürlük:</span> <b>' +
|
||
quality +
|
||
'</b></div>' +
|
||
'<div class="yaktube-info-toast-row"><span>Hız & Ses:</span> <b>' +
|
||
speed +
|
||
' | ' +
|
||
volume +
|
||
'</b></div>';
|
||
|
||
document.body.appendChild(toast);
|
||
setTimeout(function () {
|
||
if (toast.parentElement) toast.remove();
|
||
}, 4000);
|
||
|
||
announce(
|
||
'Video Bilgisi: ' +
|
||
title +
|
||
'. Konum: ' +
|
||
curTime +
|
||
', Toplam Süre: ' +
|
||
totalTime +
|
||
', Kalan: ' +
|
||
remaining +
|
||
', Oynatma Hızı: ' +
|
||
speed +
|
||
', Ses: yüzde ' +
|
||
Math.round(video.volume * 100) +
|
||
', Çözünürlük: ' +
|
||
quality,
|
||
true
|
||
);
|
||
}
|
||
|
||
var speedSteps = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];
|
||
|
||
function adjustPlaybackSpeed(increase) {
|
||
var video = getVideoElement();
|
||
if (!video) return;
|
||
var curSpeed = video.playbackRate || 1;
|
||
if (increase) {
|
||
var nextIdx = speedSteps.findIndex(function (s) {
|
||
return s > curSpeed;
|
||
});
|
||
video.playbackRate = nextIdx !== -1 ? speedSteps[nextIdx] : 2;
|
||
announce('Oynatma hızı ' + video.playbackRate + ' katına çıkarıldı.');
|
||
} else {
|
||
var prevSteps = speedSteps.filter(function (s) {
|
||
return s < curSpeed;
|
||
});
|
||
video.playbackRate = prevSteps.length > 0 ? prevSteps[prevSteps.length - 1] : 0.25;
|
||
announce('Oynatma hızı ' + video.playbackRate + ' katına düşürüldü.');
|
||
}
|
||
}
|
||
|
||
// ==========================================================================
|
||
// YAKTUBE QUICK TOAST HELPER (v1.5.0)
|
||
// ==========================================================================
|
||
function showQuickToast(message, icon) {
|
||
var existing = document.getElementById('yaktube-quick-toast');
|
||
if (existing) existing.remove();
|
||
|
||
var toast = document.createElement('div');
|
||
toast.id = 'yaktube-quick-toast';
|
||
toast.className = 'yaktube-quick-toast';
|
||
var isEmbed = (typeof isEmbedUrl === 'function' && isEmbedUrl()) || window.self !== window.top;
|
||
var toastTop = isEmbed ? '28px' : '80px';
|
||
toast.style.cssText =
|
||
'position:fixed!important;top:' +
|
||
toastTop +
|
||
'!important;left:50%!important;transform:translateX(-50%)!important;' +
|
||
'background:rgba(24,24,31,0.92)!important;border:1px solid #ff8f37!important;color:#fff!important;' +
|
||
'padding:8px 18px!important;border-radius:30px!important;font-size:13px!important;font-weight:700!important;' +
|
||
'box-shadow:0 10px 30px rgba(0,0,0,0.8)!important;z-index:999999!important;pointer-events:none!important;' +
|
||
'backdrop-filter:blur(8px)!important;display:flex!important;align-items:center!important;gap:8px!important;';
|
||
toast.innerHTML = (icon ? '<span>' + icon + '</span> ' : '') + '<span>' + message + '</span>';
|
||
document.body.appendChild(toast);
|
||
|
||
setTimeout(function () {
|
||
if (toast && toast.parentNode) {
|
||
toast.style.opacity = '0';
|
||
toast.style.transition = 'opacity 0.3s ease-out';
|
||
setTimeout(function () {
|
||
if (toast.parentNode) toast.parentNode.removeChild(toast);
|
||
}, 300);
|
||
}
|
||
}, 2200);
|
||
}
|
||
|
||
// ==========================================================================
|
||
// YAKTUBE SLEEP TIMER ENGINE (v1.5.0)
|
||
// ==========================================================================
|
||
var sleepTimer = {
|
||
countdownInterval: null,
|
||
targetTime: 0,
|
||
mode: null,
|
||
originalVolume: 1
|
||
};
|
||
|
||
function clearSleepTimer() {
|
||
if (sleepTimer.countdownInterval) clearInterval(sleepTimer.countdownInterval);
|
||
sleepTimer.countdownInterval = null;
|
||
sleepTimer.targetTime = 0;
|
||
sleepTimer.mode = null;
|
||
|
||
var badge = document.getElementById('yaktube-sleep-timer-badge');
|
||
if (badge) badge.remove();
|
||
var endListenerVideo = getVideoElement();
|
||
if (endListenerVideo && endListenerVideo._sleepEndListener) {
|
||
endListenerVideo.removeEventListener('ended', endListenerVideo._sleepEndListener);
|
||
endListenerVideo._sleepEndListener = null;
|
||
}
|
||
}
|
||
|
||
function setSleepTimer(modeMinutes) {
|
||
clearSleepTimer();
|
||
var video = getVideoElement();
|
||
if (!video) {
|
||
announce('Aktif video bulunamadı.');
|
||
return;
|
||
}
|
||
|
||
sleepTimer.mode = modeMinutes;
|
||
sleepTimer.originalVolume = video.volume || 1;
|
||
|
||
if (modeMinutes === 'end') {
|
||
announce('Uyku zamanlayıcısı ayarlandı: Bu video bitince durdurulacak.', true);
|
||
showQuickToast('⏱️ Uyku: Video Bitince');
|
||
video._sleepEndListener = function () {
|
||
video.pause();
|
||
announce('Uyku zamanlayıcısı: Video bitti, oynatma durduruldu.', true);
|
||
clearSleepTimer();
|
||
};
|
||
video.addEventListener('ended', video._sleepEndListener, { once: true });
|
||
updateSleepTimerBadge('Video Bitince');
|
||
return;
|
||
}
|
||
|
||
var mins = parseInt(modeMinutes, 10);
|
||
if (isNaN(mins) || mins <= 0) return;
|
||
|
||
sleepTimer.targetTime = Date.now() + mins * 60 * 1000;
|
||
announce('Uyku zamanlayıcısı ' + mins + ' dakikaya ayarlandı.', true);
|
||
showQuickToast('⏱️ Uyku: ' + mins + ' Dakika');
|
||
|
||
function updateTick() {
|
||
var remainingMs = Math.max(0, sleepTimer.targetTime - Date.now());
|
||
var remainingSec = Math.floor(remainingMs / 1000);
|
||
var m = Math.floor(remainingSec / 60);
|
||
var s = remainingSec % 60;
|
||
var display = (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s);
|
||
updateSleepTimerBadge(display);
|
||
|
||
// Gentle volume fadeout in last 15 seconds
|
||
if (remainingSec <= 15 && remainingSec > 0 && video && !video.paused) {
|
||
var stepRatio = remainingSec / 15;
|
||
video.volume = Math.max(0, sleepTimer.originalVolume * stepRatio);
|
||
}
|
||
|
||
if (remainingMs <= 0) {
|
||
clearSleepTimer();
|
||
if (video) {
|
||
video.pause();
|
||
video.volume = sleepTimer.originalVolume;
|
||
}
|
||
announce('Uyku zamanlayıcısı süresi doldu, video durduruldu.', true);
|
||
showQuickToast('⏱️ Uyku: Oynatma Durduruldu');
|
||
}
|
||
}
|
||
|
||
updateTick();
|
||
sleepTimer.countdownInterval = setInterval(updateTick, 1000);
|
||
}
|
||
|
||
function updateSleepTimerBadge(text) {
|
||
var bar = document.getElementById('yaktube-player-action-bar');
|
||
if (!bar) return;
|
||
var badge = document.getElementById('yaktube-sleep-timer-badge');
|
||
if (!badge) {
|
||
badge = document.createElement('span');
|
||
badge.id = 'yaktube-sleep-timer-badge';
|
||
badge.className = 'yaktube-timer-badge';
|
||
var sleepBtn = document.getElementById('yaktube-bar-sleep-btn');
|
||
if (sleepBtn && sleepBtn.nextSibling) {
|
||
bar.insertBefore(badge, sleepBtn.nextSibling);
|
||
} else {
|
||
bar.appendChild(badge);
|
||
}
|
||
}
|
||
badge.textContent = '⏱️ ' + text;
|
||
}
|
||
|
||
function openSleepTimerModal() {
|
||
var existing = document.getElementById('yaktube-sleep-modal');
|
||
if (existing) existing.remove();
|
||
|
||
var backdrop = document.createElement('div');
|
||
backdrop.id = 'yaktube-sleep-modal';
|
||
backdrop.className = 'yaktube-feature-modal-backdrop';
|
||
backdrop.setAttribute('role', 'dialog');
|
||
backdrop.setAttribute('aria-modal', 'true');
|
||
backdrop.setAttribute('aria-label', 'Uyku Zamanlayıcısı');
|
||
|
||
var card = document.createElement('div');
|
||
card.className = 'yaktube-feature-modal-card';
|
||
|
||
var header = document.createElement('div');
|
||
header.className = 'yaktube-feature-modal-header';
|
||
header.innerHTML =
|
||
'<h3 class="yaktube-feature-modal-title"><span>⏱️</span> Uyku Zamanlayıcısı</h3>' +
|
||
'<button class="yaktube-feature-modal-close" aria-label="Kapat (Escape)">×</button>';
|
||
|
||
var body = document.createElement('div');
|
||
body.className = 'yaktube-feature-modal-body';
|
||
body.innerHTML =
|
||
'<p class="yaktube-qr-desc">Videonun ne zaman durdurulacağını seçin. Süre bittiğinde ses yavaşça kısılarak oynatma durdurulur.</p>' +
|
||
'<div class="yaktube-timer-options">' +
|
||
'<button class="yaktube-timer-btn' +
|
||
(sleepTimer.mode === '15' ? ' active' : '') +
|
||
'" data-mins="15">15 Dakika</button>' +
|
||
'<button class="yaktube-timer-btn' +
|
||
(sleepTimer.mode === '30' ? ' active' : '') +
|
||
'" data-mins="30">30 Dakika</button>' +
|
||
'<button class="yaktube-timer-btn' +
|
||
(sleepTimer.mode === '45' ? ' active' : '') +
|
||
'" data-mins="45">45 Dakika</button>' +
|
||
'<button class="yaktube-timer-btn' +
|
||
(sleepTimer.mode === '60' ? ' active' : '') +
|
||
'" data-mins="60">60 Dakika</button>' +
|
||
'</div>' +
|
||
'<button class="yaktube-timer-btn' +
|
||
(sleepTimer.mode === 'end' ? ' active' : '') +
|
||
'" data-mins="end" style="width:100%;">🎬 Bu Video Bitince</button>' +
|
||
(sleepTimer.targetTime || sleepTimer.mode
|
||
? '<button id="yaktube-timer-cancel-btn" class="yaktube-timer-btn" style="background:#ef4444!important;color:#fff!important;border-color:#ef4444!important;">❌ Zamanlayıcıyı İptal Et</button>'
|
||
: '');
|
||
|
||
card.appendChild(header);
|
||
card.appendChild(body);
|
||
backdrop.appendChild(card);
|
||
document.body.appendChild(backdrop);
|
||
|
||
function closeModal() {
|
||
backdrop.remove();
|
||
announce('Uyku zamanlayıcısı penceresi kapatıldı.');
|
||
}
|
||
|
||
header.querySelector('.yaktube-feature-modal-close').addEventListener('click', closeModal);
|
||
backdrop.addEventListener('click', function (e) {
|
||
if (e.target === backdrop) closeModal();
|
||
});
|
||
|
||
body.querySelectorAll('.yaktube-timer-options .yaktube-timer-btn, button[data-mins="end"]').forEach(function (b) {
|
||
b.addEventListener('click', function () {
|
||
var mins = this.getAttribute('data-mins');
|
||
setSleepTimer(mins);
|
||
closeModal();
|
||
});
|
||
});
|
||
|
||
var cancelBtn = body.querySelector('#yaktube-timer-cancel-btn');
|
||
if (cancelBtn) {
|
||
cancelBtn.addEventListener('click', function () {
|
||
clearSleepTimer();
|
||
announce('Uyku zamanlayıcısı iptal edildi.', true);
|
||
showQuickToast('⏱️ Zamanlayıcı İptal Edildi');
|
||
closeModal();
|
||
});
|
||
}
|
||
|
||
var firstBtn = body.querySelector('.yaktube-timer-btn');
|
||
if (firstBtn) firstBtn.focus();
|
||
announce('Uyku zamanlayıcısı penceresi açıldı. Seçeneklerden birini seçin.');
|
||
}
|
||
|
||
// ==========================================================================
|
||
// YAKTUBE PHONE TRANSFER / QR CODE ENGINE (v1.5.0)
|
||
// ==========================================================================
|
||
function openPhoneTransferModal() {
|
||
var video = getVideoElement();
|
||
var currentSec = video ? Math.floor(video.currentTime || 0) : 0;
|
||
var currentUrl = new URL(window.location.href);
|
||
if (currentSec > 0) {
|
||
currentUrl.searchParams.set('start', currentSec + 's');
|
||
}
|
||
var targetUrl = currentUrl.toString();
|
||
|
||
var existing = document.getElementById('yaktube-qr-modal');
|
||
if (existing) existing.remove();
|
||
|
||
var backdrop = document.createElement('div');
|
||
backdrop.id = 'yaktube-qr-modal';
|
||
backdrop.className = 'yaktube-feature-modal-backdrop';
|
||
backdrop.setAttribute('role', 'dialog');
|
||
backdrop.setAttribute('aria-modal', 'true');
|
||
backdrop.setAttribute('aria-label', 'Telefonda Devam Et');
|
||
|
||
var card = document.createElement('div');
|
||
card.className = 'yaktube-feature-modal-card';
|
||
|
||
var header = document.createElement('div');
|
||
header.className = 'yaktube-feature-modal-header';
|
||
header.innerHTML =
|
||
'<h3 class="yaktube-feature-modal-title"><span>📱</span> Telefonda Devam Et</h3>' +
|
||
'<button class="yaktube-feature-modal-close" aria-label="Kapat (Escape)">×</button>';
|
||
|
||
var formattedTime = formatClockTime(currentSec);
|
||
var qrImageUrl =
|
||
'https://api.qrserver.com/v1/create-qr-code/?size=220x220&margin=8&data=' + encodeURIComponent(targetUrl);
|
||
|
||
var body = document.createElement('div');
|
||
body.className = 'yaktube-feature-modal-body';
|
||
body.innerHTML =
|
||
'<p class="yaktube-qr-desc">Telefonunuzun kamerasıyla QR kodu okutarak videoyu kaldığınız yerden (<strong>' +
|
||
formattedTime +
|
||
'</strong>) izlemeye devam edebilirsiniz.</p>' +
|
||
'<div class="yaktube-qr-wrapper">' +
|
||
'<img src="' +
|
||
qrImageUrl +
|
||
'" alt="Video Bağlantısı QR Kodu" width="190" height="190" style="display:block;border-radius:8px;" />' +
|
||
'</div>' +
|
||
'<button id="yaktube-qr-copy-action-btn" class="yaktube-qr-copy-btn">📋 Bağlantıyı Kopyala</button>';
|
||
|
||
card.appendChild(header);
|
||
card.appendChild(body);
|
||
backdrop.appendChild(card);
|
||
document.body.appendChild(backdrop);
|
||
|
||
function closeModal() {
|
||
backdrop.remove();
|
||
announce('Telefonda devam et penceresi kapatıldı.');
|
||
}
|
||
|
||
header.querySelector('.yaktube-feature-modal-close').addEventListener('click', closeModal);
|
||
backdrop.addEventListener('click', function (e) {
|
||
if (e.target === backdrop) closeModal();
|
||
});
|
||
|
||
var copyBtn = body.querySelector('#yaktube-qr-copy-action-btn');
|
||
copyBtn.addEventListener('click', function () {
|
||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||
navigator.clipboard
|
||
.writeText(targetUrl)
|
||
.then(function () {
|
||
copyBtn.textContent = '✅ Bağlantı Kopyalandı!';
|
||
announce('Bağlantı panoya kopyalandı: ' + targetUrl);
|
||
setTimeout(function () {
|
||
copyBtn.textContent = '📋 Bağlantıyı Kopyala';
|
||
}, 2500);
|
||
})
|
||
.catch(function () {
|
||
fallbackCopy(targetUrl, copyBtn);
|
||
});
|
||
} else {
|
||
fallbackCopy(targetUrl, copyBtn);
|
||
}
|
||
});
|
||
|
||
function fallbackCopy(text, btn) {
|
||
var tempInput = document.createElement('input');
|
||
tempInput.value = text;
|
||
document.body.appendChild(tempInput);
|
||
tempInput.select();
|
||
try {
|
||
document.execCommand('copy');
|
||
btn.textContent = '✅ Bağlantı Kopyalandı!';
|
||
announce('Bağlantı panoya kopyalandı.');
|
||
setTimeout(function () {
|
||
btn.textContent = '📋 Bağlantıyı Kopyala';
|
||
}, 2500);
|
||
} catch (e) {
|
||
btn.textContent = '❌ Kopyalanamadı';
|
||
}
|
||
document.body.removeChild(tempInput);
|
||
}
|
||
|
||
copyBtn.focus();
|
||
announce('Telefonda devam et penceresi açıldı. QR kodu okutabilir veya bağlantıyı kopyalayabilirsiniz.');
|
||
}
|
||
|
||
// ==========================================================================
|
||
// YAKTUBE DOUBLE-TAP TOUCH SEEK ENGINE (v1.5.0)
|
||
// ==========================================================================
|
||
function showDoubleTapRipple(container, isLeft) {
|
||
var className = isLeft ? 'yaktube-doubletap-left' : 'yaktube-doubletap-right';
|
||
var existing = container.querySelector('.yaktube-doubletap-overlay.' + className);
|
||
if (!existing) {
|
||
existing = document.createElement('div');
|
||
existing.className = 'yaktube-doubletap-overlay ' + className;
|
||
existing.innerHTML =
|
||
'<div class="yaktube-ripple-content">' + (isLeft ? '⏪ 10sn Geri' : '10sn İleri ⏩') + '</div>';
|
||
container.appendChild(existing);
|
||
}
|
||
existing.classList.add('yaktube-ripple-active');
|
||
clearTimeout(existing._rippleTimer);
|
||
existing._rippleTimer = setTimeout(function () {
|
||
existing.classList.remove('yaktube-ripple-active');
|
||
}, 650);
|
||
}
|
||
|
||
function initTouchSeekGesture(video) {
|
||
if (!video) return;
|
||
var playerContainer =
|
||
video.closest('.video-js, .player-container, .player, my-video-watch') || video.parentElement;
|
||
if (!playerContainer || playerContainer.hasAttribute('data-yaktube-touch-seek-hooked')) return;
|
||
playerContainer.setAttribute('data-yaktube-touch-seek-hooked', 'true');
|
||
|
||
var lastTapTime = 0;
|
||
var lastTapX = 0;
|
||
var tapTimeout = null;
|
||
|
||
playerContainer.addEventListener(
|
||
'touchend',
|
||
function (e) {
|
||
if (e.changedTouches && e.changedTouches.length === 1) {
|
||
var touch = e.changedTouches[0];
|
||
var rect = playerContainer.getBoundingClientRect();
|
||
var tapX = touch.clientX - rect.left;
|
||
var tapY = touch.clientY - rect.top;
|
||
var now = Date.now();
|
||
|
||
if (tapY > rect.height - 50) return;
|
||
|
||
if (now - lastTapTime < 320 && Math.abs(tapX - lastTapX) < 60) {
|
||
e.preventDefault();
|
||
clearTimeout(tapTimeout);
|
||
lastTapTime = 0;
|
||
|
||
var isLeft = tapX < rect.width * 0.45;
|
||
var isRight = tapX > rect.width * 0.55;
|
||
|
||
if (isLeft) {
|
||
video.currentTime = Math.max(0, video.currentTime - 10);
|
||
showDoubleTapRipple(playerContainer, true);
|
||
announce('10 saniye geri sarıldı. Konum: ' + formatTime(video.currentTime));
|
||
} else if (isRight) {
|
||
video.currentTime = Math.min(video.duration || 999999, video.currentTime + 10);
|
||
showDoubleTapRipple(playerContainer, false);
|
||
announce('10 saniye ileri sarıldı. Konum: ' + formatTime(video.currentTime));
|
||
}
|
||
} else {
|
||
lastTapTime = now;
|
||
lastTapX = tapX;
|
||
tapTimeout = setTimeout(function () {
|
||
lastTapTime = 0;
|
||
}, 330);
|
||
}
|
||
}
|
||
},
|
||
{ passive: false }
|
||
);
|
||
}
|
||
|
||
// ==========================================================================
|
||
// YAKTUBE VOICE ASSISTANT COMMANDS HANDLER (v1.5.0)
|
||
// ==========================================================================
|
||
function handleVoiceAssistantCommand(rawTranscript) {
|
||
if (!rawTranscript) return false;
|
||
var text = rawTranscript.toLowerCase().trim();
|
||
var video = getVideoElement();
|
||
|
||
if (text === 'durdur' || text === 'duraklat' || text === 'videoyu durdur' || text === 'pause') {
|
||
if (video) video.pause();
|
||
announce('Video duraklatıldı.', true);
|
||
showQuickToast('⏸️ Video Duraklatıldı');
|
||
stopVoiceInsideModal();
|
||
closeFullSearchModal();
|
||
return true;
|
||
}
|
||
|
||
if (text === 'oynat' || text === 'başlat' || text === 'devam et' || text === 'videoyu oynat' || text === 'play') {
|
||
if (video) video.play();
|
||
announce('Video oynatılıyor.', true);
|
||
showQuickToast('▶️ Video Oynatılıyor');
|
||
stopVoiceInsideModal();
|
||
closeFullSearchModal();
|
||
return true;
|
||
}
|
||
|
||
if (text === 'tam ekran' || text === 'büyük ekran' || text === 'tam ekran yap') {
|
||
var playerWrap =
|
||
document.querySelector('.player-container, .video-player-container, my-video-watch .player') || video;
|
||
if (playerWrap) {
|
||
if (!document.fullscreenElement) {
|
||
if (playerWrap.requestFullscreen) playerWrap.requestFullscreen();
|
||
announce('Tam ekran moduna geçildi.', true);
|
||
showQuickToast('⛶ Tam Ekran');
|
||
} else {
|
||
if (document.exitFullscreen) document.exitFullscreen();
|
||
announce('Tam ekrandan çıkıldı.', true);
|
||
showQuickToast('⛶ Normal Ekran');
|
||
}
|
||
}
|
||
stopVoiceInsideModal();
|
||
closeFullSearchModal();
|
||
return true;
|
||
}
|
||
|
||
if (text === 'sesi aç' || text === 'sesi yükselt' || text === 'sesi arttır' || text === 'ses aç') {
|
||
if (video) {
|
||
video.volume = Math.min(1, video.volume + 0.2);
|
||
var pct = Math.round(video.volume * 100);
|
||
announce('Ses seviyesi artırıldı: %' + pct, true);
|
||
showQuickToast('🔊 Ses: %' + pct);
|
||
}
|
||
stopVoiceInsideModal();
|
||
closeFullSearchModal();
|
||
return true;
|
||
}
|
||
|
||
if (text === 'sesi kıs' || text === 'sesi azalt' || text === 'ses kıs') {
|
||
if (video) {
|
||
video.volume = Math.max(0, video.volume - 0.2);
|
||
var pct = Math.round(video.volume * 100);
|
||
announce('Ses seviyesi azaltıldı: %' + pct, true);
|
||
showQuickToast('🔉 Ses: %' + pct);
|
||
}
|
||
stopVoiceInsideModal();
|
||
closeFullSearchModal();
|
||
return true;
|
||
}
|
||
|
||
if (text === 'sessiz' || text === 'sustur' || text === 'sesi kapat' || text === 'mute') {
|
||
if (video) {
|
||
video.muted = !video.muted;
|
||
announce(video.muted ? 'Ses kapatıldı.' : 'Ses açıldı.', true);
|
||
showQuickToast(video.muted ? '🔇 Sessiz' : '🔊 Ses Açık');
|
||
}
|
||
stopVoiceInsideModal();
|
||
closeFullSearchModal();
|
||
return true;
|
||
}
|
||
|
||
if (text === 'ileri sar' || text === '10 saniye ileri' || text === 'ileri al' || text === 'atla') {
|
||
if (video) {
|
||
video.currentTime = Math.min(video.duration || 999999, video.currentTime + 10);
|
||
announce('10 saniye ileri sarıldı.', true);
|
||
showQuickToast('⏩ +10sn İleri');
|
||
}
|
||
stopVoiceInsideModal();
|
||
closeFullSearchModal();
|
||
return true;
|
||
}
|
||
|
||
if (text === 'geri sar' || text === '10 saniye geri' || text === 'geri al') {
|
||
if (video) {
|
||
video.currentTime = Math.max(0, video.currentTime - 10);
|
||
announce('10 saniye geri sarıldı.', true);
|
||
showQuickToast('⏪ -10sn Geri');
|
||
}
|
||
stopVoiceInsideModal();
|
||
closeFullSearchModal();
|
||
return true;
|
||
}
|
||
|
||
if (text.includes('uyku') || text.includes('zamanlayıcı')) {
|
||
stopVoiceInsideModal();
|
||
closeFullSearchModal();
|
||
openSleepTimerModal();
|
||
return true;
|
||
}
|
||
|
||
if (text === 'kapat' || text === 'çık' || text === 'iptal') {
|
||
stopVoiceInsideModal();
|
||
closeFullSearchModal();
|
||
announce('Arama penceresi kapatıldı.');
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
// ==========================================================================
|
||
// YAKTUBE ACCESSIBLE VIDEO PLAYER & WATCH PAGE ENGINE (W3C WAI-ARIA)
|
||
// ==========================================================================
|
||
function focusVideoPlayer() {
|
||
var playerWrapper =
|
||
document.getElementById('videojs-wrapper') ||
|
||
document.querySelector('.video-js') ||
|
||
document.getElementById('video-wrapper');
|
||
if (playerWrapper) {
|
||
playerWrapper.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||
playerWrapper.focus();
|
||
var titleEl = document.querySelector(
|
||
'h1.video-info-name, .video-info-name h1, my-video-watch h1, .video-title, .title'
|
||
);
|
||
var videoTitle = titleEl
|
||
? titleEl.textContent.trim()
|
||
: document.title
|
||
? document.title.replace(/\s*-\s*(PeerTube|YakTube).*$/i, '').trim()
|
||
: 'Video';
|
||
var video = getVideoElement();
|
||
var status = video ? (video.paused ? 'Duraklatıldı' : 'Oynatılıyor') : '';
|
||
announce(
|
||
'Video oynatıcıya odaklanıldı: ' +
|
||
videoTitle +
|
||
(status ? ' (' + status + ')' : '') +
|
||
'. Oynatmak için Boşluk veya K, sarmak için J veya L tuşlarını kullanabilirsiniz.'
|
||
);
|
||
}
|
||
}
|
||
window.focusVideoPlayer = focusVideoPlayer;
|
||
|
||
function sanitizeWatchPageLabels(videoTitle) {
|
||
// 1. Next Video button in Video.js control bar
|
||
var firstRec =
|
||
typeof window.__yaktube_get_first_smart_rec === 'function' ? window.__yaktube_get_first_smart_rec() : null;
|
||
var nextLabel =
|
||
firstRec && firstRec.title
|
||
? 'Sonraki Video (İlk Öneri): ' + firstRec.title + ' (Shift+N)'
|
||
: 'Sonraki Video (Shift+N)';
|
||
var nextBtns = document.querySelectorAll(
|
||
'.vjs-next-video, .vjs-next-video-control, .vjs-next-control, button[title*="Next video"], button[aria-label*="Next video"]'
|
||
);
|
||
nextBtns.forEach(function (btn) {
|
||
if (
|
||
firstRec &&
|
||
!(typeof window.__yaktube_is_playlist_watch === 'function' && window.__yaktube_is_playlist_watch())
|
||
) {
|
||
btn.classList.remove('vjs-disabled');
|
||
btn.classList.remove('vjs-hidden');
|
||
btn.removeAttribute('disabled');
|
||
}
|
||
if (btn.getAttribute('aria-label') !== nextLabel) {
|
||
btn.setAttribute('aria-label', nextLabel);
|
||
}
|
||
if (btn.getAttribute('title') !== nextLabel) {
|
||
btn.setAttribute('title', nextLabel);
|
||
}
|
||
var ctrlText = btn.querySelector('.vjs-control-text');
|
||
if (ctrlText && ctrlText.textContent !== nextLabel) {
|
||
ctrlText.textContent = nextLabel;
|
||
}
|
||
});
|
||
|
||
// 2. Share modal button
|
||
var shareBtns = document.querySelectorAll(
|
||
'button[aria-label*="share this video"], button[title*="share this video"], .action-button[aria-label*="share this video"]'
|
||
);
|
||
shareBtns.forEach(function (btn) {
|
||
btn.setAttribute('aria-label', 'Videoyu Paylaş');
|
||
btn.setAttribute('title', 'Videoyu Paylaş');
|
||
});
|
||
|
||
// 3. Download modal button
|
||
var downloadBtns = document.querySelectorAll(
|
||
'button[aria-label*="download this video"], button[title*="download this video"], .action-button[aria-label*="download this video"]'
|
||
);
|
||
downloadBtns.forEach(function (btn) {
|
||
btn.setAttribute('aria-label', 'Videoyu İndir');
|
||
btn.setAttribute('title', 'Videoyu İndir');
|
||
});
|
||
|
||
// 4. Subscription dropdown / button
|
||
var subDropdowns = document.querySelectorAll(
|
||
'button[aria-label*="subscription"], .action-dropdown[aria-label*="subscription"], my-subscribe-button button'
|
||
);
|
||
subDropdowns.forEach(function (btn) {
|
||
var cur = (btn.getAttribute('aria-label') || '').toLowerCase();
|
||
if (cur.includes('subscription') || cur.includes('dropdown')) {
|
||
btn.setAttribute('aria-label', 'Abonelik Seçenekleri');
|
||
btn.setAttribute('title', 'Abonelik Seçenekleri');
|
||
}
|
||
});
|
||
|
||
// 5. Account management link
|
||
var accountLinks = document.querySelectorAll(
|
||
'a[aria-label*="manage your account"], a[title*="manage your account"]'
|
||
);
|
||
accountLinks.forEach(function (a) {
|
||
a.setAttribute('aria-label', 'Hesap Yönetim Sayfası');
|
||
a.setAttribute('title', 'Hesap Yönetim Sayfası');
|
||
});
|
||
|
||
// 6. Date Toggle Button (Clean up "Bu tarih birimini ... olarak değistir")
|
||
var dateToggles = document.querySelectorAll('my-date-toggle, .date-toggle, [role="button"].date-toggle');
|
||
dateToggles.forEach(function (el) {
|
||
var rawText = (el.textContent || '').trim();
|
||
var cleanDate = rawText.replace(/^[•\s]+|[•\s]+$/g, '').trim();
|
||
if (cleanDate) {
|
||
var dateLabel = 'Yayınlanma Tarihi: ' + cleanDate + ' (Tarih biçimini değiştirmek için tıklayın)';
|
||
if (el.getAttribute('aria-label') !== dateLabel) {
|
||
el.setAttribute('aria-label', dateLabel);
|
||
}
|
||
if (el.getAttribute('title') !== dateLabel) {
|
||
el.setAttribute('title', dateLabel);
|
||
}
|
||
}
|
||
});
|
||
|
||
// 7. Video Rate Buttons (Like & Dislike distinct separation)
|
||
var rateContainer = document.querySelector('my-video-rate, .video-actions-rates');
|
||
if (rateContainer) {
|
||
var buttons = rateContainer.querySelectorAll('button');
|
||
buttons.forEach(function (btn) {
|
||
var label = (
|
||
btn.getAttribute('aria-label') ||
|
||
btn.getAttribute('title') ||
|
||
btn.textContent ||
|
||
''
|
||
).toLowerCase();
|
||
var icon = btn.querySelector('my-global-icon, i, svg');
|
||
var iconName = icon ? icon.className || icon.getAttribute('name') || icon.getAttribute('iconName') || '' : '';
|
||
|
||
var isDislike =
|
||
label.includes('beğenme') ||
|
||
label.includes('dislike') ||
|
||
iconName.includes('thumbs-down') ||
|
||
iconName.includes('thumb-down');
|
||
var isLike =
|
||
!isDislike &&
|
||
(label.includes('beğen') ||
|
||
label.includes('like') ||
|
||
iconName.includes('thumbs-up') ||
|
||
iconName.includes('thumb-up'));
|
||
|
||
var isPressed =
|
||
btn.classList.contains('active') ||
|
||
btn.classList.contains('liked') ||
|
||
btn.getAttribute('aria-pressed') === 'true';
|
||
|
||
if (isDislike) {
|
||
btn.setAttribute('aria-label', isPressed ? 'Videoyu Beğenme (Seçildi)' : 'Videoyu Beğenme');
|
||
btn.setAttribute('title', 'Videoyu Beğenme');
|
||
} else if (isLike) {
|
||
btn.setAttribute('aria-label', isPressed ? 'Videoyu Beğen (Seçildi)' : 'Videoyu Beğen');
|
||
btn.setAttribute('title', 'Videoyu Beğen');
|
||
}
|
||
});
|
||
}
|
||
|
||
// 8. Channel Avatar Link (Turn vague single letter "y" into descriptive channel link)
|
||
var channelSection = document.querySelector('.video-info-channel, my-account-on-channel-avatar');
|
||
if (channelSection) {
|
||
var channelNameEl = document.querySelector('.video-info-channel-left-links a, a.single-link, .channel-name');
|
||
var channelName = channelNameEl ? channelNameEl.textContent.trim() : '';
|
||
var avatarAnchor = channelSection.querySelector('my-account-on-channel-avatar a, .actor-avatar a, .avatar a');
|
||
if (avatarAnchor) {
|
||
var cLabel = channelName ? channelName + ' Kanalı ve Profil Resmi' : 'Kanal Profil Resmi';
|
||
avatarAnchor.setAttribute('aria-label', cLabel);
|
||
avatarAnchor.setAttribute('title', cLabel);
|
||
var avatarImg = avatarAnchor.querySelector('img');
|
||
if (avatarImg) {
|
||
avatarImg.setAttribute('alt', cLabel);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 9. Actions Dropdown ("Eylem" / "More" button)
|
||
var actionsDropdownBtn = document.querySelector(
|
||
'my-video-actions-dropdown button, .action-dropdown button, my-action-buttons my-video-actions-dropdown'
|
||
);
|
||
if (actionsDropdownBtn) {
|
||
actionsDropdownBtn.setAttribute('aria-label', 'Diğer Video Seçenekleri ve İşlemler');
|
||
actionsDropdownBtn.setAttribute('title', 'Diğer Video Seçenekleri ve İşlemler');
|
||
}
|
||
}
|
||
|
||
function isEmbedUrl() {
|
||
if (typeof window === 'undefined' || !window.location) return false;
|
||
var p = window.location.pathname;
|
||
return p.includes('/videos/embed/') || p.startsWith('/videos/embed/');
|
||
}
|
||
|
||
function isWatchUrl() {
|
||
if (typeof window === 'undefined' || !window.location) return false;
|
||
var p = window.location.pathname;
|
||
return p.includes('/videos/watch/') || p.startsWith('/w/') || p.includes('/w/') || isEmbedUrl();
|
||
}
|
||
|
||
function injectControlBarSeekButtons(playerWrapper) {
|
||
// A11y: Video.js büyük oynat butonunu ve denetim çubuğu butonlarını ekran okuyuculara erişilebilir kıl
|
||
// big-play-button custom label removed per user preference
|
||
var playBtn = (playerWrapper || document).querySelector('.vjs-play-control');
|
||
if (playBtn && !playBtn.hasAttribute('data-yaktube-a11y-label')) {
|
||
playBtn.setAttribute('data-yaktube-a11y-label', 'true');
|
||
var videoEl = getVideoElement();
|
||
var isPaused = videoEl ? videoEl.paused : true;
|
||
playBtn.setAttribute('aria-label', isPaused ? 'Oynat (Boşluk veya K)' : 'Duraklat (Boşluk veya K)');
|
||
}
|
||
var controlBar = (playerWrapper || document).querySelector('.vjs-control-bar');
|
||
if (!controlBar) return;
|
||
|
||
var rewindBtn = controlBar.querySelector('.yaktube-vjs-rewind-btn');
|
||
var forwardBtn = controlBar.querySelector('.yaktube-vjs-forward-btn');
|
||
var speedBtn = controlBar.querySelector('.yaktube-vjs-speed-btn');
|
||
var playControl = controlBar.querySelector('.vjs-play-control');
|
||
|
||
if (!rewindBtn) {
|
||
rewindBtn = document.createElement('button');
|
||
rewindBtn.className = 'vjs-control vjs-button yaktube-vjs-seek-btn yaktube-vjs-rewind-btn';
|
||
rewindBtn.type = 'button';
|
||
rewindBtn.setAttribute('tabindex', '0');
|
||
rewindBtn.setAttribute('aria-label', '10 saniye geri sar (Sol Ok veya J)');
|
||
rewindBtn.setAttribute('title', '10 saniye geri sar (Alt+J)');
|
||
rewindBtn.innerHTML =
|
||
'<span class="yaktube-vjs-seek-icon" aria-hidden="true">⏪<span class="yaktube-vjs-seek-num">10</span></span>' +
|
||
'<span class="vjs-control-text" aria-live="polite">10 saniye geri sar</span>';
|
||
|
||
rewindBtn.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
var video = getVideoElement();
|
||
if (video) {
|
||
video.currentTime = Math.max(0, video.currentTime - 10);
|
||
announce('10 saniye geri sarıldı. Konum: ' + formatTime(video.currentTime));
|
||
showQuickToast('⏪ -10sn');
|
||
}
|
||
});
|
||
|
||
if (playControl && playControl.nextSibling) {
|
||
controlBar.insertBefore(rewindBtn, playControl.nextSibling);
|
||
} else {
|
||
controlBar.appendChild(rewindBtn);
|
||
}
|
||
}
|
||
|
||
if (!forwardBtn) {
|
||
forwardBtn = document.createElement('button');
|
||
forwardBtn.className = 'vjs-control vjs-button yaktube-vjs-seek-btn yaktube-vjs-forward-btn';
|
||
forwardBtn.type = 'button';
|
||
forwardBtn.setAttribute('tabindex', '0');
|
||
forwardBtn.setAttribute('aria-label', '10 saniye ileri sar (Sağ Ok veya L)');
|
||
forwardBtn.setAttribute('title', '10 saniye ileri sar (Alt+L)');
|
||
forwardBtn.innerHTML =
|
||
'<span class="yaktube-vjs-seek-icon" aria-hidden="true"><span class="yaktube-vjs-seek-num">10</span>⏩</span>' +
|
||
'<span class="vjs-control-text" aria-live="polite">10 saniye ileri sar</span>';
|
||
|
||
forwardBtn.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
var video = getVideoElement();
|
||
if (video) {
|
||
video.currentTime = Math.min(video.duration || 999999, video.currentTime + 10);
|
||
announce('10 saniye ileri sarıldı. Konum: ' + formatTime(video.currentTime));
|
||
showQuickToast('⏩ +10sn');
|
||
}
|
||
});
|
||
|
||
if (rewindBtn && rewindBtn.nextSibling) {
|
||
controlBar.insertBefore(forwardBtn, rewindBtn.nextSibling);
|
||
} else if (playControl && playControl.nextSibling) {
|
||
controlBar.insertBefore(forwardBtn, playControl.nextSibling);
|
||
} else {
|
||
controlBar.appendChild(forwardBtn);
|
||
}
|
||
}
|
||
|
||
if (!speedBtn) {
|
||
speedBtn = document.createElement('button');
|
||
speedBtn.className = 'vjs-control vjs-button yaktube-vjs-seek-btn yaktube-vjs-speed-btn';
|
||
speedBtn.type = 'button';
|
||
speedBtn.setAttribute('tabindex', '0');
|
||
speedBtn.setAttribute('aria-label', 'Oynatma Hızı: 1x (Değiştirmek için tıklayın veya Alt+.)');
|
||
speedBtn.setAttribute('title', 'Hız: 1x (Alt+.)');
|
||
speedBtn.innerHTML =
|
||
'<span class="yaktube-vjs-seek-icon" aria-hidden="true">⚡<span class="yaktube-vjs-speed-val">1x</span></span>' +
|
||
'<span class="vjs-control-text" aria-live="polite">Hız Değiştir</span>';
|
||
|
||
speedBtn.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
var video = getVideoElement();
|
||
if (video) {
|
||
var speeds = [1, 1.25, 1.5, 1.75, 2, 0.5, 0.75];
|
||
var cur = video.playbackRate || 1;
|
||
var curIdx = speeds.indexOf(cur);
|
||
var nextSpeed = curIdx === -1 ? 1 : speeds[(curIdx + 1) % speeds.length];
|
||
video.playbackRate = nextSpeed;
|
||
var speedText = nextSpeed + 'x';
|
||
var numEl = speedBtn.querySelector('.yaktube-vjs-speed-val');
|
||
if (numEl) numEl.textContent = speedText;
|
||
speedBtn.setAttribute('aria-label', 'Oynatma Hızı: ' + speedText);
|
||
speedBtn.setAttribute('title', 'Hız: ' + speedText + ' (Alt+.)');
|
||
announce('Oynatma hızı: ' + speedText);
|
||
showQuickToast('⚡ Hız: ' + speedText);
|
||
}
|
||
});
|
||
|
||
if (forwardBtn && forwardBtn.nextSibling) {
|
||
controlBar.insertBefore(speedBtn, forwardBtn.nextSibling);
|
||
} else {
|
||
controlBar.appendChild(speedBtn);
|
||
}
|
||
} else {
|
||
var v = getVideoElement();
|
||
if (v) {
|
||
var curRate = (v.playbackRate || 1) + 'x';
|
||
var numEl = speedBtn.querySelector('.yaktube-vjs-speed-val');
|
||
if (numEl && numEl.textContent !== curRate) {
|
||
numEl.textContent = curRate;
|
||
speedBtn.setAttribute('aria-label', 'Oynatma Hızı: ' + curRate);
|
||
speedBtn.setAttribute('title', 'Hız: ' + curRate + ' (Alt+.)');
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
function enhanceVideoPlayerAccessibility() {
|
||
var isWatch = isWatchUrl();
|
||
var skipLink = document.getElementById('yaktube-skip-to-player');
|
||
|
||
if (!isWatch) {
|
||
if (skipLink) skipLink.remove();
|
||
return;
|
||
}
|
||
|
||
// 0. Handle Video Alert accessibility & live announcement (e.g. transcoding/playback warnings)
|
||
var alertEl = document.querySelector('my-video-alert, .video-alert, .alert-warning, .vjs-error-display');
|
||
if (alertEl && !alertEl.hasAttribute('data-yaktube-alert-handled')) {
|
||
alertEl.setAttribute('data-yaktube-alert-handled', 'true');
|
||
alertEl.setAttribute('role', 'alert');
|
||
alertEl.setAttribute('aria-live', 'assertive');
|
||
var alertText = alertEl.textContent ? alertEl.textContent.trim().replace(/\s+/g, ' ') : '';
|
||
if (alertText) {
|
||
announce('Video Uyarısı: ' + alertText, true);
|
||
}
|
||
}
|
||
|
||
// 1. Remove harmful role="application" from video and containers
|
||
var videos = document.querySelectorAll('video, .vjs-tech');
|
||
videos.forEach(function (v) {
|
||
if (v.getAttribute('role') === 'application' || v.hasAttribute('role')) {
|
||
v.removeAttribute('role');
|
||
}
|
||
});
|
||
|
||
var appElements = document.querySelectorAll(
|
||
'#video-wrapper [role="application"], #videojs-wrapper [role="application"], .video-js [role="application"]'
|
||
);
|
||
appElements.forEach(function (el) {
|
||
el.removeAttribute('role');
|
||
});
|
||
|
||
// 2. Fetch current video title for accessible announcements
|
||
var titleEl = document.querySelector(
|
||
'h1.video-info-name, .video-info-name h1, my-video-watch h1, .video-title, .title'
|
||
);
|
||
var videoTitle = titleEl
|
||
? titleEl.textContent.trim()
|
||
: document.title
|
||
? document.title.replace(/\s*-\s*(PeerTube|YakTube).*$/i, '').trim()
|
||
: 'Video';
|
||
|
||
// 3. Setup Top-Level Skip Link: "🎬 Video Oynatıcıya Atla (Alt+P)"
|
||
if (!skipLink && !isEmbedUrl()) {
|
||
skipLink = document.createElement('a');
|
||
skipLink.id = 'yaktube-skip-to-player';
|
||
skipLink.className = 'yaktube-skip-link';
|
||
skipLink.href = '#videojs-wrapper';
|
||
skipLink.textContent = '🎬 Video Oynatıcıya Atla (Alt+P)';
|
||
skipLink.setAttribute('aria-label', 'Video Oynatıcıya Atla (Alt+P)');
|
||
skipLink.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
focusVideoPlayer();
|
||
});
|
||
}
|
||
|
||
if (skipLink && !isEmbedUrl()) {
|
||
var skipContent = document.querySelector('.skip-to-content, a[href*="content"]');
|
||
if (skipContent) {
|
||
if (skipContent.nextElementSibling !== skipLink) {
|
||
skipContent.insertAdjacentElement('afterend', skipLink);
|
||
}
|
||
} else if (skipLink.parentElement !== document.body) {
|
||
document.body.insertBefore(skipLink, document.body.firstChild);
|
||
}
|
||
}
|
||
|
||
// 4. Configure Player Container (#videojs-wrapper or .video-js or #video-wrapper)
|
||
var playerWrapper =
|
||
document.getElementById('videojs-wrapper') ||
|
||
document.querySelector('.video-js') ||
|
||
document.getElementById('video-wrapper');
|
||
if (playerWrapper) {
|
||
if (!playerWrapper.hasAttribute('data-yaktube-a11y-enhanced')) {
|
||
playerWrapper.setAttribute('data-yaktube-a11y-enhanced', 'true');
|
||
playerWrapper.setAttribute('role', 'region');
|
||
playerWrapper.setAttribute('aria-roledescription', 'Video Oynatıcı');
|
||
playerWrapper.setAttribute('tabindex', '0');
|
||
|
||
// Focus event: announce player status
|
||
playerWrapper.addEventListener('focus', function () {
|
||
var v = getVideoElement();
|
||
var status = v ? (v.paused ? 'Duraklatıldı' : 'Oynatılıyor') : '';
|
||
var curTitleEl = document.querySelector(
|
||
'h1.video-info-name, .video-info-name h1, my-video-watch h1, .video-title, .title'
|
||
);
|
||
var curTitle = curTitleEl ? curTitleEl.textContent.trim() : videoTitle;
|
||
announce(
|
||
'Video oynatıcı seçildi: ' +
|
||
curTitle +
|
||
(status ? ' (' + status + ')' : '') +
|
||
'. Oynatmak için Boşluk veya K, sarmak için J veya L, ses için ok tuşlarını kullanabilirsiniz.'
|
||
);
|
||
});
|
||
|
||
// Keydown handler when player container is focused
|
||
playerWrapper.addEventListener('keydown', function (e) {
|
||
var video = getVideoElement();
|
||
if (!video) return;
|
||
|
||
// Space or K: Toggle Play/Pause
|
||
if (e.key === ' ' || e.key === 'k' || e.key === 'K') {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
if (video.paused) {
|
||
video.play();
|
||
announce('Video oynatılıyor.');
|
||
showQuickToast('▶️ Oynatılıyor');
|
||
} else {
|
||
video.pause();
|
||
announce('Video duraklatıldı.');
|
||
showQuickToast('⏸️ Duraklatıldı');
|
||
}
|
||
return;
|
||
}
|
||
|
||
// Left Arrow or J: Rewind 10s
|
||
if ((e.key === 'ArrowLeft' && !e.altKey) || e.key === 'j' || e.key === 'J') {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
video.currentTime = Math.max(0, video.currentTime - 10);
|
||
announce('10 saniye geri sarıldı. Konum: ' + formatTime(video.currentTime));
|
||
showQuickToast('⏪ -10sn');
|
||
return;
|
||
}
|
||
|
||
// Right Arrow or L: Forward 10s
|
||
if ((e.key === 'ArrowRight' && !e.altKey) || e.key === 'l' || e.key === 'L') {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
video.currentTime = Math.min(video.duration || 999999, video.currentTime + 10);
|
||
announce('10 saniye ileri sarıldı. Konum: ' + formatTime(video.currentTime));
|
||
showQuickToast('⏩ +10sn');
|
||
return;
|
||
}
|
||
|
||
// Up Arrow: Volume +5%
|
||
if (e.key === 'ArrowUp') {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
video.volume = Math.min(1, Math.round((video.volume + 0.05) * 100) / 100);
|
||
var pctUp = Math.round(video.volume * 100);
|
||
announce('Ses seviyesi yüzde ' + pctUp);
|
||
showQuickToast('🔊 Ses: %' + pctUp);
|
||
return;
|
||
}
|
||
|
||
// Down Arrow: Volume -5%
|
||
if (e.key === 'ArrowDown') {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
video.volume = Math.max(0, Math.round((video.volume - 0.05) * 100) / 100);
|
||
var pctDown = Math.round(video.volume * 100);
|
||
announce('Ses seviyesi yüzde ' + pctDown);
|
||
showQuickToast('🔉 Ses: %' + pctDown);
|
||
return;
|
||
}
|
||
|
||
// M: Mute toggle
|
||
if (e.key === 'm' || e.key === 'M') {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
video.muted = !video.muted;
|
||
announce(video.muted ? 'Ses kapatıldı (Sessiz).' : 'Ses açıldı.');
|
||
showQuickToast(video.muted ? '🔇 Sessiz' : '🔊 Ses Açık');
|
||
return;
|
||
}
|
||
|
||
// F: Fullscreen toggle
|
||
if (e.key === 'f' || e.key === 'F') {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
var pTarget = document.querySelector('#video-wrapper') || playerWrapper;
|
||
if (!document.fullscreenElement) {
|
||
if (pTarget.requestFullscreen) pTarget.requestFullscreen();
|
||
announce('Tam ekran moduna geçildi.');
|
||
showQuickToast('⛶ Tam Ekran');
|
||
} else {
|
||
if (document.exitFullscreen) document.exitFullscreen();
|
||
announce('Tam ekrandan çıkıldı.');
|
||
showQuickToast('⛶ Normal Ekran');
|
||
}
|
||
return;
|
||
}
|
||
|
||
// T: Theater mode toggle
|
||
if (e.key === 't' || e.key === 'T') {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
document.body.classList.toggle('yaktube-theater-mode');
|
||
var isTheater = document.body.classList.contains('yaktube-theater-mode');
|
||
announce(isTheater ? 'Sinema modu açıldı.' : 'Sinema modundan çıkıldı.');
|
||
showQuickToast(isTheater ? '🎭 Sinema Modu' : '🎬 Normal Mod');
|
||
return;
|
||
}
|
||
|
||
// 0-9: Seek percent
|
||
if (/^[0-9]$/.test(e.key) && video.duration) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
var pct = parseInt(e.key, 10) * 10;
|
||
video.currentTime = (video.duration * pct) / 100;
|
||
announce('Yüzde ' + pct + ' konumuna sarıldı. Konum: ' + formatTime(video.currentTime));
|
||
showQuickToast('📍 %' + pct);
|
||
return;
|
||
}
|
||
|
||
// Shift+N: Next Video (Smart First Recommendation)
|
||
if (e.shiftKey && (e.key === 'n' || e.key === 'N')) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
if (
|
||
!(typeof window.__yaktube_is_playlist_watch === 'function' && window.__yaktube_is_playlist_watch()) &&
|
||
typeof window.__yaktube_play_next_smart__ === 'function'
|
||
) {
|
||
window.__yaktube_play_next_smart__('player-shortcut-shift-n');
|
||
return;
|
||
}
|
||
var nextBtn = document.querySelector('.vjs-next-video, .vjs-next-video-control, .vjs-next-control');
|
||
if (nextBtn) {
|
||
nextBtn.click();
|
||
announce('Sonraki videoya geçiliyor...');
|
||
}
|
||
return;
|
||
}
|
||
|
||
// Alt+H or ?: Shortcuts modal
|
||
if ((e.altKey && (e.key === 'h' || e.key === 'H')) || e.key === '?') {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
toggleShortcutsModal();
|
||
return;
|
||
}
|
||
});
|
||
}
|
||
|
||
// 4.1. Inject 10s Rewind & Forward buttons directly into Video.js control bar (Phones & Desktop)
|
||
injectControlBarSeekButtons(playerWrapper);
|
||
|
||
// Dynamic ARIA label updating with current title
|
||
var curAriaLabel =
|
||
'Video Oynatıcı: ' +
|
||
videoTitle +
|
||
'. Oynatmak için Boşluk veya K, sarmak için J veya L, ses seviyesi için Yukarı veya Aşağı ok tuşları, kısayol listesi için Alt+H tuşlarını kullanabilirsiniz.';
|
||
if (playerWrapper.getAttribute('aria-label') !== curAriaLabel) {
|
||
playerWrapper.setAttribute('aria-label', curAriaLabel);
|
||
}
|
||
}
|
||
|
||
// 5. Sanitize Unlocalized & Confusing Watch Page Controls
|
||
sanitizeWatchPageLabels(videoTitle);
|
||
}
|
||
|
||
// 3.1. Injects Accessible Player Action Bar under the Watch Video
|
||
function injectAccessiblePlayerBar() {
|
||
if (!isWatchUrl()) return;
|
||
if (isEmbedUrl()) return;
|
||
|
||
var targetContainer = document.querySelector(
|
||
'my-video-watch, .video-watch, .watch-container, #yaktube-ondemand-container, .player-container, #video-wrapper, #videojs-wrapper'
|
||
);
|
||
if (!targetContainer) return;
|
||
|
||
var existingBar = document.getElementById('yaktube-player-action-bar');
|
||
if (existingBar) return;
|
||
|
||
var bar = document.createElement('div');
|
||
bar.id = 'yaktube-player-action-bar';
|
||
bar.className = 'yaktube-player-action-bar';
|
||
bar.setAttribute('role', 'toolbar');
|
||
bar.setAttribute('aria-label', 'Video Araçları ve Ek Özellikler');
|
||
|
||
var initialAutoPlay = true;
|
||
try {
|
||
initialAutoPlay = localStorage.getItem('yaktube_smart_autoplay') !== 'false';
|
||
} catch (e) {}
|
||
|
||
bar.innerHTML =
|
||
'<span class="yaktube-player-bar-label">🛠️ Video Araçları:</span>' +
|
||
'<button id="yaktube-bar-back-btn" class="yaktube-player-action-btn" aria-label="Önceki Sayfaya Geri Dön (Alt+Sol Ok)" title="Önceki Sayfaya Geri Dön (Alt+Sol Ok)">⬅️ Geri Dön</button>' +
|
||
'<button id="yaktube-bar-next-btn" class="yaktube-player-action-btn" aria-label="Sıradaki İlk Önerilen Videoyu Oynat (Shift+N)" title="Sıradaki İlk Önerilen Videoyu Oynat (Shift+N)">⏭️ Sonraki</button>' +
|
||
'<button id="yaktube-bar-autoplay-btn" class="yaktube-player-action-btn" role="switch" aria-checked="' +
|
||
(initialAutoPlay ? 'true' : 'false') +
|
||
'" aria-label="Akıllı Otomatik Oynatma: ' +
|
||
(initialAutoPlay ? 'Açık' : 'Kapalı') +
|
||
'" title="Video bittiğinde ilk öneriyi otomatik oynat">' +
|
||
(initialAutoPlay ? '🔁 Oto-Oynat: Açık' : '🔁 Oto-Oynat: Kapalı') +
|
||
'</button>' +
|
||
'<button id="yaktube-bar-speed-btn" class="yaktube-player-action-btn" aria-label="Oynatma Hızını Değiştir (Alt+.)">⚡ Hız</button>' +
|
||
'<button id="yaktube-bar-sleep-btn" class="yaktube-player-action-btn" aria-label="Uyku Zamanlayıcısı (Alt+U)">⏱️ Uyku</button>' +
|
||
'<button id="yaktube-bar-qr-btn" class="yaktube-player-action-btn" aria-label="Telefonda Devam Et / QR Kod (Alt+Q)">📱 Telefonda Aç</button>' +
|
||
'<button id="yaktube-bar-theater-btn" class="yaktube-player-action-btn" aria-label="Sinema Modunu Aç/Kapat (Alt+T)">🎭 Sinema</button>' +
|
||
'<button id="yaktube-bar-info-btn" class="yaktube-player-action-btn" aria-label="Video Bilgisi ve İstatistikleri (Alt+I)">📊 Bilgi</button>' +
|
||
'<button id="yaktube-bar-audio-btn" class="yaktube-player-action-btn" aria-label="Yalnızca Ses ve Ekran Karartma Modu (Alt+O)" title="Yalnızca Ses & Ekran Karart (Alt+O)">📻 Ses Modu</button>' +
|
||
'<button id="yaktube-bar-studio-btn" class="yaktube-player-action-btn" aria-label="Canlı Ses Stüdyosu EQ ve Yüzde 300 Boost (Alt+E)" title="Ses Stüdyosu (Alt+E)">🎛️ Ses Stüdyosu</button>' +
|
||
'<button id="yaktube-bar-ab-btn" class="yaktube-player-action-btn" aria-label="A-B Tekrar Döngüsü İşaretle veya Kapat (Alt+B)" title="A-B Tekrar Döngüsü (Alt+B)">🔂 A-B Döngü</button>' +
|
||
'<button id="yaktube-bar-queue-btn" class="yaktube-player-action-btn" aria-label="Kişisel Çalma Sırası Çekmecesi (Alt+R)" title="Çalma Sırası (Alt+R)">📋 Sıra</button>' +
|
||
'<button id="yaktube-bar-transcript-btn" class="yaktube-player-action-btn" aria-label="Canlı Video Transkripti ve Bölümler (Alt+C)" title="Transkript & Bölümler (Alt+C)">📜 Transkript</button>' +
|
||
'<button id="yaktube-bar-share-btn" class="yaktube-player-action-btn" aria-label="Temiz Fediverse Paylaşımı (Alt+S)" title="Temiz Paylaşım (Alt+S)">🔗 Paylaş</button>' +
|
||
'<button id="yaktube-bar-help-btn" class="yaktube-player-action-btn" aria-label="Kısayol Kılavuzu (Alt+H veya F1)">⌨️ Kısayollar</button>';
|
||
|
||
var playerWrap = document.querySelector(
|
||
'#video-wrapper, #videojs-wrapper, .player-container, .video-player-container, .player-wrapper, my-video-watch .player'
|
||
);
|
||
if (playerWrap && playerWrap.parentNode) {
|
||
if (playerWrap.nextSibling) {
|
||
playerWrap.parentNode.insertBefore(bar, playerWrap.nextSibling);
|
||
} else {
|
||
playerWrap.parentNode.appendChild(bar);
|
||
}
|
||
} else {
|
||
var vBottom = document.querySelector('.video-bottom, .video-info');
|
||
if (vBottom && vBottom.parentNode) {
|
||
vBottom.parentNode.insertBefore(bar, vBottom);
|
||
} else {
|
||
targetContainer.prepend(bar);
|
||
}
|
||
}
|
||
|
||
// Attach button actions
|
||
var backBtn = bar.querySelector('#yaktube-bar-back-btn');
|
||
if (backBtn) {
|
||
backBtn.addEventListener('click', function () {
|
||
if (window.history.length > 1) {
|
||
window.history.back();
|
||
} else {
|
||
window.location.href = '/videos/overview';
|
||
}
|
||
});
|
||
}
|
||
|
||
var nextBarBtn = bar.querySelector('#yaktube-bar-next-btn');
|
||
if (nextBarBtn) {
|
||
nextBarBtn.addEventListener('click', function () {
|
||
if (typeof window.__yaktube_play_next_smart__ === 'function') {
|
||
window.__yaktube_play_next_smart__('action-bar-next');
|
||
}
|
||
});
|
||
}
|
||
|
||
var autoPlayBarBtn = bar.querySelector('#yaktube-bar-autoplay-btn');
|
||
if (autoPlayBarBtn) {
|
||
autoPlayBarBtn.addEventListener('click', function () {
|
||
if (typeof window.__yaktube_toggle_smart_autoplay__ === 'function') {
|
||
window.__yaktube_toggle_smart_autoplay__();
|
||
}
|
||
});
|
||
}
|
||
|
||
bar.querySelector('#yaktube-bar-speed-btn').addEventListener('click', function () {
|
||
adjustPlaybackSpeed(true);
|
||
});
|
||
|
||
var sleepBtn = bar.querySelector('#yaktube-bar-sleep-btn');
|
||
if (sleepBtn) {
|
||
sleepBtn.addEventListener('click', function () {
|
||
openSleepTimerModal();
|
||
});
|
||
}
|
||
|
||
var qrBtn = bar.querySelector('#yaktube-bar-qr-btn');
|
||
if (qrBtn) {
|
||
qrBtn.addEventListener('click', function () {
|
||
openPhoneTransferModal();
|
||
});
|
||
}
|
||
|
||
bar.querySelector('#yaktube-bar-theater-btn').addEventListener('click', function () {
|
||
document.body.classList.toggle('yaktube-theater-mode');
|
||
var isT = document.body.classList.contains('yaktube-theater-mode');
|
||
announce(isT ? 'Sinema modu açıldı.' : 'Sinema modundan çıkıldı.');
|
||
});
|
||
|
||
bar.querySelector('#yaktube-bar-info-btn').addEventListener('click', function () {
|
||
showQuickVideoInfo();
|
||
});
|
||
|
||
var audioBtn = bar.querySelector('#yaktube-bar-audio-btn');
|
||
if (audioBtn) {
|
||
audioBtn.addEventListener('click', function () {
|
||
toggleAudioOnlyMode();
|
||
});
|
||
}
|
||
|
||
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 () {
|
||
openTranscriptPanel();
|
||
});
|
||
}
|
||
|
||
var shareBtn = bar.querySelector('#yaktube-bar-share-btn');
|
||
if (shareBtn) {
|
||
shareBtn.addEventListener('click', function () {
|
||
openCleanShareModal();
|
||
});
|
||
}
|
||
|
||
bar.querySelector('#yaktube-bar-help-btn').addEventListener('click', function () {
|
||
toggleShortcutsModal();
|
||
});
|
||
}
|
||
|
||
// 4. Global Keydown Listener (Screen-Reader & Turkish Q Optimized)
|
||
window.addEventListener('keydown', function (e) {
|
||
if (e.key === 'Escape') {
|
||
var quotaModal = document.getElementById('yaktube-quota-modal');
|
||
if (quotaModal) {
|
||
quotaModal.remove();
|
||
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();
|
||
announce('Uyku zamanlayıcısı penceresi kapatıldı.');
|
||
return;
|
||
}
|
||
var qrModal = document.getElementById('yaktube-qr-modal');
|
||
if (qrModal) {
|
||
qrModal.remove();
|
||
announce('Telefonda devam et penceresi kapatıldı.');
|
||
return;
|
||
}
|
||
var shortcutsModal = document.getElementById('yaktube-shortcuts-dialog');
|
||
if (shortcutsModal && shortcutsModal.style.display !== 'none') {
|
||
shortcutsModal.style.display = 'none';
|
||
announce('Pencere kapatıldı.');
|
||
return;
|
||
}
|
||
var importModal = document.getElementById('yaktube-import-modal');
|
||
if (importModal && importModal.style.display !== 'none') {
|
||
importModal.style.display = 'none';
|
||
announce('İndirme penceresi kapatıldı.');
|
||
return;
|
||
}
|
||
if (isInputFocused()) {
|
||
document.activeElement.blur();
|
||
}
|
||
return;
|
||
}
|
||
|
||
// Jump to Video Player: Alt+P or Shift+P
|
||
if (
|
||
((e.altKey && (e.key === 'p' || e.key === 'P')) || (e.shiftKey && (e.key === 'p' || e.key === 'P'))) &&
|
||
!isInputFocused()
|
||
) {
|
||
e.preventDefault();
|
||
focusVideoPlayer();
|
||
return;
|
||
}
|
||
|
||
// Admin Login: Alt+A
|
||
if (e.altKey && (e.key === 'a' || e.key === 'A') && !isInputFocused()) {
|
||
e.preventDefault();
|
||
openLocalAdminLoginModal();
|
||
return;
|
||
}
|
||
|
||
// Sleep Timer: Alt+U
|
||
if (e.altKey && (e.key === 'u' || e.key === 'U') && !isInputFocused()) {
|
||
e.preventDefault();
|
||
openSleepTimerModal();
|
||
return;
|
||
}
|
||
|
||
// Phone QR Transfer: Alt+Q
|
||
if (e.altKey && (e.key === 'q' || e.key === 'Q') && !isInputFocused()) {
|
||
e.preventDefault();
|
||
openPhoneTransferModal();
|
||
return;
|
||
}
|
||
|
||
// Help Dialog: Alt+H, F1 or '?' key
|
||
if ((e.altKey && (e.key === 'h' || e.key === 'H')) || e.key === 'F1' || e.key === '?') {
|
||
if (!isInputFocused()) {
|
||
e.preventDefault();
|
||
toggleShortcutsModal();
|
||
return;
|
||
}
|
||
}
|
||
|
||
// 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.shiftKey && (e.key === 'k' || e.key === 'K')) ||
|
||
e.key === '/') &&
|
||
!isInputFocused()
|
||
) {
|
||
e.preventDefault();
|
||
openFullSearchModal('', false);
|
||
return;
|
||
}
|
||
|
||
// F6 or Shift+F6: Landmark Navigation (WCAG 2.2 AAA)
|
||
if (e.key === 'F6') {
|
||
e.preventDefault();
|
||
cycleLandmarks(e.shiftKey);
|
||
return;
|
||
}
|
||
|
||
// Audio-Only Mode: Alt+O
|
||
if (e.altKey && (e.key === 'o' || e.key === 'O') && !isInputFocused()) {
|
||
e.preventDefault();
|
||
toggleAudioOnlyMode();
|
||
return;
|
||
}
|
||
|
||
// Live Transcript: Alt+C
|
||
if (e.altKey && (e.key === 'c' || e.key === 'C') && !isInputFocused()) {
|
||
e.preventDefault();
|
||
openTranscriptPanel();
|
||
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'))) &&
|
||
!isInputFocused()
|
||
) {
|
||
e.preventDefault();
|
||
openFullSearchModal('', true);
|
||
return;
|
||
}
|
||
|
||
if (isInputFocused()) {
|
||
return;
|
||
}
|
||
|
||
var video = getVideoElement();
|
||
if (!video) return;
|
||
|
||
var key = e.key.toLowerCase();
|
||
var alt = e.altKey;
|
||
|
||
// Play / Pause (Alt+K, Space or K)
|
||
if (key === ' ' || key === 'k' || (alt && key === 'k')) {
|
||
e.preventDefault();
|
||
if (video.paused) {
|
||
video.play();
|
||
announce('Video oynatılıyor.');
|
||
} else {
|
||
video.pause();
|
||
announce('Video duraklatıldı.');
|
||
}
|
||
}
|
||
// Seek 10s Back / Forward (Alt+J / Alt+L or J / L)
|
||
else if (key === 'j' || (alt && key === 'j')) {
|
||
e.preventDefault();
|
||
video.currentTime = Math.max(0, video.currentTime - 10);
|
||
announce('10 saniye geri sarıldı. Konum: ' + formatTime(video.currentTime));
|
||
} else if (key === 'l' || (alt && key === 'l')) {
|
||
e.preventDefault();
|
||
video.currentTime = Math.min(video.duration || 99999, video.currentTime + 10);
|
||
announce('10 saniye ileri sarıldı. Konum: ' + formatTime(video.currentTime));
|
||
}
|
||
// Seek 5s Back / Forward (ArrowLeft / ArrowRight or Alt+Left/Right)
|
||
else if (e.key === 'ArrowLeft' && !alt) {
|
||
e.preventDefault();
|
||
video.currentTime = Math.max(0, video.currentTime - 5);
|
||
announce('5 saniye geri sarıldı. Konum: ' + formatTime(video.currentTime));
|
||
} else if (e.key === 'ArrowRight' && !alt) {
|
||
e.preventDefault();
|
||
video.currentTime = Math.min(video.duration || 99999, video.currentTime + 5);
|
||
announce('5 saniye ileri sarıldı. Konum: ' + formatTime(video.currentTime));
|
||
}
|
||
// Volume Up / Down (ArrowUp / ArrowDown or Alt+Up/Down)
|
||
else if (e.key === 'ArrowUp' || (alt && e.key === 'ArrowUp')) {
|
||
e.preventDefault();
|
||
video.volume = Math.min(1, (video.volume || 1) + 0.05);
|
||
announce('Ses seviyesi yüzde ' + Math.round(video.volume * 100));
|
||
} else if (e.key === 'ArrowDown' || (alt && e.key === 'ArrowDown')) {
|
||
e.preventDefault();
|
||
video.volume = Math.max(0, (video.volume || 1) - 0.05);
|
||
announce('Ses seviyesi yüzde ' + Math.round(video.volume * 100));
|
||
}
|
||
// Mute (Alt+M or M)
|
||
else if (key === 'm' || (alt && key === 'm')) {
|
||
e.preventDefault();
|
||
video.muted = !video.muted;
|
||
announce(video.muted ? 'Ses kapatıldı (Sessiz).' : 'Ses açıldı.');
|
||
}
|
||
// Fullscreen (Alt+F or F)
|
||
else if (key === 'f' || (alt && key === 'f')) {
|
||
e.preventDefault();
|
||
if (!document.fullscreenElement) {
|
||
var container = video.closest('.video-js') || video.parentElement || video;
|
||
if (container.requestFullscreen) container.requestFullscreen();
|
||
announce('Tam ekran moduna geçildi.');
|
||
} else {
|
||
if (document.exitFullscreen) document.exitFullscreen();
|
||
announce('Tam ekrandan çıkıldı.');
|
||
}
|
||
}
|
||
// Theater Mode (Alt+T or T)
|
||
else if (key === 't' || (alt && key === 't')) {
|
||
e.preventDefault();
|
||
document.body.classList.toggle('yaktube-theater-mode');
|
||
var isTheater = document.body.classList.contains('yaktube-theater-mode');
|
||
announce(isTheater ? 'Sinema modu açıldı.' : 'Sinema modundan çıkıldı.');
|
||
}
|
||
// Quick Video Info (Alt+I or I)
|
||
else if (key === 'i' || (alt && key === 'i')) {
|
||
e.preventDefault();
|
||
showQuickVideoInfo();
|
||
}
|
||
// Subtitles (Alt+C or C)
|
||
else if (key === 'c' || (alt && key === 'c')) {
|
||
e.preventDefault();
|
||
var tracks = video.textTracks;
|
||
if (tracks && tracks.length > 0) {
|
||
var isShowing = tracks[0].mode === 'showing';
|
||
tracks[0].mode = isShowing ? 'disabled' : 'showing';
|
||
announce(isShowing ? 'Altyazılar kapatıldı.' : 'Altyazılar açıldı.');
|
||
} else {
|
||
announce('Bu videoda altyazı bulunmuyor.');
|
||
}
|
||
}
|
||
// Speed Controls (Alt+. / Alt+, or > / <)
|
||
else if ((alt && (e.key === '.' || e.key === '>')) || e.key === '>') {
|
||
e.preventDefault();
|
||
adjustPlaybackSpeed(true);
|
||
} else if ((alt && (e.key === ',' || e.key === '<')) || e.key === '<') {
|
||
e.preventDefault();
|
||
adjustPlaybackSpeed(false);
|
||
}
|
||
// Next Video: Shift+N or Alt+N (Plays #1 Smart Recommendation)
|
||
else if ((e.shiftKey && key === 'n') || (alt && key === 'n')) {
|
||
e.preventDefault();
|
||
if (
|
||
!(typeof window.__yaktube_is_playlist_watch === 'function' && window.__yaktube_is_playlist_watch()) &&
|
||
typeof window.__yaktube_play_next_smart__ === 'function'
|
||
) {
|
||
window.__yaktube_play_next_smart__('global-shortcut-shift-n');
|
||
} else {
|
||
var nextBtnGlobal = document.querySelector('.vjs-next-video, .vjs-next-video-control, .vjs-next-control');
|
||
if (nextBtnGlobal) nextBtnGlobal.click();
|
||
}
|
||
}
|
||
// Percentage Jumps (0 - 9)
|
||
else if (key >= '0' && key <= '9' && !e.ctrlKey && !e.altKey && !e.metaKey) {
|
||
e.preventDefault();
|
||
var percent = parseInt(key, 10) * 10;
|
||
if (video.duration) {
|
||
video.currentTime = (video.duration * percent) / 100;
|
||
announce('Videonun yüzde ' + percent + ' noktasına atlandı. Konum: ' + formatTime(video.currentTime));
|
||
}
|
||
}
|
||
});
|
||
|
||
// 5. On-Demand Search & Import with Duplicate Awareness
|
||
var lastQuery = null;
|
||
var lastSearchTarget = null;
|
||
var isSearching = false;
|
||
|
||
function escapeHtml(str) {
|
||
if (!str) return '';
|
||
return String(str)
|
||
.replace(/&/g, '&')
|
||
.replace(/</g, '<')
|
||
.replace(/>/g, '>')
|
||
.replace(/"/g, '"')
|
||
.replace(/'/g, ''');
|
||
}
|
||
|
||
function formatClockTime(seconds) {
|
||
if (isNaN(seconds) || seconds < 0) return '00:00';
|
||
var hrs = Math.floor(seconds / 3600);
|
||
var mins = Math.floor((seconds % 3600) / 60);
|
||
var secs = Math.floor(seconds % 60);
|
||
var sSecs = (secs < 10 ? '0' : '') + secs;
|
||
if (hrs > 0) {
|
||
var sMins = (mins < 10 ? '0' : '') + mins;
|
||
return hrs + ':' + sMins + ':' + sSecs;
|
||
}
|
||
return (mins < 10 ? '0' : '') + mins + ':' + sSecs;
|
||
}
|
||
|
||
function switchSearchTarget(target) {
|
||
var radio = document.getElementById(target === 'local' ? 'searchTargetLocal' : 'searchTargetSearchIndex');
|
||
if (radio) {
|
||
radio.checked = true;
|
||
radio.dispatchEvent(new Event('change', { bubbles: true }));
|
||
radio.dispatchEvent(new Event('input', { bubbles: true }));
|
||
var form = radio.closest('form');
|
||
var submitBtn = form ? form.querySelector('.submit-button button') : null;
|
||
if (submitBtn) {
|
||
submitBtn.click();
|
||
return;
|
||
}
|
||
}
|
||
var url = new URL(window.location.href);
|
||
url.searchParams.set('searchTarget', target);
|
||
window.location.href = url.toString();
|
||
}
|
||
|
||
function ensureFediverseBridge(query, currentSearchTarget) {
|
||
var searchMount = document.querySelector('my-search, my-search-results');
|
||
if (!searchMount) return;
|
||
|
||
var bridge = document.getElementById('yaktube-fediverse-bridge');
|
||
var ondemandContainer = document.getElementById('yaktube-ondemand-container');
|
||
var searchResult = searchMount.querySelector('.search-result');
|
||
|
||
if (!bridge) {
|
||
bridge = document.createElement('div');
|
||
bridge.id = 'yaktube-fediverse-bridge';
|
||
bridge.className = 'yaktube-fediverse-bridge';
|
||
bridge.setAttribute('role', 'region');
|
||
bridge.setAttribute('aria-label', 'Fediverse Video Arama Ağı ve Kapsam Seçimi');
|
||
}
|
||
|
||
// Ensure bridge is always strictly inside searchMount
|
||
if (ondemandContainer && ondemandContainer.parentElement === searchMount) {
|
||
if (ondemandContainer.nextSibling !== bridge) {
|
||
searchMount.insertBefore(bridge, ondemandContainer.nextSibling);
|
||
}
|
||
} else if (searchResult && searchResult.parentElement === searchMount) {
|
||
if (bridge.nextSibling !== searchResult) {
|
||
searchMount.insertBefore(bridge, searchResult);
|
||
}
|
||
} else if (bridge.parentElement !== searchMount) {
|
||
searchMount.appendChild(bridge);
|
||
}
|
||
|
||
var isFediverse = currentSearchTarget === 'search-index';
|
||
|
||
bridge.innerHTML =
|
||
'<div class="yaktube-fediverse-bridge-content">' +
|
||
'<div class="yaktube-fediverse-bridge-left">' +
|
||
'<div class="yaktube-fediverse-bridge-badge-wrap">' +
|
||
'<span class="yaktube-fediverse-badge">🌐 Fediverse Ağı</span>' +
|
||
'<span class="yaktube-fediverse-status">' +
|
||
(isFediverse
|
||
? 'SepiaSearch Küresel Fediverse Arama Aktif'
|
||
: escapeHtml(getInstanceName()) + ' Yerel Arama Aktif') +
|
||
'</span>' +
|
||
'</div>' +
|
||
'<h2 class="yaktube-fediverse-title">🌐 Fediverse & Küresel Ağ Arama Sonuçları</h2>' +
|
||
'<p class="yaktube-fediverse-sub">Merkeziyetsiz federe ağdaki (SepiaSearch ve bağımsız PeerTube sunucuları) video sonuçları aşağıda listelenmektedir.</p>' +
|
||
'</div>' +
|
||
'<div class="yaktube-scope-selector" role="tablist" aria-label="Arama Kapsamı Seçimi">' +
|
||
'<button type="button" id="yaktube-scope-global-btn" class="yaktube-scope-btn ' +
|
||
(isFediverse ? 'active' : '') +
|
||
'" role="tab" aria-selected="' +
|
||
(isFediverse ? 'true' : 'false') +
|
||
'" aria-label="Tüm Fediverse ve SepiaSearch ağındaki videoları ara" title="Tüm Fediverse genelinde ara">' +
|
||
'🌐 Tüm Fediverse (SepiaSearch)' +
|
||
'</button>' +
|
||
'<button type="button" id="yaktube-scope-local-btn" class="yaktube-scope-btn ' +
|
||
(!isFediverse ? 'active' : '') +
|
||
'" role="tab" aria-selected="' +
|
||
(!isFediverse ? 'true' : 'false') +
|
||
'" aria-label="Sadece ' +
|
||
escapeHtml(getInstanceName()) +
|
||
' yerel sunucusundaki videoları ara" title="Sadece ' +
|
||
escapeHtml(getInstanceName()) +
|
||
' yerel kütüphanesinde ara">' +
|
||
'🏠 Sadece ' +
|
||
escapeHtml(getInstanceName()) +
|
||
' (Yerel)' +
|
||
'</button>' +
|
||
'</div>' +
|
||
'</div>';
|
||
|
||
var globalBtn = document.getElementById('yaktube-scope-global-btn');
|
||
if (globalBtn) {
|
||
globalBtn.addEventListener('click', function () {
|
||
if (currentSearchTarget !== 'search-index') {
|
||
switchSearchTarget('search-index');
|
||
}
|
||
});
|
||
}
|
||
var localBtn = document.getElementById('yaktube-scope-local-btn');
|
||
if (localBtn) {
|
||
localBtn.addEventListener('click', function () {
|
||
if (currentSearchTarget !== 'local') {
|
||
switchSearchTarget('local');
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
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 =
|
||
'<div class="yaktube-bg-import-text">✅ <strong>' +
|
||
safeTitle +
|
||
'</strong> izlemeye hazır!</div>' +
|
||
'<div class="yaktube-bg-import-actions">' +
|
||
'<a href="' +
|
||
escapeHtml(state.watchUrl) +
|
||
'" class="yaktube-bg-import-go-btn">▶️ Şimdi İzle</a>' +
|
||
'<button type="button" id="yaktube-bg-import-queue-btn" class="yaktube-bg-import-sub-btn">➕ Sıraya Ekle</button>' +
|
||
'<button type="button" id="yaktube-bg-import-dismiss-btn" class="yaktube-bg-import-close-btn" aria-label="Bildirimi kapat">✕</button>' +
|
||
'</div>';
|
||
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 =
|
||
'<div class="yaktube-bg-import-text">⚠️ <strong>' +
|
||
safeTitle +
|
||
'</strong> aktarılamadı.</div>' +
|
||
'<button type="button" id="yaktube-bg-import-dismiss-btn" class="yaktube-bg-import-close-btn" aria-label="Hata bildirimini kapat">✕</button>';
|
||
pill.querySelector('#yaktube-bg-import-dismiss-btn').addEventListener('click', function () {
|
||
bgImportMinimized = false;
|
||
pill.remove();
|
||
});
|
||
} else {
|
||
pill.classList.remove('ready');
|
||
pill.innerHTML =
|
||
'<div class="yaktube-bg-import-text">📥 <strong>' +
|
||
safeTitle +
|
||
'</strong> — ' +
|
||
escapeHtml(state.progressLabel || 'Arka planda indiriliyor...') +
|
||
'</div>' +
|
||
'<div class="yaktube-bg-import-actions">' +
|
||
'<button type="button" id="yaktube-bg-import-expand-btn" class="yaktube-bg-import-sub-btn" aria-label="İndirme penceresini büyüt">↗️ Aç</button>' +
|
||
'</div>';
|
||
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');
|
||
overlay.id = 'yaktube-import-modal';
|
||
overlay.className = 'yaktube-modal-overlay';
|
||
overlay.setAttribute('role', 'dialog');
|
||
overlay.setAttribute('aria-modal', 'true');
|
||
overlay.setAttribute('aria-labelledby', 'yaktube-modal-title');
|
||
overlay.innerHTML =
|
||
'<div class="yaktube-modal-card">' +
|
||
'<div class="yaktube-spinner" aria-hidden="true"></div>' +
|
||
'<h3 class="yaktube-modal-title" id="yaktube-modal-title" style="margin-top:0;">' +
|
||
(title || "YakTube'a Aktarılıyor...") +
|
||
'</h3>' +
|
||
'<p class="yaktube-modal-desc" id="yaktube-modal-desc">' +
|
||
(desc || 'Seçtiğiniz video D: diskinize aktarılıyor...') +
|
||
'</p>' +
|
||
'<div id="yaktube-modal-min-wrap" style="margin-top:16px; display:none; justify-content:center;">' +
|
||
'<button type="button" id="yaktube-modal-minimize-btn" class="yaktube-audio-action-btn" aria-label="İndirmeyi arka plana at ve gezinmeye devam et">⏬ Arka Plana At (Gezinmeye Devam Et)</button>' +
|
||
'</div>' +
|
||
'</div>';
|
||
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;
|
||
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);
|
||
}
|
||
}
|
||
|
||
function hideModal() {
|
||
var overlay = document.getElementById('yaktube-import-modal');
|
||
if (overlay) overlay.style.display = 'none';
|
||
}
|
||
|
||
function handleLiveStream(url, videoTitle, isRestoring) {
|
||
var videoIdMatch = url.match(/[?&]v=([^&]+)/) || url.match(/youtu\.be\/([^?]+)/);
|
||
var videoId = videoIdMatch ? videoIdMatch[1] : '';
|
||
|
||
if (!videoId) {
|
||
alert('Canl\u0131 yay\u0131n ID bulunamad\u0131.');
|
||
return;
|
||
}
|
||
|
||
// Persist active live stream state in sessionStorage
|
||
try {
|
||
sessionStorage.setItem(
|
||
'yaktube_active_live',
|
||
JSON.stringify({
|
||
url: url,
|
||
title: videoTitle,
|
||
videoId: videoId
|
||
})
|
||
);
|
||
} catch (e) {}
|
||
|
||
var liveContainer = document.getElementById('yaktube-live-watch-container');
|
||
if (liveContainer) liveContainer.remove();
|
||
|
||
liveContainer = document.createElement('div');
|
||
liveContainer.id = 'yaktube-live-watch-container';
|
||
liveContainer.className = 'yaktube-live-watch-section';
|
||
liveContainer.setAttribute('role', 'region');
|
||
liveContainer.setAttribute('tabindex', '-1');
|
||
liveContainer.setAttribute('aria-label', videoTitle + ' Canl\u0131 Yay\u0131n\u0131');
|
||
|
||
liveContainer.innerHTML =
|
||
'<div style="background: #0f172a; border-radius: 12px; padding: 20px; margin-bottom: 24px; box-shadow: 0 10px 30px rgba(0,0,0,0.6); border: 1px solid rgba(255,255,255,0.08); outline: none;">' +
|
||
'<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; flex-wrap: wrap; gap: 10px;">' +
|
||
'<div style="display: flex; align-items: center; gap: 10px;">' +
|
||
'<span style="background: #dc2626; color: #fff; font-size: 12px; padding: 4px 10px; border-radius: 6px; font-weight: 700; display: inline-flex; align-items: center; gap: 6px;">\ud83d\udd34 CANLI YAYIN</span>' +
|
||
'<h1 id="yaktube-live-title" tabindex="0" style="margin: 0; font-size: 1.25rem; font-weight: 700; color: #fff; line-height: 1.3; outline: none;">' +
|
||
videoTitle +
|
||
'</h1>' +
|
||
'</div>' +
|
||
'<button id="yaktube-close-live-theater" style="background: #334155; color: #fff; border: none; padding: 8px 16px; border-radius: 8px; font-weight: 600; cursor: pointer; font-size: 13px; display: inline-flex; align-items: center; gap: 6px;" aria-label="Canl\u0131 Yay\u0131n \u0130zleme Alan\u0131n\u0131 Kapat (Escape)">' +
|
||
'\u2715 Yay\u0131n\u0131 Kapat (Esc)' +
|
||
'</button>' +
|
||
'</div>' +
|
||
'<div style="position: relative; padding-top: 56.25%; width: 100%; background: #000; border-radius: 10px; overflow: hidden; box-shadow: 0 8px 24px rgba(0,0,0,0.7);">' +
|
||
'<iframe id="yaktube-live-iframe" src="https://www.youtube-nocookie.com/embed/' +
|
||
videoId +
|
||
'?autoplay=1&rel=0&modestbranding=1&enablejsapi=1" title="' +
|
||
videoTitle.replace(/"/g, '"') +
|
||
'" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0;" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>' +
|
||
'</div>' +
|
||
'<div style="margin-top: 14px; display: flex; justify-content: space-between; align-items: center; color: #94a3b8; font-size: 13px;">' +
|
||
'<div>\ud83d\udce1 YakTube Canl\u0131 Yay\u0131n Ak\u0131\u015f\u0131 \u2022 Reklams\u0131z ve Kesintisiz</div>' +
|
||
'<div style="color: #64748b;">ESC tu\u015funa basarak yay\u0131n\u0131 kapatabilirsiniz.</div>' +
|
||
'</div>' +
|
||
'<div id="yaktube-live-comments-panel" style="margin-top: 18px; background: #0b1120; border-radius: 10px; padding: 16px; border: 1px solid rgba(255,255,255,0.08);">' +
|
||
'<div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">' +
|
||
'<h2 style="margin: 0; font-size: 15px; font-weight: 700; color: #fff; display: flex; align-items: center; gap: 8px;">' +
|
||
'\ud83d\udcac YouTube Topluluk Yorumlar\u0131' +
|
||
'</h2>' +
|
||
'<button id="yaktube-toggle-comments-btn" style="background: #ff8f37; color: #000; border: none; padding: 7px 16px; border-radius: 6px; font-weight: 700; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 6px;" aria-label="YouTube yorumlar\u0131n\u0131 y\u00fckle ve g\u00f6ster">' +
|
||
'\ud83d\udcac Yorumlar\u0131 G\u00f6ster (20 Yorum)' +
|
||
'</button>' +
|
||
'</div>' +
|
||
'<div id="yaktube-comments-list" style="display: none; margin-top: 14px; flex-direction: column; gap: 12px;"></div>' +
|
||
'<div id="yaktube-more-comments-wrap" style="text-align: center; margin-top: 16px; display: none;">' +
|
||
'<button id="yaktube-load-more-comments-btn" style="background: #1e293b; color: #ff8f37; border: 1px solid #ff8f37; padding: 8px 20px; border-radius: 8px; font-weight: 700; cursor: pointer; font-size: 13px; display: inline-flex; align-items: center; gap: 6px;" aria-label="Daha fazla yorum y\u00fckle">' +
|
||
'\u2795 Daha Fazla Yorum G\u00f6ster (+20 Yorum)' +
|
||
'</button>' +
|
||
'</div>' +
|
||
'</div>' +
|
||
'</div>';
|
||
|
||
var mainMount = document.querySelector('my-search, my-search-results, .main-col .main-row, .main-col, main');
|
||
if (!mainMount) mainMount = document.querySelector('.main-col');
|
||
if (mainMount && mainMount.firstChild) {
|
||
mainMount.insertBefore(liveContainer, mainMount.firstChild);
|
||
} else if (mainMount) {
|
||
mainMount.appendChild(liveContainer);
|
||
}
|
||
|
||
if (!isRestoring) {
|
||
liveContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||
setTimeout(function () {
|
||
var liveTitle = document.getElementById('yaktube-live-title');
|
||
if (liveTitle) liveTitle.focus();
|
||
else liveContainer.focus();
|
||
}, 150);
|
||
announce(
|
||
videoTitle +
|
||
' canl\u0131 yay\u0131n\u0131 ba\u015flat\u0131ld\u0131. Canl\u0131 yay\u0131n alan\u0131na odaklan\u0131ld\u0131.',
|
||
true
|
||
);
|
||
}
|
||
|
||
var commentNextToken = null;
|
||
var commentsList = document.getElementById('yaktube-comments-list');
|
||
var toggleCommentsBtn = document.getElementById('yaktube-toggle-comments-btn');
|
||
var moreCommentsWrap = document.getElementById('yaktube-more-comments-wrap');
|
||
var moreCommentsBtn = document.getElementById('yaktube-load-more-comments-btn');
|
||
|
||
function renderCommentCard(c) {
|
||
var card = document.createElement('div');
|
||
card.className = 'yaktube-comment-item';
|
||
card.setAttribute('role', 'article');
|
||
card.setAttribute('tabindex', '0');
|
||
card.setAttribute('aria-label', c.author + ' isimli kullan\u0131c\u0131n\u0131n yorumu: ' + c.content);
|
||
card.style.cssText =
|
||
'background: #1e293b; padding: 12px 14px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.05); display: flex; gap: 12px; align-items: flex-start;';
|
||
|
||
var avatarLetter = (c.author || 'U').replace('@', '').charAt(0).toUpperCase();
|
||
var avatarHtml =
|
||
'<div style="width: 36px; height: 36px; border-radius: 50%; background: #334155; color: #ff8f37; font-weight: 700; display: flex; align-items: center; justify-content: center; font-size: 14px; flex-shrink: 0;">' +
|
||
avatarLetter +
|
||
'</div>';
|
||
|
||
var safeContent = c.content
|
||
.replace(/&/g, '&')
|
||
.replace(/</g, '<')
|
||
.replace(/>/g, '>')
|
||
.replace(/\n/g, '<br>');
|
||
|
||
card.innerHTML =
|
||
avatarHtml +
|
||
'<div style="flex-grow: 1; min-width: 0;">' +
|
||
'<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 4px; flex-wrap: wrap;">' +
|
||
'<h3 class="yaktube-comment-author-heading" style="margin: 0; font-size: 13px; font-weight: 700; color: #f1f5f9; display: inline-block;">' +
|
||
c.author +
|
||
'</h3>' +
|
||
'<span style="color: #64748b; font-size: 11px;">' +
|
||
c.published +
|
||
'</span>' +
|
||
(c.likeCount && c.likeCount !== '0'
|
||
? '<span style="background: rgba(255,255,255,0.08); color: #94a3b8; font-size: 11px; padding: 2px 6px; border-radius: 4px; display: inline-flex; align-items: center; gap: 4px;">👍 ' +
|
||
c.likeCount +
|
||
'</span>'
|
||
: '') +
|
||
'</div>' +
|
||
'<div style="color: #cbd5e1; font-size: 13px; line-height: 1.45; word-break: break-word;">' +
|
||
safeContent +
|
||
'</div>' +
|
||
'</div>';
|
||
|
||
return card;
|
||
}
|
||
|
||
function fetchComments(token) {
|
||
if (!token) {
|
||
toggleCommentsBtn.disabled = true;
|
||
toggleCommentsBtn.textContent = '⏳ Yorumlar Y\u00fckleniyor...';
|
||
} else {
|
||
moreCommentsBtn.disabled = true;
|
||
moreCommentsBtn.textContent = '⏳ Y\u00fckleniyor...';
|
||
}
|
||
|
||
var commentPath =
|
||
'/youtube-comments?id=' + encodeURIComponent(videoId) + (token ? '&token=' + encodeURIComponent(token) : '');
|
||
fetchPluginJson(commentPath)
|
||
.then(function (res) {
|
||
if (!token) {
|
||
commentsList.innerHTML = '';
|
||
commentsList.style.display = 'flex';
|
||
toggleCommentsBtn.textContent = '🔄 Yorumlar\u0131 Yenile';
|
||
toggleCommentsBtn.disabled = false;
|
||
} else {
|
||
moreCommentsBtn.textContent = '➕ Daha Fazla Yorum G\u00f6ster (+20 Yorum)';
|
||
moreCommentsBtn.disabled = false;
|
||
}
|
||
|
||
var list = res.comments || [];
|
||
if (list.length === 0 && !token) {
|
||
commentsList.innerHTML =
|
||
'<div style="color: #94a3b8; font-size: 13px; text-align: center; padding: 12px;">Bu videoda/yay\u0131nda hen\u00fcz yorum bulunmuyor.</div>';
|
||
moreCommentsWrap.style.display = 'none';
|
||
announce('Bu videoda henüz yorum bulunmuyor.');
|
||
return;
|
||
}
|
||
|
||
list.forEach(function (c) {
|
||
commentsList.appendChild(renderCommentCard(c));
|
||
});
|
||
|
||
commentNextToken = res.nextToken;
|
||
if (commentNextToken) {
|
||
moreCommentsWrap.style.display = 'block';
|
||
} else {
|
||
moreCommentsWrap.style.display = 'none';
|
||
}
|
||
|
||
announce(list.length + ' adet YouTube yorumu yüklendi.');
|
||
})
|
||
.catch(function (err) {
|
||
if (!token) {
|
||
toggleCommentsBtn.disabled = false;
|
||
toggleCommentsBtn.textContent = '⚠️ Tekrar Dene';
|
||
} else {
|
||
moreCommentsBtn.disabled = false;
|
||
moreCommentsBtn.textContent = '⚠️ Tekrar Dene';
|
||
}
|
||
alert('Yorumlar yüklenirken hata oluştu: ' + err.message);
|
||
});
|
||
}
|
||
|
||
if (toggleCommentsBtn) {
|
||
toggleCommentsBtn.addEventListener('click', function () {
|
||
fetchComments(null);
|
||
});
|
||
}
|
||
if (moreCommentsBtn) {
|
||
moreCommentsBtn.addEventListener('click', function () {
|
||
if (commentNextToken) fetchComments(commentNextToken);
|
||
});
|
||
}
|
||
|
||
function closeLiveTheater() {
|
||
try {
|
||
sessionStorage.removeItem('yaktube_active_live');
|
||
} catch (e) {}
|
||
if (liveContainer && liveContainer.parentNode) {
|
||
var ifr = liveContainer.querySelector('iframe');
|
||
if (ifr) ifr.src = '';
|
||
liveContainer.remove();
|
||
}
|
||
document.removeEventListener('keydown', handleEsc);
|
||
announce('Canl\u0131 yay\u0131n izleme alan\u0131 kapat\u0131ld\u0131.');
|
||
}
|
||
|
||
function handleEsc(e) {
|
||
if (e.key === 'Escape' || e.keyCode === 27) {
|
||
closeLiveTheater();
|
||
}
|
||
}
|
||
|
||
var closeBtn = document.getElementById('yaktube-close-live-theater');
|
||
if (closeBtn) closeBtn.addEventListener('click', closeLiveTheater);
|
||
document.addEventListener('keydown', handleEsc);
|
||
}
|
||
|
||
function restoreActiveLiveStream() {
|
||
try {
|
||
var saved = sessionStorage.getItem('yaktube_active_live');
|
||
if (!saved) return;
|
||
var data = JSON.parse(saved);
|
||
if (data && data.url && data.title && !document.getElementById('yaktube-live-watch-container')) {
|
||
handleLiveStream(data.url, data.title, true);
|
||
}
|
||
} catch (e) {}
|
||
}
|
||
|
||
// --- Universal Plugin API Fetcher (Works on ALL PeerTube instances via /plugins/yaktube-ondemand/router/... without needing bridge.js) ---
|
||
var preferredApiPrefix = null;
|
||
|
||
function fetchPluginJson(endpointPath, options) {
|
||
var cleanPath = endpointPath.indexOf('/') === 0 ? endpointPath : '/' + endpointPath;
|
||
var pluginUrl = '/plugins/yaktube-ondemand/router' + cleanPath;
|
||
var customUrl = '/api-custom' + cleanPath;
|
||
|
||
if (!preferredApiPrefix) {
|
||
preferredApiPrefix = '/plugins/yaktube-ondemand/router';
|
||
}
|
||
|
||
var primaryUrl = preferredApiPrefix + cleanPath;
|
||
var fallbackUrl = primaryUrl === customUrl ? pluginUrl : customUrl;
|
||
|
||
return fetch(primaryUrl, options)
|
||
.then(function (res) {
|
||
var ct = (res.headers && res.headers.get && res.headers.get('content-type')) || '';
|
||
if (ct.indexOf('application/json') !== -1) {
|
||
return res.json();
|
||
}
|
||
throw new Error('Non-JSON response');
|
||
})
|
||
.catch(function (err) {
|
||
if (err && err.name === 'AbortError') throw err;
|
||
return fetch(fallbackUrl, options).then(function (res2) {
|
||
var ct2 = (res2.headers && res2.headers.get && res2.headers.get('content-type')) || '';
|
||
if (ct2.indexOf('application/json') !== -1) {
|
||
preferredApiPrefix = fallbackUrl === pluginUrl ? '/plugins/yaktube-ondemand/router' : '/api-custom';
|
||
return res2.json();
|
||
}
|
||
throw new Error('Backend endpoint unreachable');
|
||
});
|
||
});
|
||
}
|
||
|
||
// --- Guest Video Import Quota & PeerTube Login Redirect Engine ---
|
||
var cachedGuestImportLimit = null;
|
||
var cachedCategories = null;
|
||
var cachedSmartPrefetchMode = 'auto-when-no-local';
|
||
var cachedFederatedRecommendationsMode = 'smart-relevant';
|
||
|
||
function fetchGuestImportLimit() {
|
||
if (cachedGuestImportLimit !== null && cachedCategories !== null) {
|
||
return Promise.resolve(cachedGuestImportLimit);
|
||
}
|
||
return fetchPluginJson('/quota-config')
|
||
.then(function (d) {
|
||
if (d && typeof d.guestImportLimit === 'number') {
|
||
cachedGuestImportLimit = d.guestImportLimit;
|
||
}
|
||
if (d && typeof d.yaknetSsoEnabled === 'boolean') {
|
||
cachedYakNetSsoEnabled = d.yaknetSsoEnabled;
|
||
}
|
||
if (d && typeof d.smartPrefetchMode === 'string') {
|
||
cachedSmartPrefetchMode = d.smartPrefetchMode;
|
||
}
|
||
if (d && typeof d.federatedRecommendationsMode === 'string') {
|
||
cachedFederatedRecommendationsMode = d.federatedRecommendationsMode;
|
||
}
|
||
if (d && Array.isArray(d.categories) && d.categories.length > 0) {
|
||
cachedCategories = d.categories;
|
||
try {
|
||
injectCategoryChipsBar();
|
||
} catch (e) {}
|
||
}
|
||
return cachedGuestImportLimit || 5;
|
||
})
|
||
.catch(function () {
|
||
return 5;
|
||
});
|
||
}
|
||
|
||
// --- YouTube-Style Category Chips Bar Engine (v1.6.2) ---
|
||
var defaultCategories = [
|
||
{ label: 'Tümü', key: 'all', url: '/videos/browse' },
|
||
{ label: 'Müzik', key: 'cat_1', url: '/videos/browse?categoryOneOf=1' },
|
||
{ label: 'Oyun', key: 'cat_7', url: '/videos/browse?categoryOneOf=7' },
|
||
{ label: 'Canlı', key: 'live', url: '/videos/browse?isLive=true' },
|
||
{ label: 'Rap yapma', key: 'search_rap', url: '/search?search=rap' },
|
||
{ label: 'Evcil hayvanlar', key: 'cat_16', url: '/videos/browse?categoryOneOf=16' },
|
||
{ label: 'Komedi skeç gösterileri', key: 'cat_9', url: '/videos/browse?categoryOneOf=9' },
|
||
{ label: 'Doğa', key: 'cat_6', url: '/videos/browse?categoryOneOf=6' },
|
||
{ label: 'Futbol', key: 'cat_5', url: '/videos/browse?categoryOneOf=5' },
|
||
{ label: 'Son yüklenenler', key: 'sort_publishedAt', url: '/videos/browse?sort=-publishedAt' },
|
||
{ label: 'İzlenenler', key: 'sort_views', url: '/videos/browse?sort=-views' },
|
||
{ label: 'Yeni öneriler', key: 'sort_hot', url: '/videos/browse?sort=-hot' }
|
||
];
|
||
|
||
function getActiveCategoryKey() {
|
||
var search = window.location.search || '';
|
||
var path = window.location.pathname || '';
|
||
if (search.indexOf('categoryOneOf=') !== -1) {
|
||
var m = search.match(/categoryOneOf=(\d+)/);
|
||
if (m && m[1]) return 'cat_' + m[1];
|
||
}
|
||
if (search.indexOf('isLive=true') !== -1) return 'live';
|
||
if (path.indexOf('/search') !== -1) {
|
||
var sm = search.match(/search=([^&]+)/);
|
||
if (sm && sm[1]) return 'search_' + decodeURIComponent(sm[1]).toLowerCase();
|
||
}
|
||
if (search.indexOf('sort=') !== -1) {
|
||
var sortm = search.match(/sort=(-?[^&]+)/);
|
||
if (sortm && sortm[1]) return 'sort_' + sortm[1].replace(/^-/, '');
|
||
}
|
||
return 'all';
|
||
}
|
||
|
||
function navigateCategorySeamless(targetUrl, key) {
|
||
if (!targetUrl) return;
|
||
|
||
try {
|
||
var isAll = key === 'all' || targetUrl === '/videos/browse' || targetUrl === '/';
|
||
var intermediateUrl = isAll ? '/videos/browse?all=true' : targetUrl;
|
||
|
||
// SPA transition via HTML5 History + Angular popstate
|
||
history.pushState(null, '', intermediateUrl);
|
||
window.dispatchEvent(new PopStateEvent('popstate', { state: null }));
|
||
|
||
if (isAll) {
|
||
// Clean up the URL to /videos/browse after Angular processes the change
|
||
setTimeout(function () {
|
||
try {
|
||
history.replaceState(null, '', '/videos/browse');
|
||
} catch (e) {}
|
||
}, 350);
|
||
}
|
||
|
||
// Schedule unified engine cycle to ensure DOM consistency
|
||
if (typeof scheduleUnifiedCycle === 'function') {
|
||
scheduleUnifiedCycle(true);
|
||
}
|
||
} catch (err) {
|
||
console.warn('[YakTube] Seamless navigation fallback:', err);
|
||
window.location.href = targetUrl;
|
||
}
|
||
}
|
||
|
||
function isBrowsePageUrl() {
|
||
var path = (window.location.pathname || '').toLowerCase();
|
||
if (
|
||
path.indexOf('/videos/watch') === 0 ||
|
||
path.indexOf('/w/') === 0 ||
|
||
path.indexOf('/login') === 0 ||
|
||
path.indexOf('/admin') === 0 ||
|
||
path.indexOf('/my-library') === 0 ||
|
||
path.indexOf('/settings') === 0
|
||
) {
|
||
return false;
|
||
}
|
||
return (
|
||
path === '/' ||
|
||
path === '' ||
|
||
path === '/videos/overview' ||
|
||
path.indexOf('/videos/overview') === 0 ||
|
||
path === '/videos/browse' ||
|
||
path.indexOf('/videos/browse') === 0 ||
|
||
path.indexOf('/search') === 0 ||
|
||
path.indexOf('/videos/trending') === 0 ||
|
||
path.indexOf('/videos/recently-added') === 0 ||
|
||
path.indexOf('/videos/local') === 0
|
||
);
|
||
}
|
||
|
||
function injectCategoryChipsBar() {
|
||
if (!isBrowsePageUrl()) {
|
||
var exBar = document.getElementById('yaktube-category-chips-bar');
|
||
if (exBar) exBar.remove();
|
||
return;
|
||
}
|
||
|
||
var targetElem =
|
||
document.querySelector('my-video-filters-header') ||
|
||
document.querySelector('my-videos-list') ||
|
||
document.querySelector('my-video-overview') ||
|
||
document.querySelector('my-home-menu') ||
|
||
document.querySelector('my-search-results') ||
|
||
document.querySelector('my-search') ||
|
||
document.querySelector('.main-row') ||
|
||
document.querySelector('.main-col') ||
|
||
document.querySelector('main');
|
||
|
||
if (!targetElem) return;
|
||
|
||
var categories =
|
||
Array.isArray(cachedCategories) && cachedCategories.length > 0 ? cachedCategories : defaultCategories;
|
||
|
||
var activeKey = getActiveCategoryKey();
|
||
var existingBar = document.getElementById('yaktube-category-chips-bar');
|
||
|
||
if (existingBar) {
|
||
var isDetached = !existingBar.isConnected || !document.body.contains(existingBar);
|
||
var isWrongParent =
|
||
targetElem && targetElem.parentElement && existingBar.parentElement !== targetElem.parentElement;
|
||
|
||
if (isDetached) {
|
||
try {
|
||
existingBar.remove();
|
||
} catch (e) {}
|
||
existingBar = null;
|
||
} else if (isWrongParent) {
|
||
try {
|
||
targetElem.parentElement.insertBefore(existingBar, targetElem);
|
||
} catch (e) {
|
||
existingBar.remove();
|
||
existingBar = null;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (existingBar) {
|
||
var chips = existingBar.querySelectorAll('.yaktube-category-chip');
|
||
chips.forEach(function (chip) {
|
||
var cKey = chip.getAttribute('data-chip-key');
|
||
var isActive = cKey === activeKey;
|
||
chip.classList.toggle('active', isActive);
|
||
chip.setAttribute('aria-selected', isActive ? 'true' : 'false');
|
||
chip.setAttribute('tabindex', isActive ? '0' : '-1');
|
||
});
|
||
return;
|
||
}
|
||
|
||
var bar = document.createElement('nav');
|
||
bar.id = 'yaktube-category-chips-bar';
|
||
bar.className = 'yaktube-category-chips-container';
|
||
bar.setAttribute('aria-label', 'Video Kategorileri');
|
||
bar.setAttribute('role', 'navigation');
|
||
|
||
var wrapper = document.createElement('div');
|
||
wrapper.className = 'yaktube-chips-wrapper';
|
||
|
||
var leftBtn = document.createElement('button');
|
||
leftBtn.type = 'button';
|
||
leftBtn.className = 'yaktube-chips-arrow yaktube-chips-arrow-left';
|
||
leftBtn.setAttribute('aria-label', 'Geri');
|
||
leftBtn.title = 'Geri';
|
||
leftBtn.innerHTML = '‹';
|
||
|
||
var track = document.createElement('div');
|
||
track.className = 'yaktube-chips-track';
|
||
track.setAttribute('role', 'tablist');
|
||
track.setAttribute('aria-label', 'Kategori Listesi');
|
||
|
||
var rightBtn = document.createElement('button');
|
||
rightBtn.type = 'button';
|
||
rightBtn.className = 'yaktube-chips-arrow yaktube-chips-arrow-right';
|
||
rightBtn.setAttribute('aria-label', 'İleri');
|
||
rightBtn.title = 'İleri';
|
||
rightBtn.innerHTML = '›';
|
||
|
||
leftBtn.addEventListener('click', function () {
|
||
track.scrollBy({ left: -220, behavior: 'smooth' });
|
||
});
|
||
|
||
rightBtn.addEventListener('click', function () {
|
||
track.scrollBy({ left: 220, behavior: 'smooth' });
|
||
});
|
||
|
||
categories.forEach(function (cat) {
|
||
var chip = document.createElement('a');
|
||
chip.href = cat.url || '/videos/browse';
|
||
chip.className = 'yaktube-category-chip';
|
||
chip.setAttribute('data-chip-key', cat.key || '');
|
||
chip.setAttribute('role', 'tab');
|
||
chip.textContent = cat.label || '';
|
||
|
||
var isActive = cat.key === activeKey;
|
||
if (isActive) {
|
||
chip.classList.add('active');
|
||
chip.setAttribute('aria-selected', 'true');
|
||
chip.setAttribute('tabindex', '0');
|
||
} else {
|
||
chip.setAttribute('aria-selected', 'false');
|
||
chip.setAttribute('tabindex', '-1');
|
||
}
|
||
|
||
chip.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
if (
|
||
cat.key === getActiveCategoryKey() &&
|
||
(window.location.pathname === '/videos/browse' ||
|
||
(cat.url && window.location.pathname + window.location.search === cat.url))
|
||
)
|
||
return;
|
||
|
||
announce(cat.label + ' kategorisi seçildi.');
|
||
|
||
// Immediate visual and ARIA active state update
|
||
var allChips = track.querySelectorAll('.yaktube-category-chip');
|
||
allChips.forEach(function (c) {
|
||
var isCurrent = c === chip;
|
||
c.classList.toggle('active', isCurrent);
|
||
c.setAttribute('aria-selected', isCurrent ? 'true' : 'false');
|
||
c.setAttribute('tabindex', isCurrent ? '0' : '-1');
|
||
});
|
||
|
||
// Seamless SPA navigation without page reload (v1.6.1)
|
||
navigateCategorySeamless(cat.url, cat.key);
|
||
});
|
||
|
||
chip.addEventListener('keydown', function (e) {
|
||
if (e.key === ' ' || e.key === 'Spacebar') {
|
||
e.preventDefault();
|
||
chip.click();
|
||
return;
|
||
}
|
||
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
|
||
e.preventDefault();
|
||
var next = chip.nextElementSibling;
|
||
if (next && next.classList.contains('yaktube-category-chip')) {
|
||
next.focus();
|
||
}
|
||
} else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
|
||
e.preventDefault();
|
||
var prev = chip.previousElementSibling;
|
||
if (prev && prev.classList.contains('yaktube-category-chip')) {
|
||
prev.focus();
|
||
}
|
||
}
|
||
});
|
||
|
||
track.appendChild(chip);
|
||
});
|
||
|
||
wrapper.appendChild(leftBtn);
|
||
wrapper.appendChild(track);
|
||
wrapper.appendChild(rightBtn);
|
||
bar.appendChild(wrapper);
|
||
|
||
var tag = targetElem.tagName.toLowerCase();
|
||
if (
|
||
tag === 'my-video-filters-header' ||
|
||
tag === 'my-videos-list' ||
|
||
tag === 'my-video-overview' ||
|
||
tag === 'my-home-menu' ||
|
||
tag === 'my-search-results' ||
|
||
tag === 'my-search'
|
||
) {
|
||
if (targetElem.parentElement) {
|
||
targetElem.parentElement.insertBefore(bar, targetElem);
|
||
} else {
|
||
targetElem.prepend(bar);
|
||
}
|
||
} else {
|
||
targetElem.prepend(bar);
|
||
}
|
||
}
|
||
|
||
function jumpToCategories() {
|
||
var bar = document.getElementById('yaktube-category-chips-bar');
|
||
if (bar) {
|
||
var activeOrFirst =
|
||
bar.querySelector('.yaktube-category-chip.active') || bar.querySelector('.yaktube-category-chip');
|
||
if (activeOrFirst) {
|
||
activeOrFirst.focus();
|
||
try {
|
||
activeOrFirst.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||
} catch (e) {}
|
||
announce('Kategori çubuğuna odaklanıldı: ' + (activeOrFirst.textContent || 'Tümü'));
|
||
return true;
|
||
}
|
||
}
|
||
// If categories bar is not on current page (e.g. watch page), navigate to browse
|
||
window.location.href = '/videos/browse';
|
||
return false;
|
||
}
|
||
|
||
function injectSkipToCategoriesLink() {
|
||
var skipLink = document.getElementById('yaktube-skip-to-categories');
|
||
|
||
// Only show top skip-link on browse / overview pages where category bar actually exists
|
||
if (!isBrowsePageUrl()) {
|
||
if (skipLink) skipLink.remove();
|
||
return;
|
||
}
|
||
|
||
var skipContent = document.querySelector('.skip-to-content, a[href*="content"]');
|
||
if (!skipContent) return;
|
||
|
||
if (!skipLink) {
|
||
skipLink = document.createElement('a');
|
||
skipLink.id = 'yaktube-skip-to-categories';
|
||
skipLink.href = '#yaktube-category-chips-bar';
|
||
skipLink.className = 'visually-hidden-focusable skip-to-content yaktube-skip-categories';
|
||
skipLink.setAttribute('aria-label', 'Kategorilere atla');
|
||
skipLink.textContent = 'Kategorilere atla';
|
||
|
||
skipLink.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
jumpToCategories();
|
||
});
|
||
|
||
skipLink.addEventListener('keydown', function (e) {
|
||
if (e.key === 'Enter' || e.key === ' ') {
|
||
e.preventDefault();
|
||
jumpToCategories();
|
||
}
|
||
});
|
||
}
|
||
|
||
// GUARANTEE: skipLink MUST ALWAYS be placed IMMEDIATELY AFTER skipContent ("Ana içeriğe atla")
|
||
if (skipContent.nextElementSibling !== skipLink) {
|
||
skipContent.insertAdjacentElement('afterend', skipLink);
|
||
}
|
||
}
|
||
|
||
function injectSidebarCategoriesLink() {
|
||
if (document.getElementById('yaktube-sidebar-categories-link')) return;
|
||
|
||
var menuContainer = document.querySelector('my-menu .quick-access, my-menu ul, .main-menu ul');
|
||
if (!menuContainer) return;
|
||
|
||
var li = document.createElement('li');
|
||
li.className = 'menu-item yaktube-menu-categories-item';
|
||
|
||
var link = document.createElement('a');
|
||
link.id = 'yaktube-sidebar-categories-link';
|
||
link.href = '#yaktube-category-chips-bar';
|
||
link.className = 'menu-link item-link yaktube-menu-categories-link';
|
||
link.setAttribute('role', 'button');
|
||
link.setAttribute('aria-label', 'Video kategorilerine atla');
|
||
link.innerHTML =
|
||
'<span aria-hidden="true" style="font-size: 16px; margin-right: 8px;">🏷️</span> <span>Kategorilere atla</span>';
|
||
|
||
link.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
jumpToCategories();
|
||
});
|
||
|
||
link.addEventListener('keydown', function (e) {
|
||
if (e.key === 'Enter' || e.key === ' ') {
|
||
e.preventDefault();
|
||
jumpToCategories();
|
||
}
|
||
});
|
||
|
||
li.appendChild(link);
|
||
|
||
var firstLi = menuContainer.querySelector('li');
|
||
if (firstLi && firstLi.nextSibling) {
|
||
menuContainer.insertBefore(li, firstLi.nextSibling);
|
||
} else if (firstLi) {
|
||
menuContainer.appendChild(li);
|
||
} else {
|
||
menuContainer.prepend(li);
|
||
}
|
||
}
|
||
|
||
// Pre-fetch guest import quota setting quietly on startup
|
||
setTimeout(function () {
|
||
fetchGuestImportLimit();
|
||
}, 600);
|
||
|
||
function getGuestImportCount() {
|
||
var lsCount = 0;
|
||
var cookieCount = 0;
|
||
try {
|
||
lsCount = parseInt(localStorage.getItem('yaktube_guest_import_count') || '0', 10);
|
||
if (isNaN(lsCount) || lsCount < 0) lsCount = 0;
|
||
} catch (e) {}
|
||
try {
|
||
var match = document.cookie.match(/(?:^|;\s*)yaktube_guest_imports=(\d+)/);
|
||
if (match && match[1]) {
|
||
cookieCount = parseInt(match[1], 10);
|
||
if (isNaN(cookieCount) || cookieCount < 0) cookieCount = 0;
|
||
}
|
||
} catch (e) {}
|
||
var maxCount = Math.max(lsCount, cookieCount);
|
||
// Keep localStorage and cookie synchronized so refreshing cannot reset it
|
||
if (maxCount > 0) {
|
||
try {
|
||
localStorage.setItem('yaktube_guest_import_count', String(maxCount));
|
||
} catch (e) {}
|
||
try {
|
||
document.cookie = 'yaktube_guest_imports=' + maxCount + '; path=/; max-age=31536000; SameSite=Lax';
|
||
} catch (e) {}
|
||
}
|
||
return maxCount;
|
||
}
|
||
|
||
function incrementGuestImportCount() {
|
||
var nextCount = getGuestImportCount() + 1;
|
||
try {
|
||
localStorage.setItem('yaktube_guest_import_count', String(nextCount));
|
||
} catch (e) {}
|
||
try {
|
||
document.cookie = 'yaktube_guest_imports=' + nextCount + '; path=/; max-age=31536000; SameSite=Lax';
|
||
} catch (e) {}
|
||
return nextCount;
|
||
}
|
||
|
||
function redirectToPeerTubeLogin() {
|
||
saveReturnUrlBeforeLogin();
|
||
|
||
// 1. Check PeerTube's native login link in header (handles redirectOnSingleExternalAuth / YakNet SSO automatically)
|
||
var loginLink = document.querySelector(
|
||
'my-login-link a.login-button-link, my-login-link a[href], a.login-button-link'
|
||
);
|
||
if (loginLink) {
|
||
var href = loginLink.getAttribute('href');
|
||
if (href && href !== '#' && !href.startsWith('javascript:')) {
|
||
window.location.href = href;
|
||
return;
|
||
}
|
||
loginLink.click();
|
||
return;
|
||
}
|
||
|
||
// 2. Check window.PeertubeServerConfig for single external auth (PeerTube native getDefaultLoginHref logic)
|
||
try {
|
||
var cfg = window.PeertubeServerConfig;
|
||
if (
|
||
cfg &&
|
||
cfg.client &&
|
||
cfg.client.menu &&
|
||
cfg.client.menu.login &&
|
||
cfg.client.menu.login.redirectOnSingleExternalAuth === true &&
|
||
cfg.plugin &&
|
||
Array.isArray(cfg.plugin.registeredExternalAuths) &&
|
||
cfg.plugin.registeredExternalAuths.length === 1
|
||
) {
|
||
var ext = cfg.plugin.registeredExternalAuths[0];
|
||
window.location.href = '/plugins/' + ext.name + '/' + ext.version + '/auth/' + ext.authName;
|
||
return;
|
||
}
|
||
} catch (e) {}
|
||
|
||
// 3. Standard PeerTube login route fallback
|
||
window.location.href = '/login';
|
||
}
|
||
|
||
function showQuotaExceededModal(limitVal) {
|
||
hideModal();
|
||
var existing = document.getElementById('yaktube-quota-modal');
|
||
if (existing) existing.remove();
|
||
|
||
var modal = document.createElement('div');
|
||
modal.id = 'yaktube-quota-modal';
|
||
modal.className = 'yaktube-modal-overlay';
|
||
modal.setAttribute('role', 'dialog');
|
||
modal.setAttribute('aria-modal', 'true');
|
||
modal.setAttribute('aria-labelledby', 'yaktube-quota-modal-title');
|
||
modal.setAttribute('aria-describedby', 'yaktube-quota-modal-desc');
|
||
|
||
var displayLimit = limitVal || cachedGuestImportLimit || getGuestImportCount() || 5;
|
||
var instanceName = escapeHtml(getInstanceName());
|
||
|
||
modal.innerHTML =
|
||
'<div class="yaktube-modal-box" style="max-width:480px; border:2px solid #ff8f37; border-radius:18px; padding:24px 22px; text-align:left; background:#0f172a; box-shadow:0 12px 48px rgba(0,0,0,0.85);">' +
|
||
'<div style="text-align:center; margin-bottom:12px;">' +
|
||
'<div style="font-size:38px; line-height:1;" aria-hidden="true">🎉</div>' +
|
||
'<h2 id="yaktube-quota-modal-title" class="yaktube-modal-title" style="margin:8px 0 4px 0; color:#ff8f37; font-size:22px; font-weight:800;">Ücretsiz Misafir Sınırına Ulaştınız!</h2>' +
|
||
'<div id="yaktube-quota-modal-desc" class="yaktube-modal-desc" style="font-size:13.5px; color:#94a3b8; line-height:1.5;">' +
|
||
'Misafir kullanıcılar için ayrılan <strong>' +
|
||
displayLimit +
|
||
' video aktarma kotasını</strong> doldurdunuz.' +
|
||
'</div>' +
|
||
'</div>' +
|
||
'<div style="background:rgba(255,143,55,0.08); border:1px solid rgba(255,143,55,0.25); border-radius:14px; padding:14px 16px; margin:16px 0 20px 0;">' +
|
||
'<div style="font-weight:700; font-size:14.5px; color:#ffedd5; margin-bottom:10px; display:flex; align-items:center; gap:6px;">' +
|
||
'<span aria-hidden="true">✨</span>' +
|
||
'<span>Giriş Yaptığınızda Neler Kazanacaksınız?</span>' +
|
||
'</div>' +
|
||
'<ul style="margin:0; padding-left:20px; font-size:13px; line-height:1.65; color:#e2e8f0;">' +
|
||
'<li style="margin-bottom:6px;"><strong>Sınırsız Video İndirme:</strong> İstediğiniz tüm videoları anında platforma aktarıp yüksek kalitede kesintisiz izleyin.</li>' +
|
||
'<li style="margin-bottom:6px;"><strong>Yorum Yapabilme ve Yanıtlayabilme:</strong> Toplulukla etkileşime geçin, videolara yorum yazıp fikirlerinizi paylaşın.</li>' +
|
||
'<li style="margin-bottom:6px;"><strong>Kanal Açma ve İçerik Paylaşma:</strong> Kendi video veya müzik kanallarınızı oluşturarak içeriklerinizi yayınlayın.</li>' +
|
||
'<li style="margin-bottom:6px;"><strong>Oynatma Listeleri ve Geçmiş:</strong> Beğendiğiniz videoları kaydedin, istediğiniz yerden devam edin.</li>' +
|
||
'<li><strong>Tamamen Ücretsiz ve Reklamsız:</strong> Tüm bu ayrıcalıklar hiçbir ücret ödemeden sizleri bekliyor!</li>' +
|
||
'</ul>' +
|
||
'</div>' +
|
||
'<div style="display:flex; flex-direction:column; gap:10px;">' +
|
||
'<button type="button" id="yaktube-quota-login-btn" style="background:linear-gradient(135deg, #ff8f37 0%, #ea580c 100%); color:#000; font-weight:800; font-size:15px; padding:13px 20px; border:none; border-radius:10px; cursor:pointer; box-shadow:0 4px 14px rgba(255,143,55,0.4); text-align:center; display:flex; align-items:center; justify-content:center; gap:8px;">' +
|
||
'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" aria-hidden="true"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>' +
|
||
'<span>Giriş Yap / Ücretsiz Hesap Aç (' +
|
||
instanceName +
|
||
')</span>' +
|
||
'</button>' +
|
||
'<button type="button" id="yaktube-quota-close-btn" style="background:#1e293b; color:#cbd5e1; font-weight:600; font-size:13px; padding:10px 18px; border:1px solid rgba(255,255,255,0.15); border-radius:10px; cursor:pointer; text-align:center;">Kapat</button>' +
|
||
'</div>' +
|
||
'</div>';
|
||
|
||
document.body.appendChild(modal);
|
||
|
||
var loginBtn = document.getElementById('yaktube-quota-login-btn');
|
||
var closeBtn = document.getElementById('yaktube-quota-close-btn');
|
||
|
||
if (loginBtn) {
|
||
loginBtn.addEventListener('click', function () {
|
||
modal.remove();
|
||
redirectToPeerTubeLogin();
|
||
});
|
||
setTimeout(function () {
|
||
loginBtn.focus();
|
||
}, 50);
|
||
}
|
||
|
||
if (closeBtn) {
|
||
closeBtn.addEventListener('click', function () {
|
||
modal.remove();
|
||
announce('Kota uyarısı kapatıldı.');
|
||
});
|
||
}
|
||
|
||
modal.addEventListener('click', function (e) {
|
||
if (e.target === modal) {
|
||
modal.remove();
|
||
}
|
||
});
|
||
|
||
announce(
|
||
'Ücretsiz misafir indirme sınırına ulaştınız. Sınırsız video indirme, yorum yapma ve kendi kanalınızı açma ayrıcalıkları için lütfen giriş yapın veya ücretsiz hesap açın.',
|
||
true
|
||
);
|
||
}
|
||
|
||
function handleImport(url, btn, videoTitle) {
|
||
var loggedIn = isUserLoggedIn();
|
||
var currentGuestCount = getGuestImportCount();
|
||
|
||
fetchGuestImportLimit().then(function (limit) {
|
||
if (!loggedIn && limit > 0 && currentGuestCount >= limit) {
|
||
showQuotaExceededModal(limit);
|
||
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...",
|
||
{ allowMinimize: true, videoTitle: videoTitle }
|
||
);
|
||
|
||
var headers = { 'Content-Type': 'application/json' };
|
||
try {
|
||
var token = localStorage.getItem('access_token');
|
||
if (token) {
|
||
headers['Authorization'] = 'Bearer ' + token;
|
||
}
|
||
} catch (e) {}
|
||
|
||
fetchPluginJson('/ondemand-import', {
|
||
method: 'POST',
|
||
headers: headers,
|
||
body: JSON.stringify({
|
||
targetUrl: url,
|
||
title: videoTitle,
|
||
isAuthenticated: loggedIn,
|
||
guestImportCount: currentGuestCount
|
||
})
|
||
})
|
||
.then(function (data) {
|
||
if (data && data.blocked) {
|
||
hideModal();
|
||
btn.disabled = false;
|
||
btn.innerHTML = '📥 ' + escapeHtml(getInstanceName()) + "'a Aktar & İzle";
|
||
showModal(
|
||
'🛡️ Çocuk ve Aile Güvenliği',
|
||
data.error ||
|
||
"Bu video içeriği, Çocuk ve Aile Güvenliği (Child & Family Safety) politikaları gereğince YakTube'a aktarılamaz."
|
||
);
|
||
return;
|
||
}
|
||
|
||
if (data && data.quotaExceeded) {
|
||
hideModal();
|
||
btn.disabled = false;
|
||
btn.innerHTML = '📥 ' + escapeHtml(getInstanceName()) + "'a Aktar & İzle";
|
||
if (typeof data.limit === 'number' && data.limit > 0) {
|
||
cachedGuestImportLimit = data.limit;
|
||
}
|
||
showQuotaExceededModal(data.limit || limit);
|
||
return;
|
||
}
|
||
|
||
if (!data || !data.ok) {
|
||
throw new Error(
|
||
(data && (data.userMessage || data.error)) || 'İçe aktarma başlatılamadı. Lütfen tekrar deneyin.'
|
||
);
|
||
}
|
||
|
||
if (data.alreadyImported && data.video && data.video.uuid) {
|
||
showModal('🎉 Video Hazır!', 'Bu video zaten sunucumuzda mevcut. Oynatıcı açılıyor...');
|
||
setTimeout(function () {
|
||
window.location.href = '/videos/watch/' + data.video.uuid;
|
||
}, 350);
|
||
return;
|
||
}
|
||
|
||
if (!loggedIn && !data.inProgress) {
|
||
incrementGuestImportCount();
|
||
}
|
||
|
||
var videoId = data.video.id;
|
||
var videoUuid = data.video.uuid;
|
||
|
||
var attempts = 0;
|
||
var isRequestInFlight = false;
|
||
var pollInterval = setInterval(function () {
|
||
if (isRequestInFlight) return;
|
||
attempts++;
|
||
isRequestInFlight = true;
|
||
fetchPluginJson('/status/' + videoId)
|
||
.then(function (sData) {
|
||
isRequestInFlight = false;
|
||
if (sData.isImporting) {
|
||
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) {
|
||
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);
|
||
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;
|
||
btn.innerHTML = '📥 ' + escapeHtml(getInstanceName()) + "'a Aktar & İzle";
|
||
var failMsg =
|
||
sData.errorMessage ||
|
||
"Bu video şu anda YouTube'dan aktarılamadı. Lütfen tekrar deneyin veya başka bir video seçin.";
|
||
if (bgImportMinimized) {
|
||
updateBackgroundImportPill({ status: 'failed', title: videoTitle || 'Video' });
|
||
} else {
|
||
showModal('⚠️ Video Aktarma Hatası', failMsg);
|
||
}
|
||
announce(failMsg, true);
|
||
}
|
||
})
|
||
.catch(function (e) {
|
||
isRequestInFlight = false;
|
||
console.error('[YakTube] Status poll error:', e);
|
||
});
|
||
|
||
if (attempts > 120) {
|
||
clearInterval(pollInterval);
|
||
btn.disabled = false;
|
||
btn.innerHTML = '📥 ' + escapeHtml(getInstanceName()) + "'a Aktar & İzle";
|
||
var bgMsg =
|
||
'Bu video uzun süreli olduğu için arka planda indirilmeye devam ediyor. Kısa süre içinde hazır olacaktır.';
|
||
showModal('⏳ Arka Planda Tamamlanıyor', bgMsg);
|
||
announce(bgMsg);
|
||
}
|
||
}, 1500);
|
||
})
|
||
.catch(function (err) {
|
||
btn.disabled = false;
|
||
btn.innerHTML = '📥 ' + escapeHtml(getInstanceName()) + "'a Aktar & İzle";
|
||
var errMsg = (err && err.message) || 'Video aktarılırken beklenmeyen bir hata oluştu.';
|
||
showModal('⚠️ Video Aktarma Hatası', errMsg);
|
||
announce('İndirme hatası: ' + errMsg, true);
|
||
});
|
||
});
|
||
}
|
||
|
||
function checkAndInjectSearchResults() {
|
||
// Clean up stray 404 error mascot pages if on search
|
||
try {
|
||
var errPages = document.querySelectorAll('my-error-page');
|
||
errPages.forEach(function (ep) {
|
||
ep.remove();
|
||
});
|
||
} catch (e) {}
|
||
|
||
// Instant URL fixer: redirect legacy /search/videos to native /search
|
||
if (window.location.pathname === '/search/videos' || window.location.pathname.startsWith('/search/videos/')) {
|
||
window.location.replace('/search' + window.location.search);
|
||
return;
|
||
}
|
||
|
||
var url = new URL(window.location.href);
|
||
var searchParam = url.searchParams.get('search');
|
||
|
||
if (!window.location.pathname.includes('/search') || !searchParam || searchParam.trim().length < 2) {
|
||
var existing = document.getElementById('yaktube-ondemand-container');
|
||
if (existing) existing.remove();
|
||
var existingBridge = document.getElementById('yaktube-fediverse-bridge');
|
||
if (existingBridge) existingBridge.remove();
|
||
lastQuery = null;
|
||
lastSearchTarget = null;
|
||
return;
|
||
}
|
||
|
||
var query = searchParam.trim();
|
||
|
||
// Clean up any stray containers mistakenly attached directly to document.body
|
||
try {
|
||
var strays = document.querySelectorAll('body > #yaktube-ondemand-container, body > #yaktube-fediverse-bridge');
|
||
strays.forEach(function (s) {
|
||
s.remove();
|
||
});
|
||
} catch (e) {}
|
||
|
||
// Ensure Fediverse Global Search (SepiaSearch) is default target if not specified in URL
|
||
if (!url.searchParams.has('searchTarget')) {
|
||
url.searchParams.set('searchTarget', 'search-index');
|
||
window.location.replace(url.toString());
|
||
return;
|
||
}
|
||
|
||
var currentSearchTarget = url.searchParams.get('searchTarget') || 'search-index';
|
||
|
||
// CRITICAL: We MUST wait for Angular to mount the search view (<my-search>)!
|
||
// If we inject before <my-search> exists, it lands in document.body before <my-app>,
|
||
// which pushes the entire site header, sidebar, and layout down the page.
|
||
var searchMount = document.querySelector('my-search, my-search-results');
|
||
if (!searchMount) {
|
||
return;
|
||
}
|
||
|
||
var queryKey = query + '___' + currentSearchTarget;
|
||
var lastQueryKey = lastQuery + '___' + lastSearchTarget;
|
||
|
||
var container = document.getElementById('yaktube-ondemand-container');
|
||
var nativeResults = searchMount.querySelector('.search-result');
|
||
|
||
function ensureSearchContainerMounted() {
|
||
var curSearchMount = document.querySelector('my-search, my-search-results') || searchMount;
|
||
var curNative = curSearchMount ? curSearchMount.querySelector('.search-result') : null;
|
||
var el = document.getElementById('yaktube-ondemand-container');
|
||
if (!el) {
|
||
el = document.createElement('div');
|
||
el.id = 'yaktube-ondemand-container';
|
||
el.className = 'yaktube-ondemand-section';
|
||
el.setAttribute('role', 'region');
|
||
el.setAttribute('aria-label', 'Canlı YouTube ve ' + getInstanceName() + ' Arama Sonuçları');
|
||
}
|
||
if (curSearchMount && el.parentElement !== curSearchMount) {
|
||
curSearchMount.insertBefore(el, curNative || curSearchMount.firstChild);
|
||
}
|
||
return el;
|
||
}
|
||
|
||
function renderSearchOutcome(ytData, localData, activeContainer) {
|
||
var targetContainer = activeContainer || ensureSearchContainerMounted();
|
||
ytData = ytData || {};
|
||
localData = localData || {};
|
||
|
||
if (typeof ytData.guestImportLimit === 'number') {
|
||
cachedGuestImportLimit = ytData.guestImportLimit;
|
||
}
|
||
|
||
if (ytData && ytData.blocked) {
|
||
var safetyMsg =
|
||
ytData.message ||
|
||
'Bu arama terimi veya içerik, Çocuk ve Aile Güvenliği (Child & Family Safety) politikaları gereğince filtrelenmiştir.';
|
||
targetContainer.innerHTML =
|
||
'<div class="yaktube-header" style="border-left: 4px solid #ef4444; background: rgba(239, 68, 68, 0.08); padding: 18px 20px; border-radius: 8px; margin-bottom: 24px;">' +
|
||
'<div class="yaktube-header-left">' +
|
||
'<span class="yaktube-badge" style="background:#ef4444; color:#fff; font-weight:700;">🛡️ Çocuk ve Aile Güvenliği Koruması</span>' +
|
||
'<h2 class="yaktube-title-h3" style="margin:8px 0 4px; font-size:1.15rem; color:#f87171;">Arama Filtrelendi</h2>' +
|
||
'<p style="margin:0; font-size:0.95rem; color:#cbd5e1;">' +
|
||
escapeHtml(safetyMsg) +
|
||
'</p>' +
|
||
'</div>' +
|
||
'</div>';
|
||
announce(safetyMsg, true);
|
||
return;
|
||
}
|
||
|
||
var rawYtResults = ytData.results || [];
|
||
var uniqueYtResults = [];
|
||
var seenIds = {};
|
||
|
||
rawYtResults.forEach(function (item) {
|
||
if (item && item.id && !seenIds[item.id] && item.title) {
|
||
seenIds[item.id] = true;
|
||
uniqueYtResults.push(item);
|
||
}
|
||
});
|
||
|
||
var ytCount = uniqueYtResults.length;
|
||
var localResults = localData.data || [];
|
||
var localTotal = typeof localData.total === 'number' ? localData.total : localResults.length;
|
||
|
||
if (ytCount === 0 && localResults.length === 0) {
|
||
var emptyTitle = ytData.searchError
|
||
? 'YouTube bağlantısı geçici olarak zaman aşımına uğradı'
|
||
: '"' + escapeHtml(query) + '" için Sonuç Bulunamadı';
|
||
var retryHtml = ytData.searchError
|
||
? '<div style="padding:14px 0;"><button type="button" id="yaktube-retry-search-btn" class="yaktube-shortcuts-btn" style="background:#ff8f37;color:#000;border:none;font-weight:700;">🔄 YouTube Aramasını Tekrar Dene</button></div>'
|
||
: '';
|
||
targetContainer.innerHTML =
|
||
'<div class="yaktube-header">' +
|
||
'<div class="yaktube-header-left">' +
|
||
'<span class="yaktube-badge">⚡ Canlı YouTube & Web Arama</span>' +
|
||
'<h2 class="yaktube-title-h3" style="margin:0; font-size:1.15rem;">' +
|
||
emptyTitle +
|
||
'</h2>' +
|
||
'</div>' +
|
||
'<button class="yaktube-shortcuts-btn" id="yaktube-open-shortcuts" aria-label="Klavye Kısayolları Kılavuzunu Aç">' +
|
||
'⌨️ Kısayollar (?)' +
|
||
'</button>' +
|
||
'</div>' +
|
||
retryHtml;
|
||
var rBtn = document.getElementById('yaktube-retry-search-btn');
|
||
if (rBtn) {
|
||
rBtn.addEventListener('click', function () {
|
||
window.__yaktube_last_search_snapshot__ = null;
|
||
lastQuery = null;
|
||
checkAndInjectSearchResults();
|
||
});
|
||
}
|
||
var scBtn = document.getElementById('yaktube-open-shortcuts');
|
||
if (scBtn) scBtn.addEventListener('click', toggleShortcutsModal);
|
||
announce(
|
||
ytData.searchError
|
||
? 'YouTube bağlantısı geçici olarak yanıt vermedi.'
|
||
: query + ' için eşleşen video bulunamadı.'
|
||
);
|
||
return;
|
||
}
|
||
|
||
var visibleYtCount = Math.min(12, ytCount);
|
||
|
||
function renderAll() {
|
||
var ytHeaderHtml = '';
|
||
var ytCardsHtml = '';
|
||
var ytLoadMoreHtml = '';
|
||
|
||
if (ytCount > 0) {
|
||
var countText = ytCount === 1 ? '1 Video Bulundu' : ytCount + ' Video Bulundu';
|
||
ytHeaderHtml =
|
||
'<div class="yaktube-header">' +
|
||
'<div class="yaktube-header-left">' +
|
||
'<span class="yaktube-badge">⚡ Canlı YouTube & Web Arama</span>' +
|
||
'<h2 class="yaktube-title-h3" style="margin:0; font-size:1.15rem;">"' +
|
||
escapeHtml(query) +
|
||
'" için ' +
|
||
countText +
|
||
'</h2>' +
|
||
'</div>' +
|
||
'<button class="yaktube-shortcuts-btn" id="yaktube-open-shortcuts" aria-label="Klavye Kısayolları Kılavuzunu Aç">' +
|
||
'⌨️ Kısayollar (?)' +
|
||
'</button>' +
|
||
'</div>';
|
||
|
||
var visibleResults = uniqueYtResults.slice(0, visibleYtCount);
|
||
visibleResults.forEach(function (item) {
|
||
if (item && item.title && item.channel) {
|
||
saveVideoChannelMeta(
|
||
item.title,
|
||
item.channel,
|
||
item.id || '',
|
||
(item.localVideo && item.localVideo.uuid) || ''
|
||
);
|
||
}
|
||
var isLocal = !!item.isDownloaded;
|
||
var isLive = !!item.isLive;
|
||
|
||
var statusBadge = '';
|
||
if (isLive) {
|
||
statusBadge =
|
||
'<span class="yaktube-badge" style="background: #dc2626; color: #fff; margin-bottom: 6px; display: inline-block; font-weight: 700;">🔴 CANLI YAYIN</span>';
|
||
} else if (isLocal) {
|
||
statusBadge =
|
||
'<span class="yaktube-badge" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); margin-bottom: 6px; display: inline-block;">✅ ' +
|
||
escapeHtml(getInstanceName()) +
|
||
"'da Mevcut</span>";
|
||
}
|
||
|
||
var actionButton = '';
|
||
if (isLive) {
|
||
actionButton =
|
||
'<button class="yaktube-live-btn" data-url="' +
|
||
escapeHtml(item.url) +
|
||
'" data-title="' +
|
||
escapeHtml(item.title) +
|
||
'" style="background: linear-gradient(135deg, #ef4444 0%, #b91c1c 100%); color: #fff; border: none; padding: 8px 14px; border-radius: 6px; font-weight: 700; cursor: pointer; display: inline-flex; align-items: center; gap: 6px;" aria-label="' +
|
||
escapeHtml(item.title) +
|
||
' canlı yayınını hemen izle">🔴 Canlı Yayını İzle</button>';
|
||
} else if (isLocal && item.localVideo && item.localVideo.url) {
|
||
actionButton =
|
||
'<a href="' +
|
||
escapeHtml(item.localVideo.url) +
|
||
'" class="yaktube-play-btn" aria-label="' +
|
||
escapeHtml(item.title) +
|
||
' videosunu ' +
|
||
escapeHtml(getInstanceName()) +
|
||
'\'dan hemen izle">▶️ ' +
|
||
escapeHtml(getInstanceName()) +
|
||
"'dan İzle</a>";
|
||
} else {
|
||
actionButton =
|
||
'<button class="yaktube-import-btn" data-url="' +
|
||
escapeHtml(item.url) +
|
||
'" data-title="' +
|
||
escapeHtml(item.title) +
|
||
'" aria-label="' +
|
||
escapeHtml(item.title) +
|
||
' videosunu ' +
|
||
escapeHtml(getInstanceName()) +
|
||
'\'a aktar ve izle">📥 ' +
|
||
escapeHtml(getInstanceName()) +
|
||
"'a Aktar & İzle</button>";
|
||
}
|
||
|
||
var durationText = isLive ? 'CANLI' : item.durationFormatted || formatClockTime(item.duration);
|
||
var cardLabel =
|
||
item.title +
|
||
(isLive ? ' (Canlı Yayın)' : isLocal ? ' (' + getInstanceName() + ' kütüphanenizde mevcut)' : '') +
|
||
', ' +
|
||
item.channel +
|
||
' kanalı, Süre: ' +
|
||
durationText;
|
||
|
||
var ytQueueBtn = !isLive
|
||
? '<button type="button" class="yaktube-queue-add-btn" data-id="' +
|
||
escapeHtml(item.id || '') +
|
||
'" data-uuid="' +
|
||
escapeHtml((item.localVideo && item.localVideo.uuid) || '') +
|
||
'" data-url="' +
|
||
escapeHtml(item.url || '') +
|
||
'" data-local-url="' +
|
||
escapeHtml((item.localVideo && item.localVideo.url) || '') +
|
||
'" data-title="' +
|
||
escapeHtml(item.title || '') +
|
||
'" data-channel="' +
|
||
escapeHtml(item.channel || '') +
|
||
'" data-dur="' +
|
||
escapeHtml(durationText || '') +
|
||
'" data-thumb="' +
|
||
escapeHtml(item.thumbnail || '') +
|
||
'" aria-label="' +
|
||
escapeHtml(item.title) +
|
||
' videosunu çalma sırasına ekle">➕ Sıraya Ekle</button>'
|
||
: '';
|
||
|
||
ytCardsHtml +=
|
||
'<div class="yaktube-card" role="article" tabindex="0" aria-label="' +
|
||
escapeHtml(cardLabel) +
|
||
'">' +
|
||
'<div class="yaktube-thumb-wrap">' +
|
||
'<img class="yaktube-thumb-img" src="' +
|
||
escapeHtml(item.thumbnail) +
|
||
'" alt="' +
|
||
escapeHtml(item.title) +
|
||
'" loading="lazy" />' +
|
||
'<span class="yaktube-duration-badge" style="' +
|
||
(isLive ? 'background:#dc2626;font-weight:700;' : '') +
|
||
'" aria-label="Süre">' +
|
||
escapeHtml(durationText) +
|
||
'</span>' +
|
||
'</div>' +
|
||
'<div class="yaktube-info">' +
|
||
'<div>' +
|
||
statusBadge +
|
||
'<h3 class="yaktube-video-name" title="' +
|
||
escapeHtml(item.title) +
|
||
'" style="margin:0; font-size:13px; font-weight:600; line-height:1.35;">' +
|
||
escapeHtml(item.title) +
|
||
'</h3>' +
|
||
'<div class="yaktube-channel-name">' +
|
||
escapeHtml(item.channel) +
|
||
'</div>' +
|
||
'</div>' +
|
||
'<div class="yaktube-card-actions">' +
|
||
actionButton +
|
||
ytQueueBtn +
|
||
'</div>' +
|
||
'</div>' +
|
||
'</div>';
|
||
});
|
||
|
||
if (visibleYtCount < ytCount) {
|
||
ytLoadMoreHtml =
|
||
'<div style="text-align: center; margin: 20px 0 10px 0;">' +
|
||
'<button id="yaktube-load-more-btn" class="yaktube-load-more-btn" style="background: #1e293b; color: #ff8f37; border: 1px solid #ff8f37; padding: 10px 24px; border-radius: 8px; font-weight: 700; font-size: 14px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; transition: all 0.2s ease; box-shadow: 0 4px 12px rgba(0,0,0,0.3);" aria-label="Daha fazla video yükle">' +
|
||
'➕ Daha Fazla Video Göster (' +
|
||
visibleYtCount +
|
||
' / ' +
|
||
ytCount +
|
||
')' +
|
||
'</button>' +
|
||
'</div>';
|
||
}
|
||
}
|
||
|
||
var localShelfHtml = '';
|
||
if (localResults.length > 0) {
|
||
var localCardsHtml = '';
|
||
localResults.forEach(function (lItem) {
|
||
var lThumb =
|
||
lItem.thumbnailPath ||
|
||
(lItem.thumbnails && lItem.thumbnails[0]
|
||
? lItem.thumbnails[0].fileUrl
|
||
: '/client/assets/images/default-thumbnail.jpg');
|
||
var lDuration = formatClockTime(lItem.duration);
|
||
var lChannel =
|
||
(lItem.channel && (lItem.channel.displayName || lItem.channel.name)) ||
|
||
(lItem.account && (lItem.account.displayName || lItem.account.name)) ||
|
||
getInstanceName();
|
||
var lWatchUrl = lItem.url || '/videos/watch/' + (lItem.shortUUID || lItem.uuid);
|
||
var lViews = (lItem.views || 0) + ' görüntüleme';
|
||
var lLabel =
|
||
lItem.name +
|
||
', ' +
|
||
lChannel +
|
||
', ' +
|
||
getInstanceName() +
|
||
' yerel sunucusunda mevcut, Süre: ' +
|
||
lDuration;
|
||
|
||
localCardsHtml +=
|
||
'<div class="yaktube-card yaktube-local-card" role="article" tabindex="0" aria-label="' +
|
||
escapeHtml(lLabel) +
|
||
'">' +
|
||
'<a href="' +
|
||
escapeHtml(lWatchUrl) +
|
||
'" style="text-decoration:none; color:inherit;">' +
|
||
'<div class="yaktube-thumb-wrap">' +
|
||
'<img class="yaktube-thumb-img" src="' +
|
||
escapeHtml(lThumb) +
|
||
'" alt="' +
|
||
escapeHtml(lItem.name) +
|
||
'" loading="lazy" onerror="this.src=\'/client/assets/images/default-thumbnail.jpg\'" />' +
|
||
'<span class="yaktube-duration-badge" aria-label="Süre">' +
|
||
escapeHtml(lDuration) +
|
||
'</span>' +
|
||
'</div>' +
|
||
'</a>' +
|
||
'<div class="yaktube-info">' +
|
||
'<a href="' +
|
||
escapeHtml(lWatchUrl) +
|
||
'" style="text-decoration:none; color:inherit;">' +
|
||
'<span class="yaktube-badge" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); margin-bottom: 6px; display: inline-block;">✅ ' +
|
||
escapeHtml(getInstanceName()) +
|
||
"'da Mevcut</span>" +
|
||
'<h3 class="yaktube-video-name" title="' +
|
||
escapeHtml(lItem.name) +
|
||
'" style="margin:0; font-size:13px; font-weight:600; line-height:1.35;">' +
|
||
escapeHtml(lItem.name) +
|
||
'</h3>' +
|
||
'<div class="yaktube-channel-name">' +
|
||
escapeHtml(lChannel) +
|
||
' • ' +
|
||
escapeHtml(lViews) +
|
||
'</div>' +
|
||
'</a>' +
|
||
'<div class="yaktube-card-actions">' +
|
||
'<a href="' +
|
||
escapeHtml(lWatchUrl) +
|
||
'" class="yaktube-play-btn" style="text-decoration:none;">▶️ ' +
|
||
escapeHtml(getInstanceName()) +
|
||
"'dan İzle</a>" +
|
||
'<button type="button" class="yaktube-queue-add-btn" data-uuid="' +
|
||
escapeHtml(lItem.uuid || lItem.shortUUID || '') +
|
||
'" data-local-url="' +
|
||
escapeHtml(lWatchUrl) +
|
||
'" data-url="' +
|
||
escapeHtml(lWatchUrl) +
|
||
'" data-title="' +
|
||
escapeHtml(lItem.name) +
|
||
'" data-channel="' +
|
||
escapeHtml(lChannel) +
|
||
'" data-dur="' +
|
||
escapeHtml(lDuration) +
|
||
'" data-thumb="' +
|
||
escapeHtml(lThumb) +
|
||
'" aria-label="' +
|
||
escapeHtml(lItem.name) +
|
||
' videosunu çalma sırasına ekle">➕ Sıraya Ekle</button>' +
|
||
'</div>' +
|
||
'</div>' +
|
||
'</div>';
|
||
});
|
||
|
||
localShelfHtml =
|
||
'<div id="yaktube-local-shelf" class="yaktube-local-shelf" role="region" aria-label="' +
|
||
escapeHtml(getInstanceName()) +
|
||
' Yerel Kütüphanesi">' +
|
||
'<div class="yaktube-header" style="margin-top: 24px; border-bottom-color: rgba(16, 185, 129, 0.3);">' +
|
||
'<div class="yaktube-header-left">' +
|
||
'<span class="yaktube-badge" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">✅ Yerel Kütüphane</span>' +
|
||
'<h2 class="yaktube-title-h3" style="margin:0; font-size:1.15rem;">"' +
|
||
escapeHtml(query) +
|
||
'" için ' +
|
||
escapeHtml(getInstanceName()) +
|
||
' Sunucusunda ' +
|
||
localTotal +
|
||
' Video Bulundu</h2>' +
|
||
'</div>' +
|
||
'<span class="yaktube-local-shelf-sub">Doğrudan sunucumuzda barındırılan, yüksek hızlı ve anında izlenebilen videolar</span>' +
|
||
'</div>' +
|
||
'<div class="yaktube-grid">' +
|
||
localCardsHtml +
|
||
'</div>' +
|
||
'</div>';
|
||
}
|
||
|
||
targetContainer.innerHTML =
|
||
ytHeaderHtml +
|
||
(ytCount > 0 ? '<div class="yaktube-grid">' + ytCardsHtml + '</div>' : '') +
|
||
ytLoadMoreHtml +
|
||
localShelfHtml;
|
||
|
||
var sBtn = document.getElementById('yaktube-open-shortcuts');
|
||
if (sBtn) {
|
||
sBtn.addEventListener('click', toggleShortcutsModal);
|
||
}
|
||
|
||
var loadMoreBtn = document.getElementById('yaktube-load-more-btn');
|
||
if (loadMoreBtn) {
|
||
loadMoreBtn.addEventListener('click', function () {
|
||
visibleYtCount = Math.min(visibleYtCount + 6, ytCount);
|
||
renderAll();
|
||
announce(visibleYtCount + ' adet video gösteriliyor.');
|
||
});
|
||
}
|
||
|
||
targetContainer.querySelectorAll('.yaktube-live-btn').forEach(function (btn) {
|
||
btn.addEventListener('click', function (e) {
|
||
var liveUrl = e.currentTarget.getAttribute('data-url');
|
||
var liveTitle = e.currentTarget.getAttribute('data-title');
|
||
handleLiveStream(liveUrl, liveTitle);
|
||
});
|
||
});
|
||
|
||
targetContainer.querySelectorAll('.yaktube-import-btn').forEach(function (btn) {
|
||
btn.addEventListener('click', function (e) {
|
||
var videoUrl = e.currentTarget.getAttribute('data-url');
|
||
var videoTitle = e.currentTarget.getAttribute('data-title');
|
||
handleImport(videoUrl, e.currentTarget, videoTitle);
|
||
});
|
||
});
|
||
|
||
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();
|
||
}
|
||
|
||
if (queryKey === lastQueryKey) {
|
||
if (container) {
|
||
if (container.parentElement !== searchMount) {
|
||
searchMount.insertBefore(container, nativeResults || searchMount.firstChild);
|
||
}
|
||
ensureFediverseBridge(query, currentSearchTarget);
|
||
return;
|
||
}
|
||
// If Angular re-rendered <my-search> and wiped #yaktube-ondemand-container, restore instantly!
|
||
if (!isSearching) {
|
||
var snap = window.__yaktube_last_search_snapshot__;
|
||
if (snap && snap.key === queryKey) {
|
||
var restoredContainer = ensureSearchContainerMounted();
|
||
renderSearchOutcome(snap.ytData, snap.localData, restoredContainer);
|
||
ensureFediverseBridge(query, currentSearchTarget);
|
||
return;
|
||
}
|
||
lastQuery = null;
|
||
lastSearchTarget = null;
|
||
} else {
|
||
container = ensureSearchContainerMounted();
|
||
ensureFediverseBridge(query, currentSearchTarget);
|
||
return;
|
||
}
|
||
}
|
||
lastQuery = query;
|
||
lastSearchTarget = currentSearchTarget;
|
||
container = ensureSearchContainerMounted();
|
||
|
||
container.innerHTML =
|
||
'<div class="yaktube-header">' +
|
||
'<div class="yaktube-header-left">' +
|
||
'<span class="yaktube-badge">⚡ Canlı YouTube & Web Arama</span>' +
|
||
'<h2 class="yaktube-title-h3" style="margin:0; font-size:1.15rem;">"' +
|
||
escapeHtml(query) +
|
||
'" için Sonuçlar Taranıyor...</h2>' +
|
||
'</div>' +
|
||
'<button class="yaktube-shortcuts-btn" id="yaktube-open-shortcuts" aria-label="Klavye Kısayolları Kılavuzunu Aç">' +
|
||
'⌨️ Kısayollar (?)' +
|
||
'</button>' +
|
||
'</div>' +
|
||
'<div class="yaktube-loading">' +
|
||
'<div class="yaktube-spinner" aria-hidden="true"></div>' +
|
||
'<div style="margin-top: 10px;">YouTube ve ' +
|
||
escapeHtml(getInstanceName()) +
|
||
' yerel kütüphanesindeki eşleşmeler taranıyor...</div>' +
|
||
'</div>';
|
||
|
||
var shortcutsBtn = document.getElementById('yaktube-open-shortcuts');
|
||
if (shortcutsBtn) {
|
||
shortcutsBtn.addEventListener('click', toggleShortcutsModal);
|
||
}
|
||
|
||
ensureFediverseBridge(query, currentSearchTarget);
|
||
announce(query + ' için arama başlatıldı.');
|
||
isSearching = true;
|
||
|
||
if (window.__yaktube_search_abort_controller__) {
|
||
try {
|
||
window.__yaktube_search_abort_controller__.abort();
|
||
} catch (e) {}
|
||
}
|
||
var abortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
|
||
window.__yaktube_search_abort_controller__ = abortCtrl;
|
||
var fetchOpts = abortCtrl ? { signal: abortCtrl.signal } : {};
|
||
|
||
Promise.all([
|
||
fetchPluginJson('/youtube-search?q=' + encodeURIComponent(query), fetchOpts).catch(function (err) {
|
||
if (err && err.name === 'AbortError') return { results: [], aborted: true };
|
||
console.warn('[YakTube] YouTube search fetch error:', err);
|
||
return { results: [], searchError: true };
|
||
}),
|
||
fetch('/api/v1/search/videos?search=' + encodeURIComponent(query) + '&isLocal=true&count=12', fetchOpts)
|
||
.then(function (res) {
|
||
return res.json();
|
||
})
|
||
.catch(function (err) {
|
||
if (err && err.name === 'AbortError') return { total: 0, data: [], aborted: true };
|
||
console.warn('[YakTube] Local videos search fetch error:', err);
|
||
return { total: 0, data: [] };
|
||
})
|
||
])
|
||
.then(function (responses) {
|
||
if (abortCtrl && abortCtrl.signal && abortCtrl.signal.aborted) return;
|
||
var ytData = responses[0] || {};
|
||
var localData = responses[1] || {};
|
||
if (ytData.aborted || localData.aborted) return;
|
||
|
||
window.__yaktube_last_search_snapshot__ = { key: queryKey, ytData: ytData, localData: localData };
|
||
var activeContainer = ensureSearchContainerMounted();
|
||
renderSearchOutcome(ytData, localData, activeContainer);
|
||
|
||
var ytLen = (ytData.results && ytData.results.length) || 0;
|
||
var localTotal = typeof localData.total === 'number' ? localData.total : (localData.data || []).length;
|
||
if (ytLen > 0 || localTotal > 0) {
|
||
var announceMsg = '"' + query + '" için arama sonuçları listelendi: ';
|
||
if (localTotal > 0) {
|
||
announceMsg += localTotal + ' adet yerel ' + getInstanceName() + ' videosu, ';
|
||
}
|
||
if (ytLen > 0) {
|
||
announceMsg += ytLen + ' adet YouTube sonucu ve ';
|
||
}
|
||
announceMsg += 'Fediverse sonuçları hazır.';
|
||
announce(announceMsg);
|
||
}
|
||
})
|
||
.catch(function (err) {
|
||
if (abortCtrl && abortCtrl.signal && abortCtrl.signal.aborted) return;
|
||
console.error('[YakTube] Search fetch error:', err);
|
||
var activeContainer = ensureSearchContainerMounted();
|
||
activeContainer.innerHTML =
|
||
'<div class="yaktube-header">' +
|
||
'<div class="yaktube-header-left">' +
|
||
'<span class="yaktube-badge">⚡ Canlı YouTube & Web Arama</span>' +
|
||
'<h2 class="yaktube-title-h3" style="margin:0; font-size:1.15rem;">Arama sırasında bir bağlantı sorunu oluştu.</h2>' +
|
||
'</div>' +
|
||
'</div>';
|
||
announce('Arama sırasında bir bağlantı sorunu oluştu.');
|
||
})
|
||
.finally(function () {
|
||
if (!abortCtrl || !abortCtrl.signal || !abortCtrl.signal.aborted) {
|
||
isSearching = false;
|
||
}
|
||
ensureFediverseBridge(query, currentSearchTarget);
|
||
});
|
||
}
|
||
|
||
// --------------------------------------------------------------------------
|
||
// --------------------------------------------------------------------------
|
||
// --------------------------------------------------------------------------
|
||
// --------------------------------------------------------------------------
|
||
// --------------------------------------------------------------------------
|
||
// --------------------------------------------------------------------------
|
||
// --------------------------------------------------------------------------
|
||
// --------------------------------------------------------------------------
|
||
// --------------------------------------------------------------------------
|
||
// --------------------------------------------------------------------------
|
||
// 8. FULL YOUTUBE SEARCH & VOICE MODAL ENGINE (v1.3.3 - Guaranteed Close Fix)
|
||
// --------------------------------------------------------------------------
|
||
var activeVoiceRec = null;
|
||
var isVoiceListening = false;
|
||
|
||
// Dynamic Search History & Trending Helpers with YakNet Cloud Sync
|
||
function isUserLoggedIn() {
|
||
try {
|
||
var token = localStorage.getItem('access_token');
|
||
var username = localStorage.getItem('username');
|
||
return Boolean(token || username);
|
||
} catch (e) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
function isAccountSyncEnabled() {
|
||
try {
|
||
var userPref = localStorage.getItem('yaktube_sync_search_history');
|
||
if (userPref === 'false') return false;
|
||
return isUserLoggedIn();
|
||
} catch (e) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
function getRecentSearches() {
|
||
try {
|
||
var data = localStorage.getItem('yaktube_recent_searches');
|
||
if (data) {
|
||
var parsed = JSON.parse(data);
|
||
if (Array.isArray(parsed) && parsed.length > 0) return parsed;
|
||
}
|
||
} catch (e) {}
|
||
// Default initial recent searches for first-time visitors
|
||
var defaults = ['Tarkan', 'Barış Manço', 'Yapay Zeka', 'Canlı Haber'];
|
||
if (!isUserLoggedIn()) {
|
||
try {
|
||
localStorage.setItem('yaktube_recent_searches', JSON.stringify(defaults));
|
||
} catch (e) {}
|
||
}
|
||
return defaults;
|
||
}
|
||
|
||
function callCloudSearchHistory(method, queryParams, body, onSuccess, onError) {
|
||
var token = localStorage.getItem('access_token');
|
||
var email = localStorage.getItem('email');
|
||
var username = localStorage.getItem('username');
|
||
var headers = {};
|
||
if (body) headers['Content-Type'] = 'application/json';
|
||
if (token) headers['Authorization'] = 'Bearer ' + token;
|
||
if (email) headers['X-User-Email'] = email;
|
||
if (username) headers['X-User-Username'] = username;
|
||
|
||
var authUrl = 'https://developer-console.yakhub.com.tr/api/yaktube/search-history' + (queryParams || '');
|
||
var historyPath = '/search-history' + (queryParams || '');
|
||
|
||
var options = {
|
||
method: method,
|
||
headers: headers,
|
||
credentials: 'include'
|
||
};
|
||
if (body) options.body = JSON.stringify(body);
|
||
|
||
if (!isOfficialYakTubeServer()) {
|
||
fetchPluginJson(historyPath, options)
|
||
.then(function (data) {
|
||
if (typeof onSuccess === 'function') onSuccess(data);
|
||
})
|
||
.catch(function (e) {
|
||
if (typeof onError === 'function') onError(e);
|
||
});
|
||
return;
|
||
}
|
||
|
||
fetch(authUrl, options)
|
||
.then(function (res) {
|
||
if (!res.ok) throw new Error('Auth server status ' + res.status);
|
||
return res.json();
|
||
})
|
||
.then(function (data) {
|
||
if (typeof onSuccess === 'function') onSuccess(data);
|
||
})
|
||
.catch(function () {
|
||
fetchPluginJson(historyPath, options)
|
||
.then(function (data) {
|
||
if (typeof onSuccess === 'function') onSuccess(data);
|
||
})
|
||
.catch(function (e) {
|
||
if (typeof onError === 'function') onError(e);
|
||
});
|
||
});
|
||
}
|
||
|
||
var isSyncingHistory = false;
|
||
function syncCloudSearchHistory(callback) {
|
||
if (!isAccountSyncEnabled() || isSyncingHistory) return;
|
||
isSyncingHistory = true;
|
||
|
||
callCloudSearchHistory(
|
||
'GET',
|
||
'',
|
||
null,
|
||
function (data) {
|
||
isSyncingHistory = false;
|
||
if (data && data.status === 'success' && Array.isArray(data.history)) {
|
||
if (data.history.length > 0) {
|
||
localStorage.setItem('yaktube_recent_searches', JSON.stringify(data.history));
|
||
}
|
||
if (typeof callback === 'function') callback();
|
||
}
|
||
},
|
||
function () {
|
||
isSyncingHistory = false;
|
||
}
|
||
);
|
||
}
|
||
|
||
function saveRecentSearch(query) {
|
||
if (!query || query.trim().length < 2) return;
|
||
var q = query.trim();
|
||
try {
|
||
var list = getRecentSearches();
|
||
// Remove previous occurrence of the exact term (case-insensitive) and bubble it to the very top (#1)
|
||
list = list.filter(function (item) {
|
||
return item.toLowerCase() !== q.toLowerCase();
|
||
});
|
||
list.unshift(q);
|
||
if (list.length > 20) list = list.slice(0, 20);
|
||
localStorage.setItem('yaktube_recent_searches', JSON.stringify(list));
|
||
} catch (e) {}
|
||
|
||
// If user is logged in and sync is active, sync with YakNet account
|
||
if (isAccountSyncEnabled()) {
|
||
callCloudSearchHistory('POST', '', { query: q, device_name: 'YakTube Web' }, function (data) {
|
||
if (data && data.status === 'success' && Array.isArray(data.history) && data.history.length > 0) {
|
||
localStorage.setItem('yaktube_recent_searches', JSON.stringify(data.history));
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
function deleteRecentSearch(targetQuery) {
|
||
if (!targetQuery) return;
|
||
var q = targetQuery.trim();
|
||
try {
|
||
var list = getRecentSearches();
|
||
list = list.filter(function (item) {
|
||
return item.toLowerCase() !== q.toLowerCase();
|
||
});
|
||
localStorage.setItem('yaktube_recent_searches', JSON.stringify(list));
|
||
} catch (e) {}
|
||
|
||
if (isAccountSyncEnabled()) {
|
||
callCloudSearchHistory('DELETE', '?query=' + encodeURIComponent(q), { query: q }, function (data) {
|
||
if (data && data.status === 'success' && Array.isArray(data.history)) {
|
||
localStorage.setItem('yaktube_recent_searches', JSON.stringify(data.history));
|
||
}
|
||
});
|
||
}
|
||
|
||
var modal = document.getElementById('yaktube-full-search-modal');
|
||
var filterVal = '';
|
||
if (modal) {
|
||
var inp = modal.querySelector('#yaktube-modal-input');
|
||
if (inp) filterVal = inp.value;
|
||
}
|
||
renderDynamicSearchChips(filterVal);
|
||
announce('"' + q + '" araması geçmişten silindi.');
|
||
}
|
||
|
||
function clearRecentSearches() {
|
||
try {
|
||
localStorage.removeItem('yaktube_recent_searches');
|
||
} catch (e) {}
|
||
|
||
if (isAccountSyncEnabled()) {
|
||
callCloudSearchHistory('DELETE', '', null);
|
||
}
|
||
|
||
renderDynamicSearchChips();
|
||
announce('Arama geçmişi temizlendi.');
|
||
}
|
||
|
||
var popularTrendingQueries = [
|
||
{ title: '🎵 Türkçe Pop', q: 'Türkçe Pop' },
|
||
{ title: '🎸 Anadolu Rock', q: 'Anadolu Rock' },
|
||
{ title: '🤖 Yapay Zeka', q: 'Yapay Zeka' },
|
||
{ title: '💻 Yazılım Dersleri', q: 'Yazılım Dersleri' },
|
||
{ title: '🎧 Sesli Kitap & Radyo Tiyatrosu', q: 'Sesli Kitap' },
|
||
{ title: '📺 Canlı Haber', q: 'Canlı Haber' },
|
||
{ title: '🌍 Bilim & Belgesel', q: 'Bilim Belgeseli' },
|
||
{ title: '🎼 Akustik Canlı Performans', q: 'Akustik Canlı' },
|
||
{ title: '🎙️ Podcast & Söyleşi', q: 'Podcast Türkçe' }
|
||
];
|
||
|
||
// Auto capture search query from URL into recent searches
|
||
function captureUrlSearchQuery() {
|
||
try {
|
||
var params = new URLSearchParams(window.location.search);
|
||
var q = params.get('search') || params.get('q');
|
||
if (q && q.trim().length >= 2) {
|
||
saveRecentSearch(q.trim());
|
||
}
|
||
} catch (e) {}
|
||
}
|
||
captureUrlSearchQuery();
|
||
window.addEventListener('popstate', captureUrlSearchQuery);
|
||
|
||
function renderDynamicSearchChips(filterText) {
|
||
var modal = document.getElementById('yaktube-full-search-modal');
|
||
if (!modal) return;
|
||
|
||
var container = modal.querySelector('#yaktube-modal-dynamic-chips-section');
|
||
if (!container) return;
|
||
|
||
var recent = getRecentSearches();
|
||
var loggedIn = isUserLoggedIn();
|
||
var syncEnabled = isAccountSyncEnabled();
|
||
var filter = (filterText || '').trim().toLowerCase();
|
||
|
||
var displayedRecent = recent;
|
||
var displayedPopular = popularTrendingQueries;
|
||
|
||
if (filter.length > 0) {
|
||
displayedRecent = recent.filter(function (term) {
|
||
return term.toLowerCase().includes(filter);
|
||
});
|
||
displayedPopular = popularTrendingQueries.filter(function (item) {
|
||
return item.q.toLowerCase().includes(filter) || item.title.toLowerCase().includes(filter);
|
||
});
|
||
}
|
||
|
||
var html = '';
|
||
|
||
// 1. Recent searches section
|
||
html +=
|
||
'<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; flex-wrap: wrap; gap: 8px;">' +
|
||
'<div class="yaktube-modal-section-title" style="margin-bottom: 0;">🕒 ' +
|
||
(filter.length > 0 ? 'Eşleşen Son Aramalarınız' : 'Son Aramalarınız') +
|
||
'</div>' +
|
||
'<div style="display: flex; align-items: center; gap: 8px;">';
|
||
|
||
if (loggedIn) {
|
||
var isYakNet = isYakNetSsoEnabled();
|
||
var syncTitle = syncEnabled
|
||
? isYakNet
|
||
? 'YakNet Bulut Eşitlemesi Aktif (Tüm cihazlarınızda senkronize edilir)'
|
||
: 'Hesap Arama Eşitlemesi Aktif (Sunucu hesabınızla senkronize edilir)'
|
||
: 'Eşitleme Kapalı (Aramalar sadece bu cihazda saklanır)';
|
||
var syncText = syncEnabled ? '☁️ Eşitleme: Açık' : '☁️ Eşitleme: Kapalı';
|
||
var syncBg = syncEnabled ? '#0f766e' : '#334155';
|
||
var syncColor = syncEnabled ? '#5eead4' : '#94a3b8';
|
||
html +=
|
||
'<button id="yaktube-sync-toggle-btn" style="background: ' +
|
||
syncBg +
|
||
'; border: 1px solid rgba(255,255,255,0.15); border-radius: 6px; padding: 2px 8px; color: ' +
|
||
syncColor +
|
||
'; font-size: 11px; font-weight: 600; cursor: pointer; transition: all 0.2s ease;" title="' +
|
||
syncTitle +
|
||
'" aria-label="' +
|
||
syncTitle +
|
||
'">' +
|
||
syncText +
|
||
'</button>';
|
||
} else {
|
||
html +=
|
||
'<span style="font-size: 11px; color: #94a3b8; background: #1e293b; border-radius: 6px; padding: 2px 8px;" title="Misafir modundasınız, aramalar sadece bu cihazda saklanır">🔒 Bu Cihazda</span>';
|
||
}
|
||
|
||
if (recent.length > 0 && filter.length === 0) {
|
||
html +=
|
||
'<button id="yaktube-clear-recent-btn" style="background: transparent; border: none; color: #ff8f37; font-size: 12px; font-weight: 600; cursor: pointer; text-decoration: underline;" aria-label="Tüm arama geçmişini temizle">Geçmişi Temizle</button>';
|
||
}
|
||
|
||
html += '</div></div>';
|
||
|
||
if (displayedRecent.length > 0) {
|
||
html += '<div class="yaktube-modal-chips-grid" style="margin-bottom: 18px;">';
|
||
displayedRecent.forEach(function (term) {
|
||
var safeTerm = term.replace(/"/g, '"');
|
||
html +=
|
||
'<div class="yaktube-modal-chip yaktube-recent-chip" data-query="' +
|
||
safeTerm +
|
||
'" title="' +
|
||
safeTerm +
|
||
' için ara">' +
|
||
'<span class="yaktube-recent-chip-text" data-query="' +
|
||
safeTerm +
|
||
'">🕒 ' +
|
||
safeTerm +
|
||
'</span>' +
|
||
'<button type="button" class="yaktube-recent-chip-delete" data-delete-query="' +
|
||
safeTerm +
|
||
'" title="Bu aramayı geçmişten kaldır" aria-label="' +
|
||
safeTerm +
|
||
' aramasını geçmişten kaldır">✕</button>' +
|
||
'</div>';
|
||
});
|
||
html += '</div>';
|
||
} else if (filter.length > 0) {
|
||
html +=
|
||
'<div style="font-size: 12px; color: #94a3b8; margin-bottom: 14px; font-style: italic;">Geçmişte "' +
|
||
filter.replace(/"/g, '"') +
|
||
'" ile eşleşen kayıt bulunamadı.</div>';
|
||
}
|
||
|
||
// 2. Popular & Trending searches section
|
||
if (displayedPopular.length > 0) {
|
||
html +=
|
||
'<div class="yaktube-modal-section-title">🔥 ' +
|
||
(filter.length > 0 ? 'Önerilen Aramalar' : 'Hızlı ve Popüler Aramalar') +
|
||
'</div>' +
|
||
'<div class="yaktube-modal-chips-grid">';
|
||
|
||
displayedPopular.forEach(function (item) {
|
||
var safeQ = item.q.replace(/"/g, '"');
|
||
html +=
|
||
'<button class="yaktube-modal-chip" data-query="' +
|
||
safeQ +
|
||
'" aria-label="Popüler arama: ' +
|
||
safeQ +
|
||
'">' +
|
||
item.title +
|
||
'</button>';
|
||
});
|
||
html += '</div>';
|
||
}
|
||
|
||
container.innerHTML = html;
|
||
|
||
// Attach click events
|
||
container.querySelectorAll('.yaktube-recent-chip-delete').forEach(function (delBtn) {
|
||
delBtn.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
var delTerm = delBtn.getAttribute('data-delete-query');
|
||
deleteRecentSearch(delTerm);
|
||
});
|
||
});
|
||
|
||
container.querySelectorAll('.yaktube-modal-chip').forEach(function (chip) {
|
||
chip.addEventListener('click', function (e) {
|
||
if (e.target && e.target.classList.contains('yaktube-recent-chip-delete')) {
|
||
return;
|
||
}
|
||
var query = chip.getAttribute('data-query');
|
||
var inp = modal.querySelector('#yaktube-modal-input');
|
||
if (inp) inp.value = query;
|
||
if (typeof window.__yaktube_execute_search__ === 'function') {
|
||
window.__yaktube_execute_search__(query);
|
||
}
|
||
});
|
||
});
|
||
|
||
var clearBtn = container.querySelector('#yaktube-clear-recent-btn');
|
||
if (clearBtn) {
|
||
clearBtn.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
clearRecentSearches();
|
||
});
|
||
}
|
||
|
||
var syncToggleBtn = container.querySelector('#yaktube-sync-toggle-btn');
|
||
if (syncToggleBtn) {
|
||
syncToggleBtn.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
var current = localStorage.getItem('yaktube_sync_search_history') !== 'false';
|
||
var next = !current;
|
||
localStorage.setItem('yaktube_sync_search_history', next ? 'true' : 'false');
|
||
if (next) {
|
||
announce('YakNet arama geçmişi eşitlemesi açıldı.');
|
||
syncCloudSearchHistory(renderDynamicSearchChips);
|
||
} else {
|
||
announce('Arama geçmişi eşitlemesi kapatıldı. Aramalar sadece bu cihazda saklanacak.');
|
||
}
|
||
renderDynamicSearchChips();
|
||
});
|
||
}
|
||
}
|
||
|
||
function createFullSearchModal() {
|
||
var existingModal = document.getElementById('yaktube-full-search-modal');
|
||
if (existingModal) return existingModal;
|
||
|
||
var modal = document.createElement('div');
|
||
modal.id = 'yaktube-full-search-modal';
|
||
modal.className = 'yaktube-full-search-modal';
|
||
modal.setAttribute('role', 'dialog');
|
||
modal.setAttribute('aria-modal', 'true');
|
||
modal.setAttribute('aria-labelledby', 'yaktube-modal-search-title');
|
||
|
||
modal.innerHTML =
|
||
'<div class="yaktube-modal-search-card">' +
|
||
'<div class="yaktube-modal-search-bar">' +
|
||
'<button id="yaktube-modal-back-btn" class="yaktube-modal-back-btn" aria-label="Aramadan Çık (Escape)" title="Aramadan Çık (Escape)">←</button>' +
|
||
'<div class="yaktube-modal-input-wrap">' +
|
||
'<input id="yaktube-modal-input" type="search" placeholder="Video veya kanal ara..." aria-label="Arama Metni">' +
|
||
'<button id="yaktube-modal-clear-btn" class="yaktube-modal-clear-btn" aria-label="Metni Temizle">✕</button>' +
|
||
'</div>' +
|
||
'<button id="yaktube-modal-submit-btn" class="yaktube-modal-search-action-btn" aria-label="Ara">🔍 Ara</button>' +
|
||
'<button id="yaktube-modal-voice-btn" class="yaktube-modal-voice-btn" aria-label="Sesle Ara (Shift+V)" title="Sesle Ara">🎙️</button>' +
|
||
'</div>' +
|
||
'<div class="yaktube-modal-body">' +
|
||
'<div id="yaktube-modal-voice-section" class="yaktube-modal-voice-section">' +
|
||
'<div id="yaktube-modal-voice-status" class="yaktube-modal-voice-status">🎙️ Dinleniyor...</div>' +
|
||
'<div id="yaktube-modal-voice-transcript" class="yaktube-modal-voice-transcript">Lütfen aramak istediğiniz videoyu söyleyin...</div>' +
|
||
'<button id="yaktube-modal-mic-pulse" class="yaktube-modal-mic-pulse-btn" aria-label="Mikrofonu durdur">🎙️</button>' +
|
||
'</div>' +
|
||
'<div id="yaktube-modal-dynamic-chips-section"></div>' +
|
||
'<div class="yaktube-modal-hint-footer">' +
|
||
'<span>💡 <b>Enter</b> ile ara, <b>Shift+V</b> ile sesli ara</span>' +
|
||
'<span><b>Escape</b> ile kapat</span>' +
|
||
'</div>' +
|
||
'</div>' +
|
||
'</div>';
|
||
|
||
document.body.appendChild(modal);
|
||
|
||
var inp = modal.querySelector('#yaktube-modal-input');
|
||
var clearBtn = modal.querySelector('#yaktube-modal-clear-btn');
|
||
var backBtn = modal.querySelector('#yaktube-modal-back-btn');
|
||
var submitBtn = modal.querySelector('#yaktube-modal-submit-btn');
|
||
var voiceBtn = modal.querySelector('#yaktube-modal-voice-btn');
|
||
var micPulseBtn = modal.querySelector('#yaktube-modal-mic-pulse');
|
||
|
||
// Input typing & live search history filtering
|
||
inp.addEventListener('input', function () {
|
||
var val = (inp.value || '').trim();
|
||
if (val.length > 0) {
|
||
clearBtn.style.display = 'inline-flex';
|
||
} else {
|
||
clearBtn.style.display = 'none';
|
||
}
|
||
renderDynamicSearchChips(val);
|
||
});
|
||
|
||
clearBtn.addEventListener('click', function () {
|
||
inp.value = '';
|
||
clearBtn.style.display = 'none';
|
||
inp.focus();
|
||
renderDynamicSearchChips('');
|
||
announce('Arama metni temizlendi.');
|
||
});
|
||
|
||
// Close on Back button or Escape
|
||
backBtn.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
closeFullSearchModal();
|
||
});
|
||
|
||
modal.addEventListener('click', function (e) {
|
||
if (e.target === modal) {
|
||
closeFullSearchModal();
|
||
}
|
||
});
|
||
|
||
// Search execute
|
||
function executeSearch(query) {
|
||
var q = (query || inp.value || '').trim();
|
||
if (q) {
|
||
saveRecentSearch(q);
|
||
announce('"' + q + '" için arama yapılıyor...', true);
|
||
closeFullSearchModal();
|
||
window.location.href = '/search?search=' + encodeURIComponent(q) + '&searchTarget=search-index';
|
||
}
|
||
}
|
||
window.__yaktube_execute_search__ = executeSearch;
|
||
renderDynamicSearchChips();
|
||
|
||
submitBtn.addEventListener('click', function () {
|
||
executeSearch();
|
||
});
|
||
|
||
inp.addEventListener('keydown', function (e) {
|
||
if (e.key === 'Enter') {
|
||
e.preventDefault();
|
||
executeSearch();
|
||
} else if (e.key === 'Escape') {
|
||
e.preventDefault();
|
||
closeFullSearchModal();
|
||
}
|
||
});
|
||
|
||
// Voice button click
|
||
voiceBtn.addEventListener('click', function () {
|
||
toggleVoiceInsideModal();
|
||
});
|
||
|
||
micPulseBtn.addEventListener('click', function () {
|
||
toggleVoiceInsideModal();
|
||
});
|
||
|
||
return modal;
|
||
}
|
||
|
||
function openFullSearchModal(initialQuery, autoStartVoice) {
|
||
var modal = createFullSearchModal();
|
||
modal.classList.add('yaktube-modal-open');
|
||
modal.style.display = 'flex';
|
||
renderDynamicSearchChips();
|
||
syncCloudSearchHistory(renderDynamicSearchChips);
|
||
|
||
var inp = modal.querySelector('#yaktube-modal-input');
|
||
var clearBtn = modal.querySelector('#yaktube-modal-clear-btn');
|
||
if (inp) {
|
||
inp.value = initialQuery || '';
|
||
if (inp.value) clearBtn.style.display = 'inline-flex';
|
||
setTimeout(function () {
|
||
inp.focus();
|
||
inp.select();
|
||
}, 50);
|
||
}
|
||
|
||
announce('Arama penceresi açıldı. Arayacağınız konuyu yazın veya sesle arayın.', true);
|
||
|
||
if (autoStartVoice) {
|
||
startVoiceInsideModal();
|
||
}
|
||
}
|
||
|
||
function closeFullSearchModal() {
|
||
var modal = document.getElementById('yaktube-full-search-modal');
|
||
if (modal) {
|
||
modal.classList.remove('yaktube-modal-open');
|
||
modal.style.display = 'none';
|
||
}
|
||
stopVoiceInsideModal();
|
||
announce('Arama penceresi kapatıldı.');
|
||
|
||
var trigger = document.querySelector('.yaktube-search-trigger-pill');
|
||
if (trigger) {
|
||
try {
|
||
trigger.focus();
|
||
} catch (e) {}
|
||
}
|
||
}
|
||
|
||
function toggleVoiceInsideModal() {
|
||
if (isVoiceListening) {
|
||
stopVoiceInsideModal();
|
||
} else {
|
||
startVoiceInsideModal();
|
||
}
|
||
}
|
||
|
||
function startVoiceInsideModal() {
|
||
var SpeechRec = window.SpeechRecognition || window.webkitSpeechRecognition;
|
||
var modal = document.getElementById('yaktube-full-search-modal');
|
||
if (!modal) return;
|
||
|
||
var voiceSec = modal.querySelector('#yaktube-modal-voice-section');
|
||
var statusText = modal.querySelector('#yaktube-modal-voice-status');
|
||
var transcriptEl = modal.querySelector('#yaktube-modal-voice-transcript');
|
||
var inp = modal.querySelector('#yaktube-modal-input');
|
||
|
||
if (voiceSec) voiceSec.style.display = 'block';
|
||
if (statusText) statusText.textContent = '🎙️ Dinleniyor...';
|
||
if (transcriptEl) transcriptEl.textContent = 'Lütfen aramak istediğiniz videoyu söyleyin...';
|
||
|
||
if (!SpeechRec) {
|
||
if (statusText) statusText.textContent = 'Tarayıcıda Ses Tanıma Desteklenmiyor';
|
||
if (transcriptEl) transcriptEl.textContent = 'Lütfen Google Chrome veya Microsoft Edge kullanın.';
|
||
announce('Tarayıcınız ses tanımayı desteklemiyor. Lütfen Chrome veya Edge kullanın.');
|
||
return;
|
||
}
|
||
|
||
announce('Sesli arama dinleniyor, lütfen aramak istediğiniz videoyu söyleyin.', true);
|
||
|
||
try {
|
||
activeVoiceRec = new SpeechRec();
|
||
activeVoiceRec.lang = navigator.language || 'tr-TR';
|
||
activeVoiceRec.continuous = false;
|
||
activeVoiceRec.interimResults = true;
|
||
activeVoiceRec.maxAlternatives = 1;
|
||
|
||
isVoiceListening = true;
|
||
|
||
activeVoiceRec.onresult = function (ev) {
|
||
if (ev.results && ev.results[0]) {
|
||
var transcript = ev.results[0][0].transcript.trim();
|
||
if (transcriptEl) transcriptEl.textContent = '"' + transcript + '"';
|
||
if (inp) inp.value = transcript;
|
||
|
||
if (ev.results[0].isFinal) {
|
||
if (handleVoiceAssistantCommand(transcript)) {
|
||
return;
|
||
}
|
||
announce('"' + transcript + '" için arama başlatılıyor...', true);
|
||
setTimeout(function () {
|
||
closeFullSearchModal();
|
||
window.location.href =
|
||
'/search?search=' + encodeURIComponent(transcript) + '&searchTarget=search-index';
|
||
}, 500);
|
||
}
|
||
}
|
||
};
|
||
|
||
activeVoiceRec.onerror = function (ev) {
|
||
if (statusText) statusText.textContent = 'Ses Algılanamadı';
|
||
if (transcriptEl) transcriptEl.textContent = 'Tekrar denemek için mikrofona dokunun.';
|
||
stopVoiceInsideModal();
|
||
};
|
||
|
||
activeVoiceRec.onend = function () {
|
||
stopVoiceInsideModal();
|
||
};
|
||
|
||
activeVoiceRec.start();
|
||
} catch (err) {
|
||
stopVoiceInsideModal();
|
||
}
|
||
}
|
||
|
||
function stopVoiceInsideModal() {
|
||
isVoiceListening = false;
|
||
if (activeVoiceRec) {
|
||
try {
|
||
activeVoiceRec.stop();
|
||
} catch (e) {}
|
||
activeVoiceRec = null;
|
||
}
|
||
var modal = document.getElementById('yaktube-full-search-modal');
|
||
if (modal) {
|
||
var voiceSec = modal.querySelector('#yaktube-modal-voice-section');
|
||
if (voiceSec) voiceSec.style.display = 'none';
|
||
}
|
||
}
|
||
|
||
function transformToYouTubeSearchBar(searchInp, searchContainer) {
|
||
if (searchContainer.hasAttribute('data-yaktube-trigger-styled')) return;
|
||
searchContainer.setAttribute('data-yaktube-trigger-styled', 'true');
|
||
|
||
// Hide original native inputs
|
||
searchInp.style.display = 'none';
|
||
searchInp.setAttribute('tabindex', '-1');
|
||
searchInp.setAttribute('aria-hidden', 'true');
|
||
|
||
var nativeInputs = searchContainer.querySelectorAll('input, button');
|
||
nativeInputs.forEach(function (el) {
|
||
if (
|
||
!el.classList.contains('yaktube-search-trigger-pill') &&
|
||
!el.classList.contains('yaktube-voice-search-btn')
|
||
) {
|
||
el.style.display = 'none';
|
||
el.setAttribute('tabindex', '-1');
|
||
el.setAttribute('aria-hidden', 'true');
|
||
}
|
||
});
|
||
|
||
// 1. Create Outer Wrapper
|
||
var outerWrap = searchContainer.querySelector('.yaktube-search-outer-wrap');
|
||
if (!outerWrap) {
|
||
outerWrap = document.createElement('div');
|
||
outerWrap.className = 'yaktube-search-outer-wrap';
|
||
searchContainer.appendChild(outerWrap);
|
||
}
|
||
|
||
// 2. Create Single Sleek Pill Trigger
|
||
var triggerPill = outerWrap.querySelector('.yaktube-search-trigger-pill');
|
||
if (!triggerPill) {
|
||
triggerPill = document.createElement('button');
|
||
triggerPill.type = 'button';
|
||
triggerPill.className = 'yaktube-search-trigger-pill';
|
||
triggerPill.setAttribute('aria-label', 'Ara');
|
||
triggerPill.setAttribute('title', 'Arama Yap (/)');
|
||
|
||
triggerPill.innerHTML =
|
||
'<span class="yaktube-search-trigger-icon">🔍</span>' +
|
||
'<span class="yaktube-search-trigger-text">Ara...</span>' +
|
||
'<span class="yaktube-search-trigger-shortcut">/</span>';
|
||
|
||
outerWrap.appendChild(triggerPill);
|
||
|
||
triggerPill.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
openFullSearchModal('', false);
|
||
});
|
||
}
|
||
|
||
// 3. YouTube Circular Voice Button (🎙️) Beside the Pill Box
|
||
var voiceBtn = outerWrap.querySelector('.yaktube-voice-search-btn');
|
||
if (!voiceBtn) {
|
||
voiceBtn = document.createElement('button');
|
||
voiceBtn.type = 'button';
|
||
voiceBtn.className = 'yaktube-voice-search-btn';
|
||
voiceBtn.setAttribute('aria-label', 'Sesle Ara (Shift+V)');
|
||
voiceBtn.setAttribute('title', 'Sesle Ara (Shift+V)');
|
||
voiceBtn.innerHTML = '🎙️';
|
||
|
||
outerWrap.appendChild(voiceBtn);
|
||
|
||
voiceBtn.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
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() {
|
||
var searchContainers = document.querySelectorAll(
|
||
'my-search-typeahead, .search-container, .header-search, my-header .search'
|
||
);
|
||
searchContainers.forEach(function (container) {
|
||
var searchInp = container.querySelector('input[type="search"], input[type="text"], input');
|
||
if (searchInp) {
|
||
transformToYouTubeSearchBar(searchInp, container);
|
||
}
|
||
});
|
||
|
||
// Clean up repetitive card titles and strange relative date buttons
|
||
document.querySelectorAll('my-video-miniature, .video-miniature').forEach(function (card) {
|
||
var thumbLink = card.querySelector('a.thumbnail-link, .video-thumbnail a, a.thumbnail');
|
||
if (thumbLink && !thumbLink.hasAttribute('aria-hidden')) {
|
||
thumbLink.setAttribute('aria-hidden', 'true');
|
||
thumbLink.setAttribute('tabindex', '-1');
|
||
}
|
||
|
||
var dateBtn = card.querySelector('.video-date-line button, .video-date button, button[title*="tarih"]');
|
||
if (dateBtn && !dateBtn.hasAttribute('data-cleaned')) {
|
||
dateBtn.setAttribute('data-cleaned', 'true');
|
||
var dateText = dateBtn.textContent.trim();
|
||
dateBtn.setAttribute('aria-label', dateText);
|
||
}
|
||
});
|
||
}
|
||
|
||
// Global Keyboard Shortcuts
|
||
document.addEventListener('keydown', function (e) {
|
||
var activeTag = document.activeElement ? document.activeElement.tagName.toLowerCase() : '';
|
||
var isInputActive = activeTag === 'input' || activeTag === 'textarea';
|
||
|
||
// Shift + V: Open YouTube Voice Search Modal
|
||
if (e.shiftKey && (e.key === 'V' || e.key === 'v') && !isInputActive) {
|
||
e.preventDefault();
|
||
openFullSearchModal('', true);
|
||
}
|
||
// Escape: Close Full Search Modal
|
||
else if (e.key === 'Escape' || e.keyCode === 27) {
|
||
var modal = document.getElementById('yaktube-full-search-modal');
|
||
if (modal && modal.classList.contains('yaktube-modal-open')) {
|
||
e.preventDefault();
|
||
closeFullSearchModal();
|
||
}
|
||
}
|
||
// / or S: Open Search Modal
|
||
else if ((e.key === '/' || e.key === 's' || e.key === 'S') && !isInputActive && !e.ctrlKey && !e.metaKey) {
|
||
e.preventDefault();
|
||
openFullSearchModal('', false);
|
||
}
|
||
});
|
||
|
||
// Automatically trigger cloud search history pull on startup if logged in
|
||
try {
|
||
if (isAccountSyncEnabled()) {
|
||
syncCloudSearchHistory();
|
||
}
|
||
} catch (e) {}
|
||
|
||
// 7.5. YouTube-Style Smart Recommendation, History Profiler & Up-Next Engine (Watch Page)
|
||
var currentActiveVideoKey = null;
|
||
var isFetchingRelated = false;
|
||
var relatedShowAll = false;
|
||
var cachedRelatedResults = [];
|
||
var cachedRelatedQuery = '';
|
||
var smartHasLocalMatch = false;
|
||
var smartPrefetchCandidate = null;
|
||
var smartPrefetchState = {
|
||
videoKey: null,
|
||
status: 'idle', // 'idle' | 'preparing' | 'ready' | 'failed'
|
||
pollTimer: null,
|
||
readyUrl: null,
|
||
readyTitle: null
|
||
};
|
||
var upNextCountdownTimer = null;
|
||
|
||
function cleanVideoTopicString(rawTitle) {
|
||
if (!rawTitle) return '';
|
||
return String(rawTitle)
|
||
.replace(/YakTube/gi, '')
|
||
.replace(/[\(\[].*?[\)\]]/g, '')
|
||
.replace(
|
||
/official\s*video|video\s*klip|klip|hd|4k|lyric\s*video|audio|remix|feat\.?|ft\.?|şarkı\s*sözleri/gi,
|
||
''
|
||
)
|
||
.replace(/\s+/g, ' ')
|
||
.trim();
|
||
}
|
||
|
||
function isInvalidWatchPageTitle(rawTitle) {
|
||
if (!rawTitle || typeof rawTitle !== 'string') return true;
|
||
var t = rawTitle.trim();
|
||
if (t.length < 3) return true;
|
||
return /^(bildirimler|notifications|yaktube|peertube|yükleniyor|loading|anasayfa|videolar|keşfet|kesfet|trendler)$/i.test(
|
||
t
|
||
);
|
||
}
|
||
|
||
function normalizeWatchTitleForMatch(rawTitle) {
|
||
if (!rawTitle) return '';
|
||
return String(rawTitle)
|
||
.toLowerCase()
|
||
.replace(/[\(\[].*?[\)\]]/g, ' ')
|
||
.replace(
|
||
/\b(official\s*music\s*video|official\s*video|official\s*audio|video\s*klip|klip|hd|4k|1080p|lyric\s*video|lyrics|audio|şarkı\s*sözleri|sarki\s*sozleri|full\s*izle|yaktube)\b/gi,
|
||
' '
|
||
)
|
||
.replace(/[^\w\sğüşıöçĞÜŞİÖÇ]/g, ' ')
|
||
.replace(/\s+/g, ' ')
|
||
.trim();
|
||
}
|
||
|
||
function isGenericLocalChannelName(chan) {
|
||
if (!chan) return true;
|
||
var c = String(chan).trim().toLowerCase();
|
||
if (c.length < 2) return true;
|
||
return (
|
||
/^(yaktube|root|admin|youtube|varsayılan|varsayilan|müzik kanalı|muzik kanali|muzik_kanali|genel medya|fediverse ağı)$/i.test(
|
||
c
|
||
) ||
|
||
c.indexOf('yaktube ') === 0 ||
|
||
c.indexOf(' kanalı') !== -1 ||
|
||
c.indexOf('_kanali') !== -1
|
||
);
|
||
}
|
||
|
||
function saveVideoChannelMeta(title, channel, ytId, uuid) {
|
||
if (!title || !channel || isGenericLocalChannelName(channel)) return;
|
||
try {
|
||
var raw = localStorage.getItem('yaktube_video_channel_map');
|
||
var map = raw ? JSON.parse(raw) : {};
|
||
if (!map || typeof map !== 'object') map = {};
|
||
var normT = normalizeWatchTitleForMatch(title);
|
||
var entry = {
|
||
channel: String(channel).trim(),
|
||
ytId: ytId || '',
|
||
uuid: uuid || '',
|
||
ts: Date.now()
|
||
};
|
||
if (normT && normT.length >= 3) map['t:' + normT] = entry;
|
||
if (uuid) map['u:' + String(uuid).toLowerCase()] = entry;
|
||
if (ytId) map['y:' + String(ytId)] = entry;
|
||
|
||
var keys = Object.keys(map);
|
||
if (keys.length > 120) {
|
||
keys
|
||
.sort(function (a, b) {
|
||
return ((map[a] && map[a].ts) || 0) - ((map[b] && map[b].ts) || 0);
|
||
})
|
||
.slice(0, keys.length - 90)
|
||
.forEach(function (k) {
|
||
delete map[k];
|
||
});
|
||
}
|
||
localStorage.setItem('yaktube_video_channel_map', JSON.stringify(map));
|
||
} catch (e) {}
|
||
}
|
||
|
||
function lookupVideoChannelMeta(title, uuid) {
|
||
try {
|
||
var raw = localStorage.getItem('yaktube_video_channel_map');
|
||
if (!raw) return null;
|
||
var map = JSON.parse(raw);
|
||
if (!map || typeof map !== 'object') return null;
|
||
if (uuid && map['u:' + String(uuid).toLowerCase()]) {
|
||
return map['u:' + String(uuid).toLowerCase()];
|
||
}
|
||
var normT = normalizeWatchTitleForMatch(title);
|
||
if (normT && map['t:' + normT]) {
|
||
return map['t:' + normT];
|
||
}
|
||
} catch (e) {}
|
||
return null;
|
||
}
|
||
|
||
function recordWatchedVideo(uuid, rawTitle, rawChannel, ytId) {
|
||
if (isInvalidWatchPageTitle(rawTitle)) return;
|
||
try {
|
||
var cleanTopic = cleanVideoTopicString(rawTitle);
|
||
var words = cleanTopic.split(/\s+/).filter(function (w) {
|
||
return w.length >= 2;
|
||
});
|
||
var compactTopic = words.slice(0, 4).join(' ') || cleanTopic;
|
||
if (!compactTopic || compactTopic.length < 3 || isInvalidWatchPageTitle(compactTopic)) return;
|
||
|
||
var normTitle = normalizeWatchTitleForMatch(rawTitle);
|
||
var meta = lookupVideoChannelMeta(rawTitle, uuid);
|
||
var effectiveChannel =
|
||
rawChannel && !isGenericLocalChannelName(rawChannel)
|
||
? rawChannel
|
||
: meta && meta.channel
|
||
? meta.channel
|
||
: rawChannel || '';
|
||
var effectiveYtId = ytId || (meta && meta.ytId) || '';
|
||
|
||
var rawList = localStorage.getItem('yaktube_watch_history');
|
||
var list = [];
|
||
if (rawList) {
|
||
try {
|
||
var parsed = JSON.parse(rawList);
|
||
if (Array.isArray(parsed)) list = parsed;
|
||
} catch (e) {}
|
||
}
|
||
|
||
// Purge any invalid UI titles (like "Bildirimler") and deduplicate current video
|
||
list = list.filter(function (entry) {
|
||
if (!entry || isInvalidWatchPageTitle(entry.title) || isInvalidWatchPageTitle(entry.topic)) return false;
|
||
if (uuid && entry.uuid && entry.uuid.toLowerCase() === uuid.toLowerCase()) return false;
|
||
if (effectiveYtId && entry.ytId && entry.ytId === effectiveYtId) return false;
|
||
if (normTitle && entry.normTitle && entry.normTitle === normTitle) return false;
|
||
return true;
|
||
});
|
||
|
||
list.unshift({
|
||
uuid: uuid || '',
|
||
ytId: effectiveYtId,
|
||
title: rawTitle,
|
||
normTitle: normTitle,
|
||
topic: compactTopic,
|
||
channel: effectiveChannel,
|
||
ts: Date.now()
|
||
});
|
||
|
||
if (list.length > 35) list = list.slice(0, 35);
|
||
localStorage.setItem('yaktube_watch_history', JSON.stringify(list));
|
||
} catch (e) {}
|
||
}
|
||
|
||
function getWatchedExclusionList(currentUuid, currentTitle) {
|
||
var exclusions = [];
|
||
var seen = {};
|
||
function addToken(tok) {
|
||
if (!tok) return;
|
||
var s = String(tok).trim();
|
||
if (!s || s.length < 3 || seen[s.toLowerCase()]) return;
|
||
seen[s.toLowerCase()] = true;
|
||
exclusions.push(s);
|
||
}
|
||
|
||
if (currentUuid) addToken(currentUuid);
|
||
if (currentTitle && !isInvalidWatchPageTitle(currentTitle)) {
|
||
addToken(normalizeWatchTitleForMatch(currentTitle));
|
||
}
|
||
|
||
try {
|
||
var rawWatch = localStorage.getItem('yaktube_watch_history');
|
||
if (rawWatch) {
|
||
var watchList = JSON.parse(rawWatch);
|
||
if (Array.isArray(watchList)) {
|
||
watchList.slice(0, 18).forEach(function (w) {
|
||
if (!w) return;
|
||
if (w.uuid) addToken(w.uuid);
|
||
if (w.ytId) addToken(w.ytId);
|
||
if (w.normTitle) addToken(w.normTitle);
|
||
else if (w.title && !isInvalidWatchPageTitle(w.title)) {
|
||
addToken(normalizeWatchTitleForMatch(w.title));
|
||
}
|
||
});
|
||
}
|
||
}
|
||
} catch (e) {}
|
||
|
||
return exclusions.slice(0, 45);
|
||
}
|
||
|
||
function isItemRecentlyWatched(item, currentUuid, currentTitle) {
|
||
if (!item) return true;
|
||
var itemUuid = (item.localVideo && item.localVideo.uuid) || '';
|
||
var itemId = item.id || '';
|
||
var itemNormTitle = normalizeWatchTitleForMatch(item.title || '');
|
||
var curNormTitle = normalizeWatchTitleForMatch(currentTitle || '');
|
||
|
||
if (currentUuid && itemUuid && itemUuid.toLowerCase() === currentUuid.toLowerCase()) return true;
|
||
if (curNormTitle && itemNormTitle && itemNormTitle === curNormTitle) return true;
|
||
|
||
try {
|
||
var rawWatch = localStorage.getItem('yaktube_watch_history');
|
||
if (rawWatch) {
|
||
var watchList = JSON.parse(rawWatch);
|
||
if (Array.isArray(watchList)) {
|
||
for (var i = 0; i < Math.min(watchList.length, 16); i++) {
|
||
var w = watchList[i];
|
||
if (!w) continue;
|
||
if (w.uuid && itemUuid && w.uuid.toLowerCase() === itemUuid.toLowerCase()) return true;
|
||
if (w.ytId && itemId && w.ytId === itemId) return true;
|
||
var wNorm = w.normTitle || normalizeWatchTitleForMatch(w.title || '');
|
||
if (wNorm && itemNormTitle && wNorm.length >= 4 && wNorm === itemNormTitle) return true;
|
||
}
|
||
}
|
||
}
|
||
} catch (e) {}
|
||
return false;
|
||
}
|
||
|
||
function getUserInterestHistory(excludeTopic) {
|
||
var interests = [];
|
||
var seen = {};
|
||
var normExclude = (excludeTopic || '').toLowerCase().trim();
|
||
if (normExclude) seen[normExclude] = true;
|
||
|
||
var defaultPlaceholders = {
|
||
tarkan: true,
|
||
'barış manço': true,
|
||
'baris manco': true,
|
||
'yapay zeka': true,
|
||
'canlı haber': true,
|
||
'canli haber': true,
|
||
bildirimler: true,
|
||
notifications: true
|
||
};
|
||
|
||
// 1. Recent watched video topics AND watched YouTube channels/artists
|
||
try {
|
||
var rawWatch = localStorage.getItem('yaktube_watch_history');
|
||
if (rawWatch) {
|
||
var watchList = JSON.parse(rawWatch);
|
||
if (Array.isArray(watchList)) {
|
||
watchList.forEach(function (w) {
|
||
if (!w || isInvalidWatchPageTitle(w.title)) return;
|
||
if (w.channel && !isGenericLocalChannelName(w.channel)) {
|
||
var ch = String(w.channel).trim();
|
||
var chLow = ch.toLowerCase();
|
||
if (ch.length >= 3 && !seen[chLow] && !defaultPlaceholders[chLow]) {
|
||
seen[chLow] = true;
|
||
interests.push(ch);
|
||
}
|
||
}
|
||
var t = w.topic || w.title ? String(w.topic || w.title).trim() : '';
|
||
var low = t.toLowerCase();
|
||
if (t.length >= 3 && !seen[low] && !defaultPlaceholders[low] && !isInvalidWatchPageTitle(t)) {
|
||
seen[low] = true;
|
||
interests.push(t);
|
||
}
|
||
});
|
||
}
|
||
}
|
||
} catch (e) {}
|
||
|
||
// 2. Recent user search queries
|
||
try {
|
||
var searches = getRecentSearches();
|
||
if (Array.isArray(searches)) {
|
||
var hasRealSearches = searches.some(function (s) {
|
||
return s && !defaultPlaceholders[String(s).toLowerCase().trim()];
|
||
});
|
||
searches.forEach(function (s) {
|
||
var term = String(s || '').trim();
|
||
var low = term.toLowerCase();
|
||
if (hasRealSearches && defaultPlaceholders[low]) return;
|
||
if (term.length >= 3 && !seen[low] && !isInvalidWatchPageTitle(term)) {
|
||
seen[low] = true;
|
||
interests.push(term);
|
||
}
|
||
});
|
||
}
|
||
} catch (e) {}
|
||
|
||
return interests.slice(0, 10);
|
||
}
|
||
|
||
var showNativeFediverseDrawer = false;
|
||
|
||
function isPlaylistWatch() {
|
||
if (typeof window === 'undefined' || !window.location) return false;
|
||
var p = window.location.pathname || '';
|
||
var s = window.location.search || '';
|
||
return p.includes('/w/p/') || s.includes('playlistPosition=') || s.includes('videoPlaylist=');
|
||
}
|
||
window.__yaktube_is_playlist_watch = isPlaylistWatch;
|
||
|
||
function isYakTubeAutoplayEnabled() {
|
||
try {
|
||
return localStorage.getItem('yaktube_smart_autoplay') !== 'false';
|
||
} catch (e) {
|
||
return true;
|
||
}
|
||
}
|
||
|
||
function setYakTubeAutoplayEnabled(enabled) {
|
||
var val = Boolean(enabled);
|
||
try {
|
||
localStorage.setItem('yaktube_smart_autoplay', val ? 'true' : 'false');
|
||
} catch (e) {}
|
||
syncPlayerNextButtonAndAutoplayUI();
|
||
var relContainer = document.getElementById('yaktube-hybrid-related-container');
|
||
if (relContainer && cachedRelatedResults && cachedRelatedResults.length > 0) {
|
||
renderRelatedCards(relContainer, cachedRelatedResults, cachedRelatedQuery);
|
||
}
|
||
announce(
|
||
val
|
||
? 'Akıllı otomatik oynatma açıldı. Video bittiğinde ilk öneri otomatik oynatılacak.'
|
||
: 'Akıllı otomatik oynatma kapatıldı.'
|
||
);
|
||
showQuickToast(val ? '🔁 Otomatik Oynatma: Açık' : '🔁 Otomatik Oynatma: Kapalı');
|
||
}
|
||
|
||
function toggleYakTubeAutoplay() {
|
||
setYakTubeAutoplayEnabled(!isYakTubeAutoplayEnabled());
|
||
}
|
||
window.__yaktube_toggle_smart_autoplay__ = toggleYakTubeAutoplay;
|
||
|
||
function getFirstSmartRecommendation() {
|
||
if (!cachedRelatedResults || cachedRelatedResults.length === 0) return null;
|
||
var currentPath = (window.location && window.location.pathname) || '';
|
||
var uuidMatch =
|
||
currentPath.match(/\/videos\/watch\/([a-zA-Z0-9_-]+)/) || currentPath.match(/\/w\/([a-zA-Z0-9_-]+)/);
|
||
var currentUuid = uuidMatch ? uuidMatch[1] : '';
|
||
var titleEl =
|
||
document.querySelector('my-video-watch h1.video-name') ||
|
||
document.querySelector('.video-info h1.video-name') ||
|
||
document.querySelector('h1.video-name');
|
||
var curTitle = titleEl ? (titleEl.textContent || '').trim() : '';
|
||
|
||
for (var i = 0; i < cachedRelatedResults.length; i++) {
|
||
var candidate = cachedRelatedResults[i];
|
||
if (candidate && !isItemRecentlyWatched(candidate, currentUuid, curTitle)) {
|
||
return candidate;
|
||
}
|
||
}
|
||
return cachedRelatedResults[0] || null;
|
||
}
|
||
window.__yaktube_get_first_smart_rec = getFirstSmartRecommendation;
|
||
|
||
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.');
|
||
showQuickToast('⏳ Öneriler yükleniyor...');
|
||
return false;
|
||
}
|
||
|
||
if (nextItem.title && nextItem.channel) {
|
||
saveVideoChannelMeta(
|
||
nextItem.title,
|
||
nextItem.channel,
|
||
nextItem.id || '',
|
||
(nextItem.localVideo && nextItem.localVideo.uuid) || ''
|
||
);
|
||
}
|
||
|
||
// Immediately record the target video into watch history so it cannot loop back
|
||
recordWatchedVideo(
|
||
(nextItem.localVideo && nextItem.localVideo.uuid) || '',
|
||
nextItem.title || '',
|
||
nextItem.channel || '',
|
||
nextItem.id || ''
|
||
);
|
||
|
||
if (nextItem.isDownloaded && nextItem.localVideo && nextItem.localVideo.url) {
|
||
announce('Sıradaki ilk öneri oynatılıyor: ' + (nextItem.title || ''));
|
||
showQuickToast('⏭️ ' + (nextItem.title || 'Sıradaki Video'));
|
||
currentActiveVideoKey = null;
|
||
window.location.href = nextItem.localVideo.url;
|
||
return true;
|
||
}
|
||
|
||
if (nextItem.url) {
|
||
announce(
|
||
'Sıradaki ilk öneri ' + getInstanceName() + "'a aktarılıp hemen oynatılıyor: " + (nextItem.title || '')
|
||
);
|
||
showQuickToast('📥 İlk öneri hazırlanıp oynatılıyor...');
|
||
var existingCardBtn = null;
|
||
var relContainer = document.getElementById('yaktube-hybrid-related-container');
|
||
if (relContainer) {
|
||
existingCardBtn = relContainer.querySelector('.yaktube-related-import');
|
||
}
|
||
var targetBtn = existingCardBtn || document.createElement('button');
|
||
handleImport(nextItem.url, targetBtn, nextItem.title || 'Sıradaki Video');
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
window.__yaktube_play_next_smart__ = playFirstSmartRecommendation;
|
||
|
||
function setHiddenImportantIfChanged(el) {
|
||
if (!el) return;
|
||
if (el.style.getPropertyValue('display') !== 'none' || el.style.getPropertyPriority('display') !== 'important') {
|
||
el.style.setProperty('display', 'none', 'important');
|
||
}
|
||
if (el.getAttribute('aria-hidden') !== 'true') {
|
||
el.setAttribute('aria-hidden', 'true');
|
||
}
|
||
}
|
||
|
||
function disableNativePeerTubeAutoplaySwitch() {
|
||
try {
|
||
if (localStorage.getItem('auto-play-video') !== 'false') {
|
||
localStorage.setItem('auto-play-video', 'false');
|
||
}
|
||
if (sessionStorage.getItem('auto-play-video') !== 'false') {
|
||
sessionStorage.setItem('auto-play-video', 'false');
|
||
}
|
||
} catch (e) {}
|
||
|
||
// Uncheck any native PeerTube Fediverse autoplay checkbox so Angular's internal autoPlayNextVideo stays false
|
||
var nativeCheckboxes = document.querySelectorAll(
|
||
'my-recommended-videos my-input-switch input[type="checkbox"], .other-videos my-input-switch input[type="checkbox"], input#auto-play-video'
|
||
);
|
||
nativeCheckboxes.forEach(function (cb) {
|
||
if (cb && cb.checked) {
|
||
cb.checked = false;
|
||
try {
|
||
cb.dispatchEvent(new Event('change', { bubbles: true }));
|
||
} catch (e) {}
|
||
}
|
||
});
|
||
|
||
// Permanently hide PeerTube's duplicate Fediverse autoplay header/toggle even when Fediverse drawer is expanded
|
||
var nativeAutoplayHeaders = document.querySelectorAll(
|
||
'my-recommended-videos .other-videos-header, .other-videos .other-videos-header, my-recommended-videos my-input-switch, .other-videos my-input-switch, my-recommended-videos .autoplay-line, .other-videos .autoplay-line, #auto-play-video, label[for="auto-play-video"]'
|
||
);
|
||
nativeAutoplayHeaders.forEach(setHiddenImportantIfChanged);
|
||
}
|
||
|
||
function syncPlayerNextButtonAndAutoplayUI() {
|
||
var firstRec = getFirstSmartRecommendation();
|
||
var autoOn = isYakTubeAutoplayEnabled();
|
||
|
||
var barAutoBtn = document.getElementById('yaktube-bar-autoplay-btn');
|
||
if (barAutoBtn) {
|
||
var nextChecked = autoOn ? 'true' : 'false';
|
||
var nextAria = 'Akıllı Otomatik Oynatma: ' + (autoOn ? 'Açık' : 'Kapalı');
|
||
var nextTxt = autoOn ? '🔁 Oto-Oynat: Açık' : '🔁 Oto-Oynat: Kapalı';
|
||
if (barAutoBtn.getAttribute('aria-checked') !== nextChecked)
|
||
barAutoBtn.setAttribute('aria-checked', nextChecked);
|
||
if (barAutoBtn.getAttribute('aria-label') !== nextAria) barAutoBtn.setAttribute('aria-label', nextAria);
|
||
if (barAutoBtn.textContent !== nextTxt) barAutoBtn.textContent = nextTxt;
|
||
}
|
||
|
||
var barNextBtn = document.getElementById('yaktube-bar-next-btn');
|
||
if (barNextBtn) {
|
||
var barNextLabel =
|
||
firstRec && firstRec.title
|
||
? 'Sıradaki İlk Öneri: ' + firstRec.title + ' (Shift+N)'
|
||
: 'Sıradaki İlk Önerilen Videoyu Oynat (Shift+N)';
|
||
if (barNextBtn.getAttribute('aria-label') !== barNextLabel) barNextBtn.setAttribute('aria-label', barNextLabel);
|
||
if (barNextBtn.getAttribute('title') !== barNextLabel) barNextBtn.setAttribute('title', barNextLabel);
|
||
}
|
||
|
||
if (!isPlaylistWatch()) {
|
||
// Hide PeerTube's native Fediverse upnext overlay inside Video.js so YakTube Smart Autoplay handles it
|
||
var nativeUpNext = document.querySelectorAll('.vjs-upnext-content');
|
||
nativeUpNext.forEach(setHiddenImportantIfChanged);
|
||
|
||
var nextBtns = document.querySelectorAll('.vjs-next-video, .vjs-next-video-control, .vjs-next-control');
|
||
nextBtns.forEach(function (btn) {
|
||
if (firstRec) {
|
||
if (btn.classList.contains('vjs-disabled')) btn.classList.remove('vjs-disabled');
|
||
if (btn.classList.contains('vjs-hidden')) btn.classList.remove('vjs-hidden');
|
||
if (btn.hasAttribute('disabled')) btn.removeAttribute('disabled');
|
||
var lbl = 'Sonraki Video (İlk Öneri): ' + (firstRec.title || '') + ' (Shift+N)';
|
||
if (btn.getAttribute('aria-label') !== lbl) btn.setAttribute('aria-label', lbl);
|
||
if (btn.getAttribute('title') !== lbl) btn.setAttribute('title', lbl);
|
||
var ctrlTxt = btn.querySelector('.vjs-control-text');
|
||
if (ctrlTxt && ctrlTxt.textContent !== lbl) ctrlTxt.textContent = lbl;
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
// Intercept clicks & keydowns on Video.js native ".vjs-next-video" button so it plays #1 Smart Recommendation instead of Fediverse
|
||
document.addEventListener(
|
||
'click',
|
||
function (e) {
|
||
if (!e.target || typeof e.target.closest !== 'function') return;
|
||
var nextBtn = e.target.closest(
|
||
'.vjs-next-video, .vjs-next-video-control, .vjs-next-control, .vjs-upnext-autoplay-icon'
|
||
);
|
||
if (nextBtn && !isPlaylistWatch() && getFirstSmartRecommendation()) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
e.stopImmediatePropagation();
|
||
playFirstSmartRecommendation('vjs-next-button');
|
||
}
|
||
},
|
||
true
|
||
);
|
||
|
||
document.addEventListener(
|
||
'keydown',
|
||
function (e) {
|
||
if (e.key !== 'Enter' && e.key !== ' ') return;
|
||
if (!e.target || typeof e.target.closest !== 'function') return;
|
||
var nextBtn = e.target.closest(
|
||
'.vjs-next-video, .vjs-next-video-control, .vjs-next-control, .vjs-upnext-autoplay-icon'
|
||
);
|
||
if (nextBtn && !isPlaylistWatch() && getFirstSmartRecommendation()) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
e.stopImmediatePropagation();
|
||
playFirstSmartRecommendation('vjs-next-button-key');
|
||
}
|
||
},
|
||
true
|
||
);
|
||
|
||
function suppressUnrelatedNativeRecommendations() {
|
||
disableNativePeerTubeAutoplaySwitch();
|
||
syncPlayerNextButtonAndAutoplayUI();
|
||
|
||
var shouldShowNativeList =
|
||
cachedFederatedRecommendationsMode === 'show-all' ||
|
||
(cachedFederatedRecommendationsMode === 'smart-relevant' && showNativeFediverseDrawer);
|
||
|
||
var recContainers = document.querySelectorAll('my-recommended-videos, .other-videos, .video-watch-next');
|
||
recContainers.forEach(function (rec) {
|
||
Array.from(rec.children).forEach(function (child) {
|
||
if (child.id === 'yaktube-hybrid-related-container' || child.id === 'yaktube-upnext-overlay') {
|
||
return;
|
||
}
|
||
// Never show PeerTube's native duplicate autoplay header/switch even when Fediverse drawer is expanded
|
||
if (
|
||
child.classList &&
|
||
(child.classList.contains('other-videos-header') || child.classList.contains('autoplay-line'))
|
||
) {
|
||
setHiddenImportantIfChanged(child);
|
||
return;
|
||
}
|
||
if (child.tagName && child.tagName.toLowerCase() === 'my-input-switch') {
|
||
setHiddenImportantIfChanged(child);
|
||
return;
|
||
}
|
||
if (shouldShowNativeList) {
|
||
if (child.style.getPropertyValue('display')) child.style.removeProperty('display');
|
||
if (child.hasAttribute('aria-hidden')) child.removeAttribute('aria-hidden');
|
||
} else {
|
||
setHiddenImportantIfChanged(child);
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
function renderRelatedCards(container, results, query) {
|
||
var count = results ? results.length : 0;
|
||
if (count === 0) {
|
||
container.style.display = 'none';
|
||
return;
|
||
}
|
||
|
||
container.style.display = 'block';
|
||
suppressUnrelatedNativeRecommendations();
|
||
|
||
var limit = relatedShowAll ? count : Math.min(count, 12);
|
||
var displayed = results.slice(0, limit);
|
||
var firstSmartItem = getFirstSmartRecommendation() || displayed[0];
|
||
|
||
var cardsHtml = '';
|
||
displayed.forEach(function (item, idx) {
|
||
if (item && item.title && item.channel) {
|
||
saveVideoChannelMeta(
|
||
item.title,
|
||
item.channel,
|
||
item.id || '',
|
||
(item.localVideo && item.localVideo.uuid) || ''
|
||
);
|
||
}
|
||
var isLocal = !!item.isDownloaded;
|
||
var isFed = !!item.isFederated;
|
||
var isFirstRec = firstSmartItem ? item === firstSmartItem : idx === 0;
|
||
var badgeLabel =
|
||
item.reasonBadge ||
|
||
(isFed ? "🌐 Fediverse'de İzle" : isLocal ? '✅ ' + getInstanceName() + "'da İzle" : '🔥 Benzer İçerik');
|
||
var isHistoryMatch = badgeLabel.indexOf('Geçmişinize Göre') !== -1;
|
||
var isSameChannelMatch = badgeLabel.indexOf('Aynı Kanaldan') !== -1 || item.sourceType === 'channel';
|
||
|
||
var badgeStyle = isFed
|
||
? 'background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%); color: #fff;'
|
||
: isLocal
|
||
? 'background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: #fff;'
|
||
: isSameChannelMatch
|
||
? 'background: linear-gradient(135deg, #e11d48 0%, #be123c 100%); color: #fff;'
|
||
: isHistoryMatch
|
||
? 'background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%); color: #fff;'
|
||
: 'background: linear-gradient(135deg, #ff8f37 0%, #ff5e3a 100%); color: #fff;';
|
||
|
||
var firstBadgeHtml = isFirstRec
|
||
? '<span class="yaktube-badge" style="background: #ff8f37; color: #000; margin-bottom: 4px; margin-right: 4px; display: inline-block; font-size:10px; padding:2px 7px; font-weight:800;">⏭️ İLK ÖNERİ</span>'
|
||
: '';
|
||
|
||
var statusBadge =
|
||
firstBadgeHtml +
|
||
'<span class="yaktube-badge" style="' +
|
||
badgeStyle +
|
||
' margin-bottom: 4px; display: inline-block; font-size:10px; padding:2px 8px; font-weight:700;">' +
|
||
escapeHtml(badgeLabel) +
|
||
'</span>';
|
||
|
||
var safeTitleAttr = (item.title || '').replace(/"/g, '"');
|
||
var safeChannelAttr = (item.channel || '').replace(/"/g, '"');
|
||
var safeUuidAttr = ((item.localVideo && item.localVideo.uuid) || '').replace(/"/g, '"');
|
||
var actionButton =
|
||
isLocal && item.localVideo && item.localVideo.url
|
||
? '<a href="' +
|
||
escapeHtml(item.localVideo.url) +
|
||
'" class="yaktube-play-btn yaktube-related-play-link" data-uuid="' +
|
||
safeUuidAttr +
|
||
'" data-yt-id="' +
|
||
escapeHtml(item.id || '') +
|
||
'" data-title="' +
|
||
safeTitleAttr +
|
||
'" data-channel="' +
|
||
safeChannelAttr +
|
||
'" style="font-size:11px; padding:6px 10px;' +
|
||
(isFed ? ' background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%); color:#fff;' : '') +
|
||
'" aria-label="' +
|
||
safeTitleAttr +
|
||
' videosunu ' +
|
||
(isFed ? 'Fediverse ağından' : escapeHtml(getInstanceName()) + "'dan") +
|
||
' hemen izle">' +
|
||
(isFed ? "🌐 Fediverse'den İzle" : '▶️ Hemen İzle') +
|
||
'</a>'
|
||
: '<button class="yaktube-import-btn yaktube-related-import" data-yt-id="' +
|
||
escapeHtml(item.id || '') +
|
||
'" data-url="' +
|
||
escapeHtml(item.url || '') +
|
||
'" data-title="' +
|
||
safeTitleAttr +
|
||
'" data-channel="' +
|
||
safeChannelAttr +
|
||
'" style="font-size:11px; padding:6px 10px;" aria-label="' +
|
||
safeTitleAttr +
|
||
' videosunu ' +
|
||
escapeHtml(getInstanceName()) +
|
||
'\'a indir ve izle">📥 İndir ve İzle</button>';
|
||
|
||
var cardLabel =
|
||
(isFirstRec ? 'İlk Öneri: ' : '') +
|
||
item.title +
|
||
' (' +
|
||
badgeLabel +
|
||
'), ' +
|
||
item.channel +
|
||
' kanalı, Süre: ' +
|
||
(item.durationFormatted || '');
|
||
cardsHtml +=
|
||
'<div class="yaktube-card" data-yt-id="' +
|
||
escapeHtml(item.id || '') +
|
||
'" role="article" tabindex="0"' +
|
||
(isFirstRec ? ' style="border: 1.5px solid rgba(255,143,55,0.65);"' : '') +
|
||
' aria-label="' +
|
||
cardLabel.replace(/"/g, '"') +
|
||
'">' +
|
||
'<div class="yaktube-thumb-wrap">' +
|
||
'<img class="yaktube-thumb-img" src="' +
|
||
escapeHtml(item.thumbnail || '/client/assets/images/default-thumbnail.jpg') +
|
||
'" alt="' +
|
||
safeTitleAttr +
|
||
'" loading="lazy" onerror="this.src=\'/client/assets/images/default-thumbnail.jpg\'" />' +
|
||
'<span class="yaktube-duration-badge" aria-label="Süre">' +
|
||
escapeHtml(item.durationFormatted || '') +
|
||
'</span>' +
|
||
'</div>' +
|
||
'<div class="yaktube-info">' +
|
||
'<div>' +
|
||
statusBadge +
|
||
'<h4 class="yaktube-video-name" title="' +
|
||
safeTitleAttr +
|
||
'" style="margin:0; font-size:12px; font-weight:600; line-height:1.35;">' +
|
||
escapeHtml(item.title || '') +
|
||
'</h4>' +
|
||
'<div class="yaktube-channel-name" style="font-size:10px;">' +
|
||
escapeHtml(item.channel || '') +
|
||
'</div>' +
|
||
'</div>' +
|
||
'<div class="yaktube-card-actions">' +
|
||
actionButton +
|
||
'<button type="button" class="yaktube-queue-add-btn" style="font-size:11px; padding:6px 8px;" data-id="' +
|
||
escapeHtml(item.id || '') +
|
||
'" data-uuid="' +
|
||
safeUuidAttr +
|
||
'" data-url="' +
|
||
escapeHtml(item.url || '') +
|
||
'" data-local-url="' +
|
||
escapeHtml((item.localVideo && item.localVideo.url) || '') +
|
||
'" data-title="' +
|
||
safeTitleAttr +
|
||
'" data-channel="' +
|
||
safeChannelAttr +
|
||
'" data-dur="' +
|
||
escapeHtml(item.durationFormatted || '') +
|
||
'" data-thumb="' +
|
||
escapeHtml(item.thumbnail || '') +
|
||
'" aria-label="' +
|
||
safeTitleAttr +
|
||
' videosunu çalma sırasına ekle">➕ Sıra</button>' +
|
||
'</div>' +
|
||
'</div>' +
|
||
'</div>';
|
||
});
|
||
|
||
var loadMoreBtn = '';
|
||
if (count > 12) {
|
||
if (!relatedShowAll) {
|
||
loadMoreBtn =
|
||
'<button id="yaktube-related-toggle-more" class="yaktube-shortcuts-btn" style="width:100%; margin-top:12px; padding:10px; justify-content:center; font-weight:700; background:rgba(255,143,55,0.15); border-color:#ff8f37; color:#fff;" aria-label="Daha fazla önerilen video göster">' +
|
||
'➕ Daha Fazla Öneri Göster (' +
|
||
(count - 12) +
|
||
' video daha)' +
|
||
'</button>';
|
||
} else {
|
||
loadMoreBtn =
|
||
'<button id="yaktube-related-toggle-more" class="yaktube-shortcuts-btn" style="width:100%; margin-top:12px; padding:8px; justify-content:center; font-size:11px;" aria-label="Daha az öneri göster">' +
|
||
'🔼 Daha Az Göster' +
|
||
'</button>';
|
||
}
|
||
}
|
||
|
||
var fediverseDrawerBtn = '';
|
||
if (cachedFederatedRecommendationsMode === 'smart-relevant') {
|
||
fediverseDrawerBtn =
|
||
'<button id="yaktube-toggle-native-fediverse-btn" class="yaktube-shortcuts-btn" style="width:100%; margin-top:10px; padding:9px 12px; justify-content:center; font-size:12px; font-weight:600; background:rgba(14,165,233,0.1); border:1px solid rgba(14,165,233,0.35); color:#7dd3fc;" aria-expanded="' +
|
||
(showNativeFediverseDrawer ? 'true' : 'false') +
|
||
'" aria-label="Fediverse ağındaki diğer videoları göster veya gizle">' +
|
||
(showNativeFediverseDrawer
|
||
? '🔼 Fediverse Ağındaki Diğer Videoları Gizle'
|
||
: '🌐 Fediverse Ağındaki Diğer Videoları Göster (İsteğe Bağlı)') +
|
||
'</button>';
|
||
}
|
||
|
||
var headerCountText = count > 12 && !relatedShowAll ? displayed.length + ' / ' + count : count;
|
||
var prefetchStatusHtml = '';
|
||
if (smartPrefetchState.videoKey === currentActiveVideoKey) {
|
||
if (smartPrefetchState.status === 'preparing') {
|
||
prefetchStatusHtml =
|
||
'<span id="yaktube-smart-prefetch-status" style="font-size:11px; color:#38bdf8; background:rgba(56,189,248,0.12); border:1px solid rgba(56,189,248,0.3); padding:3px 9px; border-radius:20px; font-weight:600;">⚡ Sıradaki öneri arka planda hazırlanıyor...</span>';
|
||
} else if (smartPrefetchState.status === 'ready') {
|
||
prefetchStatusHtml =
|
||
'<span id="yaktube-smart-prefetch-status" style="font-size:11px; color:#10b981; background:rgba(16,185,129,0.14); border:1px solid rgba(16,185,129,0.35); padding:3px 9px; border-radius:20px; font-weight:700;">✅ Sıradaki öneri kesintisiz izlemeye hazır!</span>';
|
||
}
|
||
}
|
||
|
||
var autoPlayEnabled = isYakTubeAutoplayEnabled();
|
||
var autoPlayBtnStyle = autoPlayEnabled
|
||
? 'background:rgba(16,185,129,0.18); border-color:#10b981; color:#6ee7b7; font-weight:700;'
|
||
: 'background:rgba(148,163,184,0.12); border-color:rgba(148,163,184,0.35); color:#cbd5e1;';
|
||
|
||
container.innerHTML =
|
||
'<div class="yaktube-header" style="flex-wrap:wrap; gap:8px;">' +
|
||
'<div class="yaktube-header-left" style="flex-wrap:wrap; gap:8px;">' +
|
||
'<span class="yaktube-badge">🔥 ' +
|
||
escapeHtml(getInstanceName()) +
|
||
' Akıllı Önerilenler</span>' +
|
||
'<h3 class="yaktube-title-h3" style="margin:0; font-size:1.05rem;">Size ve "' +
|
||
escapeHtml(query) +
|
||
'" İçeriğine Özel Öneriler (' +
|
||
headerCountText +
|
||
')</h3>' +
|
||
'<span id="yaktube-smart-prefetch-status-slot">' +
|
||
prefetchStatusHtml +
|
||
'</span>' +
|
||
'</div>' +
|
||
'<div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap;">' +
|
||
'<button id="yaktube-related-play-first-btn" class="yaktube-shortcuts-btn" style="background:rgba(255,143,55,0.16); border-color:#ff8f37; color:#fff; font-weight:700;" aria-label="Sıradaki ilk önerilen videoyu oynat (Shift+N)" title="Sıradaki ilk önerilen videoyu oynat (Shift+N)">' +
|
||
'⏭️ İlk Öneriyi Oynat' +
|
||
'</button>' +
|
||
'<button id="yaktube-related-autoplay-btn" class="yaktube-shortcuts-btn" role="switch" aria-checked="' +
|
||
(autoPlayEnabled ? 'true' : 'false') +
|
||
'" style="' +
|
||
autoPlayBtnStyle +
|
||
'" aria-label="Akıllı Otomatik Oynatma: ' +
|
||
(autoPlayEnabled ? 'Açık' : 'Kapalı') +
|
||
'" title="Video bittiğinde ilk öneriyi otomatik oynat">' +
|
||
(autoPlayEnabled ? '🔁 Otomatik Oynat: Açık' : '🔁 Otomatik Oynat: Kapalı') +
|
||
'</button>' +
|
||
'<button id="yaktube-related-refresh-btn" class="yaktube-shortcuts-btn" aria-label="Önerileri Yenile">' +
|
||
'🔄 Yenile' +
|
||
'</button>' +
|
||
'</div>' +
|
||
'</div>' +
|
||
'<div class="yaktube-grid" style="grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap:12px;">' +
|
||
cardsHtml +
|
||
'</div>' +
|
||
loadMoreBtn +
|
||
fediverseDrawerBtn;
|
||
|
||
var playFirstBtn = document.getElementById('yaktube-related-play-first-btn');
|
||
if (playFirstBtn) {
|
||
playFirstBtn.addEventListener('click', function () {
|
||
playFirstSmartRecommendation('related-header-btn');
|
||
});
|
||
}
|
||
|
||
var autoPlayHeaderBtn = document.getElementById('yaktube-related-autoplay-btn');
|
||
if (autoPlayHeaderBtn) {
|
||
autoPlayHeaderBtn.addEventListener('click', function () {
|
||
toggleYakTubeAutoplay();
|
||
});
|
||
}
|
||
|
||
var toggleBtn = document.getElementById('yaktube-related-toggle-more');
|
||
if (toggleBtn) {
|
||
toggleBtn.addEventListener('click', function () {
|
||
relatedShowAll = !relatedShowAll;
|
||
renderRelatedCards(container, cachedRelatedResults, cachedRelatedQuery);
|
||
announce(
|
||
relatedShowAll ? 'Tüm ' + cachedRelatedResults.length + ' önerilen video açıldı.' : 'Öneriler daraltıldı.'
|
||
);
|
||
});
|
||
}
|
||
|
||
var fedDrawerBtn = document.getElementById('yaktube-toggle-native-fediverse-btn');
|
||
if (fedDrawerBtn) {
|
||
fedDrawerBtn.addEventListener('click', function () {
|
||
showNativeFediverseDrawer = !showNativeFediverseDrawer;
|
||
suppressUnrelatedNativeRecommendations();
|
||
renderRelatedCards(container, cachedRelatedResults, cachedRelatedQuery);
|
||
announce(
|
||
showNativeFediverseDrawer
|
||
? 'Fediverse ağındaki diğer videolar gösteriliyor.'
|
||
: 'Fediverse ağındaki diğer videolar gizlendi.'
|
||
);
|
||
});
|
||
}
|
||
|
||
var refreshBtn = document.getElementById('yaktube-related-refresh-btn');
|
||
if (refreshBtn) {
|
||
refreshBtn.addEventListener('click', function () {
|
||
currentActiveVideoKey = null;
|
||
checkAndInjectRelatedVideos(true);
|
||
});
|
||
}
|
||
|
||
container.querySelectorAll('.yaktube-related-import').forEach(function (btn) {
|
||
btn.addEventListener('click', function (e) {
|
||
var videoUrl = e.currentTarget.getAttribute('data-url');
|
||
var videoTitle = e.currentTarget.getAttribute('data-title');
|
||
var videoChannel = e.currentTarget.getAttribute('data-channel');
|
||
var videoYtId = e.currentTarget.getAttribute('data-yt-id');
|
||
if (videoTitle && videoChannel) {
|
||
saveVideoChannelMeta(videoTitle, videoChannel, videoYtId || '', '');
|
||
}
|
||
recordWatchedVideo('', videoTitle || '', videoChannel || '', videoYtId || '');
|
||
handleImport(videoUrl, e.currentTarget, videoTitle);
|
||
});
|
||
});
|
||
|
||
container.querySelectorAll('.yaktube-related-play-link').forEach(function (link) {
|
||
link.addEventListener('click', function (e) {
|
||
var el = e.currentTarget;
|
||
var targetUuid = el.getAttribute('data-uuid') || '';
|
||
var targetYtId = el.getAttribute('data-yt-id') || '';
|
||
var targetTitle = el.getAttribute('data-title') || '';
|
||
var targetChannel = el.getAttribute('data-channel') || '';
|
||
if (targetTitle && targetChannel) {
|
||
saveVideoChannelMeta(targetTitle, targetChannel, targetYtId, targetUuid);
|
||
}
|
||
recordWatchedVideo(targetUuid, targetTitle, targetChannel, targetYtId);
|
||
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) {
|
||
var slot = document.getElementById('yaktube-smart-prefetch-status-slot');
|
||
if (!slot) return;
|
||
if (status === 'preparing') {
|
||
slot.innerHTML =
|
||
'<span id="yaktube-smart-prefetch-status" style="font-size:11px; color:#38bdf8; background:rgba(56,189,248,0.12); border:1px solid rgba(56,189,248,0.3); padding:3px 9px; border-radius:20px; font-weight:600;">⚡ Sıradaki öneri arka planda hazırlanıyor...</span>';
|
||
} else if (status === 'ready') {
|
||
slot.innerHTML =
|
||
'<span id="yaktube-smart-prefetch-status" style="font-size:11px; color:#10b981; background:rgba(16,185,129,0.14); border:1px solid rgba(16,185,129,0.35); padding:3px 9px; border-radius:20px; font-weight:700;">✅ Sıradaki öneri kesintisiz izlemeye hazır!</span>';
|
||
}
|
||
}
|
||
|
||
function upgradePrefetchedCardInPlace(candidate, watchUrl, videoUuid) {
|
||
if (!candidate || !candidate.id || !watchUrl) return;
|
||
var card = document.querySelector(
|
||
'#yaktube-hybrid-related-container .yaktube-card[data-yt-id="' + candidate.id + '"]'
|
||
);
|
||
if (!card) return;
|
||
var btn = card.querySelector('.yaktube-related-import');
|
||
if (btn && btn.parentNode) {
|
||
var link = document.createElement('a');
|
||
link.href = watchUrl;
|
||
link.className = 'yaktube-play-btn yaktube-related-play-link';
|
||
link.setAttribute('data-uuid', videoUuid || '');
|
||
link.setAttribute('data-yt-id', candidate.id || '');
|
||
link.setAttribute('data-title', candidate.title || '');
|
||
link.setAttribute('data-channel', candidate.channel || '');
|
||
link.style.cssText = 'font-size:11px; padding:6px 10px;';
|
||
link.textContent = '▶️ Hemen İzle';
|
||
link.addEventListener('click', function () {
|
||
currentActiveVideoKey = null;
|
||
});
|
||
btn.parentNode.replaceChild(link, btn);
|
||
}
|
||
}
|
||
|
||
function triggerSilentBackgroundPrefetch(candidate, videoKey) {
|
||
if (!candidate || !candidate.url || !videoKey) return;
|
||
if (smartPrefetchState.videoKey === videoKey && smartPrefetchState.status !== 'idle') return;
|
||
|
||
// Avoid duplicate background imports in the same browser session
|
||
try {
|
||
var sessionKey = 'yaktube_prefetched_' + (candidate.id || candidate.url);
|
||
if (sessionStorage.getItem(sessionKey)) return;
|
||
sessionStorage.setItem(sessionKey, 'true');
|
||
} catch (e) {}
|
||
|
||
// Respect guest quota: do not trigger silent prefetch if guest has reached limit
|
||
var loggedIn = isUserLoggedIn();
|
||
var currentGuestCount = getGuestImportCount();
|
||
if (
|
||
!loggedIn &&
|
||
cachedGuestImportLimit !== null &&
|
||
cachedGuestImportLimit > 0 &&
|
||
currentGuestCount >= cachedGuestImportLimit
|
||
) {
|
||
return;
|
||
}
|
||
|
||
if (smartPrefetchState.pollTimer) {
|
||
clearInterval(smartPrefetchState.pollTimer);
|
||
smartPrefetchState.pollTimer = null;
|
||
}
|
||
|
||
smartPrefetchState.videoKey = videoKey;
|
||
smartPrefetchState.status = 'preparing';
|
||
smartPrefetchState.readyUrl = null;
|
||
smartPrefetchState.readyTitle = candidate.title;
|
||
|
||
updatePrefetchBadgeInPlace('preparing');
|
||
|
||
var headers = { 'Content-Type': 'application/json' };
|
||
try {
|
||
var token = localStorage.getItem('access_token');
|
||
if (token) headers['Authorization'] = 'Bearer ' + token;
|
||
} catch (e) {}
|
||
|
||
fetchPluginJson('/ondemand-import', {
|
||
method: 'POST',
|
||
headers: headers,
|
||
body: JSON.stringify({
|
||
targetUrl: candidate.url,
|
||
title: candidate.title,
|
||
isAuthenticated: loggedIn,
|
||
guestImportCount: currentGuestCount
|
||
})
|
||
})
|
||
.then(function (data) {
|
||
if (!data || !data.ok || !data.video || !data.video.id) {
|
||
smartPrefetchState.status = 'failed';
|
||
return;
|
||
}
|
||
var videoId = data.video.id;
|
||
var videoUuid = data.video.uuid;
|
||
|
||
if (data.alreadyImported && videoUuid) {
|
||
var immediateWatchUrl = '/videos/watch/' + videoUuid;
|
||
smartPrefetchState.status = 'ready';
|
||
smartPrefetchState.readyUrl = immediateWatchUrl;
|
||
smartHasLocalMatch = true;
|
||
cachedRelatedResults.forEach(function (it) {
|
||
if ((candidate.id && it.id === candidate.id) || (candidate.url && it.url === candidate.url)) {
|
||
it.isDownloaded = true;
|
||
it.reasonBadge = '⚡ Sıradaki Öneri Hazır';
|
||
it.localVideo = {
|
||
id: videoId,
|
||
uuid: videoUuid,
|
||
name: (data.video && data.video.name) || candidate.title,
|
||
url: immediateWatchUrl
|
||
};
|
||
}
|
||
});
|
||
updatePrefetchBadgeInPlace('ready');
|
||
upgradePrefetchedCardInPlace(candidate, immediateWatchUrl, videoUuid);
|
||
return;
|
||
}
|
||
|
||
var attempts = 0;
|
||
|
||
smartPrefetchState.pollTimer = setInterval(function () {
|
||
attempts++;
|
||
if (currentActiveVideoKey !== videoKey || attempts > 90) {
|
||
clearInterval(smartPrefetchState.pollTimer);
|
||
smartPrefetchState.pollTimer = null;
|
||
return;
|
||
}
|
||
fetchPluginJson('/status/' + videoId)
|
||
.then(function (sData) {
|
||
if (sData && sData.isPublished) {
|
||
clearInterval(smartPrefetchState.pollTimer);
|
||
smartPrefetchState.pollTimer = null;
|
||
var watchUrl = '/videos/watch/' + (sData.uuid || videoUuid);
|
||
smartPrefetchState.status = 'ready';
|
||
smartPrefetchState.readyUrl = watchUrl;
|
||
smartHasLocalMatch = true;
|
||
|
||
// Upgrade candidate inside cachedRelatedResults to ready-to-play local video
|
||
cachedRelatedResults.forEach(function (it) {
|
||
if ((candidate.id && it.id === candidate.id) || (candidate.url && it.url === candidate.url)) {
|
||
it.isDownloaded = true;
|
||
it.reasonBadge = '⚡ Sıradaki Öneri Hazır';
|
||
it.localVideo = {
|
||
id: videoId,
|
||
uuid: sData.uuid || videoUuid,
|
||
name: sData.name || candidate.title,
|
||
url: watchUrl
|
||
};
|
||
}
|
||
});
|
||
|
||
updatePrefetchBadgeInPlace('ready');
|
||
upgradePrefetchedCardInPlace(candidate, watchUrl, sData.uuid || videoUuid);
|
||
} else if (sData && sData.isFailed) {
|
||
clearInterval(smartPrefetchState.pollTimer);
|
||
smartPrefetchState.pollTimer = null;
|
||
smartPrefetchState.status = 'failed';
|
||
}
|
||
})
|
||
.catch(function () {});
|
||
}, 2500);
|
||
})
|
||
.catch(function () {
|
||
smartPrefetchState.status = 'failed';
|
||
});
|
||
}
|
||
|
||
function checkSmartPrefetchOnTimeUpdate(video) {
|
||
if (!video || !currentActiveVideoKey) return;
|
||
if (smartPrefetchState.videoKey === currentActiveVideoKey && smartPrefetchState.status !== 'idle') return;
|
||
if (cachedSmartPrefetchMode === 'disabled') return;
|
||
|
||
var firstRec = getFirstSmartRecommendation();
|
||
var firstNeedsPrefetch = Boolean(firstRec && !firstRec.isDownloaded && firstRec.url);
|
||
var targetCandidate = firstNeedsPrefetch ? firstRec : smartPrefetchCandidate;
|
||
if (!targetCandidate) return;
|
||
|
||
// If #1 recommendation is not downloaded yet and autoplay is enabled, always pre-fetch #1 so autoplay is instant!
|
||
if (
|
||
cachedSmartPrefetchMode === 'auto-when-no-local' &&
|
||
smartHasLocalMatch &&
|
||
!(firstNeedsPrefetch && isYakTubeAutoplayEnabled())
|
||
) {
|
||
return;
|
||
}
|
||
|
||
var cur = video.currentTime || 0;
|
||
var dur = video.duration || 0;
|
||
var threshold = dur > 0 && dur < 65 ? Math.max(8, dur * 0.35) : 20;
|
||
if (cur >= threshold) {
|
||
triggerSilentBackgroundPrefetch(targetCandidate, currentActiveVideoKey);
|
||
}
|
||
}
|
||
|
||
function clearUpNextOverlay() {
|
||
if (upNextCountdownTimer) {
|
||
clearInterval(upNextCountdownTimer);
|
||
upNextCountdownTimer = null;
|
||
}
|
||
var existing = document.getElementById('yaktube-upnext-overlay');
|
||
if (existing) existing.remove();
|
||
}
|
||
|
||
function showPostVideoUpNextOverlay() {
|
||
clearUpNextOverlay();
|
||
var queuedPreview = getNextQueueItem(false);
|
||
if (!queuedPreview && (!cachedRelatedResults || cachedRelatedResults.length === 0)) return;
|
||
|
||
// 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);
|
||
var autoPlayOn = isYakTubeAutoplayEnabled();
|
||
var banner = document.createElement('div');
|
||
banner.id = 'yaktube-upnext-overlay';
|
||
banner.setAttribute('role', 'region');
|
||
banner.setAttribute('aria-label', 'Sıradaki İlk Önerilen Video');
|
||
banner.style.cssText =
|
||
'margin: 14px 0 18px 0; padding: 16px 20px; border-radius: 14px; background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); border: 2px solid #ff8f37; box-shadow: 0 10px 30px rgba(0,0,0,0.55); display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap;';
|
||
|
||
var safeTitle = escapeHtml(nextItem.title || 'İlgili Video');
|
||
var safeChannel = escapeHtml(nextItem.channel || getInstanceName());
|
||
var safeBadge = escapeHtml(nextItem.reasonBadge || '🔥 Benzer İçerik');
|
||
var safeThumb = escapeHtml(nextItem.thumbnail || '/client/assets/images/default-thumbnail.jpg');
|
||
|
||
var secondsLeft = 6;
|
||
|
||
banner.innerHTML =
|
||
'<div style="display:flex; align-items:center; gap:14px; min-width:240px; flex:1;">' +
|
||
'<img src="' +
|
||
safeThumb +
|
||
'" alt="" style="width:96px; height:56px; object-fit:cover; border-radius:8px; flex-shrink:0; border:1px solid rgba(255,255,255,0.15);" onerror="this.src=\'/client/assets/images/default-thumbnail.jpg\'" />' +
|
||
'<div style="min-width:0;">' +
|
||
'<div style="display:flex; align-items:center; gap:8px; margin-bottom:4px; flex-wrap:wrap;">' +
|
||
'<span style="background:#ff8f37; color:#000; font-size:11px; font-weight:800; padding:2px 8px; border-radius:6px;">⏭️ SIRADAKİ İLK ÖNERİ</span>' +
|
||
'<span style="font-size:11px; color:#5eead4; font-weight:600;">' +
|
||
safeBadge +
|
||
'</span>' +
|
||
'</div>' +
|
||
'<div style="font-size:14px; font-weight:700; color:#f8fafc; line-height:1.35;">' +
|
||
safeTitle +
|
||
'</div>' +
|
||
'<div style="font-size:12px; color:#94a3b8; margin-top:2px;">' +
|
||
safeChannel +
|
||
(autoPlayOn
|
||
? ' • <span id="yaktube-upnext-countdown-txt" style="color:#ff8f37; font-weight:700;">' +
|
||
secondsLeft +
|
||
' saniye içinde ' +
|
||
(isReadyLocal ? 'başlıyor...' : 'otomatik aktarılıp başlıyor...') +
|
||
'</span>'
|
||
: ' • <span id="yaktube-upnext-countdown-txt" style="color:#94a3b8;">Otomatik oynatma kapalı</span>') +
|
||
'</div>' +
|
||
'</div>' +
|
||
'</div>' +
|
||
'<div style="display:flex; align-items:center; gap:10px; flex-wrap:wrap;">' +
|
||
(isReadyLocal
|
||
? '<a id="yaktube-upnext-play-btn" href="' +
|
||
escapeHtml(nextItem.localVideo.url) +
|
||
'" style="background:linear-gradient(135deg, #10b981 0%, #059669 100%); color:#fff; text-decoration:none; padding:10px 18px; border-radius:10px; font-weight:800; font-size:13px; display:inline-flex; align-items:center; gap:6px;">▶️ Hemen İzle</a>'
|
||
: '<button type="button" id="yaktube-upnext-import-btn" style="background:linear-gradient(135deg, #ff8f37 0%, #ea580c 100%); color:#000; border:none; padding:10px 18px; border-radius:10px; font-weight:800; font-size:13px; cursor:pointer; display:inline-flex; align-items:center; gap:6px;">📥 İndir ve Hemen İzle</button>') +
|
||
'<button type="button" id="yaktube-upnext-cancel-btn" style="background:#334155; color:#e2e8f0; border:1px solid rgba(255,255,255,0.15); padding:10px 14px; border-radius:10px; font-weight:600; font-size:12px; cursor:pointer;">' +
|
||
(autoPlayOn ? '✕ Otomatik Geçişi Durdur' : '✕ Kapat') +
|
||
'</button>' +
|
||
'</div>';
|
||
|
||
var actionBar = document.getElementById('yaktube-player-action-bar');
|
||
var relContainer = document.getElementById('yaktube-hybrid-related-container');
|
||
if (actionBar && actionBar.parentNode) {
|
||
actionBar.insertAdjacentElement('afterend', banner);
|
||
} else if (relContainer && relContainer.parentNode) {
|
||
relContainer.parentNode.insertBefore(banner, relContainer);
|
||
} else {
|
||
document.body.appendChild(banner);
|
||
}
|
||
|
||
var cancelBtn = document.getElementById('yaktube-upnext-cancel-btn');
|
||
if (cancelBtn) {
|
||
cancelBtn.addEventListener('click', function () {
|
||
if (upNextCountdownTimer) {
|
||
clearInterval(upNextCountdownTimer);
|
||
upNextCountdownTimer = null;
|
||
var cdTxt = document.getElementById('yaktube-upnext-countdown-txt');
|
||
if (cdTxt) cdTxt.textContent = 'Otomatik geçiş durduruldu';
|
||
cancelBtn.textContent = '✕ Kapat';
|
||
announce('Otomatik video geçişi durduruldu.');
|
||
} else {
|
||
clearUpNextOverlay();
|
||
}
|
||
});
|
||
}
|
||
|
||
var playNowBtn = document.getElementById('yaktube-upnext-play-btn');
|
||
if (playNowBtn) {
|
||
playNowBtn.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
playFirstSmartRecommendation('upnext-play-click');
|
||
});
|
||
}
|
||
|
||
var importBtn = document.getElementById('yaktube-upnext-import-btn');
|
||
if (importBtn) {
|
||
importBtn.addEventListener('click', function () {
|
||
clearUpNextOverlay();
|
||
playFirstSmartRecommendation('upnext-banner-click');
|
||
});
|
||
}
|
||
|
||
if (autoPlayOn) {
|
||
announce(
|
||
'Video sona erdi. Sıradaki ilk önerilen video 6 saniye içinde başlayacak: ' +
|
||
nextItem.title +
|
||
'. Durdurmak için Otomatik Geçişi Durdur düğmesine basabilirsiniz.'
|
||
);
|
||
upNextCountdownTimer = setInterval(function () {
|
||
secondsLeft--;
|
||
var cdTxt = document.getElementById('yaktube-upnext-countdown-txt');
|
||
if (cdTxt && secondsLeft > 0) {
|
||
cdTxt.textContent =
|
||
secondsLeft + ' saniye içinde ' + (isReadyLocal ? 'başlıyor...' : 'otomatik aktarılıp başlıyor...');
|
||
}
|
||
if (secondsLeft <= 0) {
|
||
clearInterval(upNextCountdownTimer);
|
||
upNextCountdownTimer = null;
|
||
playFirstSmartRecommendation('autoplay-ended');
|
||
}
|
||
}, 1000);
|
||
} else {
|
||
announce('Video sona erdi. Sıradaki ilk öneri: ' + nextItem.title);
|
||
}
|
||
}
|
||
|
||
function checkAndInjectRelatedVideos(forceReload) {
|
||
var isWatchPage =
|
||
window.location.pathname.includes('/videos/watch/') || window.location.pathname.startsWith('/w/');
|
||
if (!isWatchPage) {
|
||
var existing = document.getElementById('yaktube-hybrid-related-container');
|
||
if (existing) existing.remove();
|
||
clearUpNextOverlay();
|
||
currentActiveVideoKey = null;
|
||
return;
|
||
}
|
||
|
||
// Strictly query the watch page's video heading (never generic h1 or .title which matches "Bildirimler")
|
||
var titleElem =
|
||
document.querySelector('my-video-watch h1.video-name') ||
|
||
document.querySelector('.video-info h1.video-name') ||
|
||
document.querySelector('h1.video-name') ||
|
||
document.querySelector('my-video-watch .video-info h1') ||
|
||
document.querySelector('.video-watch-heading h1');
|
||
|
||
var rawTitle = titleElem ? (titleElem.textContent || titleElem.innerText || '').trim() : '';
|
||
if (isInvalidWatchPageTitle(rawTitle)) {
|
||
return;
|
||
}
|
||
|
||
var currentPath = window.location.pathname;
|
||
var uuidMatch =
|
||
currentPath.match(/\/videos\/watch\/([a-zA-Z0-9_-]+)/) || currentPath.match(/\/w\/([a-zA-Z0-9_-]+)/);
|
||
var currentUuid = uuidMatch ? uuidMatch[1] : '';
|
||
|
||
var channelElem = document.querySelector('.video-channel-name, .channel-name, .actor-name, a.actor-link');
|
||
var rawChannel = channelElem ? (channelElem.textContent || '').trim() : '';
|
||
|
||
// Discover original YouTube channel from saved metadata or watch page tags
|
||
var savedMeta = lookupVideoChannelMeta(rawTitle, currentUuid);
|
||
var ytChannelHint = savedMeta && savedMeta.channel ? savedMeta.channel : '';
|
||
if (!ytChannelHint) {
|
||
var tagLinks = document.querySelectorAll('.video-info-tags a, .video-tags a, a[href*="tagsOneOf="]');
|
||
for (var ti = 0; ti < tagLinks.length; ti++) {
|
||
var tagTxt = (tagLinks[ti].textContent || '').trim();
|
||
if (tagTxt.length >= 3 && !isGenericLocalChannelName(tagTxt)) {
|
||
ytChannelHint = tagTxt;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
var thisVideoKey = currentPath + '::' + rawTitle.toLowerCase();
|
||
|
||
if (
|
||
!forceReload &&
|
||
thisVideoKey === currentActiveVideoKey &&
|
||
document.getElementById('yaktube-hybrid-related-container')
|
||
) {
|
||
suppressUnrelatedNativeRecommendations();
|
||
return;
|
||
}
|
||
|
||
if (isFetchingRelated) return;
|
||
isFetchingRelated = true;
|
||
clearUpNextOverlay();
|
||
|
||
var cleanTopic = cleanVideoTopicString(rawTitle);
|
||
var words = cleanTopic.split(/\s+/).filter(function (w) {
|
||
return w.length >= 2;
|
||
});
|
||
var searchQuery = words.slice(0, 4).join(' ') || cleanTopic || rawTitle;
|
||
|
||
// Gather user interest history & watched exclusion list, then record current video in watch history
|
||
var userHistoryList = getUserInterestHistory(searchQuery);
|
||
var watchedExclusions = getWatchedExclusionList(currentUuid, rawTitle);
|
||
recordWatchedVideo(currentUuid, rawTitle, ytChannelHint || rawChannel, (savedMeta && savedMeta.ytId) || '');
|
||
|
||
var container = document.getElementById('yaktube-hybrid-related-container');
|
||
if (!container) {
|
||
container = document.createElement('div');
|
||
container.id = 'yaktube-hybrid-related-container';
|
||
container.className = 'yaktube-ondemand-section';
|
||
container.setAttribute('role', 'region');
|
||
container.setAttribute('aria-label', 'YakTube Akıllı Önerilen Videolar');
|
||
}
|
||
|
||
var recVideosMount = document.querySelector('my-recommended-videos, .other-videos');
|
||
var commentsMount = document.querySelector('#yaktube-watch-comments-panel, my-video-comments, .video-comments');
|
||
var videoBottomMount = document.querySelector('.video-bottom, .video-info');
|
||
var watchMount = document.querySelector('my-video-watch') || document.querySelector('main');
|
||
|
||
if (recVideosMount) {
|
||
if (container.parentElement !== recVideosMount) {
|
||
recVideosMount.prepend(container);
|
||
}
|
||
} else if (commentsMount) {
|
||
if (container.previousElementSibling !== commentsMount) {
|
||
commentsMount.insertAdjacentElement('afterend', container);
|
||
}
|
||
} else if (videoBottomMount) {
|
||
if (container.previousElementSibling !== videoBottomMount) {
|
||
videoBottomMount.insertAdjacentElement('afterend', container);
|
||
}
|
||
} else if (watchMount) {
|
||
if (container.parentElement !== watchMount) {
|
||
watchMount.appendChild(container);
|
||
}
|
||
} else {
|
||
isFetchingRelated = false;
|
||
return;
|
||
}
|
||
|
||
suppressUnrelatedNativeRecommendations();
|
||
|
||
container.innerHTML =
|
||
'<div class="yaktube-header">' +
|
||
'<div class="yaktube-header-left">' +
|
||
'<span class="yaktube-badge">🔥 ' +
|
||
escapeHtml(getInstanceName()) +
|
||
' Akıllı Önerilenler</span>' +
|
||
'<h3 class="yaktube-title-h3" style="margin:0; font-size:1.05rem;">"' +
|
||
escapeHtml(searchQuery) +
|
||
'" ve İzleme Geçmişinize Göre Öneriler Hazırlanıyor...</h3>' +
|
||
'</div>' +
|
||
'</div>' +
|
||
'<div style="padding: 18px; text-align: center; color: #ff8f37;">' +
|
||
'<div class="yaktube-spinner" style="width: 30px; height: 30px; border-width: 3px;" aria-hidden="true"></div>' +
|
||
'<div style="margin-top: 10px; font-size: 13px;">Kanalın diğer videoları, bu içerikle alakalı videolar ve izleme geçmişiniz analiz ediliyor...</div>' +
|
||
'</div>';
|
||
|
||
announce(searchQuery + ' için ilgili video önerileri yükleniyor.');
|
||
|
||
var smartUrl =
|
||
'/smart-recommendations?uuid=' +
|
||
encodeURIComponent(currentUuid) +
|
||
'&title=' +
|
||
encodeURIComponent(rawTitle) +
|
||
'&channel=' +
|
||
encodeURIComponent(rawChannel) +
|
||
'&ytChannel=' +
|
||
encodeURIComponent(ytChannelHint) +
|
||
'&history=' +
|
||
encodeURIComponent(userHistoryList.join('|')) +
|
||
'&watched=' +
|
||
encodeURIComponent(watchedExclusions.join('|'));
|
||
|
||
fetchPluginJson(smartUrl)
|
||
.catch(function () {
|
||
return fetchPluginJson('/youtube-search?q=' + encodeURIComponent(searchQuery));
|
||
})
|
||
.then(function (data) {
|
||
if (data && typeof data.guestImportLimit === 'number') {
|
||
cachedGuestImportLimit = data.guestImportLimit;
|
||
}
|
||
if (data && typeof data.smartPrefetchMode === 'string') {
|
||
cachedSmartPrefetchMode = data.smartPrefetchMode;
|
||
}
|
||
if (data && typeof data.federatedRecommendationsMode === 'string') {
|
||
cachedFederatedRecommendationsMode = data.federatedRecommendationsMode;
|
||
}
|
||
smartHasLocalMatch = Boolean(data && data.hasLocalMatch);
|
||
smartPrefetchCandidate = (data && data.topPrefetchCandidate) || null;
|
||
if (smartPrefetchState.videoKey !== thisVideoKey) {
|
||
smartPrefetchState.videoKey = thisVideoKey;
|
||
smartPrefetchState.status = 'idle';
|
||
}
|
||
|
||
var rawResults = (data && data.results) || [];
|
||
var normalizedCurrentTitle = normalizeWatchTitleForMatch(rawTitle);
|
||
|
||
var uniqueResults = [];
|
||
var watchedBackups = [];
|
||
var seenIds = {};
|
||
var seenNormTitles = {};
|
||
|
||
rawResults.forEach(function (item) {
|
||
var itemKey = (item && (item.id || (item.localVideo && item.localVideo.uuid))) || '';
|
||
var itemNormTitle = item && item.title ? normalizeWatchTitleForMatch(item.title) : '';
|
||
if (
|
||
item &&
|
||
itemKey &&
|
||
!seenIds[itemKey] &&
|
||
itemNormTitle &&
|
||
!seenNormTitles[itemNormTitle] &&
|
||
itemNormTitle !== normalizedCurrentTitle
|
||
) {
|
||
seenIds[itemKey] = true;
|
||
seenNormTitles[itemNormTitle] = true;
|
||
if (isItemRecentlyWatched(item, currentUuid, rawTitle)) {
|
||
watchedBackups.push(item);
|
||
} else {
|
||
uniqueResults.push(item);
|
||
}
|
||
}
|
||
});
|
||
|
||
if (uniqueResults.length < 4 && watchedBackups.length > 0) {
|
||
watchedBackups.forEach(function (wb) {
|
||
if (uniqueResults.length < 8) uniqueResults.push(wb);
|
||
});
|
||
}
|
||
|
||
cachedRelatedResults = uniqueResults;
|
||
cachedRelatedQuery = (data && data.query) || searchQuery;
|
||
currentActiveVideoKey = thisVideoKey;
|
||
relatedShowAll = false;
|
||
showNativeFediverseDrawer = false;
|
||
|
||
renderRelatedCards(container, uniqueResults, cachedRelatedQuery);
|
||
|
||
var initialCount = Math.min(uniqueResults.length, 12);
|
||
if (uniqueResults.length === 0) {
|
||
announce(cachedRelatedQuery + ' için ilgili öneri bulunamadı.');
|
||
} else {
|
||
announce(
|
||
cachedRelatedQuery +
|
||
' için ' +
|
||
initialCount +
|
||
' alakalı öneri listelendi' +
|
||
(uniqueResults.length > 12 ? ', toplam ' + uniqueResults.length + ' video bulundu' : '') +
|
||
'.'
|
||
);
|
||
}
|
||
})
|
||
.catch(function (err) {
|
||
console.error('[YakTube] Related fetch error:', err);
|
||
container.style.display = 'none';
|
||
})
|
||
.finally(function () {
|
||
isFetchingRelated = false;
|
||
});
|
||
}
|
||
|
||
var lastWatchUuid = null;
|
||
|
||
function checkAndInjectWatchPageComments() {
|
||
var pathname = window.location.pathname;
|
||
var match = pathname.match(/\/videos\/watch\/([a-zA-Z0-9_-]+)/) || pathname.match(/\/w\/([a-zA-Z0-9_-]+)/);
|
||
if (!match) {
|
||
lastWatchUuid = null;
|
||
var existingWatchComments = document.getElementById('yaktube-watch-comments-panel');
|
||
if (existingWatchComments) existingWatchComments.remove();
|
||
return;
|
||
}
|
||
|
||
var uuid = match[1];
|
||
var existingPanel = document.getElementById('yaktube-watch-comments-panel');
|
||
if (uuid === lastWatchUuid) {
|
||
if (existingPanel) {
|
||
var nativeComments = document.querySelector('my-video-comments, .video-comments, .comments-block, #comments');
|
||
if (nativeComments && existingPanel.previousElementSibling !== nativeComments) {
|
||
nativeComments.insertAdjacentElement('afterend', existingPanel);
|
||
}
|
||
}
|
||
return;
|
||
}
|
||
lastWatchUuid = uuid;
|
||
|
||
var mountTarget =
|
||
document.querySelector('my-video-comments, .video-comments, my-video-watch, .video-bottom') || document.body;
|
||
if (!mountTarget) return;
|
||
|
||
fetchPluginJson('/video-origin/' + encodeURIComponent(uuid))
|
||
.then(function (originData) {
|
||
if (!originData || !originData.ok || !originData.hasYouTubeOrigin || !originData.youtubeId) {
|
||
var old = document.getElementById('yaktube-watch-comments-panel');
|
||
if (old) old.remove();
|
||
return;
|
||
}
|
||
|
||
var youtubeId = originData.youtubeId;
|
||
var existing = document.getElementById('yaktube-watch-comments-panel');
|
||
if (existing) existing.remove();
|
||
|
||
var panel = document.createElement('div');
|
||
panel.id = 'yaktube-watch-comments-panel';
|
||
panel.className = 'yaktube-comments-panel';
|
||
panel.setAttribute('role', 'region');
|
||
panel.setAttribute('aria-label', 'YouTube Orijinal Yorumlar\u0131');
|
||
panel.style.cssText =
|
||
'margin-top: 24px; margin-bottom: 24px; background: #0f172a; border-radius: 12px; padding: 20px; border: 1px solid rgba(255,255,255,0.08); box-shadow: 0 8px 24px rgba(0,0,0,0.4);';
|
||
|
||
panel.innerHTML =
|
||
'<div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px;">' +
|
||
'<div>' +
|
||
'<h2 style="margin: 0; font-size: 16px; font-weight: 700; color: #fff; display: flex; align-items: center; gap: 8px;">' +
|
||
"\ud83d\udcac YouTube'daki Orijinal Yorumlar" +
|
||
'</h2>' +
|
||
'<div style="color: #94a3b8; font-size: 12px; margin-top: 4px;">Bu video YouTube\'dan aktar\u0131lm\u0131\u015ft\u0131r. Orijinal topluluk yorumlar\u0131n\u0131 a\u015fa\u011f\u0131dan anl\u0131k olarak y\u00fckleyebilirsiniz.</div>' +
|
||
'</div>' +
|
||
'<button id="yaktube-watch-toggle-comments-btn" style="background: #ff8f37; color: #000; border: none; padding: 8px 18px; border-radius: 8px; font-weight: 700; cursor: pointer; font-size: 13px; display: inline-flex; align-items: center; gap: 6px; box-shadow: 0 4px 12px rgba(255,143,55,0.3);" aria-label="YouTube yorumlar\u0131n\u0131 y\u00fckle ve g\u00f6ster">' +
|
||
'\ud83d\udcac Yorumlar\u0131 G\u00f6ster (20 Yorum)' +
|
||
'</button>' +
|
||
'</div>' +
|
||
'<div id="yaktube-watch-comments-list" style="display: none; margin-top: 16px; flex-direction: column; gap: 12px;"></div>' +
|
||
'<div id="yaktube-watch-more-comments-wrap" style="text-align: center; margin-top: 18px; display: none;">' +
|
||
'<button id="yaktube-watch-more-comments-btn" style="background: #1e293b; color: #ff8f37; border: 1px solid #ff8f37; padding: 10px 24px; border-radius: 8px; font-weight: 700; cursor: pointer; font-size: 13px; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s ease;" aria-label="Daha fazla YouTube yorumu y\u00fckle">' +
|
||
'\u2795 Daha Fazla Yorum G\u00f6ster (+20 Yorum)' +
|
||
'</button>' +
|
||
'</div>';
|
||
|
||
var nativeComments = document.querySelector('my-video-comments, .video-comments, .comments-block, #comments');
|
||
if (nativeComments && nativeComments.parentElement) {
|
||
nativeComments.insertAdjacentElement('afterend', panel);
|
||
} else {
|
||
var watchCol = document.querySelector('.video-info, .video-bottom, my-video-watch, .main-col');
|
||
if (watchCol) {
|
||
watchCol.appendChild(panel);
|
||
} else {
|
||
mountTarget.appendChild(panel);
|
||
}
|
||
}
|
||
|
||
var watchCommentToken = null;
|
||
var listContainer = document.getElementById('yaktube-watch-comments-list');
|
||
var toggleBtn = document.getElementById('yaktube-watch-toggle-comments-btn');
|
||
var moreWrap = document.getElementById('yaktube-watch-more-comments-wrap');
|
||
var moreBtn = document.getElementById('yaktube-watch-more-comments-btn');
|
||
|
||
function fetchWatchComments(token) {
|
||
if (!token) {
|
||
toggleBtn.disabled = true;
|
||
toggleBtn.textContent = '⏳ Yorumlar Y\u00fckleniyor...';
|
||
} else {
|
||
moreBtn.disabled = true;
|
||
moreBtn.textContent = '⏳ Y\u00fckleniyor...';
|
||
}
|
||
|
||
var fPath =
|
||
'/youtube-comments?id=' +
|
||
encodeURIComponent(youtubeId) +
|
||
(token ? '&token=' + encodeURIComponent(token) : '');
|
||
fetchPluginJson(fPath)
|
||
.then(function (res) {
|
||
if (!token) {
|
||
listContainer.innerHTML = '';
|
||
listContainer.style.display = 'flex';
|
||
toggleBtn.textContent = '🔄 Yorumlar\u0131 Yenile';
|
||
toggleBtn.disabled = false;
|
||
} else {
|
||
moreBtn.textContent = '➕ Daha Fazla Yorum G\u00f6ster (+20 Yorum)';
|
||
moreBtn.disabled = false;
|
||
}
|
||
|
||
var cList = res.comments || [];
|
||
if (cList.length === 0 && !token) {
|
||
listContainer.innerHTML =
|
||
'<div style="color: #94a3b8; font-size: 13px; text-align: center; padding: 12px;">Bu videoda hen\u00fcz YouTube yorumu bulunmuyor.</div>';
|
||
moreWrap.style.display = 'none';
|
||
announce('Bu videoda henüz YouTube yorumu bulunmuyor.');
|
||
return;
|
||
}
|
||
|
||
cList.forEach(function (c) {
|
||
var card = document.createElement('div');
|
||
card.className = 'yaktube-comment-item';
|
||
card.setAttribute('role', 'article');
|
||
card.setAttribute('tabindex', '0');
|
||
card.setAttribute(
|
||
'aria-label',
|
||
c.author + ' isimli kullan\u0131c\u0131n\u0131n yorumu: ' + c.content
|
||
);
|
||
card.style.cssText =
|
||
'background: #1e293b; padding: 14px 16px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.05); display: flex; gap: 12px; align-items: flex-start;';
|
||
|
||
var avatarLetter = (c.author || 'U').replace('@', '').charAt(0).toUpperCase();
|
||
var avatarHtml =
|
||
'<div style="width: 38px; height: 38px; border-radius: 50%; background: #334155; color: #ff8f37; font-weight: 700; display: flex; align-items: center; justify-content: center; font-size: 14px; flex-shrink: 0;">' +
|
||
avatarLetter +
|
||
'</div>';
|
||
var safeContent = c.content
|
||
.replace(/&/g, '&')
|
||
.replace(/</g, '<')
|
||
.replace(/>/g, '>')
|
||
.replace(/\n/g, '<br>');
|
||
|
||
card.innerHTML =
|
||
avatarHtml +
|
||
'<div style="flex-grow: 1; min-width: 0;">' +
|
||
'<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px; flex-wrap: wrap;">' +
|
||
'<h3 class="yaktube-comment-author-heading" style="margin: 0; font-size: 13px; font-weight: 700; color: #f1f5f9; display: inline-block;">' +
|
||
c.author +
|
||
'</h3>' +
|
||
'<span style="color: #64748b; font-size: 11px;">' +
|
||
c.published +
|
||
'</span>' +
|
||
(c.likeCount && c.likeCount !== '0'
|
||
? '<span style="background: rgba(255,255,255,0.08); color: #94a3b8; font-size: 11px; padding: 2px 6px; border-radius: 4px; display: inline-flex; align-items: center; gap: 4px;">👍 ' +
|
||
c.likeCount +
|
||
'</span>'
|
||
: '') +
|
||
'</div>' +
|
||
'<div style="color: #cbd5e1; font-size: 13px; line-height: 1.5; word-break: break-word;">' +
|
||
safeContent +
|
||
'</div>' +
|
||
'</div>';
|
||
|
||
listContainer.appendChild(card);
|
||
});
|
||
|
||
watchCommentToken = res.nextToken;
|
||
if (watchCommentToken) {
|
||
moreWrap.style.display = 'block';
|
||
} else {
|
||
moreWrap.style.display = 'none';
|
||
}
|
||
|
||
announce(cList.length + ' adet YouTube yorumu y\u00fcklendi.');
|
||
})
|
||
.catch(function (err) {
|
||
if (!token) {
|
||
toggleBtn.disabled = false;
|
||
toggleBtn.textContent = '⚠️ Tekrar Dene';
|
||
} else {
|
||
moreBtn.disabled = false;
|
||
moreBtn.textContent = '⚠️ Tekrar Dene';
|
||
}
|
||
alert('Yorumlar y\u00fcklenirken hata olu\u015ftu: ' + err.message);
|
||
});
|
||
}
|
||
|
||
if (toggleBtn) {
|
||
toggleBtn.addEventListener('click', function () {
|
||
fetchWatchComments(null);
|
||
});
|
||
}
|
||
if (moreBtn) {
|
||
moreBtn.addEventListener('click', function () {
|
||
if (watchCommentToken) fetchWatchComments(watchCommentToken);
|
||
});
|
||
}
|
||
})
|
||
.catch(function () {});
|
||
}
|
||
|
||
// 6. PWA Mobile App Install Engine & Standalone Detection
|
||
var isInsideYakTubeApp =
|
||
(navigator.userAgent && navigator.userAgent.indexOf('YakTubeMobileApp') !== -1) ||
|
||
(typeof window.matchMedia === 'function' &&
|
||
window.matchMedia('(display-mode: standalone)') &&
|
||
window.matchMedia('(display-mode: standalone)').matches) ||
|
||
(window.navigator && window.navigator.standalone === true);
|
||
|
||
var isMobileDevice = /Android|iPhone|iPad|iPod|Mobile|Tablet/i.test(navigator.userAgent);
|
||
|
||
var deferredInstallPrompt = null;
|
||
|
||
window.addEventListener('beforeinstallprompt', function (e) {
|
||
if (isInsideYakTubeApp) return;
|
||
e.preventDefault();
|
||
deferredInstallPrompt = e;
|
||
injectPWAInstallButton();
|
||
});
|
||
|
||
function injectPWAInstallButton() {
|
||
if (isInsideYakTubeApp) {
|
||
var existBtn = document.getElementById('yaktube-pwa-install-btn');
|
||
if (existBtn) {
|
||
existBtn.setAttribute('aria-hidden', 'true');
|
||
existBtn.remove();
|
||
}
|
||
return;
|
||
}
|
||
if (!deferredInstallPrompt || document.getElementById('yaktube-pwa-install-btn')) return;
|
||
|
||
var headerButtons =
|
||
document.querySelector('my-header .buttons-container') ||
|
||
document.querySelector('.buttons-container') ||
|
||
document.querySelector('my-header');
|
||
if (!headerButtons) return;
|
||
|
||
var installBtn = document.createElement('button');
|
||
installBtn.id = 'yaktube-pwa-install-btn';
|
||
installBtn.className = 'yaktube-pwa-btn';
|
||
installBtn.setAttribute('type', 'button');
|
||
installBtn.setAttribute('aria-label', getInstanceName() + ' Mobil Uygulamasını Yükle');
|
||
installBtn.style.cssText =
|
||
'background: linear-gradient(135deg, #ff8f37, #f97316); color: #000; border: none; padding: 6px 14px; border-radius: 20px; font-weight: 700; font-size: 12px; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; margin-right: 8px; box-shadow: 0 4px 12px rgba(255,143,55,0.4);';
|
||
installBtn.innerHTML = '📲 Uygulamayı Yükle';
|
||
|
||
installBtn.addEventListener('click', function () {
|
||
if (deferredInstallPrompt) {
|
||
deferredInstallPrompt.prompt();
|
||
deferredInstallPrompt.userChoice.then(function (choiceResult) {
|
||
if (choiceResult.outcome === 'accepted') {
|
||
installBtn.remove();
|
||
announce(getInstanceName() + ' uygulaması cihazınıza yükleniyor.');
|
||
}
|
||
deferredInstallPrompt = null;
|
||
});
|
||
}
|
||
});
|
||
|
||
headerButtons.prepend(installBtn);
|
||
}
|
||
|
||
function isYakNetSsoEnabled() {
|
||
if (cachedYakNetSsoEnabled !== null) return cachedYakNetSsoEnabled;
|
||
return isOfficialYakTubeServer();
|
||
}
|
||
|
||
function isOfficialYakTubeServer() {
|
||
var host = (window.location.hostname || '').toLowerCase();
|
||
// Sadece ve sadece resmi YakTube alan adında veya yerel test ortamında çalışsın
|
||
// Diğer PeerTube sunucularında yaktube.apk dosyası olmayacağı için ASLA gösterilmez
|
||
return host === 'yaktube.yakhub.com.tr' || host === '127.0.0.1' || host === 'localhost';
|
||
}
|
||
|
||
function injectApkDownloadButton() {
|
||
if (!isOfficialYakTubeServer()) {
|
||
var existBtnOther = document.getElementById('yaktube-apk-download-btn');
|
||
if (existBtnOther) existBtnOther.remove();
|
||
return;
|
||
}
|
||
// 1. If inside APK: NEVER show APK button
|
||
if (isInsideYakTubeApp) {
|
||
var existBtnApp = document.getElementById('yaktube-apk-download-btn');
|
||
if (existBtnApp) {
|
||
existBtnApp.setAttribute('aria-hidden', 'true');
|
||
existBtnApp.remove();
|
||
}
|
||
return;
|
||
}
|
||
|
||
// 2. If on Desktop: NEVER show in top header (keep header clean)
|
||
if (!isMobileDevice) {
|
||
var existBtnDesktop = document.getElementById('yaktube-apk-download-btn');
|
||
if (existBtnDesktop) {
|
||
existBtnDesktop.setAttribute('aria-hidden', 'true');
|
||
existBtnDesktop.remove();
|
||
}
|
||
return;
|
||
}
|
||
|
||
// 3. If on Mobile Web: Show in header
|
||
if (document.getElementById('yaktube-apk-download-btn')) return;
|
||
|
||
var headerButtons =
|
||
document.querySelector('my-header .buttons-container') ||
|
||
document.querySelector('my-header .header-right') ||
|
||
document.querySelector('.buttons-container') ||
|
||
document.querySelector('my-header');
|
||
if (!headerButtons) return;
|
||
|
||
var apkBtn = document.createElement('a');
|
||
apkBtn.id = 'yaktube-apk-download-btn';
|
||
apkBtn.href = '/yaktube.apk';
|
||
apkBtn.className = 'yaktube-apk-btn';
|
||
apkBtn.setAttribute('download', 'YakTube.apk');
|
||
apkBtn.setAttribute('aria-label', 'YakTube Android APK İndir (4.5 MB)');
|
||
apkBtn.style.cssText =
|
||
'background: #1e293b; color: #ff8f37; border: 1px solid #ff8f37; padding: 6px 12px; border-radius: 20px; font-weight: 700; font-size: 11px; text-decoration: none; display: inline-flex; align-items: center; gap: 4px; margin-right: 6px; transition: all 0.2s; box-shadow: 0 4px 12px rgba(0,0,0,0.3);';
|
||
apkBtn.innerHTML = '🤖 APK İndir (4.5 MB)';
|
||
|
||
headerButtons.prepend(apkBtn);
|
||
}
|
||
|
||
function injectSidebarApkLink() {
|
||
if (!isOfficialYakTubeServer()) {
|
||
var existLinkOther = document.getElementById('yaktube-sidebar-apk-link');
|
||
if (existLinkOther) existLinkOther.remove();
|
||
return;
|
||
}
|
||
// If inside APK: NEVER show in sidebar
|
||
if (isInsideYakTubeApp) {
|
||
var existLink = document.getElementById('yaktube-sidebar-apk-link');
|
||
if (existLink) {
|
||
existLink.setAttribute('aria-hidden', 'true');
|
||
existLink.remove();
|
||
}
|
||
return;
|
||
}
|
||
|
||
if (document.getElementById('yaktube-sidebar-apk-link')) return;
|
||
|
||
var menuContainer = document.querySelector('my-menu, .menu, .main-menu, .nav-list');
|
||
if (!menuContainer) return;
|
||
|
||
var sidebarLink = document.createElement('a');
|
||
sidebarLink.id = 'yaktube-sidebar-apk-link';
|
||
sidebarLink.href = '/yaktube.apk';
|
||
sidebarLink.className = 'menu-link item-link';
|
||
sidebarLink.setAttribute('download', 'YakTube.apk');
|
||
sidebarLink.setAttribute('aria-label', 'YakTube Android Uygulamasını İndir (4.5 MB)');
|
||
sidebarLink.style.cssText =
|
||
'display: flex; align-items: center; gap: 10px; padding: 10px 16px; margin: 8px 12px; background: rgba(255, 143, 55, 0.1); color: #ff8f37; border: 1px solid rgba(255, 143, 55, 0.3); border-radius: 8px; font-weight: 700; font-size: 13px; text-decoration: none;';
|
||
sidebarLink.innerHTML = '<span>🤖</span> <span>YakTube Android APK (4.5 MB)</span>';
|
||
|
||
menuContainer.appendChild(sidebarLink);
|
||
}
|
||
|
||
// 9. Background Play (Screen-Off / Minimize) & MediaSession Lock-Screen Controls
|
||
var videoState = {
|
||
hasPlayed: false,
|
||
explicitlyPausedByClick: false,
|
||
lastPlayTime: 0
|
||
};
|
||
|
||
function attachVideoListeners(video) {
|
||
if (!video || video.hasAttribute('data-yaktube-bgplay-hooked')) return;
|
||
video.setAttribute('data-yaktube-bgplay-hooked', 'true');
|
||
|
||
try {
|
||
initTouchSeekGesture(video);
|
||
} catch (e) {}
|
||
|
||
video.addEventListener('play', function () {
|
||
videoState.hasPlayed = true;
|
||
videoState.explicitlyPausedByClick = false;
|
||
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) {}
|
||
});
|
||
|
||
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) {}
|
||
});
|
||
}
|
||
|
||
// Hook manual play/pause buttons
|
||
document.addEventListener(
|
||
'click',
|
||
function (e) {
|
||
var target = e.target;
|
||
if (!target) return;
|
||
var btn = target.closest(
|
||
'.vjs-play-control, button[title*="Duraklat"], button[aria-label*="Duraklat"], #yaktube-bar-play-btn'
|
||
);
|
||
if (btn) {
|
||
var video = getVideoElement();
|
||
if (video && !video.paused) {
|
||
videoState.explicitlyPausedByClick = true;
|
||
}
|
||
}
|
||
},
|
||
true
|
||
);
|
||
|
||
function handleVisibilityChange() {
|
||
var video = getVideoElement();
|
||
if (!video) return;
|
||
|
||
// When screen turns off / tab is hidden:
|
||
if (document.hidden || document.webkitHidden) {
|
||
if (videoState.hasPlayed && !videoState.explicitlyPausedByClick) {
|
||
// Unconditionally keep audio stream active
|
||
setTimeout(function () {
|
||
if (video.paused && !videoState.explicitlyPausedByClick) {
|
||
video.play().catch(function () {});
|
||
}
|
||
}, 100);
|
||
setTimeout(function () {
|
||
if (video.paused && !videoState.explicitlyPausedByClick) {
|
||
video.play().catch(function () {});
|
||
}
|
||
}, 300);
|
||
}
|
||
}
|
||
}
|
||
|
||
document.addEventListener('visibilitychange', handleVisibilityChange, false);
|
||
document.addEventListener('webkitvisibilitychange', handleVisibilityChange, false);
|
||
window.addEventListener('pagehide', handleVisibilityChange, false);
|
||
|
||
// MediaSession API Integration (Lock Screen, Bluetooth, Smart Watches)
|
||
function updateMediaSessionMetadata(video) {
|
||
if (!('mediaSession' in navigator)) return;
|
||
|
||
var titleEl = document.querySelector('h1.video-title, .video-name, my-video-watch h1, .title');
|
||
var title = titleEl ? titleEl.textContent.trim() : 'YakTube Video';
|
||
var authorEl = document.querySelector('.actor-name, .channel-name, .video-channel-name, a.actor-link');
|
||
var artist = authorEl ? authorEl.textContent.trim() : 'YakTube';
|
||
|
||
var artwork = [];
|
||
var thumbEl = document.querySelector('meta[property="og:image"]');
|
||
if (thumbEl && thumbEl.content) {
|
||
artwork.push({ src: thumbEl.content, sizes: '512x512', type: 'image/jpeg' });
|
||
}
|
||
|
||
try {
|
||
navigator.mediaSession.metadata = new MediaMetadata({
|
||
title: title,
|
||
artist: artist,
|
||
album: 'YakTube',
|
||
artwork: artwork
|
||
});
|
||
|
||
navigator.mediaSession.setActionHandler('play', function () {
|
||
video.play();
|
||
announce('Video oynatılıyor.');
|
||
});
|
||
navigator.mediaSession.setActionHandler('pause', function () {
|
||
videoState.pausedByUser = true;
|
||
video.pause();
|
||
announce('Video duraklatıldı.');
|
||
});
|
||
navigator.mediaSession.setActionHandler('seekbackward', function (details) {
|
||
var skipTime = details.seekOffset || 10;
|
||
video.currentTime = Math.max(0, video.currentTime - skipTime);
|
||
announce(skipTime + ' saniye geri sarıldı.');
|
||
});
|
||
navigator.mediaSession.setActionHandler('seekforward', function (details) {
|
||
var skipTime = details.seekOffset || 10;
|
||
video.currentTime = Math.min(video.duration || 99999, video.currentTime + skipTime);
|
||
announce(skipTime + ' saniye ileri sarıldı.');
|
||
});
|
||
navigator.mediaSession.setActionHandler('stop', function () {
|
||
videoState.pausedByUser = true;
|
||
video.pause();
|
||
});
|
||
navigator.mediaSession.setActionHandler('nexttrack', function () {
|
||
if (typeof window.__yaktube_play_next_smart__ === 'function') {
|
||
window.__yaktube_play_next_smart__('media-session-next');
|
||
}
|
||
});
|
||
} catch (e) {}
|
||
}
|
||
|
||
function updateMediaSessionPosition(video) {
|
||
if (!('mediaSession' in navigator) || !navigator.mediaSession.setPositionState) return;
|
||
if (isNaN(video.duration) || isNaN(video.currentTime) || video.duration <= 0) return;
|
||
try {
|
||
navigator.mediaSession.setPositionState({
|
||
duration: video.duration,
|
||
playbackRate: video.playbackRate || 1,
|
||
position: Math.min(video.currentTime, video.duration)
|
||
});
|
||
} catch (e) {}
|
||
}
|
||
|
||
// ============================================================================
|
||
// 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 (
|
||
'<article class="yaktube-continue-card" aria-label="' +
|
||
escapeHtml(it.title + ', kalan süre ' + formatClockShort(remaining)) +
|
||
'">' +
|
||
'<a href="' +
|
||
escapeHtml(resumeUrl) +
|
||
'" class="yaktube-continue-thumb-link">' +
|
||
'<img src="' +
|
||
escapeHtml(it.thumbnail || '/client/assets/images/default-thumbnail.jpg') +
|
||
'" alt="" loading="lazy" onerror="this.src=\'/client/assets/images/default-thumbnail.jpg\'" />' +
|
||
'<span class="yaktube-continue-badge">⏯️ ' +
|
||
escapeHtml(formatClockShort(it.startTime)) +
|
||
' / ' +
|
||
escapeHtml(formatClockShort(it.duration)) +
|
||
'</span>' +
|
||
'<div class="yaktube-continue-progress"><div style="width:' +
|
||
it.pct +
|
||
'%;"></div></div>' +
|
||
'</a>' +
|
||
'<div class="yaktube-continue-body">' +
|
||
'<a href="' +
|
||
escapeHtml(resumeUrl) +
|
||
'" class="yaktube-continue-title">' +
|
||
escapeHtml(it.title) +
|
||
'</a>' +
|
||
'<div class="yaktube-continue-sub">' +
|
||
escapeHtml(it.channel || getInstanceName()) +
|
||
'</div>' +
|
||
'<div class="yaktube-continue-actions">' +
|
||
'<a href="' +
|
||
escapeHtml(resumeUrl) +
|
||
'" class="yaktube-continue-resume-btn">▶️ Devam Et</a>' +
|
||
'<button type="button" class="yaktube-queue-add-btn yaktube-cw-queue-btn" data-slug="' +
|
||
escapeHtml(it.slug) +
|
||
'" title="Sıraya Ekle" aria-label="' +
|
||
escapeHtml(it.title) +
|
||
' videosunu sıraya ekle">➕</button>' +
|
||
'<button type="button" class="yaktube-cw-remove-btn" data-slug="' +
|
||
escapeHtml(it.slug) +
|
||
'" title="Geçmişten Kaldır" aria-label="' +
|
||
escapeHtml(it.title) +
|
||
' kaydını kaldır">✕</button>' +
|
||
'</div>' +
|
||
'</div>' +
|
||
'</article>'
|
||
);
|
||
})
|
||
.join('');
|
||
|
||
shelf.innerHTML =
|
||
'<div class="yaktube-continue-header">' +
|
||
'<h3>⏯️ Kaldığın Yerden Devam Et</h3>' +
|
||
'<button type="button" id="yaktube-cw-clear-all" class="yaktube-shortcuts-btn" style="font-size:12px;">🧹 Rafı Temizle</button>' +
|
||
'</div>' +
|
||
'<div class="yaktube-continue-grid">' +
|
||
cardsHtml +
|
||
'</div>';
|
||
|
||
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 =
|
||
'<div class="yaktube-feature-modal yaktube-cockpit-modal">' +
|
||
'<div class="yaktube-feature-modal-header">' +
|
||
'<h3 id="yaktube-cockpit-title">🚀 YakTube Yönetici Sistem Kokpiti</h3>' +
|
||
'<button type="button" id="yaktube-cockpit-close" class="yaktube-voice-modal-close-btn" aria-label="Sistem kokpitini kapat">✕</button>' +
|
||
'</div>' +
|
||
'<div id="yaktube-cockpit-body" style="padding:18px 0; text-align:center; color:#cbd5e1;">⏳ Sunucu verileri alınıyor...</div>' +
|
||
'</div>';
|
||
|
||
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 =
|
||
'<div style="color:#fca5a5; padding:14px;">⚠️ ' +
|
||
escapeHtml((data && data.error) || 'Kokpit verisi alınamadı (Yönetici oturumu gerekli).') +
|
||
'</div>';
|
||
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 =
|
||
'<div class="yaktube-cockpit-section-title">📋 Aktif / Son İşlemler & Durumlar</div>' +
|
||
'<ul class="yaktube-cockpit-issues">' +
|
||
data.recentIssues
|
||
.map(function (it) {
|
||
var lbl = it.state === 2 ? '⚙️ İşleniyor' : it.state === 3 ? '📥 İndiriliyor' : '⚠️ Hata';
|
||
return (
|
||
'<li><span><strong>' +
|
||
lbl +
|
||
'</strong> ' +
|
||
escapeHtml(it.name || '') +
|
||
'</span>' +
|
||
(it.importError
|
||
? '<small style="color:#fda4af;">' +
|
||
escapeHtml(String(it.importError).slice(0, 70)) +
|
||
'</small>'
|
||
: '') +
|
||
'</li>'
|
||
);
|
||
})
|
||
.join('') +
|
||
'</ul>';
|
||
}
|
||
|
||
bodyEl.innerHTML =
|
||
'<div class="yaktube-cockpit-grid">' +
|
||
'<div class="yaktube-cockpit-card">' +
|
||
'<div class="yaktube-cockpit-label">💾 Medya Diski</div>' +
|
||
'<div class="yaktube-cockpit-val">' +
|
||
(stDisk ? stDisk.freeGB + ' GB Boş' : 'Bilinmiyor') +
|
||
'</div>' +
|
||
'<div class="yaktube-cockpit-sub">' +
|
||
(stDisk ? stDisk.totalGB + ' GB Toplam (%' + stDisk.usedPct + ' dolu)' : '') +
|
||
'</div>' +
|
||
'</div>' +
|
||
'<div class="yaktube-cockpit-card">' +
|
||
'<div class="yaktube-cockpit-label">🎬 Yerel Kütüphane</div>' +
|
||
'<div class="yaktube-cockpit-val">' +
|
||
(vids.publishedLocal || 0) +
|
||
' Video</div>' +
|
||
'<div class="yaktube-cockpit-sub">' +
|
||
(vids.totalHoursLocal || 0) +
|
||
' saat • +' +
|
||
(vids.remoteVideos || 0) +
|
||
' Fediverse</div>' +
|
||
'</div>' +
|
||
'<div class="yaktube-cockpit-card">' +
|
||
'<div class="yaktube-cockpit-label">⚙️ İşlem Kuyruğu</div>' +
|
||
'<div class="yaktube-cockpit-val">' +
|
||
((vids.transcoding || 0) + (vids.importing || 0)) +
|
||
' Aktif</div>' +
|
||
'<div class="yaktube-cockpit-sub">' +
|
||
(imps.processing || 0) +
|
||
' indirme • ' +
|
||
(vids.transcoding || 0) +
|
||
' transcode</div>' +
|
||
'</div>' +
|
||
'<div class="yaktube-cockpit-card">' +
|
||
'<div class="yaktube-cockpit-label">🧹 Fediverse & Transkript Önbelleği</div>' +
|
||
'<div class="yaktube-cockpit-val">' +
|
||
(cache.totalSizeMB || 0) +
|
||
' MB</div>' +
|
||
'<div class="yaktube-cockpit-sub">' +
|
||
(cache.totalFiles || 0) +
|
||
' dosya • ' +
|
||
(cache.transcriptCacheCount || 0) +
|
||
' transkript</div>' +
|
||
'</div>' +
|
||
'<div class="yaktube-cockpit-card">' +
|
||
'<div class="yaktube-cockpit-label">🖥️ Sunucu Süreci</div>' +
|
||
'<div class="yaktube-cockpit-val">' +
|
||
(proc.rssMB || 0) +
|
||
' MB RAM</div>' +
|
||
'<div class="yaktube-cockpit-sub">Çalışma: ' +
|
||
formatUptimeTR(proc.uptimeSeconds) +
|
||
' • ' +
|
||
escapeHtml(proc.nodeVersion || '') +
|
||
'</div>' +
|
||
'</div>' +
|
||
'</div>' +
|
||
issuesHtml +
|
||
'<div class="yaktube-cockpit-actions">' +
|
||
'<button type="button" id="yaktube-cockpit-refresh" class="yaktube-audio-action-btn">🔄 Yenile</button>' +
|
||
'<button type="button" id="yaktube-cockpit-clean-cache" class="yaktube-audio-action-btn">🧹 Uzak Önbelleği Temizle</button>' +
|
||
'<button type="button" id="yaktube-cockpit-clean-failed" class="yaktube-audio-action-btn" ' +
|
||
((data.cleanableFailedCount || 0) > 0 ? '' : 'disabled') +
|
||
'>🗑️ Hatalı Kalıntıları Sil (' +
|
||
(data.cleanableFailedCount || 0) +
|
||
')</button>' +
|
||
'</div>';
|
||
|
||
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 = '<div style="color:#fca5a5;">⚠️ Sunucuya ulaşılamadı.</div>';
|
||
});
|
||
}
|
||
|
||
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 =
|
||
'<div class="yaktube-feature-modal yaktube-cmd-modal">' +
|
||
'<div class="yaktube-feature-modal-header">' +
|
||
'<h3 id="yaktube-cmd-heading">⌘ YakTube Hızlı Komut Paleti</h3>' +
|
||
'<button type="button" id="yaktube-cmd-close" class="yaktube-voice-modal-close-btn" aria-label="Komut paletini kapat">✕</button>' +
|
||
'</div>' +
|
||
'<input type="text" id="yaktube-cmd-input" class="yaktube-cmd-input" placeholder="Bir eylem, araç veya sayfa yazın (örn: ses, sıra, kokpit, altyazı)..." aria-label="Komut filtrele" aria-controls="yaktube-cmd-list" />' +
|
||
'<ul id="yaktube-cmd-list" class="yaktube-cmd-list" role="listbox" aria-label="Kullanılabilir komutlar"></ul>' +
|
||
'</div>';
|
||
|
||
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 = '<li class="yaktube-cmd-empty">Eşleşen komut bulunamadı.</li>';
|
||
return;
|
||
}
|
||
listEl.innerHTML = filtered
|
||
.map(function (c, i) {
|
||
return (
|
||
'<li role="option" id="yaktube-cmd-opt-' +
|
||
i +
|
||
'" class="yaktube-cmd-item ' +
|
||
(i === selectedIdx ? 'selected' : '') +
|
||
'" aria-selected="' +
|
||
(i === selectedIdx ? 'true' : 'false') +
|
||
'" data-idx="' +
|
||
i +
|
||
'">' +
|
||
'<span>' +
|
||
escapeHtml(c.label) +
|
||
'</span>' +
|
||
'<span class="yaktube-kbd">' +
|
||
escapeHtml(c.hint) +
|
||
'</span>' +
|
||
'</li>'
|
||
);
|
||
})
|
||
.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) {}
|
||
|
||
try {
|
||
var video = getVideoElement();
|
||
if (video) attachVideoListeners(video);
|
||
} catch (e) {}
|
||
|
||
try {
|
||
checkAndInjectSearchResults();
|
||
} catch (e) {}
|
||
|
||
try {
|
||
injectSearchEnhancements();
|
||
} catch (e) {}
|
||
|
||
try {
|
||
injectCategoryChipsBar();
|
||
} catch (e) {}
|
||
|
||
try {
|
||
injectContinueWatchingShelf();
|
||
} catch (e) {}
|
||
|
||
try {
|
||
injectSkipToCategoriesLink();
|
||
} catch (e) {}
|
||
|
||
try {
|
||
injectSidebarCategoriesLink();
|
||
} catch (e) {}
|
||
|
||
try {
|
||
checkAndInjectRelatedVideos(Boolean(isNav));
|
||
} catch (e) {}
|
||
|
||
try {
|
||
restoreActiveLiveStream();
|
||
} catch (e) {}
|
||
|
||
try {
|
||
checkAndInjectWatchPageComments();
|
||
} catch (e) {}
|
||
|
||
try {
|
||
syncQueueCountersUI();
|
||
} catch (e) {}
|
||
|
||
try {
|
||
injectPWAInstallButton();
|
||
} catch (e) {}
|
||
|
||
try {
|
||
injectApkDownloadButton();
|
||
} catch (e) {}
|
||
|
||
try {
|
||
injectSidebarApkLink();
|
||
} catch (e) {}
|
||
}
|
||
|
||
function scheduleUnifiedCycle(immediate, debounceDelay) {
|
||
if (unifiedTimer) {
|
||
clearTimeout(unifiedTimer);
|
||
unifiedTimer = null;
|
||
}
|
||
if (immediate) {
|
||
runUnifiedCycle(true);
|
||
return;
|
||
}
|
||
var delay = typeof debounceDelay === 'number' ? debounceDelay : 150;
|
||
unifiedTimer = setTimeout(function () {
|
||
unifiedTimer = null;
|
||
runUnifiedCycle(false);
|
||
}, delay);
|
||
}
|
||
|
||
// SPA Navigation Handler
|
||
function onLocationChange() {
|
||
currentActiveVideoKey = null;
|
||
try {
|
||
clearAbLoop(false);
|
||
} catch (e) {}
|
||
scheduleUnifiedCycle(true);
|
||
setTimeout(function () {
|
||
scheduleUnifiedCycle(false, 0);
|
||
}, 150);
|
||
setTimeout(function () {
|
||
scheduleUnifiedCycle(false, 0);
|
||
}, 450);
|
||
setTimeout(function () {
|
||
scheduleUnifiedCycle(false, 0);
|
||
}, 950);
|
||
}
|
||
|
||
window.addEventListener('popstate', onLocationChange);
|
||
|
||
// History pushState / replaceState interception for seamless Angular routing
|
||
(function hookHistory() {
|
||
try {
|
||
var origPush = history.pushState;
|
||
var origReplace = history.replaceState;
|
||
if (origPush) {
|
||
history.pushState = function () {
|
||
var ret = origPush.apply(this, arguments);
|
||
try {
|
||
onLocationChange();
|
||
} catch (e) {}
|
||
return ret;
|
||
};
|
||
}
|
||
if (origReplace) {
|
||
history.replaceState = function () {
|
||
var ret = origReplace.apply(this, arguments);
|
||
try {
|
||
onLocationChange();
|
||
} catch (e) {}
|
||
return ret;
|
||
};
|
||
}
|
||
} catch (e) {}
|
||
})();
|
||
|
||
// MutationObserver: react immediately to DOM changes instead of CPU polling
|
||
if (typeof MutationObserver !== 'undefined') {
|
||
try {
|
||
var observer = new MutationObserver(function () {
|
||
scheduleUnifiedCycle(false, 150);
|
||
});
|
||
if (document.body) {
|
||
observer.observe(document.body, { childList: true, subtree: true });
|
||
} else {
|
||
document.addEventListener('DOMContentLoaded', function () {
|
||
observer.observe(document.body, { childList: true, subtree: true });
|
||
});
|
||
}
|
||
} catch (e) {}
|
||
}
|
||
|
||
// Gentle 3.5s heartbeat fallback (replaces aggressive 800ms polling, reduces idle CPU by 80%)
|
||
setInterval(function () {
|
||
scheduleUnifiedCycle(false, 0);
|
||
}, 3500);
|
||
|
||
// Initial trigger
|
||
runUnifiedCycle(true);
|
||
})();
|
||
} catch (err) {
|
||
console.error('[YakTube] Safe catch error:', err);
|
||
}
|
||
|
||
// PeerTube Plugin Client Hook Registration
|
||
export async function register({ registerHook, peertubeHelpers } = {}) {
|
||
if (typeof registerHook === 'function') {
|
||
try {
|
||
registerHook({
|
||
target: 'filter:internal.video-watch.player.load-options.result',
|
||
handler: function (result) {
|
||
if (!result || typeof result !== 'object') return result;
|
||
var origNextVideo = result.nextVideo;
|
||
result.nextVideo = function () {
|
||
var orig = typeof origNextVideo === 'function' ? origNextVideo() : {};
|
||
if (typeof window !== 'undefined' && typeof window.__yaktube_is_playlist_watch === 'function') {
|
||
if (window.__yaktube_is_playlist_watch()) return orig;
|
||
}
|
||
var firstRec =
|
||
typeof window !== 'undefined' && typeof window.__yaktube_get_first_smart_rec === 'function'
|
||
? window.__yaktube_get_first_smart_rec()
|
||
: null;
|
||
return Object.assign({}, orig, {
|
||
enabled: Boolean(firstRec) || Boolean(orig && orig.enabled),
|
||
displayControlBarButton: true,
|
||
getClipTitle: function () {
|
||
var rec =
|
||
typeof window !== 'undefined' && typeof window.__yaktube_get_first_smart_rec === 'function'
|
||
? window.__yaktube_get_first_smart_rec()
|
||
: null;
|
||
if (rec && rec.title) return rec.title;
|
||
return orig && typeof orig.getClipTitle === 'function' ? orig.getClipTitle() : 'Sonraki Önerilen Video';
|
||
},
|
||
handler: function () {
|
||
if (typeof window !== 'undefined' && typeof window.__yaktube_play_next_smart__ === 'function') {
|
||
window.__yaktube_play_next_smart__('peertube-player-hook');
|
||
return;
|
||
}
|
||
if (orig && typeof orig.handler === 'function') orig.handler();
|
||
}
|
||
});
|
||
};
|
||
|
||
if (result.upnext && typeof result.upnext === 'object') {
|
||
var origUpnext = result.upnext;
|
||
result.upnext = Object.assign({}, origUpnext, {
|
||
isEnabled: function () {
|
||
if (typeof window !== 'undefined' && typeof window.__yaktube_is_playlist_watch === 'function') {
|
||
if (window.__yaktube_is_playlist_watch()) {
|
||
return origUpnext && typeof origUpnext.isEnabled === 'function' ? origUpnext.isEnabled() : false;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
});
|
||
}
|
||
return result;
|
||
}
|
||
});
|
||
} catch (e) {}
|
||
}
|
||
return true;
|
||
}
|
||
|
||
export { register as registerClient };
|
||
export default register;
|