B站合集、列表时间查询

实现B站合集的总时长、观看时长、剩余时长

当前为 2024-08-26 提交的版本,查看 最新版本

// ==UserScript==
// @name         B站合集、列表时间查询
// @namespace    http://tampermonkey.net/
// @version      3
// @description  实现B站合集的总时长、观看时长、剩余时长
// @author       Lint
// @match        https://www.bilibili.com/video/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=greasyfork.org
// @grant        none
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // 创建时间显示的元素
    const timeDisplay = document.createElement('div');
    timeDisplay.id = 'time-display';
    timeDisplay.style.position = 'fixed';
    timeDisplay.style.left = '10px';
    timeDisplay.style.bottom = '10px';
    timeDisplay.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    timeDisplay.style.color = 'white';
    timeDisplay.style.padding = '10px';
    timeDisplay.style.borderRadius = '5px';
    // 为时长按钮添加重叠优先级,防止被其他元素覆盖
    timeDisplay.style.zIndex = '9999999999';
    document.body.appendChild(timeDisplay);

    // 创建按钮容器,使按钮并排显示
    const buttonContainer = document.createElement('div');
    buttonContainer.style.position = 'fixed';
    buttonContainer.style.right = '10px';
    buttonContainer.style.bottom = '10px';
    buttonContainer.style.zIndex = '10000000000';
    document.body.appendChild(buttonContainer);

    // 创建更新/开启时间按钮
    const executeButton = document.createElement('button');
    executeButton.id = 'execute-button';
    executeButton.textContent = '更新/开启';
    executeButton.style.display = 'inline-block';
    executeButton.style.backgroundColor = '#007BFF';
    executeButton.style.color = 'white';
    executeButton.style.border = 'none';
    executeButton.style.padding = '5px';
    executeButton.style.fontSize = '12px';
    executeButton.style.borderRadius = '3px';
    executeButton.style.cursor = 'pointer';
    executeButton.style.marginRight = '5px'; // 与关闭按钮之间的间距
    executeButton.onmouseover = () => executeButton.style.backgroundColor = '#0056b3';
    executeButton.onmouseout = () => executeButton.style.backgroundColor = '#007BFF';
    buttonContainer.appendChild(executeButton);
    // 为按钮添加点击事件,更新时间并重新显示时间窗口(如果已关闭)
    executeButton.onclick = () => {
        if (timeDisplay.style.display === 'none') {
            timeDisplay.style.display = 'block';
        }
        updateDurations();
    };

    // 创建关闭时间窗口的按钮
    const closeButton = document.createElement('button');
    closeButton.id = 'close-button';
    closeButton.textContent = '关闭';
    closeButton.style.display = 'inline-block';
    closeButton.style.backgroundColor = '#DC3545';
    closeButton.style.color = 'white';
    closeButton.style.border = 'none';
    closeButton.style.padding = '5px';
    closeButton.style.fontSize = '12px';
    closeButton.style.borderRadius = '3px';
    closeButton.style.cursor = 'pointer';
    closeButton.onmouseover = () => closeButton.style.backgroundColor = '#C82333';
    closeButton.onmouseout = () => closeButton.style.backgroundColor = '#DC3545';
    buttonContainer.appendChild(closeButton);
    // 为关闭按钮添加点击事件,关闭时间显示窗口
    closeButton.onclick = () => {
        timeDisplay.style.display = 'none';
    };


    // 格式化时长函数
    function formatDuration(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const remainingSeconds = seconds % 60;
        return `${hours}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    }

    // 解析时长并转换为秒的函数
    function parseDuration(durationText) {
        const timeParts = durationText.trim().split(':').map(Number);
        let seconds = 0;
        if (timeParts.length === 3) {
            // 如果包含小时部分
            const [hours, minutes, secs] = timeParts;
            seconds = hours * 3600 + minutes * 60 + secs;
        } else if (timeParts.length === 2) {
            // 如果只有分钟和秒
            const [minutes, secs] = timeParts;
            seconds = minutes * 60 + secs;
        }
        return seconds;
    }

    // 计算时长的函数
    function calculateDurations(durationsInSeconds, currentVideoIndex) {
        const totalDurationInSeconds = durationsInSeconds.reduce((total, duration) => total + duration, 0);
        const watchedDurationInSeconds = durationsInSeconds.slice(0, currentVideoIndex).reduce((total, duration) => total + duration, 0);
        const currentVideoProgressInSeconds = 0; // 假设当前视频的观看进度为0,需要根据实际情况调整
        const totalWatchedDurationInSeconds = watchedDurationInSeconds + currentVideoProgressInSeconds;
        const remainingDurationInSeconds = totalDurationInSeconds - totalWatchedDurationInSeconds;
        return {
            totalDurationInSeconds,
            totalWatchedDurationInSeconds,
            remainingDurationInSeconds
        };
    }

    // 更新合集时长的函数
    function updateCollectionDurations() {
        const currentPageElement = document.querySelector('.cur-page');
        if (!currentPageElement) return false;
        const [currentVideoIndex, totalVideos] = currentPageElement.textContent.match(/\d+/g).map(Number);
        const currentVideoZeroBasedIndex = currentVideoIndex - 1;

        const videoDurations = document.querySelectorAll('.video-episode-card__info-duration');
        if (videoDurations.length === 0) return false;

        const durationsInSeconds = Array.from(videoDurations).map(durationElement => parseDuration(durationElement.textContent));

        const { totalDurationInSeconds, totalWatchedDurationInSeconds, remainingDurationInSeconds } = calculateDurations(durationsInSeconds, currentVideoZeroBasedIndex);

        timeDisplay.innerHTML = `
            总时长: ${formatDuration(totalDurationInSeconds)}<br>
            已观看时长: ${formatDuration(totalWatchedDurationInSeconds)}<br>
            剩余时长: ${formatDuration(remainingDurationInSeconds)}
        `;
        return true;
    }

    // 更新列表时长的函数
    function updateListDurations() {
        const listBox = document.querySelector('.list-box');
        if (!listBox) return false;

        const videoItems = listBox.querySelectorAll('li');
        if (videoItems.length === 0) return false;

        const durationsInSeconds = Array.from(videoItems).map(item => {
            const durationElement = item.querySelector('.duration');
            return durationElement ? parseDuration(durationElement.textContent) : 0;
        });

        const currentVideoItem = listBox.querySelector('.on');
        if (!currentVideoItem) return false;

        const currentVideoIndex = Array.from(videoItems).indexOf(currentVideoItem);

        const { totalDurationInSeconds, totalWatchedDurationInSeconds, remainingDurationInSeconds } = calculateDurations(durationsInSeconds, currentVideoIndex);

        timeDisplay.innerHTML = `
            总时长: ${formatDuration(totalDurationInSeconds)}<br>
            已观看时长: ${formatDuration(totalWatchedDurationInSeconds)}<br>
            剩余时长: ${formatDuration(remainingDurationInSeconds)}
        `;
        return true;
    }

    // 更新时长的主函数
    function updateDurations() {
        if (!updateCollectionDurations()) {
            updateListDurations();
        }
    }

    // 初始延迟2000ms执行一次,避免第一次载入网址时无法及时加载数据而导致时长为0
    setTimeout(function(){
        // 初始加载时执行一次
        updateDurations();
    },2000);
})();