Youtube - Resumer

Store video.currentTime locally

当前为 2023-11-19 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Youtube - Resumer
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Store video.currentTime locally
// @author       You
// @match        https://www.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant        GM.setValue
// @grant        GM.getValue
// @grant        GM_addStyle
// @license      MIT
// ==/UserScript==


function l(...args){
    console.log('[Resumer]', ...args)
}

function videoId(url=document.URL){
    return new URL(url).searchParams.get('v')
}

let lastTimeInSeconds
function save(video, id){
    const seconds = Math.floor(video.currentTime)
    if(lastTimeInSeconds != seconds){ // save less often
        let completion = video.currentTime / video.duration
        GM.setValue(id, video.currentTime)
        GM.setValue(id + '-completion', completion)
    }
    lastTimeInSeconds = seconds
}

function findVideo(onVideoFound){
    let videos = [] // for some reason there is more than 1 video found
    let removeListeners
    const observer = new MutationObserver((mutations, observer) => {
        // Keep trying to find video
        let video = document.querySelector('video')
        if(video){
            let alreadyFound = videos.includes(video)
            if(!alreadyFound){
                videos.push(video)

                l('videos found:', videos)
                if(removeListeners) removeListeners()
                removeListeners = onVideoFound(video)
            }
        }
    })
    observer.observe(document, {childList:true, subtree:true})
    return () => {
        observer.disconnect()
    }
}


let id = videoId() //if you use the miniplayer the url no longer includes the video id
function listen(video){
    let lastSrc

    function handleTimeUpdate(){
        l('timeupdate')
        //Video source is '' and duration is NaN when going back to the home page
        //When loading a new video, the event is fired with currentTime 0 and duration NaN
        if(video.src && !isNaN(video.duration)){
            l(id, lastId, video.src, lastSrc)
            if(id){
                save(video, id)
                lastSrc = video.src
            }else if(video.src === lastSrc){ //in case you click another video while using the miniplayer
                save(video, lastId) //save even if in miniplayer
            }
        }
    }

    video.addEventListener('timeupdate', handleTimeUpdate)
    return () => {
        video.removeEventListener('timeupdate', handleTimeUpdate)
    }
}

async function resume(video){
    id = videoId() // set id here because in firefox the url changes before navigate-finish completes
    let lastTime = await GM.getValue(id)
    if(lastTime){
        l('resuming', id, video.currentTime, lastTime)
        video.currentTime = lastTime
    }else{
        l('new', video.currentTime)
    }
}

function cleanUrl(){
    //Remove t paramater when opening a video that had a progress bar
    let url = new URL(document.URL)
    url.searchParams.delete('t')
    window.history.replaceState(null, null, url)
}

let lastId // don't resume if going back to same page from miniplayer

let cleanListeners
// Event for each page change
document.addEventListener("yt-navigate-finish", () => {
    l('navigate-finish', lastId, videoId())
    // video page
    if(videoId() && lastId !== videoId()) {
        lastId = videoId()
        cleanUrl()

        if(cleanListeners) cleanListeners()
        cleanListeners = findVideo(video => {
            resume(video)
            return listen(video)
        })
    }
})

/////////////////////


function addProgressBar(thumbnail, completion){
    let overlays = thumbnail.querySelector('#overlays')
    let existingProgressBar = thumbnail.querySelector('ytd-thumbnail-overlay-resume-playback-renderer')
    if(!existingProgressBar) {
        let parent = document.createElement('div')
        parent.innerHTML = `
        <ytd-thumbnail-overlay-resume-playback-renderer class="style-scope ytd-thumbnail">
             <div id="progress" class="style-scope ytd-thumbnail-overlay-resume-playback-renderer" style="width: 100%"></div>
        </ytd-thumbnail-overlay-resume-playback-renderer>
        `
        overlays.appendChild(parent.children[0])
    }

    // style
    let progress = overlays.querySelector('#progress')
    let width = parseInt(completion * 100)
    progress.style.width = `${width}%`
    progress.style.backgroundColor = 'blue'
}

function progressBars(){
    // Add progress bars in the related section
    const observer = new MutationObserver(async (mutations, observer) => {
        for(let mutation of mutations){
            if(mutation.addedNodes.length > 0) {
                let thumbnails = mutation.target.querySelectorAll('a.ytd-thumbnail')
                for(let thumbnail of thumbnails){
                    let href = thumbnail.href
                    if(href) {
                        let id = videoId(href)
                        let completion = await GM.getValue(id + '-completion')
                        if(completion) {
                            addProgressBar(thumbnail, completion)
                        }
                    }
                }
            }
        }
    })
    observer.observe(document, {childList:true, subtree:true})
}

progressBars() // TODO doesn't always work