Skip to content

Commit

Permalink
fix: using GM storage instead of URL params cause YTM strips them out
Browse files Browse the repository at this point in the history
  • Loading branch information
Sv443 committed Nov 23, 2024
1 parent df4feb9 commit 6fc8eaf
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 24 deletions.
1 change: 1 addition & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

- **Plugin Changes:**
- Added authenticated function `reloadTab()` to keep video time and volume and disable BYTM features like initial tab volume
- Exposed the constants `initialParams` (initial URLParams object) and `sessionStorageAvailable` (bool) on the BYTM API

</details>

Expand Down
22 changes: 13 additions & 9 deletions src/features/volume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { getFeature } from "../config.js";
import { addStyleFromResource, error, log, resourceAsString, setGlobalCssVar, setInnerHtml, t, waitVideoElementReady, warn } from "../utils/index.js";
import { siteEvents } from "../siteEvents.js";
import { featInfo } from "./index.js";
import "./volume.css";
import { addSelectorListener } from "../observers.js";
import "./volume.css";

//#region init vol features

Expand Down Expand Up @@ -36,8 +36,7 @@ export async function initVolumeFeatures() {

// the following are only run once:

if(getFeature("setInitialTabVolume") || new URL(location.href).searchParams.has("bytm_volume"))
setInitialTabVolume(sliderElem);
setInitialTabVolume(sliderElem);

if(typeof getFeature("volumeSliderSize") === "number")
setVolSliderSize();
Expand Down Expand Up @@ -248,18 +247,23 @@ export async function volumeSharedBetweenTabsDisabled() {

/** Sets the volume slider to a set volume level when the session starts */
async function setInitialTabVolume(sliderElem: HTMLInputElement) {
const reloadTabVol = Number(await GM.getValue("bytm-reload-tab-volume", 0));
GM.deleteValue("bytm-reload-tab-volume").catch(() => void 0);

if(!getFeature("setInitialTabVolume") || reloadTabVol === 0 || isNaN(reloadTabVol))
return;

await waitVideoElementReady();
const urlVol = new URL(location.href).searchParams.get("bytm_volume");
const initialVol = urlVol ? Number(urlVol) / 100 : getFeature("initialTabVolumeLevel");

const initialVol = reloadTabVol > 0 ? Math.round(reloadTabVol) : getFeature("initialTabVolumeLevel");

if(getFeature("volumeSharedBetweenTabs")) {
lastCheckedSharedVolume = ignoreVal = initialVol;
if(getFeature("volumeSharedBetweenTabs"))
GM.setValue("bytm-shared-volume", String(initialVol));
GM.setValue("bytm-shared-volume", String(initialVol)).catch((err) => error("Couldn't save shared volume level due to an error:", err));
}
sliderElem.value = String(initialVol);
sliderElem.dispatchEvent(new Event("change", { bubbles: true }));

urlVol && history.replaceState({}, document.title, location.href.replace(/([&?]?bytm_volume=\d+($|&))/g, ""));

log(`Set initial tab volume to ${initialVol}%${urlVol ? " (from URL)" : "(from configuration)"}`);
log(`Set initial tab volume to ${initialVol}%${reloadTabVol > 0 ? " (from GM storage)" : " (from configuration)"}`);
}
4 changes: 3 additions & 1 deletion src/interface.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as UserUtils from "@sv443-network/userutils";
import * as compareVersions from "compare-versions";
import { mode, branch, host, buildNumber, compressionFormat, scriptInfo } from "./constants.js";
import { mode, branch, host, buildNumber, compressionFormat, scriptInfo, initialParams, sessionStorageAvailable } from "./constants.js";
import { getDomain, waitVideoElementReady, getResourceUrl, getSessionId, getVideoTime, log, setLocale, getLocale, hasKey, hasKeyFor, t, tp, type TrLocale, info, error, onInteraction, getThumbnailUrl, getBestThumbnailUrl, fetchVideoVotes, setInnerHtml, getCurrentMediaType, tl, tlp, PluginError, formatNumber, reloadTab } from "./utils/index.js";
import { addSelectorListener } from "./observers.js";
import { getFeatures, setFeatures } from "./config.js";
Expand Down Expand Up @@ -167,7 +167,9 @@ export function initInterface() {
branch,
host,
buildNumber,
initialParams,
compressionFormat,
sessionStorageAvailable,
...scriptInfo,
// functions
...globalFuncs,
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export type BytmObject =
// information from the userscript header
& typeof scriptInfo
// certain variables from `src/constants.ts`
& Pick<typeof consts, "mode" | "branch" | "host" | "buildNumber" | "compressionFormat">
& Pick<typeof consts, "mode" | "branch" | "host" | "buildNumber" | "initialParams" | "compressionFormat" | "sessionStorageAvailable" | "scriptInfo">
// global functions exposed through the interface in `src/interface.ts`
& InterfaceFunctions
// others
Expand Down
33 changes: 20 additions & 13 deletions src/utils/misc.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { clamp, compress, decompress, fetchAdvanced, openInNewTab, pauseFor, randomId, randRange, type Prettify } from "@sv443-network/userutils";
import { compress, decompress, fetchAdvanced, openInNewTab, pauseFor, randomId, randRange, type Prettify } from "@sv443-network/userutils";
import { marked } from "marked";
import { branch, compressionFormat, repo, sessionStorageAvailable } from "../constants.js";
import { type Domain, type NumberLengthFormat, type ResourceKey, type StringGen } from "../types.js";
Expand Down Expand Up @@ -221,22 +221,29 @@ export function formatNumber(num: number, notation?: NumberLengthFormat): string
);
}

/** Reloads the tab. If a video is currently playing, its time and volume will be preserved through the URL parameters `time_continue` and `bytm_volume` */
/** Reloads the tab. If a video is currently playing, its time and volume will be preserved through the URL parameter `time_continue` and `bytm-reload-tab-volume` in GM storage */
export async function reloadTab() {
let time = 0, volume = 0;
try {
let time = 0, volume = 0;

if(getVideoElement()) {
time = (await getVideoTime() ?? 0) - 0.25;
volume = clamp(Math.round(getVideoElement()!.volume * 100), 0, 100);
}
if(getVideoElement()) {
time = (await getVideoTime() ?? 0) - 0.25;
volume = Math.round(getVideoElement()!.volume * 100);
}

const url = new URL(location.href);

const url = new URL(location.href);
if(time > 0)
url.searchParams.set("time_continue", String(time));
if(volume > 0)
url.searchParams.set("bytm_volume", String(volume));
if(isNaN(time) && time > 0)
url.searchParams.set("time_continue", String(time));
if(isNaN(volume) && volume > 0)
await GM.setValue("bytm-reload-tab-volume", String(volume));

location.href = url.href;
location.href = url.href;
}
catch(err) {
error("Couldn't save video time and volume before reloading tab:", err);
location.reload();
}
}

//#region resources
Expand Down

0 comments on commit 6fc8eaf

Please sign in to comment.