// ==UserScript== // @name Universal Video Split // @namespace http://tampermonkey.net/ // @version 1.9 // Incrementing version // @author Gemini (Combined by AI) // @match *://vk.com/video_ext.php* // @match *://vkvideo.ru/video_ext.php* // @match *://rutube.ru/video/* // @match *://www.youtube.com/watch* // @grant GM_addStyle // @grant GM_log // @description Универсальный сплит по времени для VK, Rutube, YouTube (v1.9). Панель управления, статистика, оверлей, звук, таймер // @downloadURL none // ==/UserScript== (function() { 'use strict'; // --- КОНФИГУРАЦИЯ (Общая) --- let splitMinutes = null; let totalVideoMinutes = null; const extendCost = 300; // The sound URL seems to be causing a 'Format error' or 'ERR_BLOCKED_BY_CLIENT' specifically on VK. // This indicates an issue with VK's environment blocking loading from raw.githubusercontent.com // or a format incompatibility there. // If sound doesn't work on VK, try hosting a different, simple MP3 file elsewhere (e.g., a file hosting service or your own server) and replace this URL. const splitSoundUrl = 'https://github.com/lardan099/donat/raw/refs/heads/main/mix_06s.mp3'; const overlayGifUrl = 'https://i.imgur.com/SS5Nfff.gif'; const localStorageVolumeKey = 'universalSplitAlertVolume'; const localStorageTimerKey = 'universalSplitOverlayTimer'; const defaultOverlayTimerDuration = 360; const defaultAlertVolume = '1.0'; const setupIntervalDelay = 500; // How often to try setting up the script if elements aren't found // --- ГЛОБАЛЬНЫЕ ПЕРЕМЕННЫЕ СОСТОЯНИЯ --- let currentPlatform = 'unknown'; let platformConfig = null; let video = null; let overlay = null; let splitTriggered = false; // Flag to ensure split actions only happen once per trigger event let audioPlayer = null; let audioPrimed = false; // Flag to track if we've attempted to prime the audio context for the *current* audioPlayer instance let splitCheckIntervalId = null; let setupIntervalId = null; // Interval to poll for video/insertion elements on complex pages let panelAdded = false; let panelElement = null; let controlsElement = null; // Specific for VK visibility check let visibilityCheckIntervalId = null; // Specific for VK visibility check let navigationObserver = null; // Observer to detect URL changes for SPAs let lastUrl = location.href; // Track last URL for navigation observer let videoPlayListenerAdded = false; // Flag to ensure we only add the video 'play' listener once per video element instance let overlayTimerDuration = parseInt(localStorage.getItem(localStorageTimerKey), 10); if (isNaN(overlayTimerDuration) || overlayTimerDuration < 0) { overlayTimerDuration = defaultOverlayTimerDuration; } let overlayTimerIntervalId = null; let overlayCountdownRemaining = overlayTimerDuration; // --- КОНФИГУРАЦИЯ ПЛАТФОРМ --- const platformConfigs = { vk: { idPrefix: 'vk', controlPanelSelector: '#split-control-panel-vk', videoSelector: 'video', insertionSelector: '.videoplayer_title', // Insert panel after this insertionMethod: 'afterend', controlsElementSelector: '.videoplayer_controls', // Element to watch for visibility (VK only) needsVisibilityCheck: true, // --- CORRECTED VK TITLE SELECTOR based on provided HTML --- videoTitleSelector: '.videoplayer_title a.videoplayer_title_link', // Selects the tag containing the title text // --- END CORRECTED VK TITLE SELECTOR --- styles: ` #split-control-panel-vk { background: #f0f2f5; border: 1px solid #dce1e6; color: #333; display: none; opacity: 0; transition: opacity 0.2s ease-in-out; position: relative; z-index: 10; } #split-control-panel-vk.visible { display: flex; opacity: 1; } #split-control-panel-vk label { color: #656565; } #split-control-panel-vk label i { color: #828282; } #split-control-panel-vk input[type="number"] { background: #fff; color: #000; border: 1px solid #c5d0db; } #split-control-panel-vk input[type="number"]:focus { border-color: #aebdcb; } #split-control-panel-vk button { background: #e5ebf1; color: #333; border: 1px solid #dce1e6; } #split-control-panel-vk button:hover { background: #dae2ea; } #split-control-panel-vk button:active { background: #ccd5e0; border-color: #c5d0db; } #split-control-panel-vk .split-input-group button { background: #f0f2f5; border: 1px solid #dce1e6; } #split-control-panel-vk .split-input-group button:hover { background: #e5ebf1; } #split-control-panel-vk .set-split-button { background: #5181b8; color: #fff; border: none; } #split-control-panel-vk .set-split-button:hover { background: #4a76a8; } #split-control-panel-vk .set-split-button.active { background: #6a9e42; } #split-control-panel-vk .set-split-button.active:hover { background: #5c8c38; } #split-control-panel-vk .split-volume-control label { color: #656565; } #split-control-panel-vk .split-volume-control input[type="range"] { background: #dae2ea; } #split-control-panel-vk .split-volume-control input[type="range"]::-webkit-slider-thumb { background: #5181b8; } #split-control-panel-vk .split-volume-control input[type="range"]::-moz-range-thumb { background: #5181b8; } #split-control-panel-vk .split-stats { color: #333; } ` }, rutube: { idPrefix: 'rutube', controlPanelSelector: '#split-control-panel-rutube', videoSelector: 'video', insertionSelector: '.video-pageinfo-container-module__pageInfoContainer', // Insert panel into this insertionMethod: 'prepend', needsVisibilityCheck: false, // --- RUTUBE TITLE SELECTOR based on provided HTML --- videoTitleSelector: 'h1.video-pageinfo-container-module__videoTitleSectionHeader', // Selector for video title // --- END RUTUBE TITLE SELECTOR --- styles: ` #split-control-panel-rutube { background: #222; border: 1px solid #444; color: #eee; } #split-control-panel-rutube label { color: #aaa; } #split-control-panel-rutube label i { color: #888; } #split-control-panel-rutube input[type="number"] { background: #333; color: #eee; border: 1px solid #555; } #split-control-panel-rutube button { background: #444; color: #eee; border: none; } #split-control-panel-rutube button:hover { background: #555; } #split-control-panel-rutube .split-input-group button { background: #333; border: 1px solid #555; } #split-control-panel-rutube .split-input-group button:hover { background: #444; } #split-control-panel-rutube .set-split-button { background: #007bff; color: white; } #split-control-panel-rutube .set-split-button:hover { background: #0056b3; } #split-control-panel-rutube .set-split-button.active { background: #28a745; } #split-control-panel-rutube .set-split-button.active:hover { background: #1e7e34; } #split-control-panel-rutube .split-volume-control label { color: #aaa; } #split-control-panel-rutube .split-volume-control input[type="range"] { background: #444; } #split-control-panel-rutube .split-volume-control input[type="range"]::-webkit-slider-thumb { background: #007bff; } #split-control-panel-rutube .split-volume-control input[type="range"]::-moz-range-thumb { background: #007bff; } #split-control-panel-rutube .split-stats { color: #eee; } ` }, youtube: { idPrefix: 'youtube', controlPanelSelector: '#split-control-panel-youtube', videoSelector: 'video', insertionSelector: 'ytd-watch-flexy #primary', // Insert panel into this insertionMethod: 'prepend', needsVisibilityCheck: false, videoTitleSelector: '#title h1', // Selector for video title styles: ` #split-control-panel-youtube { background: var(--yt-spec-badge-chip-background); border: 1px solid var(--yt-spec-border-div); color: var(--yt-spec-text-primary); max-width: var(--ytd-watch-flexy-width); } ytd-watch-flexy:not([theater]) #primary #split-control-panel-youtube { margin-left: auto; margin-right: auto; } ytd-watch-flexy[theater] #primary #split-control-panel-youtube { max-width: 100%; } #split-control-panel-youtube label { color: var(--yt-spec-text-secondary); } #split-control-panel-youtube label i { color: var(--yt-spec-text-disabled); } #split-control-panel-youtube input[type="number"] { background: var(--yt-spec-filled-button-background); color: var(--yt-spec-text-primary); border: 1px solid var(--yt-spec-action-simulate-border); } #split-control-panel-youtube button { background: var(--yt-spec-grey-1); color: var(--yt-spec-text-primary); border: none; } #split-control-panel-youtube button:hover { background: var(--yt-spec-grey-2); } #split-control-panel-youtube .split-input-group button { background: var(--yt-spec-filled-button-background); border: 1px solid var(--yt-spec-action-simulate-border); } #split-control-panel-youtube .split-input-group button:hover { background: var(--yt-spec-grey-2); } #split-control-panel-youtube .set-split-button { background: var(--yt-spec-brand-suggested-action); color: var(--yt-spec-text-reverse); } #split-control-panel-youtube .set-split-button:hover { background: var(--yt-spec-brand-suggested-action-hover); } #split-control-panel-youtube .set-split-button.active { background: var(--yt-spec-call-to-action); } #split-control-panel-youtube .set-split-button.active:hover { background: var(--yt-spec-call-to-action-hover); } #split-control-panel-youtube .split-volume-control label { color: var(--yt-spec-text-secondary); } #split-control-panel-youtube .split-volume-control input[type="range"] { background: var(--yt-spec-grey-1); } #split-control-panel-youtube .split-volume-control input[type="range"]::-webkit-slider-thumb { background: var(--yt-spec-brand-button-background); } #split-control-panel-youtube .split-volume-control input[type="range"]::-moz-range-thumb { background: var(--yt-spec-brand-button-background); } #split-control-panel-youtube .split-stats { color: var(--yt-spec-text-primary); } ` } }; // --- ОБЩИЕ СТИЛИ (Панель + Оверлей) --- function injectGlobalStyles() { let platformStyles = platformConfig ? platformConfig.styles : ''; GM_addStyle(` /* --- Общие стили панели управления --- */ .split-control-panel-universal { margin-top: 10px; margin-bottom: 15px; padding: 10px 15px; border-radius: 8px; display: flex; flex-direction: column; align-items: flex-start; gap: 8px; font-family: -apple-system, BlinkMacSystemFont, "Roboto", "Helvetica Neue", Geneva, "Noto Sans Armenian", "Noto Sans Bengali", "Noto Sans Cherokee", "Noto Sans Devanagari", "Noto Sans Ethiopic", "Noto Sans Georgian", "Noto Sans Hebrew", "Noto Sans Kannada", "Noto Sans Khmer", "Noto Sans Lao", "Noto Sans Osmanya", "Noto Sans Tamil", "Noto Sans Telugu", "Noto Sans Thai", sans-serif,arial,Tahoma,verdana; font-size: 13px; width: 100%; box-sizing: border-box; line-height: 1.4; } /* Reduced margin-bottom on the title */ .split-control-panel-universal .panel-video-title { font-size: 14px; font-weight: bold; margin-bottom: 0; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* Style for panel title */ .split-control-panel-universal .panel-controls-row { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 15px; width: 100%; } .split-control-panel-universal label { font-weight: 500; flex-shrink: 0; } .split-control-panel-universal label i { font-style: normal; font-size: 11px; display: block; } .split-input-group { display: flex; align-items: center; gap: 4px; } .split-control-panel-universal input[type="number"] { width: 55px; padding: 6px 8px; border-radius: 4px; text-align: center; font-size: 14px; -moz-appearance: textfield; } .split-control-panel-universal input[type="number"]::-webkit-outer-spin-button, .split-control-panel-universal input[type="number"]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } .split-control-panel-universal button { padding: 6px 12px; font-size: 13px; cursor: pointer; border-radius: 4px; transition: background 0.15s ease-in-out; font-weight: 500; flex-shrink: 0; line-height: normal; } .split-input-group button { padding: 6px 8px; } .set-split-button { order: -1; margin-right: auto; } /* Keep set button to the left */ .split-volume-control { display: flex; align-items: center; gap: 5px; margin-left: auto; } .split-volume-control label { flex-shrink: 0; } .split-volume-control input[type="range"] { flex-grow: 1; min-width: 70px; -webkit-appearance: none; appearance: none; height: 6px; outline: none; opacity: 0.8; transition: opacity .2s; border-radius: 3px; cursor: pointer; } .split-volume-control input[type="range"]:hover { opacity: 1; } .split-control-panel-universal input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 12px; height: 12px; cursor: pointer; border-radius: 50%; } .split-control-panel-universal input[type="range"]::-moz-range-thumb { width: 12px; height: 12px; cursor: pointer; border-radius: 50%; border: none; } .split-stats { font-size: 14px; font-weight: 500; white-space: nowrap; } /* --- Общие стили оверлея --- */ .split-overlay-universal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.95); color: white; display: flex; flex-direction: column; justify-content: center; align-items: center; z-index: 999999 !important; font-family: -apple-system, BlinkMacSystemFont, "Roboto", "Helvetica Neue", Geneva, "Noto Sans Armenian", "Noto Sans Bengali", "Noto Sans Cherokee", "Noto Sans Devanagari", "Noto Sans Ethiopic", "Noto Sans Georgian", "Noto Sans Hebrew", "Noto Sans Kannada", "Noto Sans Khmer", "Noto Sans Lao", "Noto Sans Osmanya", "Noto Sans Tamil", "Noto Sans Telugu", "Noto Sans Thai", sans-serif,arial,Tahoma,verdana; text-align: center; padding: 20px; box-sizing: border-box; } .split-overlay-universal .overlay-video-title { font-size: clamp(18px, 3vw, 28px); margin-bottom: 15px; color: #ccc; font-weight: normal; max-width: 90%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .split-overlay-universal .warning-message { font-size: clamp(24px, 4vw, 36px); margin-bottom: 15px; color: yellow; font-weight: bold; text-shadow: 0 0 8px rgba(255, 255, 0, 0.5); } .split-overlay-universal .main-message { font-size: clamp(40px, 8vw, 72px); font-weight: bold; margin-bottom: 20px; color: red; text-shadow: 0 0 15px rgba(255, 0, 0, 0.7); } .split-overlay-universal .overlay-timer, .split-overlay-universal .overlay-remaining-minutes { font-size: clamp(28px, 5vw, 48px); font-weight: bold; margin-bottom: 20px; } .split-overlay-universal .overlay-timer { color: orange; } .split-overlay-universal .overlay-remaining-minutes { color: cyan; } .split-overlay-universal .overlay-timer-control { margin-bottom: 20px; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; justify-content: center; color: white; font-size: 18px; } .split-overlay-universal .overlay-timer-control label { font-weight: 500; } .split-overlay-universal .overlay-timer-control input[type="number"] { width: 70px; padding: 8px 10px; background: rgba(255, 255, 255, 0.1); color: white; border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px; text-align: center; font-size: 18px; -moz-appearance: textfield; } .split-overlay-universal .overlay-timer-control input[type="number"]::-webkit-outer-spin-button, .split-overlay-universal .overlay-timer-control input[type="number"]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } .split-overlay-universal .overlay-timer-control button { padding: 8px 12px; font-size: 16px; cursor: pointer; background: rgba(255, 255, 255, 0.1); color: white; border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px; transition: background 0.2s ease-in-out; font-weight: 500; } .split-overlay-universal .overlay-timer-control button:hover { background: rgba(255, 255, 255, 0.2); } .split-overlay-universal .extend-buttons { display: flex; gap: 15px; flex-wrap: wrap; justify-content: center; margin-bottom: 40px; } .split-overlay-universal .extend-buttons button { padding: 12px 25px; font-size: clamp(18px, 3vw, 24px); cursor: pointer; background: #dc3545; border: none; color: white; border-radius: 4px; font-weight: bold; transition: background 0.2s ease-in-out; } .split-overlay-universal .extend-buttons button:hover { background: #c82333; } .split-overlay-universal img { max-width: 90%; max-height: 45vh; height: auto; border-radius: 8px; margin-top: 20px; } /* --- Стили конкретных платформ --- */ ${platformStyles} `); } // --- ФУНКЦИИ ЯДРА --- function getElementId(baseId) { return platformConfig ? `${baseId}-${platformConfig.idPrefix}` : baseId; } // Helper function to get the video title from the DOM function getVideoTitle() { if (!platformConfig?.videoTitleSelector) return "Неизвестное видео"; const titleElement = document.querySelector(platformConfig.videoTitleSelector); let title = "Неизвестное видео"; if (titleElement) { // Use textContent and trim for clean text title = titleElement.textContent ? titleElement.textContent.trim() : "Неизвестное видео"; if (!title) title = "Неизвестное видео"; // Fallback if trim results in empty string } else { // GM_log(`[${currentPlatform}] Video title element not found with selector: ${platformConfig.videoTitleSelector}`); } return title; } function updateSplitDisplay() { const inputField = document.getElementById(getElementId("split-input")); if (inputField) inputField.valueAsNumber = splitMinutes === null ? 0 : splitMinutes; updateSplitStatsDisplay(); // Also update the panel title text if the panel exists const panelTitleElement = panelElement?.querySelector('.panel-video-title'); if (panelTitleElement) { panelTitleElement.textContent = getVideoTitle(); } } function updateSplitStatsDisplay() { const statsElement = document.getElementById(getElementId("split-stats")); if (statsElement) { const boughtMinutes = splitMinutes === null ? 0 : splitMinutes; statsElement.textContent = `Выкуплено: ${boughtMinutes} / Всего: ${totalVideoMinutes !== null ? totalVideoMinutes : '?'} минут`; } if (overlay) updateOverlayRemainingMinutes(); } function modifySplitInput(minutesToModify) { const inputField = document.getElementById(getElementId("split-input")); if (!inputField) return; let currentVal = inputField.valueAsNumber; if (isNaN(currentVal)) currentVal = 0; let newVal = currentVal + minutesToModify; if (newVal < 0) newVal = 0; inputField.valueAsNumber = newVal; } function modifyTimerInputOverlay(secondsToModify) { const inputField = document.getElementById(getElementId("overlay-timer-input")); if (!inputField) return; let currentVal = inputField.valueAsNumber; if (isNaN(currentVal)) currentVal = 0; let newVal = currentVal + secondsToModify; if (newVal < 0) newVal = 0; inputField.valueAsNumber = newVal; overlayTimerDuration = newVal; localStorage.setItem(localStorageTimerKey, overlayTimerDuration.toString()); overlayCountdownRemaining = overlayTimerDuration; if (overlayCountdownRemaining < 0) overlayCountdownRemaining = 0; if (overlayTimerIntervalId) { clearInterval(overlayTimerIntervalId); overlayTimerIntervalId = null; } updateOverlayTimer(); if (overlayTimerDuration > 0) { overlayTimerIntervalId = setInterval(updateOverlayTimer, 1000); } } function startSplitCheckInterval() { if (!splitCheckIntervalId) { splitCheckIntervalId = setInterval(checkSplitCondition, 500); GM_log(`[${currentPlatform || 'unknown'}] Split check interval started.`); } } function stopSplitCheckInterval() { if (splitCheckIntervalId) { clearInterval(splitCheckIntervalId); splitCheckIntervalId = null; GM_log(`[${currentPlatform || 'unknown'}] Split check interval stopped.`); } } function addMinutesToActiveSplit(minutesToAdd) { if (splitMinutes === null) return; splitMinutes += minutesToAdd; updateSplitDisplay(); const thresholdSeconds = splitMinutes * 60; // If video is before the new threshold AND overlay was active, remove overlay if (video && isFinite(video.currentTime) && video.currentTime < thresholdSeconds && splitTriggered) { GM_log(`[${currentPlatform}] Added minutes, new split threshold ${thresholdSeconds}s. Current time ${video.currentTime.toFixed(1)}s is before threshold. Removing overlay.`); removeOverlay(); splitTriggered = false; // Reset the flag // Resume video if it was paused by the split, UNLESS the user paused it manually // This is tricky - simply attempting play is the most straightforward approach if (video.paused) { GM_log(`[${currentPlatform}] Attempting to play video after adding minutes.`); video.play().catch(e => GM_log(`[${currentPlatform}] Error playing video after adding minutes: ${e.message}`)); } } GM_log(`[${currentPlatform}] Added ${minutesToAdd} minutes. New split: ${splitMinutes} minutes (${splitMinutes*60}s).`); } function updateOverlayTimer() { const timerElement = document.getElementById(getElementId('overlay-timer')); if (!timerElement) { if (overlayTimerIntervalId) { clearInterval(overlayTimerIntervalId); overlayTimerIntervalId = null; } return; } if (overlayCountdownRemaining > 0) { const minutes = Math.floor(overlayCountdownRemaining / 60); const seconds = overlayCountdownRemaining % 60; timerElement.textContent = `ЖДЕМ ${minutes}:${seconds < 10 ? '0' : ''}${seconds}, ИНАЧЕ СКИП`; overlayCountdownRemaining--; } else { timerElement.textContent = `ЖДЕМ 0:00, ИНАЧЕ СКИП`; // Timer reached 0. Decide what to do? Maybe jump ahead or just stay paused? // Current logic: stay paused and wait for user interaction (add minutes) or manual resume. if (overlayTimerIntervalId) { clearInterval(overlayTimerIntervalId); overlayTimerIntervalId = null; } } } function updateOverlayRemainingMinutes() { const remainingElement = document.getElementById(getElementId('overlay-remaining-minutes')); if (remainingElement) { const remainingMinutes = totalVideoMinutes !== null && splitMinutes !== null ? Math.max(0, totalVideoMinutes - splitMinutes) : '?'; remainingElement.textContent = `ОСТАЛОСЬ ${remainingMinutes} минут выкупить`; } } // Function to try and prime the audio context (help bypass autoplay) // This attempts to play a muted sound on the video's first 'play' event. function primeAudio() { // Only attempt if audio player exists, video exists, and we haven't added the listener for this video instance yet if (audioPlayer && video && !videoPlayListenerAdded) { GM_log(`[${currentPlatform}] Adding 'play' listener to video for audio priming.`); // Store the listener function to be able to remove it later if needed (e.g. on reset) const listener = function _listener() { GM_log(`[${currentPlatform}] Video started playing. Attempting to prime audio...`); // Check if audioPlayer is still valid when the event fires if (!audioPlayer) { GM_log(`[${currentPlatform}] Audio player became null before priming attempt. (Likely due to load error)`); return; // Cannot prime if player is null } // Try to play a muted sound immediately const originalVolume = audioPlayer.volume; audioPlayer.volume = 0; // Play muted audioPlayer.play().then(() => { GM_log(`[${currentPlatform}] Audio priming successful (muted playback started).`); audioPrimed = true; // Pause the muted sound immediately, unless it finished already (very short sound) if (!audioPlayer.paused) { audioPlayer.pause(); } audioPlayer.currentTime = 0; // Reset sound position audioPlayer.volume = originalVolume; // Restore volume }).catch(e => { GM_log(`[${currentPlatform}] Audio priming play() Promise rejected: ${e.message}. This may be due to browser autoplay policies preventing even muted playback without stronger user gesture.`); audioPrimed = false; // Priming failed audioPlayer.volume = originalVolume; // Restore volume }); // Remove the listener after it triggers once. // Using { once: true } is the modern way. videoPlayListenerAdded = true; // Mark the listener as added for this video instance }; // Add the listener using { once: true } for automatic removal after first trigger video.addEventListener('play', listener, { once: true }); // Also set the flag immediately to prevent adding multiple listeners via the interval videoPlayListenerAdded = true; } else if (!audioPlayer) { // GM_log(`[${currentPlatform}] Audio player not initialized, cannot prime audio.`); } else if (!video) { // GM_log(`[${currentPlatform}] Video element not found yet, cannot prime audio.`); } else if (videoPlayListenerAdded) { // GM_log(`[${currentPlatform}] 'play' listener already added for this video.`); } } function checkSplitCondition() { if (!platformConfig) return; // Ensure video element is found and audio player is initialized/primed if (!video) { video = document.querySelector(platformConfig.videoSelector); if (!video) return; // Exit if video element isn't available yet GM_log(`[${currentPlatform}] Video element found during split check.`); // Initialize audio player and attempt priming immediately upon finding video initAudioPlayer(); primeAudio(); const volumeSlider = document.getElementById(getElementId('split-volume-slider')); if (audioPlayer && volumeSlider) { try { audioPlayer.volume = parseFloat(volumeSlider.value); } catch(e){} } } // Get total video duration if available and not already set if (video && totalVideoMinutes === null && isFinite(video.duration) && video.duration > 0) { totalVideoMinutes = Math.ceil(video.duration / 60); GM_log(`[${currentPlatform}] Total video duration found: ${totalVideoMinutes} minutes.`); if (panelAdded) updateSplitStatsDisplay(); } // Note: Handling live streams or cases where duration changes might require more logic. // For now, totalVideoMinutes is set once if a valid duration is found. // Check the split condition only if splitMinutes is set and greater than 0, and video exists if (video && splitMinutes !== null && splitMinutes > 0) { const thresholdSeconds = splitMinutes * 60; // Trigger split if current time is at or past the threshold AND split hasn't been triggered yet for this segment if (isFinite(video.currentTime) && video.currentTime >= thresholdSeconds && !splitTriggered) { GM_log(`[${currentPlatform}] Split condition met at ${video.currentTime.toFixed(1)}s (threshold: ${thresholdSeconds}s). Triggering split...`); video.pause(); // Pause the video splitTriggered = true; // Set the flag to prevent re-triggering showOverlay(); // Show the overlay // Play the alert sound ONLY if audioPlayer exists (i.e., it loaded successfully) if (audioPlayer) { try { // Pause and reset *before* playing to ensure it starts from the beginning each time audioPlayer.pause(); audioPlayer.currentTime = 0; GM_log(`[${currentPlatform}] Attempting to play split sound.`); // Log before playing // Play the sound and log the promise result audioPlayer.play().then(() => { GM_log(`[${currentPlatform}] Split sound play() Promise resolved successfully.`); }).catch(e => { // This catch block specifically handles rejections from the play() promise GM_log(`[${currentPlatform}] Split sound play() Promise rejected: ${e.message}. This may be due to browser autoplay policies.`); console.error("Universal Split: Ошибка воспроизведения звука (вероятно, политика автоплея):", e); }); } catch(e) { // This catch block handles synchronous errors (e.g., audioPlayer became null unexpectedly) GM_log(`[${currentPlatform}] Error during audio playback attempt (sync error?): ${e.message}`); console.error("Universal Split: Синхронная ошибка при попытке воспроизведения звука:", e); } } else { GM_log(`[${currentPlatform}] audioPlayer is null, cannot play split sound. (Likely due to load error)`); // If audioPlayer is null here, it means initAudioPlayer failed earlier (due to format or blocked error) // We don't try to re-initialize immediately here, as it might hit the same error. } } // Handle the case where the user *manually seeks back* before the split point while the overlay is active if (splitTriggered && isFinite(video.currentTime) && video.currentTime < thresholdSeconds) { GM_log(`[${currentPlatform}] Video time (${video.currentTime.toFixed(1)}s) is now before split threshold (${thresholdSeconds}s) after seeking back. Removing overlay.`); removeOverlay(); // Remove the overlay splitTriggered = false; // Reset the flag so it can trigger again if the user seeks forward // Resume video if it was paused by the split // This assumes if video.paused is true AND splitTriggered was true, the split paused it. // It's not perfect but works in most cases. if (video.paused) { GM_log(`[${currentPlatform}] Attempting to play video after seeking back past split point.`); video.play().catch(e => GM_log(`[${currentPlatform}] Attempted to play video after seeking back past split point failed: ${e.message}`)); } } } else if (splitTriggered) { // If splitMinutes is 0 or null, and the split was previously triggered, clean up GM_log(`[${currentPlatform}] Split cancelled (splitMinutes is ${splitMinutes}). Removing overlay.`); removeOverlay(); // Remove the overlay splitTriggered = false; // Reset the flag // No need to resume video here, as it would only be paused if splitMinutes > 0 initially. } } function showOverlay() { if (overlay) return; // Only show if not already visible if (!platformConfig) return; // Need config to proceed GM_log(`[${currentPlatform}] Showing split overlay.`); // Get video title for the overlay const videoTitle = getVideoTitle(); overlay = document.createElement("div"); overlay.id = getElementId("split-overlay"); overlay.className = 'split-overlay-universal'; // --- ADD VIDEO TITLE TO OVERLAY --- const titleElement = document.createElement("div"); titleElement.className = "overlay-video-title"; titleElement.textContent = videoTitle; overlay.appendChild(titleElement); // Add title at the top of the overlay // --- END ADD VIDEO TITLE TO OVERLAY --- const warningMessage = document.createElement("div"); warningMessage.className = "warning-message"; warningMessage.textContent = "⚠️ НУЖНО ДОНАТНОЕ ТОПЛИВО ⚠️"; overlay.appendChild(warningMessage); const mainMessage = document.createElement("div"); mainMessage.className = "main-message"; mainMessage.textContent = "СПЛИТ НЕ ОПЛАЧЕН"; overlay.appendChild(mainMessage); const timerElement = document.createElement("div"); timerElement.id = getElementId('overlay-timer'); timerElement.className = "overlay-timer"; overlay.appendChild(timerElement); const remainingMinutesElement = document.createElement("div"); remainingMinutesElement.id = getElementId('overlay-remaining-minutes'); remainingMinutesElement.className = "overlay-remaining-minutes"; overlay.appendChild(remainingMinutesElement); const overlayTimerControlGroup = document.createElement("div"); overlayTimerControlGroup.id = getElementId('overlay-timer-control'); overlayTimerControlGroup.className = "overlay-timer-control"; const timerLabel = document.createElement("label"); timerLabel.setAttribute("for", getElementId('overlay-timer-input')); timerLabel.textContent = "Таймер (сек):"; overlayTimerControlGroup.appendChild(timerLabel); const timerInputField = document.createElement("input"); timerInputField.type = "number"; timerInputField.id = getElementId('overlay-timer-input'); timerInputField.min = "0"; timerInputField.value = overlayTimerDuration; // Initialize with saved duration overlayTimerControlGroup.appendChild(timerInputField); const timerButtons = [ { text: '-60', seconds: -60 }, { text: '-10', seconds: -10 }, { text: '-5', seconds: -5 }, { text: '+5', seconds: 5 }, { text: '+10', seconds: 10 }, { text: '+60', seconds: 60 } ]; timerButtons.forEach(btnInfo => { const button = document.createElement("button"); button.textContent = btnInfo.text; button.dataset.seconds = btnInfo.seconds; overlayTimerControlGroup.appendChild(button); }); overlay.appendChild(overlayTimerControlGroup); const extendButtonsContainer = document.createElement("div"); extendButtonsContainer.id = getElementId('split-extend-buttons'); extendButtonsContainer.className = "extend-buttons"; const extendButtonConfigs = [ { minutes: 1, cost: extendCost }, { minutes: 5, cost: extendCost * 5 }, { minutes: 10, cost: extendCost * 10 }, { minutes: 20, cost: extendCost * 20 } ]; extendButtonConfigs.forEach(config => { const button = document.createElement("button"); button.textContent = `+ ${config.minutes} минут${getMinuteEnding(config.minutes)} - ${config.cost} рублей`; button.addEventListener("click", () => addMinutesToActiveSplit(config.minutes)); extendButtonsContainer.appendChild(button); }); overlay.appendChild(extendButtonsContainer); const gifElement = document.createElement("img"); gifElement.src = overlayGifUrl; gifElement.alt = "Split GIF"; overlay.appendChild(gifElement); document.body.appendChild(overlay); // Add overlay to the DOM // Add event listeners for timer controls *after* adding to DOM overlay.querySelector(`#${getElementId('overlay-timer-input')}`).addEventListener('input', function() { const val = this.valueAsNumber; if (!isNaN(val) && val >= 0) { overlayTimerDuration = val; localStorage.setItem(localStorageTimerKey, overlayTimerDuration.toString()); overlayCountdownRemaining = overlayTimerDuration; // Reset countdown when duration changes if (overlayTimerIntervalId) { clearInterval(overlayTimerIntervalId); overlayTimerIntervalId = null; } if (overlayTimerDuration > 0) overlayTimerIntervalId = setInterval(updateOverlayTimer, 1000); updateOverlayTimer(); // Update immediately } else { /* Optional: revert to last valid value on invalid input */ } }); overlay.querySelectorAll(`#${getElementId('overlay-timer-control')} button`).forEach(button => { button.addEventListener("click", () => modifyTimerInputOverlay(parseInt(button.dataset.seconds, 10))); }); // Initialize and start the countdown timer overlayCountdownRemaining = overlayTimerDuration; // Start countdown from the set duration if (overlayCountdownRemaining < 0) overlayCountdownRemaining = 0; // Ensure non-negative updateOverlayTimer(); // Initial display update updateOverlayRemainingMinutes(); // Update remaining minutes display // Start timer interval if duration is positive, otherwise ensure it's stopped if (overlayTimerDuration > 0 && !overlayTimerIntervalId) { overlayTimerIntervalId = setInterval(updateOverlayTimer, 1000); } else if (overlayTimerDuration <= 0 && overlayTimerIntervalId) { clearInterval(overlayTimerIntervalId); overlayTimerIntervalId = null; } } function getMinuteEnding(count) { count = Math.abs(count); const d1 = count % 10; const d2 = count % 100; if (d2 >= 11 && d2 <= 19) return ''; if (d1 === 1) return 'а'; if (d1 >= 2 && d1 <= 4) return 'ы'; return ''; } function removeOverlay() { if (overlay) { GM_log(`[${currentPlatform || 'unknown'}] Removing split overlay.`); overlay.remove(); // Remove element from DOM overlay = null; // Clear the variable // Stop the timer interval if it's running if (overlayTimerIntervalId) { clearInterval(overlayTimerIntervalId); overlayTimerIntervalId = null; } // Pause the audio player if it's playing the alert sound if (audioPlayer) { try { audioPlayer.pause(); } catch(e){} } } } function initAudioPlayer() { // Only create a new Audio player if one doesn't exist AND we have a valid sound URL // The check `audioPlayer === null` is crucial here if a previous attempt failed. if (audioPlayer === null && splitSoundUrl && !splitSoundUrl.includes('YOUR_DIRECT_URL_HERE')) { GM_log(`[${currentPlatform || 'unknown'}] Initializing audio player with URL: ${splitSoundUrl}`); try { audioPlayer = new Audio(splitSoundUrl); audioPlayer.preload = 'auto'; // Start loading the audio early audioPlayer.loop = true; // IMPORTANT: Ensure the sound does NOT loop // Handle errors during loading/decoding audioPlayer.onerror = (e) => { const errorMsg = e.message || e.target.error?.message || 'Unknown error'; GM_log(`[${currentPlatform || 'unknown'}] ERROR loading audio: ${errorMsg}. Audio player will be null.`); console.error("Universal Split: Ошибка загрузки звука:", e); audioPlayer = null; // Explicitly set player to null on error audioPrimed = false; // Reset priming state videoPlayListenerAdded = false; // Reset listener flag // You might want to visually inform the user that sound won't work here. // alert("Ошибка загрузки звука для сплита. Проверьте URL звука или настройки браузера."); }; // Set volume from local storage or use the default let savedVolume = localStorage.getItem(localStorageVolumeKey) ?? defaultAlertVolume; audioPlayer.volume = parseFloat(savedVolume); // Add event listener to log when sound finishes playing (for debugging) audioPlayer.onended = () => { GM_log(`[${currentPlatform}] Split sound finished playing.`); }; audioPrimed = false; // Reset priming state for the new player instance videoPlayListenerAdded = false; // Reset video listener flag for the new player instance GM_log(`[${currentPlatform || 'unknown'}] Audio player object created.`); } catch (error) { // Handle errors that occur *during* the 'new Audio()' call itself GM_log(`[${currentPlatform || 'unknown'}] ERROR creating Audio object: ${error.message}`); console.error("Universal Split: Ошибка создания Audio:", error); audioPlayer = null; // Ensure player is null on creation error audioPrimed = false; videoPlayListenerAdded = false; } } else if (audioPlayer !== null) { // If audioPlayer exists AND is not null (meaning it didn't fail loading earlier) // If player already exists, just ensure settings are correct (e.g., after navigation) let savedVolume = localStorage.getItem(localStorageVolumeKey) ?? defaultAlertVolume; try { audioPlayer.volume = parseFloat(savedVolume); } catch(e){} audioPlayer.loop = true; // Double-check loop is false // Re-add onended listener if needed (usually persists unless player was null) if (!audioPlayer.onended) { audioPlayer.onended = () => { GM_log(`[${currentPlatform}] Split sound finished playing.`); }; } // audioPrimed and videoPlayListenerAdded state persist with the existing audioPlayer instance } // If audioPlayer is still null here, it means init failed and we don't have a player. } // --- ФУНКЦИИ УПРАВЛЕНИЯ ПАНЕЛЬЮ --- function addControlPanel() { // Prevent adding the panel if it's already added or if no config is available if (panelAdded || !platformConfig) return; const insertionElement = document.querySelector(platformConfig.insertionSelector); // We need the insertion element to place the panel if (!insertionElement) { GM_log(`[${currentPlatform}] Insertion element (${platformConfig.insertionSelector}) not found.`); return; } GM_log(`[${currentPlatform}] Adding control panel...`); panelElement = document.createElement("div"); panelElement.id = getElementId("split-control-panel"); panelElement.className = 'split-control-panel-universal'; // Apply universal styles + platform-specific via id // --- GET VIDEO TITLE FOR PANEL AND ADD TO PANEL --- const videoTitle = getVideoTitle(); // Use the helper function const panelTitleElement = document.createElement("div"); panelTitleElement.className = "panel-video-title"; panelTitleElement.textContent = videoTitle; panelElement.appendChild(panelTitleElement); // Add title at the top // --- END ADD VIDEO TITLE TO PANEL --- // --- Create a row for controls and stats to manage layout --- const controlsRow = document.createElement("div"); controlsRow.className = "panel-controls-row"; const setButton = document.createElement("button"); setButton.id = getElementId('set-split-button'); setButton.className = 'set-split-button'; setButton.textContent = "НАЧАТЬ СПЛИТ"; // Set button text and class based on current split state if (splitMinutes !== null && splitMinutes > 0) { setButton.textContent = "СПЛИТ НАЧАТ"; setButton.classList.add("active"); } controlsRow.appendChild(setButton); // Add set button to the row const splitLabel = document.createElement("label"); splitLabel.setAttribute("for", getElementId('split-input')); splitLabel.appendChild(document.createTextNode("Сплит (мин):")); const splitLabelInstruction = document.createElement("i"); splitLabelInstruction.textContent = "(уст. перед \"Начать\")"; splitLabel.appendChild(splitLabelInstruction); controlsRow.appendChild(splitLabel); // Add label to the row const splitInputGroup = document.createElement("div"); splitInputGroup.id = getElementId('split-input-group'); splitInputGroup.className = 'split-input-group'; const splitInputField = document.createElement("input"); splitInputField.type = "number"; splitInputField.id = getElementId('split-input'); splitInputField.min = "0"; splitInputField.value = splitMinutes === null ? 0 : splitMinutes; // Initialize input with current split state splitInputGroup.appendChild(splitInputField); const splitModifyButtons = [ { text: '+1', minutes: 1 }, { text: '+5', minutes: 5 }, { text: '+10', minutes: 10 }, { text: '+20', minutes: 20 } ]; splitModifyButtons.forEach(btnInfo => { const button = document.createElement("button"); button.textContent = btnInfo.text; button.dataset.minutes = btnInfo.minutes; splitInputGroup.appendChild(button); }); controlsRow.appendChild(splitInputGroup); // Add input group to the row const volumeControlGroup = document.createElement("div"); volumeControlGroup.id = getElementId('split-volume-control'); volumeControlGroup.className = 'split-volume-control'; const volumeLabel = document.createElement("label"); volumeLabel.setAttribute("for", getElementId('split-volume-slider')); volumeLabel.textContent = "Громк. алерта:"; const volumeSlider = document.createElement("input"); volumeSlider.type = "range"; volumeSlider.id = getElementId('split-volume-slider'); volumeSlider.min = "0"; volumeSlider.max = "1"; volumeSlider.step = "0.05"; volumeSlider.value = localStorage.getItem(localStorageVolumeKey) ?? defaultAlertVolume; // Initialize slider with saved volume or default volumeControlGroup.appendChild(volumeLabel); volumeControlGroup.appendChild(volumeSlider); controlsRow.appendChild(volumeControlGroup); // Add volume control to the row const statsElement = document.createElement("span"); statsElement.id = getElementId('split-stats'); statsElement.className = 'split-stats'; statsElement.textContent = "Выкуплено: 0 / Всего: ? минут"; // Initial text, updated by updateSplitDisplay/Stats panelElement.appendChild(controlsRow); // Add the row containing controls (button, input, volume) panelElement.appendChild(statsElement); // Add stats element below the controls row // Insert the panel into the DOM according to platform config switch (platformConfig.insertionMethod) { case 'prepend': insertionElement.insertBefore(panelElement, insertionElement.firstChild); break; case 'appendChild': insertionElement.appendChild(panelElement); break; case 'before': insertionElement.parentNode.insertBefore(panelElement, insertionElement); break; case 'afterend': insertionElement.parentNode.insertBefore(panelElement, insertionElement.nextSibling); break; default: insertionElement.insertBefore(panelElement, insertionElement.firstChild); // Default to prepend } panelAdded = true; // Mark panel as added // --- Event Listeners --- setButton.addEventListener("click", () => { const inputVal = parseInt(splitInputField.value, 10); if (!isNaN(inputVal) && inputVal >= 0) { splitMinutes = inputVal; // Set the global splitMinutes state if (splitMinutes > 0) { startSplitCheckInterval(); // Start the interval if split is active setButton.textContent = "СПЛИТ НАЧАТ"; setButton.classList.add("active"); // Attempt autoplay if video is paused when split starts if (video && video.paused) { GM_log(`[${currentPlatform}] Attempting to play video on split start...`); video.play().catch(e => GM_log(`[${currentPlatform}] Autoplay on split start failed (likely autoplay policy): ${e.message}`)); } } else { // splitMinutes is 0 or set to 0 stopSplitCheckInterval(); // Stop the interval if split is disabled splitTriggered = false; // Ensure the triggered flag is false removeOverlay(); // Remove overlay if it was visible setButton.textContent = "НАЧАТЬ СПЛИТ"; setButton.classList.remove("active"); } updateSplitDisplay(); // Update stats/input field display } else { alert("Введите корректное число минут."); splitInputField.valueAsNumber = splitMinutes === null ? 0 : splitMinutes; // Revert input to last valid value } }); splitInputGroup.querySelectorAll("button").forEach(button => { button.addEventListener("click", () => modifySplitInput(parseInt(button.dataset.minutes, 10))); }); volumeSlider.addEventListener("input", function() { const newVolume = parseFloat(this.value); if (audioPlayer) audioPlayer.volume = newVolume; // Update audio player volume localStorage.setItem(localStorageVolumeKey, newVolume.toString()); // Save volume preference }); updateSplitDisplay(); // Initial update for stats and input field (in case splitMinutes was restored) // Initialize visibility check for VK if required by the platform if (platformConfig.needsVisibilityCheck) { controlsElement = document.querySelector(platformConfig.controlsElementSelector); if (controlsElement) startVisibilityCheckInterval(); else GM_log(`[${currentPlatform}] Native controls element (${platformConfig.controlsElementSelector}) not found for visibility check.`); } // Start the split check interval if split was already active (e.g., after page reload/navigation) if (splitMinutes !== null && splitMinutes > 0) { startSplitCheckInterval(); } else { stopSplitCheckInterval(); // Ensure it's stopped if split is off } GM_log(`[${currentPlatform}] Control panel added successfully.`); } // Ensures the panel stays in the correct place on sites with dynamic layouts function ensurePanelPosition() { if (!panelAdded || !panelElement || !platformConfig) return; const insertionElement = document.querySelector(platformConfig.insertionSelector); // If the element we attach to is gone, remove the panel if (!insertionElement) { GM_log(`[${currentPlatform}] Insertion element (${platformConfig.insertionSelector}) disappeared. Removing panel.`); removeControlPanel(); return; } // Check if the panel element is currently positioned correctly relative to the insertion element let currentPositionCorrect = false; switch(platformConfig.insertionMethod) { case 'prepend': currentPositionCorrect = (insertionElement.firstChild === panelElement); break; case 'appendChild': currentPositionCorrect = (insertionElement.lastChild === panelElement); break; case 'before': currentPositionCorrect = (insertionElement.previousSibling === panelElement); break; case 'afterend': currentPositionCorrect = (insertionElement.nextSibling === panelElement); break; default: currentPositionCorrect = (insertionElement.firstChild === panelElement); // Assume prepend if method is undefined } // Also check if the panel is still a child of *any* element (it might have been removed by site JS) if (!panelElement.parentNode) { currentPositionCorrect = false; // It's definitely not in the correct position if it's not attached anywhere GM_log(`[${currentPlatform}] Panel element detached from DOM. Attempting re-insertion.`); } if (!currentPositionCorrect) { GM_log(`[${currentPlatform}] Panel position incorrect or detached. Attempting re-insertion...`); try { // Remove the element from its current parent before re-inserting if (panelElement.parentNode) { panelElement.parentNode.removeChild(panelElement); } // Re-insert according to the configured method switch(platformConfig.insertionMethod) { case 'prepend': insertionElement.insertBefore(panelElement, insertionElement.firstChild); break; case 'appendChild': insertionElement.appendChild(panelElement); break; case 'before': insertionElement.parentNode.insertBefore(panelElement, insertionElement); break; case 'afterend': insertionElement.parentNode.insertBefore(panelElement, insertionElement.nextSibling); break; default: insertionElement.insertBefore(panelElement, insertionElement.firstChild); } GM_log(`[${currentPlatform}] Panel re-inserted successfully.`); // Update the title text after re-insertion, as it might have been reset const panelTitleElement = panelElement?.querySelector('.panel-video-title'); if (panelTitleElement) { panelTitleElement.textContent = getVideoTitle(); } } catch (e) { GM_log(`[${currentPlatform}] Failed to re-insert panel: ${e.message}`); removeControlPanel(); // If re-insertion fails, remove the panel to avoid further errors } } else { // If position is correct, just update the title text in case the video changed without a full navigation const panelTitleElement = panelElement?.querySelector('.panel-video-title'); if (panelTitleElement) { const currentTitle = panelTitleElement.textContent.trim(); const latestTitle = getVideoTitle(); if (currentTitle !== latestTitle) { GM_log(`[${currentPlatform}] Panel title out of sync. Updating title.`); panelTitleElement.textContent = latestTitle; } } } } function removeControlPanel() { if (panelElement) { try { panelElement.remove(); // Remove element from DOM GM_log(`[${currentPlatform || 'unknown'}] Control panel element removed.`); } catch (e) { GM_log(`[${currentPlatform || 'unknown'}] Error removing panel element: ${e.message}`); } panelElement = null; // Clear the variable } panelAdded = false; // Mark panel as removed stopVisibilityCheckInterval(); // Stop the VK visibility check controlsElement = null; // Clear the controls element reference // Note: splitMinutes and totalVideoMinutes state are *not* reset here, allowing them to persist across navigation. } // --- СПЕЦИФИЧНЫЕ ФУНКЦИИ ДЛЯ VK (Видимость панели) --- function checkControlsVisibility() { // Only run if VK, and if both the panel and controls elements exist if (!panelElement || !controlsElement || currentPlatform !== 'vk') { // If VK, but elements are missing, stop check and clean up if (currentPlatform === 'vk' && (!controlsElement || !panelElement)) { GM_log(`[${currentPlatform}] Controls or panel element missing during visibility check. Stopping check and potentially removing panel.`); stopVisibilityCheckInterval(); if (!panelElement) removeControlPanel(); // Only remove if panel itself is gone } return; } // Check VK's common methods for hiding controls const isHiddenByStyle = controlsElement.style.display === 'none'; const isHiddenByClass = controlsElement.classList.contains('hidden') || controlsElement.classList.contains('videoplayer_controls_hide'); const controlsAreVisible = !isHiddenByStyle && !isHiddenByClass; // Toggle the 'visible' class on the panel based on native controls visibility if (controlsAreVisible && !panelElement.classList.contains('visible')) { panelElement.classList.add('visible'); } else if (!controlsAreVisible && panelElement.classList.contains('visible')) { panelElement.classList.remove('visible'); } } function startVisibilityCheckInterval() { // Only start if VK, required, interval not running, and controls element found if (!visibilityCheckIntervalId && platformConfig?.needsVisibilityCheck && currentPlatform === 'vk' && controlsElement) { GM_log(`[${currentPlatform}] Starting controls visibility check interval.`); visibilityCheckIntervalId = setInterval(checkControlsVisibility, 300); checkControlsVisibility(); // Run immediately on start } } function stopVisibilityCheckInterval() { if (visibilityCheckIntervalId) { GM_log(`[${currentPlatform}] Stopping controls visibility check interval.`); clearInterval(visibilityCheckIntervalId); visibilityCheckIntervalId = null; } } // --- ОПРЕДЕЛЕНИЕ ТЕКУЩЕЙ ПЛАТФОРМЫ --- function getCurrentPlatform() { const hostname = location.hostname; const pathname = location.pathname; if (hostname.includes('vk.com')) { if (pathname.includes('/video_ext.php')) return 'vk'; } else if (hostname.includes('vkvideo.ru')) { if (pathname.includes('/video_ext.php')) return 'vk'; } // Treat vkvideo.ru the same as vk.com else if (hostname.includes('rutube.ru')) { if (pathname.startsWith('/video/')) return 'rutube'; } else if (hostname.includes('youtube.com')) { if (pathname.startsWith('/watch')) return 'youtube'; } return 'unknown'; // Return 'unknown' if none match } // --- СБРОС СОСТОЯНИЯ ПРИ СМЕНЕ ВИДЕО ИЛИ ПЛАТФОРМЫ --- function resetState() { const platformToLog = currentPlatform !== 'unknown' ? currentPlatform : 'Previous'; GM_log(`[${platformToLog}] Resetting state...`); // Stop all active intervals and observers managed by the script stopSplitCheckInterval(); stopVisibilityCheckInterval(); if (overlayTimerIntervalId) { clearInterval(overlayTimerIntervalId); overlayTimerIntervalId = null; } // Note: setupIntervalId is *not* cleared here, it's needed to re-setup on the new page // Remove UI elements from the DOM removeOverlay(); removeControlPanel(); // This also stops the VK visibility check // Reset state variables specific to the current video/split splitMinutes = null; // Clear the configured split time totalVideoMinutes = null; // Clear the total duration video = null; // Clear the video element reference splitTriggered = false; // Reset the split triggered flag audioPrimed = false; // Reset audio priming state for the new context videoPlayListenerAdded = false; // Reset the flag for adding the play listener for the new video element // Pause and reset audio player, but keep the player object for reuse unless it was null/errored if (audioPlayer) { try { audioPlayer.pause(); audioPlayer.currentTime = 0; } catch(e){ GM_log(`[${platformToLog}] Error resetting audio player: ${e.message}`); } } // Do NOT set audioPlayer to null here, as it might be reused for the next video unless load failed. // Reset overlay timer countdown, but keep the duration setting from local storage overlayCountdownRemaining = overlayTimerDuration; // Reset countdown using the saved duration } // --- ГЛАВНАЯ ФУНКЦИЯ НАСТРОЙКИ СКРИПТА НА СТРАНИЦЕ --- // This function is called periodically by setupIntervalId and by the MutationObserver on URL change. // It detects the platform, resets state if needed, and attempts to set up the UI and intervals. function setupPlatformSplit() { const detectedPlatform = getCurrentPlatform(); // Step 1: Detect platform change and reset if necessary if (detectedPlatform !== currentPlatform) { if (currentPlatform !== 'unknown') { GM_log(`Platform or video likely changed from ${currentPlatform} to ${detectedPlatform}. Resetting state for previous page...`); resetState(); } currentPlatform = detectedPlatform; // Update current platform state if (currentPlatform !== 'unknown') { platformConfig = platformConfigs[currentPlatform]; // Get configuration for the new platform GM_log(`[${currentPlatform}] Initializing for new platform...`); injectGlobalStyles(); // Re-inject styles (important for new platform styles) // initAudioPlayer() will be called below once video is found, if audioPlayer is null } else { platformConfig = null; // No config for unknown platform GM_log(`[Universal] Unknown platform detected (${location.href}), stopping setup interval.`); // If platform becomes unknown, stop the setup interval as we can't proceed if (setupIntervalId) { clearInterval(setupIntervalId); setupIntervalId = null; } return; // Exit if platform is unknown } } // Step 2: If we are on a recognized platform... if (currentPlatform !== 'unknown' && platformConfig) { // Always try to find the video element if (!video) { video = document.querySelector(platformConfig.videoSelector); if (video) { GM_log(`[${currentPlatform}] Video element found during setup.`); // When a *new* video element is found, try to initialize audio player if it's not already valid if (audioPlayer === null) { // Only try initializing if it's null (e.g., first load or previous load error) initAudioPlayer(); } } } // Attempt audio priming if we have a video and a valid audio player instance if (video && audioPlayer !== null) { primeAudio(); // Attempt to prime audio for this video/player instance } else if (video && audioPlayer === null) { // Video found, but audio player is null (likely due to previous load error) // Log message already happens in initAudioPlayer's onerror } // Step 3: If the panel is already added, ensure its position and sync state if (panelAdded) { ensurePanelPosition(); // Check and fix panel position; updates title // Re-check controls visibility for VK if necessary if (platformConfig.needsVisibilityCheck && currentPlatform === 'vk' && !visibilityCheckIntervalId) { controlsElement = document.querySelector(platformConfig.controlsElementSelector); // Re-find element if needed if (controlsElement) startVisibilityCheckInterval(); } // Re-start split check interval if split was active across navigation if (splitMinutes !== null && splitMinutes > 0 && !splitCheckIntervalId) { startSplitCheckInterval(); checkSplitCondition(); // Check condition immediately after restarting the interval } else if (splitCheckIntervalId && (splitMinutes === null || splitMinutes <= 0)) { stopSplitCheckInterval(); // Ensure interval is stopped if split is inactive } // The setupIntervalId remains active. } else { // Step 4: If panel is not yet added, try to find elements and add it const insertionElement = document.querySelector(platformConfig.insertionSelector); controlsElement = platformConfig.needsVisibilityCheck && currentPlatform === 'vk' ? document.querySelector(platformConfig.controlsElementSelector) : null; // Find controls for VK // If necessary elements are found (video, insertion point, and optionally VK controls), add the control panel // Check if video is not null as it's crucial for duration/current time if (video && insertionElement && (!platformConfig.needsVisibilityCheck || controlsElement)) { addControlPanel(); // This function handles adding the panel, listeners, and starting related intervals } else { // Elements not found yet. The setupIntervalId remains active and will call setupPlatformSplit again. // This is normal for SPAs or pages where elements load dynamically. // GM_log(`[${currentPlatform}] Needed elements not found yet for panel. Video: ${!!video}, Insertion: ${!!insertionElement}, VK Controls: ${platformConfig.needsVisibilityCheck ? !!controlsElement : 'N/A'}. Retrying...`); } } } // If platform is unknown, the interval was stopped earlier in this function. } // --- ИНИЦИАЛИЗАЦИЯ СКРИПТА И ОТСЛЕЖИВАНИЕ НАВИГАЦИИ --- function initialize() { GM_log(`Universal Video Split: Initializing (v${GM_info.script.version})...`); // Use GM_info for version lastUrl = location.href; // Store the initial URL // Start a persistent polling interval to repeatedly try setting up the script. // This handles pages where elements load asynchronously or are delayed, and acts // as a failsafe if the MutationObserver misses an event. // This interval will *not* stop itself after initial setup, ensuring continuous checks. if (!setupIntervalId) { setupIntervalId = setInterval(setupPlatformSplit, setupIntervalDelay); GM_log(`Setup interval started with ${setupIntervalDelay}ms delay.`); } // Use a MutationObserver to detect significant changes in the DOM, often indicative of SPA navigation. // This is more efficient than polling for URL changes constantly, but the interval provides a backup. // We observe the entire document body for childList and subtree changes. if (!navigationObserver) { navigationObserver = new MutationObserver((mutations) => { // Check if the URL has changed. This is the primary trigger for a "new page" event in an SPA. // We check location.href against our stored lastUrl. if (location.href !== lastUrl) { GM_log(`URL change detected by observer from ${lastUrl} to ${location.href}`); lastUrl = location.href; // Update the last known URL // When URL changes, reset the state related to the *previous* video/platform. // The persistent setupInterval will automatically detect the new platform/URL // on its next tick and run setupPlatformSplit accordingly. resetState(); // This stops specific intervals/observers but leaves setupIntervalId active. // No need to restart setupIntervalId here, as it's designed to be persistent. } else { // Optional: Add logic here to check for *other* significant DOM changes // if needed, but the current setupPlatformSplit should handle most cases // where elements appear late, even without a URL change. } }); // Observe changes in the body's subtree. childList and subtree are needed to catch element additions/removals during navigation. navigationObserver.observe(document.body, { childList: true, subtree: true }); GM_log("MutationObserver for navigation started."); } // Run setup once immediately on script load setupPlatformSplit(); } // --- Очистка при выходе со страницы --- window.addEventListener('beforeunload', () => { GM_log("Universal Video Split: Unloading, cleaning up..."); resetState(); // Perform a full reset of intervals, observers, and UI elements // Explicitly clear the setup interval on page unload if (setupIntervalId) { clearInterval(setupIntervalId); setupIntervalId = null; GM_log("Setup interval cleared on unload."); } // Disconnect the navigation observer on page unload if (navigationObserver) { navigationObserver.disconnect(); navigationObserver = null; GM_log("MutationObserver disconnected on unload."); } // Explicitly pause and nullify audioPlayer (though browser might handle this) if (audioPlayer) { try { audioPlayer.pause(); } catch(e){} audioPlayer = null; GM_log("Audio player cleared on unload."); } }); // --- Запуск скрипта --- initialize(); })();