used youtube's videodatachange event

This commit is contained in:
Araxeus
2021-11-09 16:08:40 +02:00
parent 65ce62adc1
commit 895136af0a
3 changed files with 43 additions and 30 deletions

View File

@ -6,6 +6,8 @@ function $(selector) { return document.querySelector(selector); }
let options;
let api;
const switchButtonDiv = ElementFromFile(
templatePath(__dirname, "button_template.html")
);
@ -17,7 +19,9 @@ module.exports = (_options) => {
document.addEventListener('apiLoaded', setup, { once: true, passive: true });
}
function setup() {
function setup(e) {
api = e.detail;
$('ytmusic-player-page').prepend(switchButtonDiv);
$('#song-image.ytmusic-player').style.display = "block"
@ -36,6 +40,8 @@ function setup() {
})
$('video').addEventListener('srcChanged', videoStarted);
observeThumbnail();
}
function changeDisplay(showVideo) {
@ -51,11 +57,8 @@ function changeDisplay(showVideo) {
}
function videoStarted() {
if (videoExist()) {
const thumbnails = $('#movie_player').getPlayerResponse()?.videoDetails?.thumbnail?.thumbnails;
if (thumbnails && thumbnails.length > 0) {
$('#song-image img').src = thumbnails[thumbnails.length-1].url;
}
if (api.getPlayerResponse().videoDetails.musicVideoType === 'MUSIC_VIDEO_TYPE_OMV') { // or `$('#player').videoMode_`
forceThumbnail($('#song-image img'));
switchButtonDiv.style.display = "initial";
if (!options.hideVideo && $('#song-video.ytmusic-player').style.display === "none") {
changeDisplay(true);
@ -66,10 +69,6 @@ function videoStarted() {
}
}
function videoExist() {
return $('#player').videoMode_;
}
// on load, after a delay, the page overrides the playback-mode to 'OMV_PREFERRED' which causes weird aspect ratio in the image container
// this function fix the problem by overriding that override :)
function forcePlaybackMode() {
@ -83,3 +82,22 @@ function forcePlaybackMode() {
});
playbackModeObserver.observe($('ytmusic-player'), { attributeFilter: ["playback-mode"] })
}
function observeThumbnail() {
const playbackModeObserver = new MutationObserver(mutations => {
if (!$('#player').videoMode_) return;
mutations.forEach(mutation => {
if (!mutation.target.src.startsWith('data:')) return;
forceThumbnail(mutation.target)
});
});
playbackModeObserver.observe($('#song-image img'), { attributeFilter: ["src"] })
}
function forceThumbnail(img) {
const thumbnails = $('#movie_player').getPlayerResponse()?.videoDetails?.thumbnail?.thumbnails;
if (thumbnails && thumbnails.length > 0) {
img.src = thumbnails[thumbnails.length - 1].url;
}
}