-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyoutube-enhanced.js
More file actions
287 lines (233 loc) · 9.39 KB
/
youtube-enhanced.js
File metadata and controls
287 lines (233 loc) · 9.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
{
// * ---------------------------------------------------------------- situations
const s = {
//
/**
* channel's home, mini player
* https://www.youtube.com/@MrBeast
*/
1: "#container > #c4-player > .html5-video-container > video[src]",
/**
* main player, mini player
* https://www.youtube.com/watch?v=mwKJfNYwvm8
*/
2: "#container > #movie_player > .html5-video-container > video[src]",
/**
* short player
* https://www.youtube.com/shorts/V6In4tmd-w8
*/
3: "#container > #shorts-player > .html5-video-container > video[src]",
};
// * ---------------------------------------------------------------- get video elements
const getVideos = () => {
/** @type {HTMLVideoElement} */
const channelVideo = document.querySelector("#c4-player video");
/** @type {HTMLVideoElement} */
const shortVideo = document.querySelector("#shorts-player video");
/** @type {HTMLVideoElement} */
const normalVideo = document.querySelector("#movie_player video");
const href = location.href;
/** 主 video */
const main = href.includes("youtube.com/@") ? channelVideo : href.includes("youtube.com/shorts") ? shortVideo : normalVideo;
/** 所有 video 元素 */
const videos = [channelVideo, shortVideo, normalVideo].filter((e) => e);
return { main, videos };
};
/** @param {string} text */
const toast = (text) => mediaControl.toast(getVideos().main.parentElement.parentElement, text);
// * ---------------------------------------------------------------- global solo playing
document.addEventListener("DOMContentLoaded", () => {
mediaControl.enableGlobalSoloPlaying(() => getVideos().videos);
});
// * ---------------------------------------------------------------- keep youtube actived and non stop
{
/** while playing, press F32 every 10 mins */
let ticker;
const bust = () => document.dispatchEvent(new KeyboardEvent("keyup", { keyCode: 143 }));
document.addEventListener(
"play",
() => {
bust();
clearInterval(ticker);
ticker = setInterval(bust, 600000);
},
true,
);
document.addEventListener("pause", () => clearInterval(ticker), true);
}
// document.addEventListener(
// "pause",
// (e) => {
// const popup = document.querySelector("ytd-popup-container tp-yt-paper-dialog");
// const text = popup.querySelector("tp-yt-paper-dialog-scrollable yt-formatted-string")?.textContent;
// // @ts-ignore
// if (popup?.style.display !== "none" && text?.includes("Video paused. Continue watching?")) {
// // @ts-ignore
// popup.querySelector("#confirm-button button")?.click();
// }
// },
// true
// );
// * ---------------------------------------------------------------- auto set resolution
{
const setResolution = () => {
const maxHqLimit = [
//
// "hd2160",
"hd1440",
"hd1080",
"hd720",
];
const node = document.querySelector("#movie_player");
/** @type string[] */
// @ts-ignore
const resolutions = node.getAvailableQualityLevels();
const nextRes = resolutions.find((e) => maxHqLimit.includes(e));
// @ts-ignore
node.setPlaybackQualityRange(nextRes);
};
domObserverOnce("#movie_player", (node) => {
/** after initial page load */
setResolution();
/** after video src changed */
node.querySelector("video").addEventListener("loadstart", setResolution);
});
}
// * ---------------------------------------------------------------- get caption
let captionUrl;
// * ----------------
const obs = new PerformanceObserver((list) => {
/** get caption url directly, it has poToken and it works */
const url = list.getEntries().find((e) => e.name.includes("/api/timedtext"))?.name;
if (url) captionUrl = url;
});
obs.observe({ entryTypes: ["resource"] });
// @ts-ignore
window.navigation.addEventListener("navigate", () => {
captionUrl = undefined;
});
// * ----------------
const copyCaption = async () => {
if (!captionUrl) return toast("无字幕");
const res = await fetch(captionUrl).then((e) => e.text());
const captionText = JSON.parse(res)
.events.map((e) => e.segs?.map((e) => e.utf8).join(" "))
.join(" ");
navigator.clipboard.writeText(captionText);
toast("复制字幕");
};
// * ---------------------------------------------------------------- hotkey
{
document.addEventListener("keydown", (e) => {
if (["INPUT", "TEXTAREA"].includes(document.activeElement?.tagName ?? "")) return;
const ytbVideo = getVideos().main;
if (!ytbVideo) return;
// * ----------------
const mc = mediaControl;
const jumpStep = 1;
const speedStep = 0.125;
/** @type [number,number] */
const speedRange = [0.125, 4];
// * ----------------
/** @param {HTMLVideoElement} video */
const toastPlaybackSpeed = (video) => {
const curRatio = video?.playbackRate;
curRatio && toast("倍速 " + curRatio.toFixed(3).replace(/\.?0+$/, ""));
};
// * ----------------
if (false) "";
// * ---------------- playlist
else if (e.key === "[" || e.key === "PageUp") (e.preventDefault(), playlistJump(-1));
else if (e.key === "]" || e.key === "PageDown") (e.preventDefault(), playlistJump(1));
// * ---------------- play speed
else if (!(e.ctrlKey || e.metaKey || e.shiftKey) && e.key === "z") {
mc.setPlaybackSpeedBy(ytbVideo, -speedStep, speedRange);
toastPlaybackSpeed(ytbVideo);
} else if (!(e.ctrlKey || e.metaKey || e.shiftKey) && e.key === "x") {
mc.setPlaybackSpeedBy(ytbVideo, +speedStep, speedRange);
toastPlaybackSpeed(ytbVideo);
} else if (!(e.ctrlKey || e.metaKey || e.shiftKey) && e.key === "v") {
mc.togglePlaybackSpeed(ytbVideo);
toastPlaybackSpeed(ytbVideo);
}
// * ---------------- jump
else if (e.key === "Backspace") mediaControl.setPlaybackJumpToPercent(ytbVideo, 0);
else if (!(e.ctrlKey || e.metaKey || e.shiftKey) && e.key === "q") mc.setPlaybackJumpBySec(ytbVideo, -jumpStep);
else if (!(e.ctrlKey || e.metaKey || e.shiftKey) && e.key === "e") mc.setPlaybackJumpBySec(ytbVideo, +jumpStep);
// * ---------------- snap
else if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === "s") {
mediaControl.videoSnap(ytbVideo);
toast("复制截图");
}
// * ---------------- caption
else if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === "d") {
e.preventDefault();
copyCaption();
}
});
// * ---------------- playlist control
/** @param {-1|1} direction */
const playlistJump = (direction) => {
if (direction === -1) {
// @ts-ignore
document.querySelector("#movie_player .ytp-prev-button")?.click();
} else if (direction === 1) {
// @ts-ignore
document.querySelector("#movie_player .ytp-next-button")?.click();
}
};
}
// * ---------------------------------------------------------------- progress bar
{
// * ---------------- calculation
/**
* 因为 列表、children、时间标签 都是动态加载的,所以不容易做缓存什么的
* 简单的每次都计算,性能影响不会很大
*
* @param {HTMLElement} playlistEl
* @returns {[number,number]} [current time, total time]
*/
const calcTime = (playlistEl) => {
const playlistItems = Array.from(playlistEl.querySelector("#items")?.children);
const currentVideoIndex = playlistItems.findIndex((e) => e.attributes["selected"]);
// @ts-ignore
const timesList = playlistItems.map((e) => e.querySelector("span.ytd-thumbnail-overlay-time-status-renderer")?.innerText).map((e) => progressBar.readable2sec(e));
return [
//
timesList.slice(0, currentVideoIndex).reduce((a, e) => a + e, 0) + getVideos().main?.currentTime,
timesList.reduce((a, e) => a + e, 0),
];
};
// * ---------------- start
const mediasFlag = new WeakMap();
document.addEventListener(
"loadstart",
(e) => {
const media = e.target;
if (mediasFlag.has(media)) return;
const shouldControl = media === getVideos().main;
if (!shouldControl) return mediasFlag.set(media, false);
const updateHandler = () => {
// const isPlaylist = new URL(window.location.href).searchParams.get("list") !== null;
// if (!isPlaylist) return;
/** @type {HTMLElement} */
const playlistEl = document.querySelector("#content ytd-playlist-panel-renderer");
if (!playlistEl) return;
const pb = progressBar;
if (!playlistEl.contains(pb.pbEl)) {
playlistEl.style.position = "relative";
Object.assign(pb.pbEl.style, { position: "absolute", top: "0", right: "0", width: "100%" });
Object.assign(pb.textEl.style, { right: "8px" });
playlistEl.appendChild(pb.pbEl);
}
const [currentTime, totalTime] = calcTime(playlistEl);
pb.updateProgressBar(currentTime, totalTime);
};
media.addEventListener("timeupdate", updateHandler);
mediasFlag.set(media, updateHandler);
},
true,
);
}
// * ----------------------------------------------------------------
}