// ==UserScript==
// @name B站稍后再看功能增强
// @version 4.37.4.20240827
// @namespace laster2800
// @author Laster2800
// @description 与稍后再看功能相关,一切你能想到和想不到的功能
// @icon https://www.bilibili.com/favicon.ico
// @homepageURL https://greasyfork.org/zh-CN/scripts/395456
// @supportURL https://greasyfork.org/zh-CN/scripts/395456/feedback
// @license LGPL-3.0
// @include *://www.bilibili.com/*
// @include *://t.bilibili.com/*
// @include *://message.bilibili.com/*
// @include *://search.bilibili.com/*
// @include *://space.bilibili.com/*
// @include *://account.bilibili.com/*
// @exclude *://message.bilibili.com/*/*
// @exclude *://t.bilibili.com/h5/*
// @exclude *://www.bilibili.com/correspond/*
// @exclude *://www.bilibili.com/page-proxy/*
// @require https://update.greasyfork.org/scripts/409641/1435266/UserscriptAPI.js
// @require https://update.greasyfork.org/scripts/431998/1161016/UserscriptAPIDom.js
// @require https://update.greasyfork.org/scripts/432000/1095149/UserscriptAPIMessage.js
// @require https://update.greasyfork.org/scripts/432002/1161015/UserscriptAPIWait.js
// @require https://update.greasyfork.org/scripts/432003/1381253/UserscriptAPIWeb.js
// @require https://update.greasyfork.org/scripts/432936/1161000/PushQueue.js
// @require https://update.greasyfork.org/scripts/432807/1160998/InputNumber.js
// @grant GM_registerMenuCommand
// @grant GM_notification
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant GM_listValues
// @grant GM_addValueChangeListener
// @grant GM.cookie
// @connect api.bilibili.com
// @run-at document-start
// @compatible edge 版本不小于 93
// @compatible chrome 版本不小于 93
// @compatible firefox 版本不小于 92
// @downloadURL https://update.greasyfork.cloud/scripts/395456/B%E7%AB%99%E7%A8%8D%E5%90%8E%E5%86%8D%E7%9C%8B%E5%8A%9F%E8%83%BD%E5%A2%9E%E5%BC%BA.user.js
// @updateURL https://update.greasyfork.cloud/scripts/395456/B%E7%AB%99%E7%A8%8D%E5%90%8E%E5%86%8D%E7%9C%8B%E5%8A%9F%E8%83%BD%E5%A2%9E%E5%BC%BA.meta.js
// ==/UserScript==
/* global UserscriptAPI, PushQueue */
(function() {
'use strict'
if (GM_info.scriptHandler !== 'Tampermonkey') {
const { script } = GM_info
script.author ??= 'Laster2800'
script.homepage ??= 'https://greasyfork.org/zh-CN/scripts/395456'
script.supportURL ??= 'https://greasyfork.org/zh-CN/scripts/395456/feedback'
}
const sortType = {
default: 'serial',
defaultR: 'serial:R',
duration: 'duration',
durationR: 'duration:R',
pubtime: 'pubtime',
pubtimeR: 'pubtime:R',
progress: 'progress',
uploader: 'uploader',
title: 'vTitle',
fixed: 'fixed',
}
/**
* 脚本内用到的枚举定义
*/
const Enums = {
/**
* @readonly
* @enum {string}
*/
headerButtonOp: {
openListInCurrent: 'openListInCurrent',
openListInNew: 'openListInNew',
playAllInCurrent: 'playAllInCurrent',
playAllInNew: 'playAllInNew',
clearWatchlater: 'clearWatchlater',
clearWatchedInWatchlater: 'clearWatchedInWatchlater',
openUserSetting: 'openUserSetting',
openRemoveHistory: 'openRemoveHistory',
openBatchAddManager: 'openBatchAddManager',
exportWatchlaterList: 'exportWatchlaterList',
noOperation: 'noOperation',
},
/**
* @readonly
* @enum {string}
*/
headerMenu: {
enable: 'enable',
enableSimple: 'enableSimple',
disable: 'disable',
},
/**
* @readonly
* @enum {string}
*/
headerCompatible: {
none: 'none',
bilibiliEvolved: 'bilibiliEvolved',
},
/**
* @readonly
* @enum {string}
*/
sortType,
/**
* @readonly
* @enum {string}
*/
autoSort: {
auto: 'auto',
...sortType,
},
/**
* @readonly
* @enum {string}
*/
openHeaderMenuLink: {
openInCurrent: 'openInCurrent',
openInNew: 'openInNew',
},
/**
* @readonly
* @enum {string}
*/
removeHistorySavePoint: {
list: 'list',
listAndMenu: 'listAndMenu',
anypage: 'anypage',
},
/**
* @readonly
* @enum {string}
*/
fillWatchlaterStatus: {
dynamic: 'dynamic',
dynamicAndVideo: 'dynamicAndVideo',
anypage: 'anypage',
never: 'never',
},
/**
* @readonly
* @enum {string}
*/
autoRemove: {
always: 'always',
openFromList: 'openFromList',
never: 'never',
absoluteNever: 'absoluteNever',
},
/**
* @readonly
* @enum {string}
*/
openListVideo: {
openInCurrent: 'openInCurrent',
openInNew: 'openInNew',
},
/**
* @readonly
* @enum {string}
*/
menuScrollbarSetting: {
beautify: 'beautify',
hidden: 'hidden',
original: 'original',
},
/**
* @readonly
* @enum {string}
*/
mainRunAt: {
DOMContentLoaded: 'DOMContentLoaded',
load: 'load',
},
}
// 将名称不完全对应的补上,这样校验才能生效
Enums.headerButtonOpL = Enums.headerButtonOpR = Enums.headerButtonOpM = Enums.headerButtonOp
const gmId = 'gm395456'
/**
* 全局对象
* @typedef GMObject
* @property {string} id 脚本标识
* @property {number} configVersion 配置版本,为最后一次执行初始化设置或功能性更新设置时脚本对应的配置版本号
* @property {number} configUpdate 当前版本对应的配置版本号,只要涉及到配置的修改都要更新;若同一天修改多次,可以追加小数来区分
* @property {URLSearchParams} searchParams URL 查询参数
* @property {GMObject_config} config 用户配置
* @property {GMObject_configMap} configMap 用户配置属性
* @property {GMObject_infoMap} infoMap 信息属性
* @property {GMObject_runtime} runtime 运行时变量
* @property {string[]} configDocumentStart document-start 时期配置
* @property {GMObject_data} data 脚本数据
* @property {GMObject_url} url URL
* @property {GMObject_regex} regex 正则表达式
* @property {{[c: string]: *}} const 常量
* @property {GMObject_panel} panel 面板
* @property {{[s: string]: HTMLElement}} el HTML 元素
*/
/**
* @typedef GMObject_config
* @property {boolean} headerButton 顶栏入口
* @property {headerButtonOp} headerButtonOpL 顶栏入口左键点击行为
* @property {headerButtonOp} headerButtonOpR 顶栏入口右键点击行为
* @property {headerButtonOp} headerButtonOpM 顶栏入口中键点击行为
* @property {headerMenu} headerMenu 顶栏入口弹出面板设置
* @property {openHeaderMenuLink} openHeaderMenuLink 弹出面板内链接点击行为
* @property {boolean} headerMenuKeepRemoved 弹出面板保留被移除稿件
* @property {boolean} headerMenuSearch 弹出面板搜索框
* @property {boolean} headerMenuSortControl 弹出面板排序控制器
* @property {boolean} headerMenuAutoRemoveControl 弹出面板自动移除控制器
* @property {boolean} headerMenuFnSetting 弹出面板:设置
* @property {boolean} headerMenuFnHistory 弹出面板:历史
* @property {boolean} headerMenuFnExport 弹出面板:导出
* @property {boolean} headerMenuFnBatchAdd 弹出面板:批量添加
* @property {boolean} headerMenuFnRemoveAll 弹出面板:清空
* @property {boolean} headerMenuFnRemoveWatched 弹出面板:移除已看
* @property {boolean} headerMenuFnShowAll 弹出面板:显示
* @property {boolean} headerMenuFnPlayAll 弹出面板:播放
* @property {boolean} removeHistory 稍后再看移除记录
* @property {removeHistorySavePoint} removeHistorySavePoint 保存稍后再看历史数据的时间点
* @property {number} removeHistorySavePeriod 数据保存最小时间间隔
* @property {number} removeHistoryFuzzyCompare 模糊比对深度
* @property {number} removeHistorySaves 稍后再看历史数据记录保存数
* @property {boolean} removeHistoryTimestamp 使用时间戳优化移除记录
* @property {number} removeHistorySearchTimes 历史回溯深度
* @property {boolean} batchAddLoadForward 批量添加:加载关注者转发的稿件
* @property {boolean} batchAddUsingFavTime 批量添加:从收藏夹导入时使用「收藏时间」作为时间节点
* @property {boolean} batchAddLoadAfterTimeSync 批量添加:执行时间同步后是否自动加载稿件
* @property {string} batchAddManagerSnapshotPrefix 批量添加:文件快照前缀
* @property {fillWatchlaterStatus} fillWatchlaterStatus 填充稍后再看状态
* @property {boolean} searchDefaultValue 激活搜索框默认值功能
* @property {autoSort} autoSort 自动排序
* @property {boolean} videoButton 视频播放页稍后再看状态快速切换
* @property {autoRemove} autoRemove 自动将稿件从播放列表移除
* @property {boolean} redirect 稍后再看模式重定向至常规模式播放
* @property {boolean} dynamicBatchAddManagerButton 动态主页批量添加管理器按钮
* @property {number} autoReloadList 自动刷新列表页面
* @property {openListVideo} openListVideo 列表页面稿件点击行为
* @property {boolean} listStickControl 列表页面控制栏随页面滚动
* @property {boolean} listSearch 列表页面搜索框
* @property {boolean} listSortControl 列表页面排序控制器
* @property {boolean} listAutoRemoveControl 列表页面自动移除控制器
* @property {boolean} listExportWatchlaterListButton 列表页面列表导出按钮
* @property {boolean} listBatchTransferButton 列表页面批量转移按钮
* @property {boolean} listBatchAddManagerButton 列表页面批量添加管理器按钮
* @property {boolean} removeButton_playAll 移除「全部播放」按钮
* @property {boolean} removeButton_removeAll 移除「一键清空」按钮
* @property {boolean} removeButton_removeWatched 移除「移除已观看视频」按钮
* @property {boolean} headerCompatible 兼容第三方顶栏
* @property {menuScrollbarSetting} menuScrollbarSetting 弹出面板的滚动条设置
* @property {mainRunAt} mainRunAt 主要逻辑运行时期
* @property {boolean} hideDisabledSubitems 设置页隐藏被禁用项的子项
* @property {number} watchlaterListCacheValidPeriod 稍后再看列表数据本地缓存有效期(单位:秒)
* @property {string} appendCookies 追加 Cookie(主要用于修复极个别用户 HttpOnly Cookie 没有被请求携带的问题)
* @property {boolean} reloadAfterSetting 设置生效后刷新页面
* @property {string} importWl_regex 稍后再看列表导入:正则表达式
* @property {string} importWl_aid 稍后再看列表导入:捕获组/AID
* @property {string} importWl_bvid 稍后再看列表导入:捕获组/BVID
* @property {string} importWl_title 稍后再看列表导入:捕获组/标题
* @property {string} importWl_source 稍后再看列表导入:捕获组/来源
* @property {string} importWl_tsS 稍后再看列表导入:捕获组/时间节点(秒)
* @property {string} importWl_tsMs 稍后再看列表导入:捕获组/时间节点(毫秒)
*/
/**
* @typedef {{[config: string]: GMObject_configMap_item}} GMObject_configMap
*/
/**
* @typedef GMObject_configMap_item
* @property {*} default 默认值
* @property {'string' | 'boolean' | 'int' | 'float'} [type] 数据类型
* @property {'checked' | 'value' | 'none'} attr 对应 `DOM` 元素上的属性,`none` 表示无对应元素
* @property {boolean} [manual] 配置保存时是否需要手动处理
* @property {boolean} [needNotReload] 配置改变后是否不需要重新加载就能生效
* @property {number} [min] 最小值
* @property {number} [max] 最大值
* @property {number} [configVersion] 涉及配置更改的最后配置版本
*/
/**
* @typedef {{[info: string]: GMObject_infoMap_item}} GMObject_infoMap
*/
/**
* @typedef GMObject_infoMap_item
* @property {number} [configVersion] 涉及信息更改的最后配置版本
*/
/**
* @typedef GMObject_runtime
* @property {'old' | '2022' | '3rd-party'} headerType 顶栏版本
* @property {boolean} reloadWatchlaterListData 刷新稍后再看列表数据
* @property {boolean} loadingWatchlaterListData 正在加载稍后再看列表数据
* @property {*} watchlaterListDataError 稍后再看列表数据加载过程错误(无错误为 `null`);发现错误时 `gm.data.watchlaterListData()` 将获取到旧列表数据
* @property {boolean} savingRemoveHistoryData 正在存储稍后再看历史数据
* @property {number} autoReloadListTid 列表页面自动刷新定时器 ID
*/
/**
* @callback removeHistoryData 通过懒加载方式获取稍后再看历史数据
* @param {boolean} [remove] 是否将稍后再看历史数据移除
* @returns {PushQueue} 稍后再看历史数据
*/
/**
* @callback watchlaterListData 通过懒加载方式获取稍后再看列表数据
* @param {boolean} [reload] 是否重新加载稍后再看列表数据
* @param {boolean} [pageCache=false] 是否使用页面缓存
* @param {boolean} [localCache=true] 是否使用本地缓存
* @returns {Promise} 稍后再看列表数据
*/
/**
* `api_queryWatchlaterList` 返回数据中的稿件单元
* @typedef GMObject_data_item0
* @property {number} aid 稿件 AV 号,务必统一为字符串格式再使用
* @property {string} bvid 稿件 BV 号
* @property {string} title 稿件标题
* @property {number} state 稿件状态
* @property {string} [pic] 稿件封面
* @property {Object} [owner] UP主信息
* @property {number} [owner.mid] UP主 ID
* @property {string} [owner.name] UP主名字
* @property {number} [progress] 稿件播放进度
* @property {number} [duration] 稿件时长
* @property {number} [pubdate] 稿件发布时间
* @property {number} [videos] 稿件分P数
* @see {@link https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/history&toview/toview.md#获取稍后再看视频列表 获取稍后再看视频列表}
*/
/**
* @typedef {[bvid: string, title: string, lastModified: number]} GMObject_data_item
* `bvid` 稿件 BV 号
*
* `title` 稿件标题
*
* `[lastModified]` 时间戳:最后被观察到的时间点
*/
/**
* @callback fixedItem 访问固定列表项
* @param {string} id 项目标识
* @param {boolean} [op] 不设置 - 只读;`true` - 添加;`false` - 移除
* @returns {boolean} 访问后项目是否在固定列表项中
*/
/**
* @typedef GMObject_data
* @property {removeHistoryData} removeHistoryData 稍后再看历史数据
* @property {watchlaterListData} watchlaterListData 当前稍后再看列表数据
* @property {fixedItem} fixedItem 固定列表项
*/
/**
* @callback page_userSpace
* @param {string} [uid] `uid`
* @returns {string} 用户空间 URL
*/
/**
* @typedef GMObject_url
* @property {string} api_queryWatchlaterList 稍后再看列表数据
* @property {string} api_addToWatchlater 将稿件添加至稍后再看
* @property {string} api_removeFromWatchlater 将稿件从稍后再看移除
* @property {string} api_clearWatchlater 清空稍后再看,要求 POST 一个含 `csrf` 的表单
* @property {string} api_listFav 列出所有收藏夹
* @property {string} api_dealFav 将稿件添加/移除至收藏夹
* @property {string} api_favResourceList 获取收藏夹内容明细列表
* @property {string} api_dynamicList 动态列表
* @property {string} page_watchlaterList 列表页面
* @property {string} page_videoNormalMode 常规播放页
* @property {string} page_videoWatchlaterMode 稍后再看播放页
* @property {string} page_listWatchlaterMode 列表播放页(稍后再看)
* @property {string} page_watchlaterPlayAll 稍后再看播放全部(临时禁用重定向)
* @property {string} page_dynamic 动态页
* @property {page_userSpace} page_userSpace 用户空间
* @property {string} gm_changelog 更新日志
*/
/**
* @typedef GMObject_regex
* @property {RegExp} page_watchlaterList 匹配列表页面
* @property {RegExp} page_videoNormalMode 匹配常规播放页
* @property {RegExp} page_videoWatchlaterMode 匹配稍后再看播放页
* @property {RegExp} page_listMode 匹配列表播放页
* @property {RegExp} page_listWatchlaterMode 匹配列表播放页(稍后再看)
* @property {RegExp} page_dynamic 匹配动态页面
* @property {RegExp} page_dynamicMenu 匹配旧版动态面板
* @property {RegExp} page_userSpace 匹配用户空间
* @property {RegExp} page_search 匹配搜索页面
*/
/**
* @typedef GMObject_panel
* @property {GMObject_panel_item} setting 设置
* @property {GMObject_panel_item} history 移除记录
* @property {GMObject_panel_item} batchAddManager 批量添加管理器
* @property {GMObject_panel_item} entryPopup 入口弹出面板
*/
/**
* @typedef GMObject_panel_item
* @property {0 | 1 | 2 | 3 | -1} state 打开状态(关闭 | 开启中 | 打开 | 关闭中 | 错误)
* @property {0 | 1 | 2} wait 等待阻塞状态(无等待阻塞 | 等待开启 | 等待关闭)
* @property {HTMLElement} el 面板元素
* @property {() => (void | Promise)} [openHandler] 打开面板的回调函数
* @property {() => (void | Promise)} [closeHandler] 关闭面板的回调函数
* @property {() => void} [openedHandler] 彻底打开面板后的回调函数
* @property {() => void} [closedHandler] 彻底关闭面板后的回调函数
*/
/**
* 全局对象
* @type {GMObject}
*/
const gm = {
id: gmId,
configVersion: GM_getValue('configVersion'),
configUpdate: 20240522,
searchParams: new URL(location.href).searchParams,
config: {},
configMap: {
headerButton: { default: true, attr: 'checked' },
headerButtonOpL: { default: Enums.headerButtonOp.openListInCurrent, attr: 'value', configVersion: 20221008 },
headerButtonOpR: { default: Enums.headerButtonOp.openUserSetting, attr: 'value', configVersion: 20221008 },
headerButtonOpM: { default: Enums.headerButtonOp.openListInNew, attr: 'value', configVersion: 20221008 },
headerMenu: { default: Enums.headerMenu.enable, attr: 'value', configVersion: 20210706 },
openHeaderMenuLink: { default: Enums.openHeaderMenuLink.openInCurrent, attr: 'value', configVersion: 20200717 },
headerMenuKeepRemoved: { default: true, attr: 'checked', needNotReload: true, configVersion: 20210724 },
headerMenuSearch: { default: true, attr: 'checked', configVersion: 20210323.1 },
headerMenuSortControl: { default: true, attr: 'checked', configVersion: 20210810 },
headerMenuAutoRemoveControl: { default: true, attr: 'checked', configVersion: 20210723 },
headerMenuFnSetting: { default: true, attr: 'checked', configVersion: 20210322 },
headerMenuFnHistory: { default: true, attr: 'checked', configVersion: 20210322 },
headerMenuFnExport: { default: false, attr: 'checked', configVersion: 20221008 },
headerMenuFnBatchAdd: { default: false, attr: 'checked', configVersion: 20221008 },
headerMenuFnRemoveAll: { default: false, attr: 'checked', configVersion: 20210322 },
headerMenuFnRemoveWatched: { default: false, attr: 'checked', configVersion: 20210723 },
headerMenuFnShowAll: { default: false, attr: 'checked', configVersion: 20210322 },
headerMenuFnPlayAll: { default: true, attr: 'checked', configVersion: 20210322 },
removeHistory: { default: true, attr: 'checked', manual: true, configVersion: 20210911 },
removeHistorySavePoint: { default: Enums.removeHistorySavePoint.listAndMenu, attr: 'value', configVersion: 20210628 },
removeHistorySavePeriod: { default: 60, type: 'int', attr: 'value', max: 600, needNotReload: true, configVersion: 20210908 },
removeHistoryFuzzyCompare: { default: 1, type: 'int', attr: 'value', max: 5, needNotReload: true, configVersion: 20210722 },
removeHistorySaves: { default: 500, type: 'int', attr: 'value', manual: true, needNotReload: true, min: 10, max: 1500, configVersion: 20240522 },
removeHistoryTimestamp: { default: true, attr: 'checked', needNotReload: true, configVersion: 20210703 },
removeHistorySearchTimes: { default: 500, type: 'int', attr: 'value', manual: true, needNotReload: true, min: 1, max: 1500, configVersion: 20240522 },
batchAddLoadForward: { default: true, attr: 'checked', configVersion: 20220607, needNotReload: true },
batchAddUsingFavTime: { default: true, attr: 'checked', configVersion: 20230422.1, needNotReload: true },
batchAddLoadAfterTimeSync: { default: true, attr: 'checked', configVersion: 20220513, needNotReload: true },
batchAddManagerSnapshotPrefix: { default: 'bwpBAM-snapshot', attr: 'value', configVersion: 20230422, needNotReload: true },
fillWatchlaterStatus: { default: Enums.fillWatchlaterStatus.dynamic, attr: 'value', configVersion: 20200819 },
searchDefaultValue: { default: true, attr: 'checked', configVersion: 20220606 },
autoSort: { default: Enums.autoSort.auto, attr: 'value', configVersion: 20220115 },
videoButton: { default: true, attr: 'checked' },
autoRemove: { default: Enums.autoRemove.openFromList, attr: 'value', configVersion: 20210612 },
redirect: { default: false, attr: 'checked', configVersion: 20210322.1 },
dynamicBatchAddManagerButton: { default: true, attr: 'checked', configVersion: 20210902 },
autoReloadList: { default: 0, type: 'int', attr: 'value', min: 5, max: 600, configVersion: 20220710 },
openListVideo: { default: Enums.openListVideo.openInCurrent, attr: 'value', configVersion: 20200717 },
listStickControl: { default: true, attr: 'checked', configVersion: 20220410 },
listSearch: { default: true, attr: 'checked', configVersion: 20210810.1 },
listSortControl: { default: true, attr: 'checked', configVersion: 20210810 },
listAutoRemoveControl: { default: true, attr: 'checked', configVersion: 20210908 },
listExportWatchlaterListButton: { default: true, attr: 'checked', configVersion: 20221008 },
listBatchTransferButton: { default: true, attr: 'checked', configVersion: 20231127 },
listBatchAddManagerButton: { default: true, attr: 'checked', configVersion: 20210908 },
removeButton_playAll: { default: false, attr: 'checked', configVersion: 20221008 },
removeButton_removeAll: { default: false, attr: 'checked', configVersion: 20200722 },
removeButton_removeWatched: { default: false, attr: 'checked', configVersion: 20200722 },
headerCompatible: { default: Enums.headerCompatible.none, attr: 'value', configVersion: 20220410 },
menuScrollbarSetting: { default: Enums.menuScrollbarSetting.beautify, attr: 'value', configVersion: 20210808.1 },
mainRunAt: { default: Enums.mainRunAt.DOMContentLoaded, attr: 'value', needNotReload: true, configVersion: 20210726 },
watchlaterListCacheValidPeriod: { default: 15, type: 'int', attr: 'value', needNotReload: true, min: 8, max: 600, configVersion: 20210908 },
appendCookies: { default: '', type: 'string', attr: 'value', configVersion: 20240522 },
hideDisabledSubitems: { default: true, attr: 'checked', configVersion: 20210505 },
reloadAfterSetting: { default: true, attr: 'checked', needNotReload: true, configVersion: 20200715 },
importWl_regex: { default: 'bv[\\dA-Za-z]{10}', attr: 'none', configVersion: 20230419 },
importWl_aid: { default: -1, type: 'int', attr: 'none', configVersion: 20230419 },
importWl_bvid: { default: 0, type: 'int', attr: 'none', configVersion: 20230419 },
importWl_title: { default: -1, type: 'int', attr: 'none', configVersion: 20230419 },
importWl_source: { default: -1, type: 'int', attr: 'none', configVersion: 20230419 },
importWl_tsS: { default: -1, type: 'int', attr: 'none', configVersion: 20230419 },
importWl_tsMs: { default: -1, type: 'int', attr: 'none', configVersion: 20230419 },
},
infoMap: {
clearRemoveHistoryData: {},
watchlaterMediaList: { configVersion: 20231127 },
exportWatchlaterList: { configVersion: 20221008 },
importWatchlaterList: { configVersion: 20230419 },
},
runtime: {},
configDocumentStart: ['redirect', 'menuScrollbarSetting', 'mainRunAt', 'appendCookies'],
data: {},
url: {
api_queryWatchlaterList: 'https://api.bilibili.com/x/v2/history/toview',
api_addToWatchlater: 'https://api.bilibili.com/x/v2/history/toview/add',
api_removeFromWatchlater: 'https://api.bilibili.com/x/v2/history/toview/del',
api_clearWatchlater: 'https://api.bilibili.com/x/v2/history/toview/clear',
api_listFav: 'https://api.bilibili.com/x/v3/fav/folder/created/list-all',
api_favResourceList: 'https://api.bilibili.com/x/v3/fav/resource/list',
api_dealFav: 'https://api.bilibili.com/x/v3/fav/resource/deal',
api_dynamicList: 'https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/all',
page_watchlaterList: 'https://www.bilibili.com/watchlater/#/list',
page_videoNormalMode: 'https://www.bilibili.com/video',
page_videoWatchlaterMode: 'https://www.bilibili.com/medialist/play/watchlater',
page_listWatchlaterMode: 'https://www.bilibili.com/list/watchlater',
page_watchlaterPlayAll: `https://www.bilibili.com/list/watchlater?${gmId}_disable_redirect=true`,
page_dynamic: 'https://t.bilibili.com',
page_userSpace: uid => `https://space.bilibili.com/${uid}`,
gm_changelog: 'https://gitee.com/liangjiancang/userscript/blob/master/script/BilibiliWatchlaterPlus/changelog.md',
},
regex: {
// 只要第一个「#」后是「/list([/?#]|$)」即被视为列表页面
// B站并不会将「#/list」之后的「[/?#]」视为锚点的一部分,这不符合 URL 规范,但只能将错就错了
page_watchlaterList: /\.com\/watchlater\/[^#]*#\/list([#/?]|$)/,
page_videoNormalMode: /\.com\/video([#/?]|$)/,
page_videoWatchlaterMode: /\.com\/medialist\/play\/(watchlater|ml\d+)([#/?]|$)/,
page_listMode: /\.com\/list\/.+/,
page_listWatchlaterMode: /\.com\/list\/watchlater([#/?]|$)/,
page_dynamic: /\/t\.bilibili\.com(\/|$)/,
page_dynamicMenu: /\.com\/pages\/nav\/index_new([#/?]|$)/,
page_userSpace: /space\.bilibili\.com([#/?]|$)/,
page_search: /search\.bilibili\.com\/.+/, // 不含搜索主页
},
const: {
fadeTime: 400,
textFadeTime: 100,
noticeTimeout: 5600,
updateHighlightColor: '#4cff9c',
inputThrottleWait: 250,
batchAddRequestInterval: 350,
fixerHint: '固定在列表最后,并禁用自动移除及排序功能\n右键点击可取消所有固定项',
searchDefaultValueHint: '右键点击保存默认值,中键点击清空默认值\n当前默认值:$1',
exportWatchlaterList_default: '导出至剪贴板 = 是\n导出至新页面 = 否\n导出至文件 = 否\n稿件导出模板 = \'https://www.bilibili.com/video/${ITEM.bvid}\'',
},
panel: {
setting: { state: 0, wait: 0, el: null },
history: { state: 0, wait: 0, el: null },
batchAddManager: { state: 0, wait: 0, el: null },
entryPopup: { state: 0, wait: 0, el: null },
},
el: {
gmRoot: null,
setting: null,
history: null,
},
}
const api = new UserscriptAPI({
id: gm.id,
label: GM_info.script.name,
fadeTime: gm.const.fadeTime,
})
/** @type {Script} */
let script = null
/** @type {Webpage} */
let webpage = null
/**
* 脚本运行的抽象,为脚本本身服务的核心功能
*/
class Script {
/** 内部数据 */
#data = {}
/** 通用方法 */
method = {
/**
* GM 读取流程
*
* 一般情况下,读取用户配置;如果配置出错,则沿用默认值,并将默认值写入配置中
* @param {string} gmKey 键名
* @param {*} defaultValue 默认值
* @param {boolean} [writeback=true] 配置出错时是否将默认值回写入配置中
* @returns {*} 通过校验时是配置值,不能通过校验时是默认值
*/
getConfig(gmKey, defaultValue, writeback = true) {
let invalid = false
let value = GM_getValue(gmKey)
if (Enums && gmKey in Enums) {
if (!Object.values(Enums[gmKey]).includes(value)) {
invalid = true
}
} else if (typeof value === typeof defaultValue) { // 对象默认赋 null 无需额外处理
const { type } = gm.configMap[gmKey]
if (type === 'int' || type === 'float') {
invalid = gm.configMap[gmKey].min > value || gm.configMap[gmKey].max < value
}
} else {
invalid = true
}
if (invalid) {
value = defaultValue
writeback && GM_setValue(gmKey, value)
}
return value
},
/**
* 重置脚本
*/
reset() {
const gmKeys = GM_listValues()
for (const gmKey of gmKeys) {
GM_deleteValue(gmKey)
}
},
}
/**
* document-start 级别初始化
*/
initAtDocumentStart() {
if (gm.configVersion > 0) {
for (const name of gm.configDocumentStart) {
gm.config[name] = this.method.getConfig(name, gm.configMap[name].default)
}
}
// 追加 Cookie
if (gm.config.appendCookies !== '') {
api.options.web.preproc = async details => {
if (new URL(details.url).host === 'api.bilibili.com') {
if (!gm.runtime.appendCookies) {
if (gm.config.appendCookies === 'SESSDATA') {
try {
gm.runtime.appendCookies = `SESSDATA=${(await GM.cookie.list({ name: 'SESSDATA' }))[0].value}`
} catch (e) {
api.message.alert('当前脚本管理器不支持 GM.cookie
API。若要使用自动追加 SESSDATA
Cookie 功能必须使用支持该 API 的脚本管理器(如 Tampermonkey BETA 版本)。', { html: true })
throw e
}
} else {
gm.runtime.appendCookies = gm.config.appendCookies
}
}
if (details.cookie && details.cookie.trim() !== '') {
details.cookie = `${gm.runtime.appendCookies};${details.cookie}`
} else {
details.cookie = gm.runtime.appendCookies
}
}
}
}
}
/**
* 初始化
*/
init() {
try {
this.initGMObject()
this.updateVersion()
this.readConfig()
if (self === top) {
if (gm.config.searchDefaultValue) {
GM_addValueChangeListener('searchDefaultValue_value', (name, oldVal, newVal) => window.dispatchEvent(new CustomEvent('updateSearchTitle', { detail: { value: newVal } })))
}
}
} catch (e) {
api.logger.error(e)
api.message.confirm('初始化错误!是否彻底清空内部数据以重置脚本?').then(result => {
if (result) {
this.method.reset()
location.reload()
}
})
}
}
/**
* 初始化全局对象
*/
initGMObject() {
gm.data = {
...gm.data,
removeHistoryData: remove => {
const $data = this.#data
if (remove) {
$data.removeHistoryData = undefined
return
}
if ($data.removeHistoryData == null) {
/** @type {PushQueue} */
let data = GM_getValue('removeHistoryData')
if (data && typeof data === 'object') {
Reflect.setPrototypeOf(data, PushQueue.prototype) // 初始化替换原型不会影响内联缓存
if (data.maxSize !== gm.config.removeHistorySaves) {
data.setMaxSize(gm.config.removeHistorySaves)
GM_setValue('removeHistoryData', data)
}
} else {
data = new PushQueue(gm.config.removeHistorySaves)
GM_setValue('removeHistoryData', data)
}
$data.removeHistoryData = data
}
return $data.removeHistoryData
},
watchlaterListData: async (reload, pageCache, localCache = true) => {
const $data = this.#data
gm.runtime.watchlaterListDataError = null
if (gm.runtime.reloadWatchlaterListData) {
reload = true
gm.runtime.reloadWatchlaterListData = false
}
if ($data.watchlaterListData == null || reload || !pageCache) {
if (gm.runtime.loadingWatchlaterListData) {
// 一旦数据已在加载中,那么直接等待该次加载完成
// 无论加载成功与否,所有被阻塞的数据请求均都使用该次加载的结果,完全保持一致
// 注意:加载失败时,返回的空数组并非同一对象
try {
return await api.wait.waitForConditionPassed({
condition: () => {
if (!gm.runtime.loadingWatchlaterListData) {
return $data.watchlaterListData ?? []
}
},
})
} catch (e) {
gm.runtime.watchlaterListDataError = e
gm.runtime.loadingWatchlaterListData = false
api.logger.error(e)
return $data.watchlaterListData ?? []
}
}
if (!reload && localCache && gm.config.watchlaterListCacheValidPeriod > 0) {
const cacheTime = GM_getValue('watchlaterListCacheTime')
if (cacheTime) {
const current = Date.now()
if (current - cacheTime < gm.config.watchlaterListCacheValidPeriod * 1000) {
const list = GM_getValue('watchlaterListCache')
if (list) {
$data.watchlaterListData = list
return list // 默认缓存不为空
}
}
}
}
gm.runtime.loadingWatchlaterListData = true
try {
const resp = await api.web.request({
url: gm.url.api_queryWatchlaterList,
}, { check: r => r.code === 0 })
const current = resp.data.list ?? []
if (gm.config.watchlaterListCacheValidPeriod > 0) {
GM_setValue('watchlaterListCacheTime', Date.now())
GM_setValue('watchlaterListCache', current.map(item => ({
aid: item.aid,
bvid: item.bvid,
title: item.title,
state: item.state,
pic: item.pic,
owner: {
mid: item.owner.mid,
name: item.owner.name,
},
progress: item.progress,
duration: item.duration,
pubdate: item.pubdate,
videos: item.videos,
})))
}
$data.watchlaterListData = current
return current
} catch (e) {
api.logger.error(e)
gm.runtime.watchlaterListDataError = e
return $data.watchlaterListData ?? []
} finally {
gm.runtime.loadingWatchlaterListData = false
}
} else {
return $data.watchlaterListData
}
},
fixedItem: (id, op) => {
const uid = webpage.method.getDedeUserID()
const items = GM_getValue(`fixedItems_${uid}`) ?? []
const idx = items.indexOf(id)
const fixed = idx >= 0
if (op == null) return fixed
if (op) {
if (!fixed) {
items.push(id)
GM_setValue(`fixedItems_${uid}`, items)
}
return true
} else {
if (fixed) {
items.splice(idx, 1)
GM_setValue(`fixedItems_${uid}`, items)
}
return false
}
},
}
gm.el.gmRoot = document.createElement('div')
gm.el.gmRoot.id = gm.id
api.wait.executeAfterElementLoaded({ // body 已存在时无异步
selector: 'body',
callback: body => body.append(gm.el.gmRoot),
})
}
/**
* 版本更新处理
*/
updateVersion() {
if (gm.configVersion >= 20220513) { // 4.26.13.20220513 最旧保留版本
if (gm.configVersion < gm.configUpdate) {
// 必须按从旧到新的顺序写
// 内部不能使用 gm.configUpdate,必须手写更新后的配置版本号!
// 4.26.13.20220513
if (gm.configVersion < 20220513) {
GM_deleteValue('batchAddLoadAfterTimeSync')
}
// 4.27.0.20220605
if (gm.configVersion < 20220605) {
const bp = GM_getValue('batchParams')
if (bp && (!bp.id4a || Number.parseInt(bp.id4a) < 350)) {
bp.id4a = '350'
GM_setValue('batchParams', bp)
}
}
// 4.34.0.20231127
if (gm.configVersion < 20231127) {
const items = GM_getValue('fixedItems')
if (items) {
const uid = webpage.method.getDedeUserID()
GM_setValue(`fixedItems_${uid}`, items)
GM_deleteValue('fixedItems')
}
}
// 4.36.0.20240522
if (gm.configVersion < 20240522) {
GM_deleteValue('removeHistorySaves')
GM_deleteValue('removeHistorySearchTimes')
}
// 功能性更新后更新此处配置版本,通过时跳过功能性更新设置,否则转至 readConfig() 中处理
if (gm.configVersion >= 20240522) {
gm.configVersion = gm.configUpdate
GM_setValue('configVersion', gm.configVersion)
}
}
} else {
this.method.reset()
gm.configVersion = null
}
}
/**
* 用户配置读取
*/
readConfig() {
if (gm.configVersion > 0) {
for (const [name, item] of Object.entries(gm.configMap)) {
if (!gm.configDocumentStart.includes(name)) {
gm.config[name] = this.method.getConfig(name, item.default)
}
}
if (gm.configVersion !== gm.configUpdate) {
this.openUserSetting(2)
}
} else {
// 用户强制初始化,或第一次安装脚本,或版本过旧
gm.configVersion = 0
for (const [name, item] of Object.entries(gm.configMap)) {
gm.config[name] = item.default
GM_setValue(name, item.default)
}
this.openUserSetting(1)
}
}
/**
* 添加脚本菜单
*/
addScriptMenu() {
// 用户配置设置
GM_registerMenuCommand('用户设置', () => this.openUserSetting())
// 批量添加管理器
GM_registerMenuCommand('批量添加管理器', () => this.openBatchAddManager())
if (gm.config.removeHistory) {
// 稍后再看移除记录
GM_registerMenuCommand('稍后再看移除记录', () => this.openRemoveHistory())
}
GM_registerMenuCommand('导出稍后再看列表', () => this.exportWatchlaterList())
// 强制初始化
GM_registerMenuCommand('初始化脚本', () => this.resetScript())
}
/**
* 打开用户设置
* @param {number} [type=0] 常规 `0` | 初始化 `1` | 功能性更新 `2`
*/
openUserSetting(type = 0) {
if (gm.el.setting) {
this.openPanelItem('setting')
} else {
/** @type {{[n: string]: HTMLElement}} */
const el = {}
setTimeout(() => {
initSetting()
processConfigItem()
processSettingItem()
this.openPanelItem('setting')
})
/**
* 设置页初始化
*/
const initSetting = () => {
gm.el.setting = gm.el.gmRoot.appendChild(document.createElement('div'))
gm.panel.setting.el = gm.el.setting
gm.el.setting.className = 'gm-setting gm-modal-container'
if (gm.config.hideDisabledSubitems) {
gm.el.setting.classList.add('gm-hideDisabledSubitems')
}
const getItemHTML = (label, ...items) => {
let html = `${label}
`
for (const item of items) {
html += `
${item.html}
`
}
html += '
'
return html
}
let itemsHTML = ''
itemsHTML += getItemHTML('全局功能', {
desc: '在顶栏「动态」和「收藏」之间加入稍后再看入口,鼠标移至上方时弹出列表面板,支持点击功能设置。',
html: ``,
}, {
desc: '选择左键点击入口时执行的操作。',
html: `
在入口上点击鼠标左键时
`,
}, {
desc: '选择右键点击入口时执行的操作。',
html: `
在入口上点击鼠标右键时
`,
}, {
desc: '选择中键点击入口时执行的操作。',
html: `
在入口上点击鼠标中键时
`,
}, {
desc: '设置入口弹出面板。',
html: `
将鼠标移动至入口上方时
`,
}, {
desc: '选择在弹出面板中点击链接的行为。',
html: `
在弹出面板中点击链接时
`,
}, {
desc: '在弹出面板中显示自当前页面打开以来从弹出面板移除的稿件。',
html: ``,
}, {
desc: '在弹出面板顶部显示搜索框。',
html: ``,
}, {
desc: '在弹出面板底部显示排序控制器。',
html: ``,
}, {
desc: '在弹出面板底部显示自动移除控制器。',
html: ``,
}, {
desc: '设置在弹出列表显示的快捷功能。',
html: `
在弹出面板底部显示:
`,
})
itemsHTML += getItemHTML('全局功能', {
desc: '保留稍后再看列表中的数据,以查找出一段时间内将哪些稿件移除出稍后再看,用于拯救误删操作。关闭该选项会将内部历史数据清除!',
html: ``,
}, {
desc: '选择在何时保存稍后再看历史数据。',
html: `
为生成移除记录,
`,
}, {
desc: '距离上一次保存稍后再看历史数据间隔超过该时间,才会再次进行保存。',
html: `
数据保存最小时间间隔(单位:秒)
`,
}, {
desc: '设置模糊比对深度以快速舍弃重复数据从而降低开销,但可能会造成部分记录遗漏。',
html: `
模糊比对模式深度
💬
`,
}, {
desc: '较大的数值可能会带来较大的开销(具体参考右侧弹出说明)。将该项修改为比原来小的值会清理过期数据,无法恢复!',
html: `
不重复数据记录保存数
💬
清空数据(0条)
`,
}, {
desc: '在稍后再看历史数据记录中保存时间戳,以其优化对数据记录的排序及展示。',
html: ``,
}, {
desc: '搜寻时在最近多少条数据记录中查找,设置较小的值能较好地定位最近被添加到稍后再看的稿件。',
html: `
默认历史回溯深度
`,
})
itemsHTML += getItemHTML('全局功能', {
html: '批量添加:
',
}, {
desc: '在批量添加管理器中,执行加载步骤时是否加载关注者转发的稿件?',
html: ``,
}, {
desc: '在批量添加管理器中,从收藏夹导入时使用「收藏时间」而非「稿件发布时间」作为时间节点。\n时间节点被用于在步骤 ② 中判断稿件是否超出设定的时间范围。',
html: ``,
}, {
desc: '在批量添加管理器中,执行时间同步后,是否自动执行稿件加载步骤?',
html: ``,
}, {
desc: '设置批量添加管理器快照文件名称前缀。',
html: ``,
})
itemsHTML += getItemHTML('全局功能', {
desc: '填充默认情况下缺失的稍后再看状态信息。',
html: `
填充缺失的稍后再看状态信息:
💬
`,
})
itemsHTML += getItemHTML('全局功能', {
desc: '激活后在搜索框上右键点击保存默认值,中键点击清空默认值。',
html: ``,
})
itemsHTML += getItemHTML('全局功能', {
desc: '决定首次打开列表页面或弹出面板时,如何对稍后再看列表内容进行排序。',
html: `
自动排序:
`,
})
itemsHTML += getItemHTML('全局功能', {
desc: '指定使用批量转移及收藏功能时,将稿件从稍后再看移动至哪个收藏夹。',
html: `
稍后再看收藏夹
设置
`,
})
itemsHTML += getItemHTML('全局功能', {
desc: '设置稍后再看列表导出方式。',
html: `
导出稍后再看列表
设置
`,
}, {
desc: '设置稍后再看列表导入方式。该功能入口在批量添加管理器中。',
html: `
导入稍后再看列表
设置
💬
`,
})
itemsHTML += getItemHTML('播放页面', {
desc: '在播放页面中加入能将稿件快速添加或移除出稍后再看列表的按钮。',
html: ``,
})
itemsHTML += getItemHTML('播放页面', {
desc: '打开播放页面时,自动将稿件从稍后再看列表中移除,或在特定条件下执行自动移除。',
html: `
打开页面时,
`,
})
itemsHTML += getItemHTML('播放页面', {
desc: `打开「${gm.url.page_listWatchlaterMode}」或「${gm.url.page_videoWatchlaterMode}」页面时,自动切换至「${gm.url.page_videoNormalMode}」页面进行播放,但不影响「播放全部」等相关功能。`,
html: ``,
})
itemsHTML += getItemHTML('动态主页', {
desc: '批量添加管理器可以将投稿批量添加到稍后再看。',
html: ``,
})
itemsHTML += getItemHTML('列表页面', {
desc: `设置「${gm.url.page_watchlaterList}」页面的自动刷新策略。`,
html: `
自动刷新时间间隔(单位:分钟)
💬
`,
})
itemsHTML += getItemHTML('列表页面', {
desc: `设置在「${gm.url.page_watchlaterList}」页面点击稿件时的行为。`,
html: `
点击稿件时
`,
})
itemsHTML += getItemHTML('列表页面', {
desc: '控制栏跟随页面滚动,建议配合「[相关调整] 将顶栏固定在页面顶部」使用。',
html: ``,
})
itemsHTML += getItemHTML('列表页面', {
desc: '在列表页面显示……',
html: `
显示组件:
`,
})
itemsHTML += getItemHTML('列表页面', {
desc: '在列表页面移除……',
html: `
移除组件:
`,
})
itemsHTML += getItemHTML('相关调整', {
desc: '无须兼容第三方顶栏时务必选择「无」,否则脚本无法正常工作!\n若列表中没有提供你需要的第三方顶栏,且该第三方顶栏有一定用户基数,可在脚本反馈页发起请求。',
html: `
兼容第三方顶栏:
⚠
`,
})
itemsHTML += getItemHTML('相关调整', {
desc: '对顶栏各入口弹出面板中滚动条的样式进行设置。',
html: `
对于弹出面板中的滚动条
`,
})
itemsHTML += getItemHTML('脚本设置', {
desc: '选择脚本主要逻辑的运行时期。',
html: `
脚本运行时期:
💬
`,
})
itemsHTML += getItemHTML('脚本设置', {
desc: '稍后再看列表数据本地缓存有效期(单位:秒)',
html: `
稍后再看列表数据本地缓存有效期(单位:秒)
💬
`,
})
itemsHTML += getItemHTML('脚本设置', {
desc: '追加 Cookie(仅针对 api.bilibili.com)。主要用于修复极个别用户 HttpOnly Cookie 没有被请求携带的问题,也可用于随意追加或覆盖 Cookie 以达到更多目的,正常情况下没有必要也不要使用!',
html: `
追加 Cookie:
💬
⚠
`,
})
itemsHTML += getItemHTML('用户设置', {
desc: '一般情况下,是否在用户设置中隐藏被禁用项的子项?',
html: ``,
})
itemsHTML += getItemHTML('用户设置', {
desc: '如果更改的配置需要重新加载才能生效,那么在设置完成后重新加载页面。',
html: ``,
})
gm.el.setting.innerHTML = `
${itemsHTML}
初始化脚本
更新日志
`
// 找出配置对应的元素
for (const name of Object.keys({ ...gm.configMap, ...gm.infoMap })) {
el[name] = gm.el.setting.querySelector(`#gm-${name}`)
}
el.settingPage = gm.el.setting.querySelector('.gm-setting-page')
el.items = gm.el.setting.querySelector('.gm-items')
el.maintitle = gm.el.setting.querySelector('.gm-maintitle')
el.changelog = gm.el.setting.querySelector('.gm-changelog')
switch (type) {
case 1: {
el.settingPage.dataset.type = 'init'
el.maintitle.innerHTML += '
(初始化设置)'
break
}
case 2: {
el.settingPage.dataset.type = 'updated'
el.maintitle.innerHTML += '
(功能性更新设置)'
for (const [name, item] of Object.entries({ ...gm.configMap, ...gm.infoMap })) {
if (el[name] && item.configVersion > gm.configVersion) {
const updated = el[name].closest('.gm-item, .gm-lineitem')
updated?.classList.add('gm-updated')
}
}
break
}
default: {
break
}
}
el.save = gm.el.setting.querySelector('.gm-save')
el.cancel = gm.el.setting.querySelector('.gm-cancel')
el.shadow = gm.el.setting.querySelector('.gm-shadow')
el.reset = gm.el.setting.querySelector('.gm-reset')
// 提示信息
el.rhfcInformation = gm.el.setting.querySelector('#gm-rhfcInformation')
api.message.hoverInfo(el.rhfcInformation, `
模糊比对模式:设当前时间点获取到的稍后再看列表数据为 A,上一次获取到的数据为 B。若 A 与 B 的前 N 项均一致就认为这段时间没有往稍后再看中添加新稿件,直接跳过后续处理。
其中,N 即为模糊比对深度。注意,深度设置过大反而会降低比对效率,建议先设置较小的值,若后续观察到有记录被误丢弃,再增加该项的值。最佳参数与个人使用习惯相关,请根据自身情况微调。你也可以选择设置 0 以关闭模糊比对模式(不推荐)。
`, null, { width: '36em', position: { top: '80%' } })
el.rhsInformation = gm.el.setting.querySelector('#gm-rhsInformation')
api.message.hoverInfo(el.rhsInformation, `
取值过小时,非常久远的稿件可能无法被跟踪;取值过大则不必要,原因是移除记录本质上是一种误删后的挽回手段,不必真正涵盖到所有历史。建议设置为自己日常稍后再看稿件数量的两到五倍。
`, null, { width: '36em', position: { top: '80%' } })
el.rhtInformation = gm.el.setting.querySelector('#gm-rhtInformation')
api.message.hoverInfo(el.rhtInformation, `
在历史数据记录中添加时间戳,用于改善移除记录中的数据排序,使得排序以「稿件『最后一次』被观察到处于稍后再看的时间点」为基准,而非以「稿件『第一次』被观察到处于稍后再看的时间点」为基准;同时也利于数据展示与查看。注意,此功能在数据存读及处理上都有额外开销。
`, null, { width: '36em', position: { top: '80%' } })
el.balatsInformation = gm.el.setting.querySelector('#gm-balatsInformation')
api.message.hoverInfo(el.balatsInformation, '若同步时间距离当前时间超过 48 小时,则不会执行自动加载。')
el.fwsInformation = gm.el.setting.querySelector('#gm-fwsInformation')
api.message.hoverInfo(el.fwsInformation, `
在动态页、视频播放页以及其他页面,稿件卡片的右下角方存在一个将稿件加入或移除出稍后再看的快捷按钮。然而,在刷新页面后,B站不会为之加载稍后再看的状态——即使稿件已经在稍后再看中,也不会显示出来。启用该功能后,会自动填充这些缺失的状态信息。
第三项「所有页面」,会用一套固定的逻辑对脚本能匹配到的所有非特殊页面尝试进行信息填充。脚本本身没有匹配所有B站页面,如果有需要,请在脚本管理器(如 Tampermonkey)中为脚本设置额外的页面匹配规则。由于B站各页面的设计不是很规范,某些页面中稿件卡片的设计可能跟其他地方不一致,所以不保证必定能填充成功。
`, null, { width: '36em', position: { top: '80%' } })
el.sdvInformation = gm.el.setting.querySelector('#gm-sdvInformation')
api.message.hoverInfo(el.sdvInformation, '激活后在搜索框上右键点击保存默认值,中键点击清空默认值。')
el.iwlInformation = gm.el.setting.querySelector('#gm-iwlInformation')
api.message.hoverInfo(el.iwlInformation, '该功能入口在批量添加管理器中。')
el.mraInformation = gm.el.setting.querySelector('#gm-mraInformation')
api.message.hoverInfo(el.mraInformation, `
DOMContentLoaded:与页面内容同步加载,避免脚本在页面加载度较高时才对页面作修改。上述情况会给人页面加载时间过长的错觉,并且伴随页面变化突兀的不适感。
load:在页面初步加载完成时运行。从理论上来说这个时间点更为合适,且能保证脚本在网页加载速度极慢时仍可正常工作。但要注意的是,以上所说「网页加载速度极慢」的情况并不常见,以下为常见原因:1. 短时间内(在后台)打开十几乃至数十个网页;2. 网络问题。
`, null, { width: '36em', flagSize: '2em', position: { top: '80%' } })
el.arlInformation = gm.el.setting.querySelector('#gm-arlInformation')
api.message.hoverInfo(el.arlInformation, `
设置列表页面自动刷新的时间间隔。
设置为 0 时禁用自动刷新。
`)
el.wlcvpInformation = gm.el.setting.querySelector('#gm-wlcvpInformation')
api.message.hoverInfo(el.wlcvpInformation, `
在有效期内使用本地缓存代替网络请求——除非是须确保数据正确性的场合。有效期过大会导致各种诡异现象,取值最好能匹配自身的B站使用习惯。
`, null, { width: '36em', flagSize: '2em' })
el.acInformation = gm.el.setting.querySelector('#gm-acInformation')
api.message.hoverInfo(el.acInformation, `
该功能主要用于修复极个别用户 HttpOnly Cookie 没有被请求携带的问题,正常情况下没有必要也不要使用!
如果出现脚本无法使用的情况,响应中出现「账号未登录」信息,极有可能是 HttpOnly Cookie 没有被请求携带导致的。该现象出现原因不明,无法复现。
将该项设置为 SESSDATA
,脚本将在发送给 api.bilibili.com
的请求中追加 SESSDATA
Cookie 以解决该问题,但该功能需要脚本管理器支持 GM.cookie
API(建议使用 Tampermonkey BETA 版本)。或者手动设置 SESSDATA
,格式为 SESSDATA=A1B2C3D4E5
(注意 SESSDATA
需定期更新以避免过期)。
当然也可以随意追加或覆盖 Cookie 以达到更多目的,格式为 a=1;b=2;c=3;d=4
。
`, null, { width: '36em', flagSize: '2em' })
el.hcWarning = gm.el.setting.querySelector('#gm-hcWarning')
api.message.hoverInfo(el.hcWarning, '无须兼容第三方顶栏时务必选择「无」,否则脚本无法正常工作!', '⚠')
el.rhWarning = gm.el.setting.querySelector('#gm-rhWarning')
api.message.hoverInfo(el.rhWarning, '关闭移除记录,或将稍后再看历史数据保存次数设置为比原来小的值,都会造成对内部过期历史数据的清理!', '⚠')
el.acWarning = gm.el.setting.querySelector('#gm-acWarning')
api.message.hoverInfo(el.acWarning, '如果不理解在干什么,请将该项留空!', '⚠')
el.headerButtonOpL.innerHTML = el.headerButtonOpR.innerHTML = el.headerButtonOpM.innerHTML = `
`
}
/**
* 维护与设置项相关的数据和元素
*/
const processConfigItem = () => {
// 子项与父项相关联
const subitemChange = (target, disabled) => {
const content = target.closest('.gm-item-content')
for (const option of content.querySelectorAll('[id|=gm]:not(:first-child)')) {
if (!target.contains(option)) {
option.disabled = disabled
}
}
for (let i = 1; i < content.childElementCount; i++) {
const item = content.children[i]
if (disabled) {
item.setAttribute('disabled', '')
} else {
item.removeAttribute('disabled')
}
}
}
el.headerMenuFn = el.headerMenuFnSetting.parentElement.parentElement
el.headerButton.init = () => {
const target = el.headerButton
subitemChange(target, !target.checked)
}
el.headerButton.addEventListener('change', el.headerButton.init)
el.headerCompatible.init = () => setHcWarning()
el.headerCompatible.addEventListener('change', el.headerCompatible.init)
el.removeHistory.init = () => {
const target = el.removeHistory
subitemChange(target, !target.checked)
setRhWaring()
}
el.removeHistory.addEventListener('change', el.removeHistory.init)
el.removeHistorySaves.addEventListener('input', setRhWaring)
el.removeHistorySaves.addEventListener('blur', setRhWaring)
el.appendCookies.init = () => setAcWarning()
el.appendCookies.addEventListener('input', el.appendCookies.init)
el.appendCookies.addEventListener('change', () => {
el.appendCookies.value = el.appendCookies.value.trim()
el.appendCookies.init()
})
}
/**
* 处理与设置页相关的数据和元素
*/
const processSettingItem = () => {
gm.panel.setting.openHandler = onOpen
gm.panel.setting.openedHandler = onOpened
gm.el.setting.fadeInDisplay = 'flex'
el.save.addEventListener('click', onSave)
el.cancel.addEventListener('click', () => this.closePanelItem('setting'))
el.shadow.addEventListener('click', () => {
if (!el.shadow.hasAttribute('disabled')) {
this.closePanelItem('setting')
}
})
el.reset.addEventListener('click', () => this.resetScript())
el.clearRemoveHistoryData.addEventListener('click', () => {
el.removeHistory.checked && this.clearRemoveHistoryData()
})
el.watchlaterMediaList.addEventListener('click', async () => {
const uid = webpage.method.getDedeUserID()
const mlid = await api.message.prompt(`
指定使用收藏功能时,将稿件从稍后再看移动至哪个收藏夹。
下方应填入目标收藏夹 ID,置空时使用默认收藏夹。收藏夹页面网址为 https://space.bilibili.com/\${uid}/favlist?fid=\${mlid}
,mlid
即收藏夹 ID。
`, GM_getValue(`watchlaterMediaList_${uid}`) ?? undefined, { html: true })
if (mlid != null) {
GM_setValue(`watchlaterMediaList_${uid}`, mlid)
api.message.info('已保存稍后再看收藏夹设置')
}
})
el.importWatchlaterList.addEventListener('click', () => this.setImportWatchlaterList())
el.exportWatchlaterList.addEventListener('click', () => this.setExportWatchlaterList())
if (type > 0) {
if (type === 2) {
el.save.title = '向下滚动……'
el.save.disabled = true
}
el.cancel.disabled = true
el.shadow.setAttribute('disabled', '')
}
}
let needReload = false
/**
* 设置保存时执行
*/
const onSave = () => {
// 通用处理
for (const [name, item] of Object.entries(gm.configMap)) {
if (!item.manual && item.attr !== 'none') {
const change = saveConfig(name, item.attr)
if (!item.needNotReload) {
needReload ||= change
}
}
}
let shutDownRemoveHistory = false
// removeHistory
if (gm.config.removeHistory !== el.removeHistory.checked) {
gm.config.removeHistory = el.removeHistory.checked
GM_setValue('removeHistory', gm.config.removeHistory)
shutDownRemoveHistory = true
needReload = true
}
// 「因」中无 removeHistory,就说明 needReload 需要设置为 true,除非「果」不需要刷新页面就能生效
if (gm.config.removeHistory) {
const rhsV = Number.parseInt(el.removeHistorySaves.value)
if (rhsV !== gm.config.removeHistorySaves && !Number.isNaN(rhsV)) {
// 因:removeHistorySaves
// 果:removeHistorySaves & removeHistoryData
const data = gm.data.removeHistoryData()
data.setMaxSize(rhsV)
gm.config.removeHistorySaves = rhsV
GM_setValue('removeHistorySaves', rhsV)
GM_setValue('removeHistoryData', data)
// 不需要修改 needReload
}
// 因:removeHistorySearchTimes
// 果:removeHistorySearchTimes
const rhstV = Number.parseInt(el.removeHistorySearchTimes.value)
if (rhstV !== gm.config.removeHistorySearchTimes && !Number.isNaN(rhstV)) {
gm.config.removeHistorySearchTimes = rhstV
GM_setValue('removeHistorySearchTimes', rhstV)
// 不需要修改 needReload
}
} else if (shutDownRemoveHistory) {
// 因:removeHistory
// 果:most thing about history
gm.data.removeHistoryData(true)
GM_deleteValue('removeHistoryData')
GM_deleteValue('removeHistoryFuzzyCompare')
GM_deleteValue('removeHistoryFuzzyCompareReference')
GM_deleteValue('removeHistorySaves')
}
this.closePanelItem('setting')
if (type > 0) {
// 更新配置版本
gm.configVersion = gm.configUpdate
GM_setValue('configVersion', gm.configVersion)
// 关闭特殊状态
setTimeout(() => {
delete el.settingPage.dataset.type
el.maintitle.textContent = GM_info.script.name
el.cancel.disabled = false
el.shadow.removeAttribute('disabled')
}, gm.const.fadeTime)
}
if (gm.config.reloadAfterSetting && needReload) {
needReload = false
location.reload()
}
}
/**
* 设置打开时执行
*/
const onOpen = () => {
for (const [name, item] of Object.entries(gm.configMap)) {
const { attr } = item
if (attr !== 'none') {
el[name][attr] = gm.config[name]
}
}
for (const name of Object.keys(gm.configMap)) {
// 需要等所有配置读取完成后再进行初始化
el[name]?.init?.()
}
el.clearRemoveHistoryData.textContent = gm.config.removeHistory ? `清空数据(${gm.data.removeHistoryData().size}条)` : '清空数据(0条)'
}
/**
* 设置打开后执行
*/
const onOpened = () => {
el.items.scrollTop = 0
if (type === 2) {
const resetSave = () => {
el.save.title = ''
el.save.disabled = false
}
const points = []
const totalLength = el.items.scrollHeight
const items = el.items.querySelectorAll('.gm-updated')
for (const item of items) {
points.push(item.offsetTop / totalLength * 100)
}
if (points.length > 0) {
let range = 5 // 显示宽度
const actualRange = items[0].offsetHeight / totalLength * 100 // 实际宽度
let realRange = actualRange // 校正后原点到真实末尾的宽度
if (actualRange > range) {
range = actualRange
} else {
const offset = (actualRange - range) / 2
for (let i = 0; i < points.length; i++) {
points[i] += offset
}
realRange = range + offset
}
const start = []
const end = []
let currentStart = points[0]
let currentEnd = points[0] + range
for (let i = 1; i < points.length; i++) {
const point = points[i]
if (point < currentEnd) {
currentEnd = point + range
} else {
start.push(currentStart)
end.push(currentEnd)
currentStart = point
currentEnd = point + range
if (currentEnd >= 100) {
currentEnd = 100
break
}
}
}
start.push(currentStart)
end.push(currentEnd)
let linear = ''
for (const [idx, val] of start.entries()) {
linear += `, transparent ${val}%, ${gm.const.updateHighlightColor} ${val}%, ${gm.const.updateHighlightColor} ${end[idx]}%, transparent ${end[idx]}%`
}
linear = linear.slice(2)
api.base.addStyle(`
#${gm.id} [data-type=updated] .gm-items::-webkit-scrollbar {
background: linear-gradient(${linear})
}
`)
if (el.items.scrollHeight === el.items.clientHeight) {
resetSave()
} else {
const last = Math.min((points.pop() + realRange) / 100, 0.95) // 给计算误差留点余地
const onScroll = api.base.throttle(() => {
const { items } = el
const bottom = (items.scrollTop + items.clientHeight) / items.scrollHeight
if (bottom > last) { // 可视区底部超过最后一个更新点
resetSave()
items.removeEventListener('scroll', onScroll)
}
}, 200)
el.items.addEventListener('scroll', onScroll)
el.items.dispatchEvent(new Event('scroll'))
}
} else {
resetSave()
}
}
}
/**
* 保存配置
* @param {string} name 配置名称
* @param {string} attr 从对应元素的什么属性读取
* @returns {boolean} 是否有实际更新
*/
const saveConfig = (name, attr) => {
let val = el[name][attr]
const { type } = gm.configMap[name]
if (type === 'int' || type === 'float') {
if (typeof val !== 'number') {
val = type === 'int' ? Number.parseInt(val) : Number.parseFloat(val)
}
if (Number.isNaN(val)) {
val = gm.configMap[name].default
}
}
if (gm.config[name] === val) return false
gm.config[name] = val
GM_setValue(name, gm.config[name])
return true
}
/**
* 设置 headerCompatible 警告项
*/
const setHcWarning = () => {
const warn = el.headerCompatible.value !== Enums.headerCompatible.none
if (el.hcWarning.show) {
if (!warn) {
api.dom.fade(false, el.hcWarning)
el.hcWarning.show = false
}
} else {
if (warn) {
api.dom.fade(true, el.hcWarning)
el.hcWarning.show = true
}
}
}
/**
* 设置 appendCookies 警告项
*/
const setAcWarning = () => {
const warn = el.appendCookies.value !== ''
if (el.acWarning.show) {
if (!warn) {
api.dom.fade(false, el.acWarning)
el.acWarning.show = false
}
} else {
if (warn) {
api.dom.fade(true, el.acWarning)
el.acWarning.show = true
}
}
}
/**
* 设置 removeHistory 警告项
*/
const setRhWaring = () => {
let warn = false
const rh = el.removeHistory.checked
if (!rh && gm.config.removeHistory) {
warn = true
} else {
let rhs = Number.parseInt(el.removeHistorySaves.value)
if (Number.isNaN(rhs)) {
rhs = 0
}
if (rhs < gm.config.removeHistorySaves && gm.config.removeHistory) {
warn = true
}
}
if (el.rhWarning.show) {
if (!warn) {
api.dom.fade(false, el.rhWarning)
el.rhWarning.show = false
}
} else {
if (warn) {
api.dom.fade(true, el.rhWarning)
el.rhWarning.show = true
}
}
}
}
}
/**
* 打开批量添加管理器
*/
openBatchAddManager() {
if (gm.el.batchAddManager) {
this.openPanelItem('batchAddManager')
} else {
/** @type {{[n: string]: HTMLElement}} */
const el = {}
let history = null
if (gm.config.removeHistory) {
const records = gm.data.removeHistoryData().toArray(50) // 回溯限制到 50 条
if (records.length > 0) {
history = new Set()
for (const record of records) {
history.add(webpage.method.bvTool.bv2av(record[0]))
}
}
}
setTimeout(() => {
initManager()
processItem()
this.openPanelItem('batchAddManager')
})
/**
* 初始化管理器
*/
const initManager = () => {
gm.el.batchAddManager = gm.el.gmRoot.appendChild(document.createElement('div'))
gm.panel.batchAddManager.el = gm.el.batchAddManager
gm.el.batchAddManager.className = 'gm-batchAddManager gm-modal-container'
gm.el.batchAddManager.innerHTML = `
`
const ids = ['1a', '1b', '1c', '1d', '1e', '1f', '2a', '2b', '2c', '3a', '3b', '3c', '4a', '4b', '4c']
for (const id of ids) {
el[`id${id}`] = gm.el.batchAddManager.querySelector(`#gm-batch-${id}`)
}
el.items = gm.el.batchAddManager.querySelector('.gm-items')
el.bottom = gm.el.batchAddManager.querySelector('.gm-bottom')
el.lastAddTime = gm.el.batchAddManager.querySelector('#gm-last-add-time')
el.uncheckedDisplay = gm.el.batchAddManager.querySelector('#gm-unchecked-display')
el.selectAll = gm.el.batchAddManager.querySelector('#gm-select-all')
el.deselectAll = gm.el.batchAddManager.querySelector('#gm-deselect-all')
el.saveSnapshot = gm.el.batchAddManager.querySelector('#gm-save-snapshot')
el.loadSnapshot = gm.el.batchAddManager.querySelector('#gm-load-snapshot')
el.saveParams = gm.el.batchAddManager.querySelector('#gm-save-batch-params')
el.loadParams = gm.el.batchAddManager.querySelector('#gm-load-batch-params')
el.shadow = gm.el.batchAddManager.querySelector('.gm-shadow')
el.saveParams.paramIds = ['1a', '1b', '3a', '3b', '4a']
const batchParams = GM_getValue('batchParams')
setBatchParamsToManager(batchParams)
}
let busy = false
/**
* 设置 BUSY 状态
* @param {boolean} status BUSY 状态
*/
const setBusy = status => {
busy = status
el.id1b.disabled = status
el.id1c.disabled = status
el.id1e.disabled = status
el.id1f.disabled = status
el.id4b.disabled = status
if (status) {
el.bottom.setAttribute('disabled', '')
el.bottom.firstElementChild.style.pointerEvents = 'none'
} else {
el.bottom.removeAttribute('disabled')
el.bottom.firstElementChild.style.pointerEvents = ''
}
}
/**
* 从批量添加管理器获取参数
* @returns {Object} 参数
*/
const getBatchParamsFromManager = () => {
const params = {}
for (const id of el.saveParams.paramIds) {
params[`id${id}`] = el[`id${id}`].value
}
return params
}
/**
* 将参数设置到批量添加管理器
*/
const setBatchParamsToManager = params => {
if (params) {
for (const id of el.saveParams.paramIds) {
el[`id${id}`].value = params[`id${id}`]
}
}
}
/**
* 维护内部元素和数据
*/
const processItem = () => {
gm.el.batchAddManager.fadeInDisplay = 'flex'
el.shadow.addEventListener('click', () => this.closePanelItem('batchAddManager'))
// 处理鼠标与加载出来的稿件项目的交互
const itemLinkSelector = '.gm-item input + a'
// 鼠标左键:切换勾选状态
// 阻止左键触发链接点击行为,并还原点击标签内元素切换复选框状态的行为
el.items.addEventListener('click', e => {
if (e.target.matches(itemLinkSelector)) {
e.preventDefault()
e.target.previousElementSibling.click()
}
}, true)
// 鼠标右键:打开稿件
el.items.addEventListener('contextmenu', e => {
if (e.target.matches(itemLinkSelector)) {
e.preventDefault()
if (e.target.href.length > 0) {
window.open(e.target.href)
}
}
})
// 鼠标中键:后台打开稿件并取消勾选状态
// 后台打开稿件已由浏览器自行完成,这里要追加取消勾选行为
el.items.addEventListener('mousedown', e => {
if (e.target.matches(itemLinkSelector) && e.button === 1) {
const cb = e.target.previousElementSibling
if (cb.checked) {
if (el.uncheckedDisplay._hide) {
setTimeout(() => cb.click(), 300) // 要稍加延迟,否则浏览器会来不及触发中键点击链接的逻辑
} else {
cb.checked = false
}
}
}
})
// 时间同步
const setLastAddTime = (time = null, writeBack = true) => {
writeBack && GM_setValue('batchLastAddTime', time)
el.lastAddTime.val = time
el.lastAddTime.title = `将一个合适的时间点同步到加载步骤中,以便与上次批量添加操作无缝对接。该功能仅对于常规加载方式生效。\n执行加载步骤:若完成且没有找到新稿件,同步「加载时间」。\n执行添加步骤:若完成且加载步骤完成,同步「加载时间」;否则同步「最后一个添加成功的稿件的投稿时间」。${time ? `\n当前同步时间:${new Date(time).toLocaleString()}` : ''}`
el.lastAddTime.disabled = !time
}
setLastAddTime(GM_getValue('batchLastAddTime'), false)
el.lastAddTime.addEventListener('click', () => {
if (busy) return api.message.info('执行中,无法同步')
const target = el.lastAddTime
if (target.val == null) return
const secInterval = (Date.now() - target.val) / 1000
el.id1a.value = secInterval / el.id1b.value // 取精确时间要比向上取整好
if (gm.config.batchAddLoadAfterTimeSync) {
if ((Date.now() - target.val) / (1000 * 3600) <= 48) {
el.id1c.dispatchEvent(new Event('click'))
} else {
api.message.info(`已同步到 ${new Date(target.val).toLocaleString()}。同步时间距离当前时间超过 48 小时,不执行自动加载。`, { ms: 2000 })
}
} else {
api.message.info(`已同步到 ${new Date(target.val).toLocaleString()}`)
}
})
// 避免不同页面中脚本实例互相影响而产生的同步时间错误
GM_addValueChangeListener('batchLastAddTime', (name, oldVal, newVal, remote) => remote && setLastAddTime(newVal))
// 非选显示
const setUncheckedDisplayText = () => {
el.uncheckedDisplay.textContent = el.uncheckedDisplay._hide ? '显示非选' : '隐藏非选'
}
el.uncheckedDisplay._hide = GM_getValue('batchUncheckedDisplay') ?? false
setUncheckedDisplayText()
el.uncheckedDisplay.addEventListener('click', () => {
const target = el.uncheckedDisplay
target._hide = !target._hide
GM_setValue('batchUncheckedDisplay', target._hide)
setUncheckedDisplayText()
const display = target._hide ? 'none' : ''
for (let i = 0; i < el.items.childElementCount; i++) {
const item = el.items.children[i]
if (!item.firstElementChild.checked) {
item.style.display = display
}
}
})
el.items.addEventListener('click', e => {
if (e.target.type === 'checkbox' && !e.target.checked && el.uncheckedDisplay._hide) {
e.target.parentElement.style.display = 'none'
}
})
// 选中全部
el.selectAll.addEventListener('click', () => {
const hide = el.uncheckedDisplay._hide
for (let i = 0; i < el.items.childElementCount; i++) {
const item = el.items.children[i]
const cb = item.firstElementChild
if (!cb.checked && !cb.disabled) {
cb.checked = true
if (hide) {
item.style.display = ''
}
}
}
})
// 取消全部
el.deselectAll.addEventListener('click', () => {
const hide = el.uncheckedDisplay._hide
for (let i = 0; i < el.items.childElementCount; i++) {
const item = el.items.children[i]
const cb = item.firstElementChild
if (cb.checked) {
cb.checked = false
if (hide) {
item.style.display = 'none'
}
}
}
})
// 快照
el.saveSnapshot.addEventListener('click', () => {
const snapshot = {
params: getBatchParamsFromManager(),
items: el.items.innerHTML,
}
const filename = `${gm.config.batchAddManagerSnapshotPrefix}.${webpage.method.getTimeString(null, '', '', '-')}.json`
const file = new Blob([JSON.stringify(snapshot)], { type: 'application/json' })
const a = document.createElement('a')
a.href = URL.createObjectURL(file)
a.download = filename
a.click()
api.message.info('保存成功', 1800)
})
const loadSnapshotF = el.loadSnapshot.firstElementChild
el.loadSnapshot.addEventListener('click', () => loadSnapshotF.click())
loadSnapshotF.addEventListener('change', async () => {
if (busy) return
const file = loadSnapshotF.files[0]
try {
setBusy(true)
if (file) {
const content = await new Promise((resolve, reject) => {
const reader = new FileReader()
reader.addEventListener('load', () => resolve(reader.result))
reader.addEventListener('error', e => reject(e))
reader.readAsText(file)
})
const snapshot = JSON.parse(content)
setBatchParamsToManager(snapshot.params)
el.items.innerHTML = snapshot.items
initItemHints()
el.id2a.value = el.id2a.defaultValue = el.id2a.max = ''
api.message.info('读取成功', 1800)
}
} catch (e) {
api.logger.error(e)
api.message.alert(`快照 ${file.name}
读取失败。`, { html: true })
} finally {
setBusy(false)
loadSnapshotF.value = '' // 重置控件,否则重新选择相同文件不会触发 change 事件;置空行为不会触发 change 事件
}
})
// 参数
el.saveParams.addEventListener('click', () => {
GM_setValue('batchParams', getBatchParamsFromManager())
api.message.info('保存成功')
})
el.saveParams.addEventListener('contextmenu', e => {
e.preventDefault()
GM_deleteValue('batchParams')
api.message.info('重置成功,刷新页面后生效', 1800)
})
el.loadParams.addEventListener('click', () => {
const params = GM_getValue('batchParams')
if (params) {
setBatchParamsToManager(params)
el.id3c.dispatchEvent(new Event('click')) // 自动执行第三步
api.message.info('读取成功')
} else {
api.message.info('未读取到参数')
}
})
let loadType = null
let loadTime = 0
let stopLoad = false
let readers = []
// 加载投稿
el.id1c.addEventListener('click', async () => {
if (busy) return
let error = false
try {
setBusy(true)
let page = 1
let offset = -1
const tzo = new Date().getTimezoneOffset()
const v1a = Number.parseFloat(el.id1a.value)
if (Number.isNaN(v1a)) throw new TypeError('v1a is NaN')
el.id1a.value = v1a
el.id1c.textContent = '执行中'
el.id1d.disabled = false
el.id2a.defaultValue = el.id2a.max = v1a
el.id2b.syncVal = el.id1b.value
el.items.textContent = ''
loadType = 'FEED'
loadTime = Date.now() // 提前记录 loadTime,这样衔接时绝对不会遗漏动态
const end = loadTime - v1a * el.id1b.value * 1000
const avSet = new Set()
gm.runtime.reloadWatchlaterListData = true
// eslint-disable-next-line no-unmodified-loop-condition
while (!stopLoad) {
const data = new URLSearchParams()
data.append('timezone_offset', tzo)
data.append('type', 'all') // video 分类会遗漏一些内容,需手动筛选
data.append('page', page++) // page 似乎只在第 1 页有意义
if (offset > 0) { // 后续通过 offset 而非 page 确定位置
data.append('offset', offset)
}
const resp = await api.web.request({
url: `${gm.url.api_dynamicList}?${data.toString()}`,
}, { check: r => r.code === 0 })
const { items, has_more } = resp.data
if (!items || items.length === 0) return // -> finally
offset = resp.data.offset // data.offset 是字符串类型,不会丢失精度;无需 +1 额外偏移
let html = ''
for (let item of items) {
let ts = -1
let fwSrc = null // 转发源
let fwSrcHint = null // 转发源说明
// 关注者转发的动态
if (gm.config.batchAddLoadForward && item.type === 'DYNAMIC_TYPE_FORWARD') {
fwSrc = `${gm.url.page_dynamic}/${item.id_str}`
fwSrcHint = item.modules.module_author.name
ts = item.modules.module_author.pub_ts // 使用转发时间
item = item.orig
}
// [视频投稿, 已订阅合集]
if (['DYNAMIC_TYPE_AV', 'DYNAMIC_TYPE_UGC_SEASON'].includes(item.type)) {
const { modules } = item
const author = modules.module_author
if (ts < 0) ts = author.pub_ts
if (ts * 1000 < end) {
el.items.insertAdjacentHTML('afterbegin', html)
return // -> finally
}
const { major } = modules.module_dynamic
const core = major[major.type.replace(/^MAJOR_TYPE_/, '').toLowerCase()]
const aid = String(core.aid)
if (!await webpage.method.getVideoWatchlaterStatusByAid(aid, false, true)) { // 完全跳过存在于稍后再看的稿件
if (avSet.has(aid)) continue
avSet.add(aid)
const uncheck = history?.has(aid)
const displayNone = uncheck && el.uncheckedDisplay._hide
const bvid = webpage.method.bvTool.av2bv(aid)
const hrefStr = bvid ? ` href=${gm.url.page_videoNormalMode}/${bvid}` : ''
html = `` + html
}
}
}
el.items.insertAdjacentHTML('afterbegin', html)
if (!has_more) return // -> finally
await new Promise(resolve => setTimeout(resolve, 250 * (Math.random() * 0.5 + 0.75))) // 切线程,顺便给请求留点间隔
}
// 执行到这里只有一个原因:stopLoad 导致任务终止
api.message.info('批量添加:任务终止', 1800)
} catch (e) {
error = true
api.message.alert('批量添加:执行失败')
api.logger.error(e)
} finally {
if (!error && !stopLoad) {
api.message.info('批量添加:稿件加载完成', 1800)
if (loadTime > 0 && el.items.querySelectorAll('.gm-item input:checked').length === 0) {
// 无有效新稿件时直接更新同步时间
setLastAddTime(loadTime)
}
}
if (error || stopLoad) {
loadTime = 0
}
initItemHints()
setBusy(false)
stopLoad = false
el.id1c.textContent = '重新执行'
el.id1d.disabled = true
el.id4b.textContent = '执行'
// 更新第二步的时间范围
if (el.id2a.defaultValue && el.id2b.syncVal) {
el.id2a.value = el.id2a.defaultValue
el.id2b.value = el.id2b.syncVal // 非用户操作不会触发 change 事件
el.id2b.prevVal = el.id2b.value
}
// 自动执行第三步
el.id3c.dispatchEvent(new Event('click'))
}
})
el.id1a.addEventListener('keyup', e => {
if (e.key === 'Enter') {
const target = el[busy ? 'id1d' : 'id1c']
if (!target.disabled) {
target.dispatchEvent(new Event('click'))
}
}
})
// 稍后再看列表导入
async function importWatchlaterList(content, avSet) {
const innerRegex = gm.config.importWl_regex.replaceAll(/\(\?(=|!)[^)]*\)/g, '') // 内嵌组移除前视/后视断言
const r = new RegExp(innerRegex, 'i')
const gr = new RegExp(gm.config.importWl_regex, 'gi')
const strs = content.match(gr)
let html = ''
for (const str of strs) {
const m = r.exec(str)
let aid = m?.[gm.config.importWl_aid]
if (!aid) {
try {
aid = webpage.method.bvTool.bv2av(m?.[gm.config.importWl_bvid])
} catch { /* BV 号有问题,忽略 */ }
}
if (aid) {
if (avSet.has(aid)) continue
avSet.add(aid)
const exist = await webpage.method.getVideoWatchlaterStatusByAid(aid, false, true) // 不跳过已存在稿件,仅作提示
const uncheck = history?.has(aid) || exist
const displayNone = uncheck && el.uncheckedDisplay._hide
const disabledStr = exist ? ' disabled' : ''
const title = m?.[gm.config.importWl_title]
const source = m?.[gm.config.importWl_source]
let tsS = m?.[gm.config.importWl_tsS]
if (!tsS) {
const tsMs = m?.[gm.config.importWl_tsS]
if (tsMs) {
tsS = Math.round(Number.parseInt(tsMs) / 1000)
}
}
const bvid = webpage.method.bvTool.av2bv(aid)
const hrefStr = bvid ? ` href=${gm.url.page_videoNormalMode}/${bvid}` : ''
html = `` + html
}
}
el.items.insertAdjacentHTML('afterbegin', html)
}
const id1eF = el.id1e.firstElementChild
el.id1e.addEventListener('click', () => id1eF.click())
el.id1e.addEventListener('contextmenu', e => {
this.setImportWatchlaterList()
e.preventDefault()
})
id1eF.addEventListener('change', async () => {
if (busy) return
let error = false
try {
setBusy(true)
el.id1d.disabled = false
el.id1e.children[1].textContent = '文件导入中'
el.id2a.value = el.id2a.defaultValue = el.id2a.max = ''
el.items.textContent = ''
loadType = 'FILE'
loadTime = 0
const ps = []
const avSet = new Set()
for (const file of id1eF.files) {
ps.push(new Promise((resolve, reject) => {
const reader = new FileReader()
reader.addEventListener('load', async () => {
try {
await importWatchlaterList(reader.result, avSet)
resolve()
} catch (e) {
api.message.alert(`文件 ${file.name}
读取失败,终止导入。`, { html: true })
reject(e)
}
})
reader.addEventListener('abort', () => resolve(''))
reader.addEventListener('error', e => {
api.message.alert(`文件 ${file.name}
读取失败,终止导入。`, { html: true })
reject(e)
})
reader.readAsText(file)
readers.push(reader)
}))
}
await Promise.all(ps)
} catch (e) {
error = true
api.logger.error(e)
if (readers.length > 0) {
for (const r of readers) {
r.abort()
}
}
} finally {
if (stopLoad) {
api.message.info('批量添加:任务终止', 1800)
} else if (!error) {
api.message.info('批量添加:稍后再看列表导入成功', 1800)
}
readers = []
setBusy(false)
stopLoad = false
el.id1d.disabled = true
el.id1e.children[1].textContent = '文件'
// 自动执行第三步
el.id3c.dispatchEvent(new Event('click'))
id1eF.value = '' // 重置控件,否则重新选择相同文件不会触发 change 事件;置空行为不会触发 change 事件
}
})
// 收藏夹导入
el.id1f.addEventListener('click', async () => {
let favExecuted = false
if (busy) return
try {
setBusy(true)
el.id1d.disabled = true
el.id1f.textContent = '收藏夹导入中'
el.id2a.value = el.id2a.defaultValue = el.id2a.max = ''
el.items.textContent = ''
loadType = 'FAV'
loadTime = 0
let mlid = await api.message.prompt(`
指定需导入的收藏夹。下方应填入目标收藏夹 ID,可使用英文逗号「,
」分隔多个收藏夹。置空时使用稍后再看收藏夹。
收藏夹页面网址为 https://space.bilibili.com/\${uid}/favlist?fid=\${mlid}
,mlid
即收藏夹 ID。
`, null, { html: true })
if (mlid == null) return
if (mlid.trim() === '') {
const uid = webpage.method.getDedeUserID()
mlid = GM_getValue(`watchlaterMediaList_${uid}`)
if (!mlid) {
mlid = await webpage.method.getDefaultMediaListId(uid)
}
}
let error = false
try {
favExecuted = true
el.id1d.disabled = false
const avSet = new Set()
const favIds = mlid.split(',')
// eslint-disable-next-line no-unreachable-loop
id1fFavLoop: for (const favId of favIds) {
let page = 1
// eslint-disable-next-line no-unmodified-loop-condition
while (!stopLoad) {
const data = new URLSearchParams()
data.append('media_id', favId)
data.append('ps', '20') // 每页数,最大 20
data.append('pn', page++)
const resp = await api.web.request({
url: `${gm.url.api_favResourceList}?${data.toString()}`,
}, { check: r => r.code === 0 })
const { medias, info, has_more } = resp.data
if (!medias || medias.length === 0) continue id1fFavLoop
const source = info.title
let html = ''
for (const item of medias) {
const aid = String(item.id)
if (avSet.has(aid)) continue
avSet.add(aid)
const exist = await webpage.method.getVideoWatchlaterStatusByAid(aid, false, true) // 不跳过已存在稿件,仅作提示
const uncheck = history?.has(aid) || exist
const displayNone = uncheck && el.uncheckedDisplay._hide
const disabledStr = exist ? ' disabled' : ''
const bvid = webpage.method.bvTool.av2bv(aid)
const hrefStr = bvid ? ` href=${gm.url.page_videoNormalMode}/${bvid}` : ''
html = `` + html
}
el.items.insertAdjacentHTML('afterbegin', html)
if (!has_more) continue id1fFavLoop
await new Promise(resolve => setTimeout(resolve, 250 * (Math.random() * 0.5 + 0.75))) // 切线程,顺便给请求留点间隔
}
// 执行到这里只有一个原因:stopLoad 导致任务终止
api.message.info('批量添加:任务终止', 1800)
break
}
} catch (e) {
error = true
api.message.alert('批量添加:执行失败')
api.logger.error(e)
} finally {
if (!error && !stopLoad) {
api.message.info('批量添加:稿件加载完成', 1800)
}
}
} finally {
setBusy(false)
stopLoad = false
el.id1d.disabled = true
el.id1f.textContent = '收藏夹'
if (favExecuted) {
// 自动执行第三步
el.id3c.dispatchEvent(new Event('click'))
}
}
})
// 终止加载 / 导入
el.id1d.addEventListener('click', () => {
stopLoad = true
if (readers.length > 0) {
for (const r of readers) {
r.abort()
}
}
})
// 时间过滤
function filterTime() {
if (busy) return
try {
busy = true
const v2a = Number.parseFloat(el.id2a.value)
if (Number.isNaN(v2a)) {
for (let i = 0; i < el.items.childElementCount; i++) {
el.items.children[i].classList.remove('gm-filtered-time')
}
} else {
const newEnd = Date.now() - v2a * el.id2b.value * 1000
for (let i = 0; i < el.items.childElementCount; i++) {
const item = el.items.children[i]
const timestamp = Number.parseInt(item.dataset.timestamp)
if (timestamp * 1000 < newEnd) {
item.classList.add('gm-filtered-time')
} else {
item.classList.remove('gm-filtered-time')
}
}
}
} catch (e) {
api.message.alert('批量添加:执行失败')
api.logger.error(e)
} finally {
busy = false
}
}
const throttledFilterTime = api.base.throttle(filterTime, gm.const.inputThrottleWait)
el.id2a.addEventListener('input', throttledFilterTime)
el.id2a.addEventListener('change', throttledFilterTime)
el.id2b.addEventListener('change', filterTime)
el.id2c.addEventListener('click', filterTime)
// 正则过滤
function filterRegex() {
if (busy) return
try {
const getRegex = str => {
let result = null
str = str.trim()
if (str !== '') {
try {
str = str.replaceAll(/\s*\|\s*/g, '|') // 移除关键词首末空白符
.replaceAll(/[$()+.[\\\]^{}]/g, '\\$&') // escape regex except |
.replaceAll('?', '.').replaceAll('*', '.*') // 通配符
result = new RegExp(str, 'i')
} catch {}
}
return result
}
busy = true
el.id3a.value = el.id3a.value.trimStart()
el.id3b.value = el.id3b.value.trimStart()
const v3a = getRegex(el.id3a.value)
const v3b = getRegex(el.id3b.value)
for (let i = 0; i < el.items.childElementCount; i++) {
const item = el.items.children[i]
const ss = item.dataset.searchStr ?? item.textContent
if ((v3a && !v3a.test(ss)) || v3b?.test(ss)) {
item.classList.add('gm-filtered-regex')
} else {
item.classList.remove('gm-filtered-regex')
}
}
} catch (e) {
api.message.alert('批量添加:执行失败')
api.logger.error(e)
} finally {
busy = false
}
}
const throttledFilterRegex = api.base.throttle(filterRegex, gm.const.inputThrottleWait)
el.id3a.addEventListener('input', throttledFilterRegex)
el.id3b.addEventListener('input', throttledFilterRegex)
el.id3c.addEventListener('click', throttledFilterRegex)
// 添加到稍后再看
let stopAdd = false
el.id4b.addEventListener('click', async () => {
if (busy) return
let added = false
let lastAddTime = 0
try {
setBusy(true)
let v4a = Number.parseFloat(el.id4a.value)
v4a = Number.isNaN(v4a) ? gm.const.batchAddRequestInterval : Math.max(v4a, 250)
el.id4a.value = v4a
el.id4b.textContent = '执行中'
el.id4c.disabled = false
const checks = el.items.querySelectorAll('.gm-item:not([class*=gm-filtered-]) input:checked')
for (const check of checks) {
if (stopAdd) return api.message.info('批量添加:任务终止', 1800) // -> finally
const item = check.parentElement
const success = await webpage.method.switchVideoWatchlaterStatus(item.dataset.aid)
if (!success) throw new Error('add request error')
lastAddTime = item.dataset.timestamp
check.checked = false
if (el.uncheckedDisplay._hide) {
item.style.display = 'none'
}
added = true
await new Promise(resolve => setTimeout(resolve, v4a * (Math.random() * 0.5 + 0.75)))
}
if (loadTime > 0) {
lastAddTime = loadTime
}
api.message.info('批量添加:已将所有选定稿件添加到稍后再看', 1800)
} catch (e) {
api.message.alert('批量添加:执行失败。可能是因为目标稿件不可用或稍后再看不支持该稿件类型(如互动视频),可尝试取消勾选当前列表中第一个选定的稿件后重新执行。')
api.logger.error(e)
} finally {
if (lastAddTime && loadType === 'FEED') {
if (typeof lastAddTime !== 'number') {
lastAddTime = Number.parseInt(lastAddTime) * 1000
}
if (lastAddTime > 0) {
setLastAddTime(lastAddTime)
}
}
setBusy(false)
stopAdd = false
el.id4b.textContent = '重新执行'
el.id4c.disabled = true
gm.runtime.reloadWatchlaterListData = true
window.dispatchEvent(new CustomEvent('reloadWatchlaterListData'))
if (added && api.base.urlMatch(gm.regex.page_watchlaterList)) {
webpage.reloadWatchlaterListPage(null)
}
}
})
el.id4c.addEventListener('click', () => {
stopAdd = true
})
el.id4a.addEventListener('keyup', e => {
if (e.key === 'Enter') {
const target = el[busy ? 'id4c' : 'id4b']
if (!target.disabled) {
target.dispatchEvent(new Event('click'))
}
}
})
// 时间单位转换
const syncTimeUnit = (unitEl, valEl) => {
unitEl.prevVal = unitEl.value
unitEl.addEventListener('change', () => {
if (valEl.max !== Number.POSITIVE_INFINITY) {
valEl.max = (valEl.max * unitEl.prevVal / unitEl.value).toFixed(1)
}
if (valEl.defaultValue) {
valEl.defaultValue = (valEl.defaultValue * unitEl.prevVal / unitEl.value).toFixed(1)
}
if (valEl.value) {
valEl.value = (valEl.value * unitEl.prevVal / unitEl.value).toFixed(1)
unitEl.prevVal = unitEl.value
}
}, true)
}
syncTimeUnit(el.id1b, el.id1a)
syncTimeUnit(el.id2b, el.id2a)
}
/**
* 初始化项目鼠标悬浮提示
*/
const initItemHints = () => {
const hintEls = el.items.querySelectorAll('[data-src-hint]')
for (const el of hintEls) {
api.message.hoverInfo(el, `转发者:${el.dataset.srcHint}`)
}
}
}
}
/**
* 打开移除记录
*/
openRemoveHistory() {
if (!gm.config.removeHistory) {
api.message.info('请在设置中开启稍后再看移除记录')
return
}
GM_deleteValue('removeHistorySaveTime') // 保险起见,清理一下
/** @type {{[n: string]: HTMLElement}} */
const el = {}
if (gm.el.history) {
el.searchTimes = gm.el.history.querySelector('#gm-history-search-times')
el.searchTimes.value = gm.config.removeHistorySearchTimes
el.searchTimes.current = el.searchTimes.value
el.sort = gm.el.history.querySelector('#gm-history-sort')
if (el.sort.type !== 0) {
el.sort.type = 0 // 降序
}
this.openPanelItem('history')
} else {
setTimeout(() => {
initHistory()
processItem()
this.openPanelItem('history')
})
/**
* 初始化移除记录页面
*/
const initHistory = () => {
gm.el.history = gm.el.gmRoot.appendChild(document.createElement('div'))
gm.panel.history.el = gm.el.history
gm.el.history.className = 'gm-history gm-modal-container'
gm.el.history.innerHTML = `
`
el.historyPage = gm.el.history.querySelector('.gm-history-page')
el.comment = gm.el.history.querySelector('.gm-comment')
el.content = gm.el.history.querySelector('.gm-content')
el.sort = gm.el.history.querySelector('#gm-history-sort')
el.timePoint = gm.el.history.querySelector('#gm-history-time-point')
el.saveTimes = gm.el.history.querySelector('#gm-history-save-times')
el.removedNum = gm.el.history.querySelector('#gm-history-removed-num')
el.searchTimes = gm.el.history.querySelector('#gm-history-search-times')
el.newOrOld = gm.el.history.querySelector('#gm-history-new-or-old')
el.shadow = gm.el.history.querySelector('.gm-shadow')
}
/**
* 维护内部元素和数据
*/
const processItem = () => {
el.content.fadeOutDisplay = 'block'
el.content.fadeInTime = gm.const.textFadeTime
el.content.fadeOutTime = gm.const.textFadeTime
el.searchTimes.current = el.searchTimes.value
el.searchTimes.addEventListener('blur', () => {
const target = el.searchTimes
if (target.value !== el.searchTimes.current) {
el.searchTimes.current = target.value
gm.panel.history.openHandler()
}
})
el.searchTimes.addEventListener('keyup', e => {
if (e.key === 'Enter') {
el.searchTimes.dispatchEvent(new Event('blur'))
}
})
el.content.addEventListener('click', async e => {
if (e.target.type === 'checkbox') {
const box = e.target
const status = box.checked
const { bvid } = box.dataset
const note = status ? '添加到稍后再看' : '从稍后再看移除'
const success = await webpage?.method.switchVideoWatchlaterStatus(bvid, status)
if (success) {
api.message.info(`${note}成功`)
} else {
box.checked = !status
api.message.info(`${note}失败${status ? ',可能是因为该稿件不可用' : ''}`)
}
}
})
// 排序方式
const typeText = ['降序', '升序', '完全升序']
const typeDesc = [
'降序回溯历史,降序显示结果',
'降序回溯历史,升序显示结果',
'升序回溯历史,升序显示结果',
]
Reflect.defineProperty(el.sort, 'type', {
get() { return Number.parseInt(this.dataset.type) },
set(val) {
this.dataset.type = val
this.textContent = typeText[val]
this.title = typeDesc[val]
el.newOrOld.textContent = val < 2 ? '最近' : '最早'
},
})
el.sort.type = 0
el.sort.addEventListener('click', () => {
const target = el.sort
target.type = (target.type + 1) % typeText.length
gm.panel.history.openHandler()
})
gm.panel.history.openHandler = onOpen
gm.el.history.fadeInDisplay = 'flex'
el.shadow.addEventListener('click', () => this.closePanelItem('history'))
}
/**
* 移除记录打开时执行
*/
const onOpen = async () => {
api.dom.fade(false, el.content)
el.timePoint.textContent = gm.config.removeHistoryTimestamp ? '最后一次' : '第一次'
try {
const map = await webpage.method.getWatchlaterDataMap(item => item.bvid, 'bvid', true)
const depth = Number.parseInt(el.searchTimes.value)
let data = null
if (el.sort.type < 2) {
data = gm.data.removeHistoryData().toArray(depth)
} else {
const rhd = gm.data.removeHistoryData()
data = rhd.toArray(depth, rhd.size - depth)
}
el.saveTimes.textContent = data.length
const history = []
const result = []
for (const record of data) {
if (!map.has(record[0])) {
history.push(record)
}
}
if (gm.config.removeHistoryTimestamp) { // 两种情况有大量同类项,但合并后处理速度会降不少
if (history.length > 1) {
// ES2019 后 Array#sort() 为稳定排序
history.sort((a, b) => (b[2] ?? 0) - (a[2] ?? 0))
if (el.sort.type >= 1) {
history.reverse()
}
}
for (const rm of history) {
result.push(`
${rm[1]}
${rm[2] ? `
${new Date(rm[2]).toLocaleString()}
` : ''}
`)
}
} else {
if (history.length > 1 && el.sort.type >= 1) {
history.reverse()
}
for (const rm of history) {
result.push(`
`)
}
}
el.removedNum.textContent = result.length
if (result.length > 0) {
el.content.innerHTML = result.join('')
el.content.scrollTop = 0
} else {
setEmptyContent('没有找到移除记录,请尝试增大历史回溯深度')
}
} catch (e) {
setEmptyContent(`网络连接错误或内部数据错误,初始化脚本或清空稍后再看历史数据或许能解决问题。无法解决时请提供反馈:
${GM_info.script.supportURL}`)
api.logger.error(e)
} finally {
api.dom.fade(true, el.content)
}
}
const setEmptyContent = text => {
el.content.innerHTML = ``
}
}
}
/**
* 初始化脚本
*/
async resetScript() {
const result = await api.message.confirm('是否要初始化脚本?本操作不会清理稍后再看历史数据,要清理之请在用户设置中操作。')
if (result) {
const keyNoReset = { removeHistoryData: true, removeHistorySaves: true }
const gmKeys = GM_listValues()
for (const gmKey of gmKeys) {
if (!keyNoReset[gmKey]) {
GM_deleteValue(gmKey)
}
}
gm.configVersion = 0
GM_setValue('configVersion', gm.configVersion)
location.reload()
}
}
/**
* 清空 removeHistoryData
*/
async clearRemoveHistoryData() {
const result = await api.message.confirm('是否要清空稍后再看历史数据?')
if (result) {
GM_deleteValue('removeHistoryData')
GM_deleteValue('removeHistoryFuzzyCompareReference')
location.reload()
}
}
/**
* 取消所有固定项
*/
async clearFixedItems() {
const result = await api.message.confirm('是否要取消所有固定项?')
if (result) {
const uid = webpage.method.getDedeUserID()
GM_setValue(`fixedItems_${uid}`, [])
for (const item of document.querySelectorAll('.gm-fixed')) {
item.classList?.remove('gm-fixed')
}
api.message.info('已取消所有固定项')
}
}
/**
* 打开面板项
* @param {string} name 面板项名称
* @param {(panel: GMObject_panel_item) => void} [callback] 打开面板项后的回调函数
* @param {boolean} [keepOthers] 打开时保留其他面板项
* @returns {Promise} 操作是否成功
*/
async openPanelItem(name, callback, keepOthers) {
let success = false
/** @type {GMObject_panel_item} */
const panel = gm.panel[name]
if (panel.wait > 0) return false
try {
try {
if (panel.state === 1) {
panel.wait = 1
await api.wait.waitForConditionPassed({
condition: () => panel.state === 2,
timeout: 1500 + (panel.el.fadeInTime ?? gm.const.fadeTime),
})
return true
} else if (panel.state === 3) {
panel.wait = 1
await api.wait.waitForConditionPassed({
condition: () => panel.state === 0,
timeout: 1500 + (panel.el.fadeOutTime ?? gm.const.fadeTime),
})
}
} catch (e) {
panel.state = -1
api.logger.error(e)
} finally {
panel.wait = 0
}
if (panel.state === 0 || panel.state === -1) {
panel.state = 1
if (!keepOthers) {
for (const [key, curr] of Object.entries(gm.panel)) {
if (key === name || curr.state === 0) continue
this.closePanelItem(key)
}
}
await panel.openHandler?.()
await new Promise(resolve => {
api.dom.fade(true, panel.el, () => {
resolve()
panel.openedHandler?.()
callback?.(panel)
})
})
panel.state = 2
success = true
}
if (success && document.fullscreenElement) {
document.exitFullscreen()
}
} catch (e) {
panel.state = -1
api.logger.error(e)
}
return success
}
/**
* 关闭面板项
* @param {string} name 面板项名称
* @param {(panel: GMObject_panel_item) => void} [callback] 关闭面板项后的回调函数
* @returns {Promise} 操作是否成功
*/
async closePanelItem(name, callback) {
/** @type {GMObject_panel_item} */
const panel = gm.panel[name]
if (panel.wait > 0) return
try {
try {
if (panel.state === 1) {
panel.wait = 2
await api.wait.waitForConditionPassed({
condition: () => panel.state === 2,
timeout: 1500 + (panel.el.fadeInTime ?? gm.const.fadeTime),
})
} else if (panel.state === 3) {
panel.wait = 2
await api.wait.waitForConditionPassed({
condition: () => panel.state === 0,
timeout: 1500 + (panel.el.fadeOutTime ?? gm.const.fadeTime),
})
return true
}
} catch (e) {
panel.state = -1
api.logger.error(e)
} finally {
panel.wait = 0
}
if (panel.state === 2 || panel.state === -1) {
panel.state = 3
await panel.closeHandler?.()
await new Promise(resolve => {
api.dom.fade(false, panel.el, () => {
resolve()
panel.closedHandler?.()
callback?.(panel)
})
})
panel.state = 0
return true
}
} catch (e) {
panel.state = -1
api.logger.error(e)
}
return false
}
/**
* 导出稍后再看列表
*/
async exportWatchlaterList() {
try {
const ITEMS = await gm.data.watchlaterListData(true)
/* eslint-disable no-eval */
/* eslint-disable no-unused-vars */
const 是 = true
const 否 = false
/* eslint-disable prefer-const */
let 导出至剪贴板 = true
let 导出至新页面 = false
let 导出至文件 = false
let 导出文件名 = null
let 相邻稿件换行 = true
let 前置内容 = null
let 后置内容 = null
let 稿件导出模板 = null
/* eslint-enable prefer-const */
let config = GM_getValue('exportWatchlaterListConfig')
if (!config || config.trim() === '') {
config = gm.const.exportWatchlaterList_default
GM_setValue('exportWatchlaterListConfig', config)
}
eval(config)
const front = 前置内容 ? eval('`' + 前置内容 + '`') : ''
const rear = 后置内容 ? eval('`' + 后置内容 + '`') : ''
const items = []
for (const [idx, ITEM] of ITEMS.entries()) {
const INDEX = idx + 1
items.push(eval('`' + 稿件导出模板 + '`'))
}
if (导出至剪贴板 || 导出至文件) {
const content = `${front}${相邻稿件换行 ? items.join('\n') : items.join('')}${rear}`
if (导出至剪贴板) {
await navigator.clipboard.writeText(content).then(
() => api.message.info('稍后再看列表已导出至剪贴板'),
() => api.message.info('稍后再看列表写入剪贴板失败', 3000),
)
}
if (导出至文件) {
const filename = 导出文件名 ? eval('`' + 导出文件名 + '`') : `稍后再看列表.${Date.now()}.txt`
const file = new Blob([content], { type: 'text/plain' })
const a = document.createElement('a')
a.href = URL.createObjectURL(file)
a.download = filename
a.click()
}
}
if (导出至新页面) {
const center = 相邻稿件换行 ? items.join('
') : items.join('')
const content = `${front !== '' ? `
${front}
` : ''}${center}
${rear !== '' ? `${rear}
` : ''}`.replaceAll(/\n(?!<\/p>)/g, '
').replaceAll('\n', '')
const w = window.open()
w.document.write(content)
w.document.close()
w.document.title = `稍后再看列表@${new Date().toLocaleString()}`
}
/* eslint-enable no-eval */
/* eslint-enable no-unused-vars */
} catch (e) {
api.logger.error(e)
const result = await api.message.confirm('稍后再看列表导出失败,可能是导出方式配置错误(错误信息详见控制台)。是否打开导出设置?')
if (result) {
this.setExportWatchlaterList()
}
}
}
/**
* 设置稍后再看列表导入方式
*/
setImportWatchlaterList() {
const msg = `
设置稍后再看列表导入方式。默认简单读取所有形如 BV###
的字符串。
若有进一步的需求,请提前设计好稍后再看列表文件的格式,使用正则表达式(不区分大小写)指定每个稿件对应的文本,然后指定稿件 ID、稿件标题、来源(建议:上传者名称)、时间节点等信息对应的捕获组。
可填写 -1
禁用某项信息,但 aid / bvid
至少填写一个(冲突时优先使用「AV 号」)。时间节点在批量添加管理器中被用于在步骤 ② 中判断稿件是否超出设定的时间范围,根据用户需要可设定为稿件发布时间或文件导出时间等,冲突时优先使用「时间节点(秒)」。
`
const btnText = ['重置', '确定', '取消']
const dialog = api.message.dialog(msg, { html: true, buttons: btnText })
const [regex, aid, bvid, title, source, tsS, tsMs, reset, confirm, cancel] = dialog.interactives
const config = { regex, aid, bvid, title, source, tsS, tsMs }
reset.addEventListener('click', () => {
for (const [n, el] of Object.entries(config)) {
el.value = gm.configMap[`importWl_${n}`].default
}
})
confirm.addEventListener('click', () => {
dialog.close()
for (const [n, el] of Object.entries(config)) {
const k = `importWl_${n}`
const v = gm.configMap[k]?.type === 'int' ? Number.parseInt(el.value) : el.value
gm.config[k] = v
GM_setValue(k, v)
}
api.message.info('已保存稍后再看列表导入设置')
})
cancel.addEventListener('click', () => dialog.close())
for (const [n, el] of Object.entries(config)) {
el.value = gm.config[`importWl_${n}`]
}
dialog.open()
}
/**
* 设置稍后再看列表导出方式
*/
setExportWatchlaterList() {
const msg = '设置稍后再看列表导出方式。默认情况下简单地导出各稿件的普通播放页 URL 到剪贴板,如需使用其他导出模板或使用文件等方式导出,请参考「示例」进行定义。置空时使用默认值。'
const btnText = ['示例', '重置', '确定', '取消']
const dialog = api.message.dialog(msg, {
buttons: btnText,
boxInput: true,
})
const [input, example, reset, confirm, cancel] = dialog.interactives
const config = GM_getValue('exportWatchlaterListConfig')
input.value = (config && config.trim() !== '') ? config : gm.const.exportWatchlaterList_default
input.style.height = '20em'
input.style.fontSize = '0.8em'
input.style.fontFamily = 'monospace'
input.focus({ preventScroll: true })
example.addEventListener('click', async () => {
let ref = ''
const data = await gm.data.watchlaterListData(true)
if (data[0]) {
const attrs = []
for (const attr in data[0]) {
if (Object.hasOwn(data[0], attr)) {
attrs.push(attr)
}
}
ref = `// ITEM 属性如下行所示,可在点击「示例」后在控制台查看详细内容结构\n// ${attrs.join(', ')}\n`
api.logger.info('ITEM 内容结构如下:')
api.logger.info(data[0])
}
input.value = `// 右键点击稍后再看列表页面的「导出列表」按钮可快速打开此设置框\n\n// 不需要的配置直接删除行即可,缺省配置会使用默认值\n// 使用 \${} 引用变量,配合单引号 '' 或双引号 "" 使用(而非反引号 \`\`)\n// - \${INDEX}: 稿件在列表中的位置(从 1 开始)\n// - \${ITEMS}: 稿件项目数组\n// - \${ITEM}: 稿件项目\n${ref}\n导出至剪贴板 = 否\n导出至新页面 = 否\n导出至文件 = 是\n导出文件名 = '稍后再看列表.\${Date.now()}.txt' // 注意文件名是否合法\n相邻稿件换行 = 是\n\n前置内容 = '稍后再看列表@\${new Date().toLocaleString()}\\n'\n后置内容 = '\\n--------------- 共 \${ITEMS.length} 个稿件 ---------------'\n稿件导出模板 = '[\${INDEX}] www.bilibili.com/video/\${ITEM.bvid}'\n\n// 可在此处通过 JavaScript 代码进行导出前的准备操作\n// 示例:按稿件硬币数进行排序,随后按此顺序导出(取消注释以使用)\n// ITEMS.sort((a, b) => a.stat.coin - b.stat.coin) // 实际编写时建议增加异常处理`
})
reset.addEventListener('click', () => {
input.value = gm.const.exportWatchlaterList_default
})
confirm.addEventListener('click', () => {
dialog.close()
GM_setValue('exportWatchlaterListConfig', input.value)
api.message.info('已保存稍后再看列表导出设置')
})
cancel.addEventListener('click', () => dialog.close())
dialog.open()
}
}
/**
* 页面处理的抽象,脚本围绕网站的特化部分
*/
class Webpage {
/** 内部数据 */
#data = {}
/** 通用方法 */
method = {
/** @type {Webpage} */
obj: null,
/**
* 获取指定 Cookie
* @param {string} key 键
* @returns {string} 值
* @see {@link https://developer.mozilla.org/zh-CN/docs/Web/API/Document/cookie#示例2_得到名为test2的cookie Document.cookie - Web API 接口参考 | MDN}
*/
cookie(key) {
return document.cookie.replace(new RegExp(String.raw`(?:(?:^|.*;\s*)${key}\s*=\s*([^;]*).*$)|^.*$`), '$1')
},
/**
* 判断用户是否已登录
* @returns {boolean} 用户是否已登录
*/
isLogin() {
return Boolean(this.getCSRF())
},
/**
* 获取当前登录用户 ID
* @returns {string} `DedeUserID`
*/
getDedeUserID() {
return this.cookie('DedeUserID')
},
/**
* 获取 CSRF
* @returns {string} `csrf`
*/
getCSRF() {
return this.cookie('bili_jct')
},
/**
* av/bv 互转工具类
*
* 转换算法最初由知乎用户 {@link https://www.zhihu.com/people/-._.- mcfx} 破解:{@link https://www.zhihu.com/question/381784377/answer/1099438784 如何看待 2020 年 3 月 23 日哔哩哔哩将稿件的「av 号」变更为「BV 号」? - 知乎 - mcfx 的回答},但只支持 av < 2 ** 30 的情况。更完善的算法来自B站上的某个 JavaScript 文件,另 GitHub 上也有一份员工泄露版——但不管怎么说,目前版本应该就是B站实际使用版本,AV 最大值为 2 ** 51。
* @see {@link https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/misc/bvid_desc.md SocialSisterYi/bilibili-API-collect · bvid说明}
*/
bvTool: new class BvTool {
constructor() {
const XOR_CODE = 23442827791579n
const MASK_CODE = 2251799813685247n
const MAX_AID = 1n << 51n
const BASE = 58n
const data = 'FcwAPNKTMug3GV5Lj7EJnHpWsx4tb8haYeviqBz6rkCy12mUSDQX9RdoZf'
this.av2bv = av2bv
this.bv2av = bv2av
function av2bv(aid) {
try {
const bytes = ['B', 'V', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0']
let bvIndex = bytes.length - 1
let tmp = (MAX_AID | BigInt(aid)) ^ XOR_CODE
while (tmp > 0) {
bytes[bvIndex] = data[Number(tmp % BigInt(BASE))]
tmp /= BASE
bvIndex -= 1
}
[bytes[3], bytes[9]] = [bytes[9], bytes[3]];
[bytes[4], bytes[7]] = [bytes[7], bytes[4]]
return bytes.join('')
} catch {
return null
}
}
function bv2av(bvid) {
try {
const bvidArr = [...bvid];
[bvidArr[3], bvidArr[9]] = [bvidArr[9], bvidArr[3]];
[bvidArr[4], bvidArr[7]] = [bvidArr[7], bvidArr[4]]
bvidArr.splice(0, 3)
const tmp = bvidArr.reduce((pre, bvidChar) => pre * BASE + BigInt(data.indexOf(bvidChar)), 0n)
return String((tmp & MASK_CODE) ^ XOR_CODE)
} catch {
return null
}
}
}
}(),
/**
* 从 URL 获取稿件 ID
* @param {string} [url=location.href] 提取稿件 ID 的源字符串
* @returns {{id: string, type: 'aid' | 'bvid'}} `{id, type}`
*/
getVid(url = location.href) {
let m = null
if ((m = /(\/|bvid=)bv([\da-z]+)([#&/?]|$)/i.exec(url))) {
return { id: 'BV' + m[2], type: 'bvid' }
} else if ((m = /(\/(av)?|aid=)(\d+)([#&/?]|$)/i.exec(url))) { // 兼容 BV 号被第三方修改为 AV 号的情况
return { id: m[3], type: 'aid' }
}
return null
},
/**
* 从 URL 获取稿件 `aid`
* @param {string} [url=location.href] 提取稿件 `aid` 的源字符串
* @returns {string} `aid`
*/
getAid(url = location.href) {
const vid = this.getVid(url)
if (!vid) return null
return (vid.type === 'bvid') ? this.bvTool.bv2av(vid.id) : vid.id
},
/**
* 从 URL 获取稿件 `bvid`
* @param {string} [url=location.href] 提取稿件 `bvid` 的源字符串
* @returns {string} `bvid`
*/
getBvid(url = location.href) {
const vid = this.getVid(url)
if (!vid) return null
return (vid.type === 'aid') ? this.bvTool.av2bv(vid.id) : vid.id
},
/**
* 根据 `aid` 获取稿件的稍后再看状态
* @param {string | number} aid 稿件 `aid`
* @param {boolean} [reload] 是否重新加载
* @param {boolean} [pageCache] 是否禁用页面缓存
* @param {boolean} [localCache=true] 是否使用本地缓存
* @returns {Promise} 稿件是否在稍后再看中
*/
async getVideoWatchlaterStatusByAid(aid, reload, pageCache, localCache = true) {
const map = await this.getWatchlaterDataMap(item => String(item.aid), 'aid', reload, pageCache, localCache)
return map.has(String(aid))
},
/**
* 将稿件加入稍后再看,或从稍后再看移除
* @param {string} id 稿件 `aid` 或 `bvid`(执行移除时优先选择 `aid`)
* @param {boolean} [status=true] 添加 `true` / 移除 `false`
* @returns {Promise} 操作是否成功(稿件不在稍后在看中不被判定为失败)
*/
async switchVideoWatchlaterStatus(id, status = true) {
try {
let typeA = /^\d+$/.test(id)
if (!typeA && !status) { // 移除 API 只支持 aid,先作转换
id = this.bvTool.bv2av(id)
typeA = true
}
const data = new URLSearchParams()
if (typeA) {
data.append('aid', id)
} else {
data.append('bvid', id)
}
data.append('csrf', this.getCSRF())
return await api.web.request({
method: 'POST',
url: status ? gm.url.api_addToWatchlater : gm.url.api_removeFromWatchlater,
data,
}, { parser: 'check', check: r => r.code === 0 })
} catch (e) {
api.logger.error(e)
return false
}
},
/**
* 清空稍后再看
* @returns {Promise} 操作是否成功
*/
async clearWatchlater() {
try {
const data = new URLSearchParams()
data.append('csrf', this.getCSRF())
const success = await api.web.request({
method: 'POST',
url: gm.url.api_clearWatchlater,
data,
}, { parser: 'check', check: r => r.code === 0 })
if (success) {
gm.runtime.reloadWatchlaterListData = true
window.dispatchEvent(new CustomEvent('reloadWatchlaterListData'))
}
return success
} catch (e) {
api.logger.error(e)
return false
}
},
/**
* 移除稍后再看已观看稿件
* @returns {Promise} 操作是否成功
*/
async clearWatchedInWatchlater() {
try {
const data = new URLSearchParams()
data.append('viewed', true)
data.append('csrf', this.getCSRF())
const success = await api.web.request({
method: 'POST',
url: gm.url.api_removeFromWatchlater,
data,
}, { parser: 'check', check: r => r.code === 0 })
if (success) {
gm.runtime.reloadWatchlaterListData = true
window.dispatchEvent(new CustomEvent('reloadWatchlaterListData'))
}
return success
} catch (e) {
api.logger.error(e)
return false
}
},
/**
* 使用稍后再看列表数据更新稍后再看历史数据
* @param {boolean} [reload] 是否重新加载稍后再看列表数据
*/
async updateRemoveHistoryData(reload) {
if (gm.config.removeHistory) {
const removeHistorySaveTime = GM_getValue('removeHistorySaveTime') ?? 0
const removeHistorySavePeriod = GM_getValue('removeHistorySavePeriod') ?? gm.configMap.removeHistorySavePeriod.default
if ((Date.now() - removeHistorySaveTime > removeHistorySavePeriod * 1000) && !gm.runtime.savingRemoveHistoryData) {
gm.runtime.savingRemoveHistoryData = true
await gm.data.watchlaterListData(reload).then(current => {
if (current.length > 0) {
if (gm.config.removeHistoryFuzzyCompare > 0) {
const ref = GM_getValue('removeHistoryFuzzyCompareReference')
let same = true
if (ref) {
for (let i = 0; i < gm.config.removeHistoryFuzzyCompare; i++) {
const c = current[i]
const r = ref[i]
if (c) { // 如果 current 没有数据直接跳过得了
if (r) {
if (c.bvid !== r) {
same = false
break
}
} else {
same = false
break
}
}
}
} else {
same = false
}
if (same) {
GM_setValue('removeHistorySaveTime', Date.now())
return
}
if (current.length >= gm.config.removeHistoryFuzzyCompare) {
const newRef = []
for (let i = 0; i < gm.config.removeHistoryFuzzyCompare; i++) {
newRef.push(current[i].bvid)
}
GM_setValue('removeHistoryFuzzyCompareReference', newRef)
} else {
// 若 current 长度不够,那么加进去也白搭
GM_deleteValue('removeHistoryFuzzyCompareReference')
}
}
const data = gm.data.removeHistoryData()
let updated = false
if (gm.config.removeHistoryTimestamp) {
const timestamp = Date.now()
const map = new Map()
for (const [index, record] of data.entries()) {
map.set(record[0], index)
}
for (let i = current.length - 1; i >= 0; i--) {
const item = current[i]
if (map.has(item.bvid)) {
const idx = map.get(item.bvid)
data.data[idx][2] = timestamp
} else {
data.enqueue([item.bvid, item.title, timestamp])
}
}
updated = true
} else {
const set = new Set()
for (const record of data) {
set.add(record[0])
}
for (let i = current.length - 1; i >= 0; i--) {
const item = current[i]
if (!set.has(item.bvid)) {
data.enqueue([item.bvid, item.title])
updated = true
}
}
}
if (updated) {
GM_setValue('removeHistoryData', data)
}
// current.length === 0 时不更新
// 不要提到前面,否则时间不准确
GM_setValue('removeHistorySaveTime', Date.now())
}
}).finally(() => {
gm.runtime.savingRemoveHistoryData = false
})
}
}
},
/**
* 获取稍后再看列表数据以指定值为键的映射
* @param {(item: GMObject_data_item0) => *} key 计算键值的方法
* @param {string} [cacheId] 缓存 ID,传入空值时不缓存
* @param {boolean} [reload] 是否重新加载
* @param {boolean} [pageCache] 是否使用页面缓存
* @param {boolean} [localCache=true] 是否使用本地缓存
* @returns {Promise