Refactor inject.js (#216)

This commit is contained in:
rlauuzo 2024-07-24 12:56:12 +02:00 committed by GitHub
parent 29f79e8f84
commit 96dc3a9763
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,84 +1,67 @@
let introSkipper = { const introSkipper = {
allowEnter: true,
skipSegments: {},
videoPlayer: {},
// .bind() is used here to prevent illegal invocation errors
originalFetch: window.fetch.bind(window), originalFetch: window.fetch.bind(window),
}; d: msg => console.debug("[intro skipper] ", msg),
introSkipper.d = function (msg) { setup() {
console.debug("[intro skipper] ", msg); this.initializeState();
} document.addEventListener("viewshow", this.viewShow.bind(this));
/** Setup event listeners */ window.fetch = this.fetchWrapper.bind(this);
introSkipper.setup = function () { this.videoPositionChanged = this.videoPositionChanged.bind(this);
document.addEventListener("viewshow", introSkipper.viewShow); this.d("Registered hooks");
window.fetch = introSkipper.fetchWrapper; },
introSkipper.d("Registered hooks"); initializeState() {
} Object.assign(this, { allowEnter: true, skipSegments: {}, videoPlayer: null, skipButton: null, osdElement: null });
},
/** Wrapper around fetch() that retrieves skip segments for the currently playing item. */ /** Wrapper around fetch() that retrieves skip segments for the currently playing item. */
introSkipper.fetchWrapper = async function (...args) { async fetchWrapper(resource, options) {
// Based on JellyScrub's trickplay.js const response = await this.originalFetch(resource, options);
let [resource, options] = args;
let response = await introSkipper.originalFetch(resource, options);
// Bail early if this isn't a playback info URL
try { try {
let path = new URL(resource).pathname; const url = new URL(resource);
if (!path.includes("/PlaybackInfo")) { return response; } if (!url.pathname.includes("/PlaybackInfo")) return response;
introSkipper.d("Retrieving skip segments from URL"); this.d("Retrieving skip segments from URL", url.pathname);
introSkipper.d(path); const pathArr = url.pathname.split("/");
const id = pathArr[1] === "Items" ? pathArr[2] : pathArr[3];
// Check for context root and set id accordingly this.skipSegments = await this.secureFetch(`Episode/${id}/IntroSkipperSegments`);
let path_arr = path.split("/"); this.d("Successfully retrieved skip segments", this.skipSegments);
let id = ""; } catch (e) {
if (path_arr[1] == "Items") {
id = path_arr[2];
} else {
id = path_arr[3];
}
introSkipper.skipSegments = await introSkipper.secureFetch(`Episode/${id}/IntroSkipperSegments`);
introSkipper.d("Successfully retrieved skip segments");
introSkipper.d(introSkipper.skipSegments);
}
catch (e) {
console.error("Unable to get skip segments from", resource, e); console.error("Unable to get skip segments from", resource, e);
} }
return response; return response;
} },
/** /**
* Event handler that runs whenever the current view changes. * Event handler that runs whenever the current view changes.
* Used to detect the start of video playback. * Used to detect the start of video playback.
*/ */
introSkipper.viewShow = function () { viewShow() {
const location = window.location.hash; const location = window.location.hash;
introSkipper.d("Location changed to " + location); this.d(`Location changed to ${location}`);
if (location !== "#/video") { if (location !== "#/video") {
introSkipper.d("Ignoring location change"); if (this.videoPlayer) this.initializeState();
return; return;
} }
introSkipper.injectCss(); this.injectCss();
introSkipper.injectButton(); this.injectButton();
introSkipper.videoPlayer = document.querySelector("video"); this.videoPlayer = document.querySelector("video");
if (introSkipper.videoPlayer != null) { if (this.videoPlayer) {
introSkipper.d("Hooking video timeupdate"); this.d("Hooking video timeupdate");
introSkipper.videoPlayer.addEventListener("timeupdate", introSkipper.videoPositionChanged); this.videoPlayer.addEventListener("timeupdate", this.videoPositionChanged);
document.body.addEventListener('keydown', introSkipper.eventHandler, true); this.osdElement = document.querySelector("div.videoOsdBottom")
}
} }
},
/** /**
* Injects the CSS used by the skip intro button. * Injects the CSS used by the skip intro button.
* Calling this function is a no-op if the CSS has already been injected. * Calling this function is a no-op if the CSS has already been injected.
*/ */
introSkipper.injectCss = function () { injectCss() {
if (introSkipper.testElement("style#introSkipperCss")) { if (document.querySelector("style#introSkipperCss")) {
introSkipper.d("CSS already added"); this.d("CSS already added");
return; return;
} }
introSkipper.d("Adding CSS"); this.d("Adding CSS");
let styleElement = document.createElement("style"); const styleElement = document.createElement("style");
styleElement.id = "introSkipperCss"; styleElement.id = "introSkipperCss";
styleElement.innerText = ` styleElement.textContent = `
:root { :root {
--rounding: .2em; --rounding: 4px;
--accent: 0, 164, 220; --accent: 0, 164, 220;
} }
#skipIntro.upNextContainer { #skipIntro.upNextContainer {
@ -87,236 +70,164 @@ introSkipper.d = function (msg) {
} }
#skipIntro { #skipIntro {
position: absolute; position: absolute;
bottom: 6em; bottom: 7.5em;
right: 4.5em; right: 5em;
background-color: transparent; background-color: transparent;
font-size: 1.2em;
} }
#skipIntro .emby-button { #skipIntro .emby-button {
text-shadow: 0 0 3px rgba(0, 0, 0, 0.7); color: #ffffff;
font-size: 110%;
background: rgba(0, 0, 0, 0.8);
border-radius: var(--rounding); border-radius: var(--rounding);
background-color: rgba(0, 0, 0, 0.3); box-shadow: 0 0 4px rgba(0, 0, 0, 0.6);
will-change: opacity, transform; transition: opacity 0.3s cubic-bezier(0.4,0,0.2,1),
transform 0.3s cubic-bezier(0.4,0,0.2,1),
background-color 0.2s ease-out,
box-shadow 0.2s ease-out;
opacity: 0; opacity: 0;
transition: opacity 0.3s ease-in, transform 0.3s ease-out; transform: translateY(50%);
} }
#skipIntro.show .emby-button { #skipIntro.show .emby-button {
opacity: 1; opacity: 1;
transform: translateY(0);
} }
#skipIntro .emby-button:hover, #skipIntro .emby-button:hover,
#skipIntro .emby-button:focus { #skipIntro .emby-button:focus {
background-color: rgba(var(--accent),0.7); background: rgba(var(--accent), 1);
transform: scale(1.05); box-shadow: 0 0 8px rgba(var(--accent), 0.6);
} }
#btnSkipSegmentText { #btnSkipSegmentText {
padding-right: 0.15em; letter-spacing: 0.5px;
padding-left: 0.2em; padding: 0 5px 0 5px;
margin-top: -0.1em;
} }
`; `;
document.querySelector("head").appendChild(styleElement); document.querySelector("head").appendChild(styleElement);
} },
/** /**
* Inject the skip intro button into the video player. * Inject the skip intro button into the video player.
* Calling this function is a no-op if the CSS has already been injected. * Calling this function is a no-op if the CSS has already been injected.
*/ */
introSkipper.injectButton = async function () { async injectButton() {
// Ensure the button we're about to inject into the page doesn't conflict with a pre-existing one // Ensure the button we're about to inject into the page doesn't conflict with a pre-existing one
const preExistingButton = introSkipper.testElement("div.skipIntro"); const preExistingButton = document.querySelector("div.skipIntro");
if (preExistingButton) { if (preExistingButton) {
preExistingButton.style.display = "none"; preExistingButton.style.display = "none";
} }
if (introSkipper.testElement(".btnSkipIntro.injected")) { if (document.querySelector(".btnSkipIntro.injected")) {
introSkipper.d("Button already added"); this.d("Button already added");
this.skipButton = document.querySelector("#skipIntro");
return; return;
} }
introSkipper.d("Adding button"); const config = await this.secureFetch("Intros/UserInterfaceConfiguration");
let config = await introSkipper.secureFetch("Intros/UserInterfaceConfiguration");
if (!config.SkipButtonVisible) { if (!config.SkipButtonVisible) {
introSkipper.d("Not adding button: not visible"); this.d("Not adding button: not visible");
return; return;
} }
// Construct the skip button div this.d("Adding button");
const button = document.createElement("div"); this.skipButton = document.createElement("div");
button.id = "skipIntro" this.skipButton.id = "skipIntro";
button.classList.add("hide"); this.skipButton.classList.add("hide", "upNextContainer");
button.addEventListener("click", introSkipper.doSkip); this.skipButton.addEventListener("click", this.doSkip.bind(this));
button.innerHTML = ` this.skipButton.addEventListener("keydown", this.eventHandler.bind(this));
this.skipButton.innerHTML = `
<button is="emby-button" type="button" class="btnSkipIntro injected"> <button is="emby-button" type="button" class="btnSkipIntro injected">
<span id="btnSkipSegmentText"></span> <span id="btnSkipSegmentText"></span>
<span class="material-icons skip_next"></span> <span class="material-icons">skip_next</span>
</button> </button>
`; `;
button.dataset["intro_text"] = config.SkipButtonIntroText; this.skipButton.dataset.Introduction = config.SkipButtonIntroText;
button.dataset["credits_text"] = config.SkipButtonEndCreditsText; this.skipButton.dataset.Credits = config.SkipButtonEndCreditsText;
/* const controls = document.querySelector("div#videoOsdPage");
* Alternative workaround for #44. Jellyfin's video component registers a global click handler controls.appendChild(this.skipButton);
* (located at src/controllers/playback/video/index.js:1492) that pauses video playback unless },
* the clicked element has a parent with the class "videoOsdBottom" or "upNextContainer".
*/
button.classList.add("upNextContainer");
// Append the button to the video OSD
let controls = document.querySelector("div#videoOsdPage");
controls.appendChild(button);
}
/** Tests if the OSD controls are visible. */ /** Tests if the OSD controls are visible. */
introSkipper.osdVisible = function () { osdVisible() {
const osd = document.querySelector("div.videoOsdBottom"); return this.osdElement ? !this.osdElement.classList.contains("hide") : false;
return osd ? !osd.classList.contains("hide") : false; },
}
/** Get the currently playing skippable segment. */ /** Get the currently playing skippable segment. */
introSkipper.getCurrentSegment = function (position) { getCurrentSegment(position) {
for (let key in introSkipper.skipSegments) { for (const [key, segment] of Object.entries(this.skipSegments)) {
const segment = introSkipper.skipSegments[key]; if ((position > segment.ShowSkipPromptAt && position < segment.HideSkipPromptAt - 1) ||
if ((position >= segment.ShowSkipPromptAt && position < segment.HideSkipPromptAt) || (introSkipper.osdVisible() && position >= segment.IntroStart && position < segment.IntroEnd)) { (this.osdVisible() && position > segment.IntroStart && position < segment.IntroEnd - 1)) {
segment["SegmentType"] = key; segment.SegmentType = key;
return segment; return segment;
} }
} }
return { "SegmentType": "None" }; return { SegmentType: "None" };
} },
introSkipper.overrideBlur = function(embyButton) { overrideBlur(button) {
if (!embyButton.originalBlur) { if (!button.originalBlur) {
embyButton.originalBlur = embyButton.blur; button.originalBlur = button.blur;
} button.blur = () => {
embyButton.blur = function () { if (!button.contains(document.activeElement)) {
if (!introSkipper.osdVisible() || !embyButton.contains(document.activeElement)) { button.originalBlur();
embyButton.originalBlur.call(this);
} }
}; };
};
introSkipper.restoreBlur = function(embyButton) {
if (embyButton.originalBlur) {
embyButton.blur = embyButton.originalBlur;
delete embyButton.originalBlur;
} }
}; },
restoreBlur(button) {
if (button.originalBlur) {
button.blur = button.originalBlur;
delete button.originalBlur;
}
},
/** Playback position changed, check if the skip button needs to be displayed. */ /** Playback position changed, check if the skip button needs to be displayed. */
introSkipper.videoPositionChanged = function () { videoPositionChanged() {
const skipButton = document.querySelector("#skipIntro"); if (!this.skipButton) return;
if (introSkipper.videoPlayer.currentTime === 0 || !skipButton || !introSkipper.allowEnter) return; const embyButton = this.skipButton.querySelector(".emby-button");
const embyButton = skipButton.querySelector(".emby-button"); const segmentType = introSkipper.getCurrentSegment(this.videoPlayer.currentTime).SegmentType;
const tvLayout = document.documentElement.classList.contains("layout-tv"); if (segmentType === "None") {
const segment = introSkipper.getCurrentSegment(introSkipper.videoPlayer.currentTime); if (!this.skipButton.classList.contains('show')) return;
switch (segment.SegmentType) { this.skipButton.classList.remove('show');
case "None":
if (!skipButton.classList.contains('show')) return;
skipButton.classList.remove('show');
embyButton.addEventListener("transitionend", () => { embyButton.addEventListener("transitionend", () => {
skipButton.classList.add("hide"); this.skipButton.classList.add("hide");
if (tvLayout) { this.restoreBlur(embyButton);
introSkipper.restoreBlur(embyButton);
embyButton.blur(); embyButton.blur();
} this.allowEnter = true;
}, { once: true }); }, { once: true });
return; return;
case "Introduction":
skipButton.querySelector("#btnSkipSegmentText").textContent = skipButton.dataset.intro_text;
break;
case "Credits":
skipButton.querySelector("#btnSkipSegmentText").textContent = skipButton.dataset.credits_text;
break;
} }
if (!skipButton.classList.contains("hide")) return; this.skipButton.querySelector("#btnSkipSegmentText").textContent = this.skipButton.dataset[segmentType];
if (!this.skipButton.classList.contains("hide")) {
if (!this.osdVisible() && !embyButton.contains(document.activeElement)) embyButton.focus({ focusVisible: true });
return;
}
requestAnimationFrame(() => { requestAnimationFrame(() => {
skipButton.classList.remove("hide"); this.skipButton.classList.remove("hide");
requestAnimationFrame(() => { requestAnimationFrame(() => {
skipButton.classList.add('show'); this.skipButton.classList.add('show');
if (tvLayout) { this.overrideBlur(embyButton);
introSkipper.overrideBlur(embyButton);
embyButton.focus({ focusVisible: true }); embyButton.focus({ focusVisible: true });
}
}); });
}); });
} },
introSkipper.throttle = function (func, limit) {
let inThrottle;
return function(...args) {
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
/** Seeks to the end of the intro. */ /** Seeks to the end of the intro. */
introSkipper.doSkip = introSkipper.throttle(async function () { doSkip() {
introSkipper.d("Skipping intro"); if (!this.allowEnter) return;
introSkipper.d(introSkipper.skipSegments); const segment = this.getCurrentSegment(this.videoPlayer.currentTime);
const segment = introSkipper.getCurrentSegment(introSkipper.videoPlayer.currentTime);
if (segment.SegmentType === "None") { if (segment.SegmentType === "None") {
console.warn("[intro skipper] doSkip() called without an active segment"); console.warn("[intro skipper] doSkip() called without an active segment");
return; return;
} }
const currentSrc = introSkipper.videoPlayer.currentSrc; this.d(`Skipping ${segment.SegmentType}`);
const controller = new AbortController(); this.allowEnter = false;
const signal = controller.signal; this.videoPlayer.currentTime = segment.SegmentType === "Credits" && this.videoPlayer.duration - segment.IntroEnd < 3
const seekToSegmentEnd = () => new Promise((resolve) => { ? this.videoPlayer.duration + 10
const onSeeked = () => requestAnimationFrame(resolve); : segment.IntroEnd;
introSkipper.videoPlayer.addEventListener('seeked', onSeeked, { once: true, signal }); },
introSkipper.videoPlayer.currentTime = segment.IntroEnd;
});
const nextEpisodeLoaded = () => new Promise(resolve => {
const onLoadStart = () => resolve(true);
const timeoutId = setTimeout(() => resolve(false), 500);
introSkipper.videoPlayer.addEventListener('loadstart', onLoadStart, { signal });
signal.addEventListener('abort', () => clearTimeout(timeoutId));
});
// Disable keydown events
introSkipper.allowEnter = false;
try {
// Check if the segment is "Credits" and skipping would leave less than 3 seconds of video
if (segment.SegmentType === "Credits" && introSkipper.videoPlayer.duration - segment.IntroEnd < 3) {
// Simulate 'N' key press to go to the next episode
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'N', shiftKey: true, bubbles: true }));
// Check if the next episode actually starts loading
const loaded = await nextEpisodeLoaded();
// If the next episode didn't load, just seek to the end of the current segment
if (!loaded) {
await new Promise(resolve => setTimeout(resolve, 100)); // Short delay
if (introSkipper.videoPlayer.currentSrc === currentSrc) {
await seekToSegmentEnd();
}
}
} else {
// Default behavior: seek to the end of the current segment
await seekToSegmentEnd();
}
} finally {
introSkipper.allowEnter = true; // Always re-enable keydown events
controller.abort(); // Cleanup any remaining listeners
}
}, 3000);
/** Tests if an element with the provided selector exists. */
introSkipper.testElement = function (selector) { return document.querySelector(selector); }
/** Make an authenticated fetch to the Jellyfin server and parse the response body as JSON. */ /** Make an authenticated fetch to the Jellyfin server and parse the response body as JSON. */
introSkipper.secureFetch = async function (url) { async secureFetch(url) {
url = ApiClient.serverAddress() + "/" + url; url = new URL(url, ApiClient.serverAddress());
const reqInit = { headers: { "Authorization": "MediaBrowser Token=" + ApiClient.accessToken() } }; const res = await fetch(url, { headers: { "Authorization": `MediaBrowser Token=${ApiClient.accessToken()}` } });
const res = await fetch(url, reqInit); if (!res.ok) throw new Error(`Expected status 200 from ${url}, but got ${res.status}`);
if (res.status !== 200) { throw new Error(`Expected status 200 from ${url}, but got ${res.status}`); } return res.json();
return await res.json(); },
}
/** Handle keydown events. */ /** Handle keydown events. */
introSkipper.eventHandler = function (e) { eventHandler(e) {
const skipButton = document.querySelector("#skipIntro");
if (!skipButton || skipButton.classList.contains("hide")) return;
// Ignore all keydown events
if (!introSkipper.allowEnter) {
e.preventDefault();
return;
}
if (e.key !== "Enter") return; if (e.key !== "Enter") return;
const embyButton = skipButton.querySelector(".emby-button");
if (document.documentElement.classList.contains("layout-tv") && embyButton.contains(document.activeElement)) {
e.stopPropagation(); e.stopPropagation();
return;
}
if (document.documentElement.classList.contains("layout-desktop")) {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); this.doSkip();
introSkipper.doSkip();
}
} }
};
introSkipper.setup(); introSkipper.setup();