Browser based potokens
This commit is contained in:
1 parent
5e798f19de
commit
63f9ac693a
27 files changed
+722
-499
No files matched your search
@@ -24,8 +24,19 @@
|
||||
import BookmarksScreen from "lib/Screens/BookmarksScreen.svelte";
|
||||
import RemoteControlScreen from "lib/Screens/RemoteControlScreen.svelte";
|
||||
import { fetchLocale } from "lib/Api/Locale";
|
||||
import { ensureDevicePoTokenWithToast } from "lib/ensureDevicePoToken";
|
||||
import Toast from "lib/Toast.svelte";
|
||||
|
||||
// Mint on load, then refresh hourly while the page is open.
|
||||
const POTOKEN_REFRESH_INTERVAL_MS = 60 * 60 * 1000;
|
||||
|
||||
onMount(() => {
|
||||
ensureDevicePoTokenWithToast();
|
||||
const poTokenRefreshInterval = setInterval(
|
||||
ensureDevicePoTokenWithToast,
|
||||
POTOKEN_REFRESH_INTERVAL_MS,
|
||||
);
|
||||
|
||||
PlayletApi.getState().then((value) => {
|
||||
playletStateStore.set(value);
|
||||
fetchLocale(value.device?.current_locale);
|
||||
@@ -62,6 +73,8 @@
|
||||
PlayletApi.getBookmarkFeeds().then((value) => {
|
||||
bookmarksStore.set(value);
|
||||
});
|
||||
|
||||
return () => clearInterval(poTokenRefreshInterval);
|
||||
});
|
||||
|
||||
let currentScreen: AppState["screen"];
|
||||
@@ -93,3 +106,5 @@
|
||||
</div>
|
||||
<BottomNavigation />
|
||||
</main>
|
||||
|
||||
<Toast />
|
||||
@@ -164,6 +164,27 @@ export class PlayletApi {
|
||||
return await fetch(`${PlayletApi.host()}/api/cache`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
static async getDevicePoToken() {
|
||||
const response = await fetch(`${PlayletApi.host()}/api/innertube/potoken`);
|
||||
if (!response.ok) {
|
||||
const body = await response.text().catch(() => "");
|
||||
throw new Error(`Failed to read device poToken (HTTP ${response.status}): ${body}`);
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
static async sendPoToken(identity: string, poToken: string, mintedAt: number, expiresAt: number) {
|
||||
const response = await PlayletApi.postJson(`${PlayletApi.host()}/api/innertube/potoken`, { identity, poToken, mintedAt, expiresAt });
|
||||
if (!response.ok) {
|
||||
const body = await response.text().catch(() => "");
|
||||
throw new Error(`Device rejected poToken (HTTP ${response.status}): ${body}`);
|
||||
}
|
||||
}
|
||||
|
||||
static async clearPoTokens() {
|
||||
return await fetch(`${PlayletApi.host()}/api/innertube/potoken/all`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
static async getBookmarkFeeds() {
|
||||
const response = await fetch(`${PlayletApi.host()}/api/bookmarks/feeds`);
|
||||
return await response.json();
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import { getHost } from "lib/Api/Host";
|
||||
import { PlayletApi } from "lib/Api/PlayletApi";
|
||||
import { BG, buildURL, GOOG_API_KEY, type WebPoSignalOutput, type BgConfig } from "bgutils-js";
|
||||
|
||||
// Fallback lifetime when GenerateIT reports no TTL.
|
||||
const DEFAULT_POTOKEN_TTL_SECONDS = 60 * 60 * 6;
|
||||
|
||||
// Re-mint when the device's token is older than this; the web app owns the refresh cadence.
|
||||
const REFRESH_AGE_SECONDS = 60 * 60;
|
||||
|
||||
export type EnsurePoTokenResult =
|
||||
| { status: "minted" }
|
||||
| { status: "current" }
|
||||
| { status: "no-session" }
|
||||
| { status: "failed"; error: string };
|
||||
|
||||
interface DevicePoToken {
|
||||
identity?: string;
|
||||
poToken?: string;
|
||||
mintedAt?: number;
|
||||
expiresAt?: number;
|
||||
}
|
||||
|
||||
// Mints a GVS poToken in the browser (BotGuard) and hands it to the Roku.
|
||||
export class PoTokenMinter {
|
||||
static webPoMinter: BG.WebPoMinter;
|
||||
static webPoMinterPromise: Promise<void>;
|
||||
static integrityTokenExpiresAtMs = 0;
|
||||
|
||||
// Proxied through the Roku to dodge browser CORS.
|
||||
static async fetch(input: RequestInfo | URL, init?: RequestInit) {
|
||||
const method = init?.method
|
||||
? init.method
|
||||
: input instanceof Request
|
||||
? input.method
|
||||
: 'GET';
|
||||
|
||||
const url = typeof input === 'string'
|
||||
? new URL(input)
|
||||
: input instanceof URL
|
||||
? input
|
||||
: new URL(input.url);
|
||||
|
||||
const headers = init?.headers
|
||||
? new Headers(init.headers)
|
||||
: input instanceof Request
|
||||
? input.headers
|
||||
: new Headers();
|
||||
|
||||
const headersObject = {};
|
||||
headers.forEach((value, key) => {
|
||||
headersObject[key] = value;
|
||||
});
|
||||
|
||||
const body = init?.body;
|
||||
|
||||
const args = {
|
||||
Method: method,
|
||||
Url: url,
|
||||
Headers: headersObject,
|
||||
Body: body,
|
||||
CacheSeconds: -1,
|
||||
};
|
||||
|
||||
const response = await fetch(`http://${getHost()}/api/innertube/proxy`, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
method: "POST",
|
||||
body: JSON.stringify(args)
|
||||
});
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
return new Response(responseData.body, {
|
||||
status: responseData.status,
|
||||
statusText: `${responseData.status}`,
|
||||
headers: responseData.headers,
|
||||
});
|
||||
}
|
||||
|
||||
static async initWebPoMinter() {
|
||||
// Re-attest once the integrity token nears expiry.
|
||||
if (PoTokenMinter.webPoMinter && Date.now() < PoTokenMinter.integrityTokenExpiresAtMs - 60_000) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
if (PoTokenMinter.webPoMinterPromise) {
|
||||
return PoTokenMinter.webPoMinterPromise;
|
||||
}
|
||||
|
||||
PoTokenMinter.webPoMinterPromise = new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const requestKey = 'O43z0dpjhgX20SCx4KAo';
|
||||
|
||||
const bgConfig: BgConfig = {
|
||||
fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => PoTokenMinter.fetch(input, init),
|
||||
globalObj: globalThis,
|
||||
requestKey,
|
||||
identifier: ''
|
||||
};
|
||||
|
||||
const bgChallenge = await BG.Challenge.create(bgConfig);
|
||||
if (!bgChallenge) {
|
||||
throw new Error('Could not get challenge');
|
||||
}
|
||||
|
||||
const interpreterJavascript = bgChallenge.interpreterJavascript.privateDoNotAccessOrElseSafeScriptWrappedValue;
|
||||
if (interpreterJavascript) {
|
||||
new Function(interpreterJavascript)();
|
||||
} else {
|
||||
throw new Error('Could not load VM');
|
||||
}
|
||||
|
||||
const botguard = await BG.BotGuardClient.create({
|
||||
globalName: bgChallenge.globalName,
|
||||
globalObj: globalThis,
|
||||
program: bgChallenge.program
|
||||
});
|
||||
|
||||
const webPoSignalOutput: WebPoSignalOutput = [];
|
||||
const botguardResponse = await botguard.snapshot({ webPoSignalOutput });
|
||||
|
||||
const integrityTokenResponse = await bgConfig.fetch(buildURL('GenerateIT', true), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json+protobuf',
|
||||
'x-goog-api-key': GOOG_API_KEY,
|
||||
'x-user-agent': 'grpc-web-javascript/0.1'
|
||||
},
|
||||
body: JSON.stringify([requestKey, botguardResponse])
|
||||
});
|
||||
|
||||
const response = await integrityTokenResponse.json() as unknown[];
|
||||
|
||||
if (typeof response[0] !== 'string')
|
||||
throw new Error('Could not get integrity token');
|
||||
|
||||
// GenerateIT returns the integrity token's estimated TTL (seconds) as body[1].
|
||||
const ttlSeconds = typeof response[1] === 'number' && response[1] > 0
|
||||
? Math.floor(response[1])
|
||||
: DEFAULT_POTOKEN_TTL_SECONDS;
|
||||
PoTokenMinter.integrityTokenExpiresAtMs = Date.now() + ttlSeconds * 1000;
|
||||
|
||||
PoTokenMinter.webPoMinter = await BG.WebPoMinter.create({ integrityToken: response[0] }, webPoSignalOutput);
|
||||
PoTokenMinter.webPoMinterPromise = null;
|
||||
resolve();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
PoTokenMinter.webPoMinter = null;
|
||||
PoTokenMinter.integrityTokenExpiresAtMs = 0;
|
||||
PoTokenMinter.webPoMinterPromise = null;
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
return PoTokenMinter.webPoMinterPromise;
|
||||
}
|
||||
|
||||
static async mintPoToken(identity: string) {
|
||||
await PoTokenMinter.initWebPoMinter();
|
||||
|
||||
if (!PoTokenMinter.webPoMinter) {
|
||||
throw new Error('WebPoMinter is not initialized');
|
||||
}
|
||||
|
||||
return await PoTokenMinter.webPoMinter.mintAsWebsafeString(identity);
|
||||
}
|
||||
|
||||
// Re-mint when the device has no token, it expired, or it is older than the refresh window.
|
||||
static shouldRefresh(device: DevicePoToken): boolean {
|
||||
if (!device.poToken || typeof device.mintedAt !== "number" || typeof device.expiresAt !== "number") {
|
||||
return true;
|
||||
}
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
if (now >= device.expiresAt) {
|
||||
return true;
|
||||
}
|
||||
return now - device.mintedAt >= REFRESH_AGE_SECONDS;
|
||||
}
|
||||
|
||||
// Mints + uploads a poToken when the device's token needs refreshing, or always when forced.
|
||||
static async ensureDevicePoToken(force = false): Promise<EnsurePoTokenResult> {
|
||||
let device: DevicePoToken;
|
||||
try {
|
||||
device = await PlayletApi.getDevicePoToken();
|
||||
} catch (error) {
|
||||
return { status: "failed", error: String(error) };
|
||||
}
|
||||
|
||||
// Identity = what the device sends to the decipher server (empty = nothing to mint for).
|
||||
const identity = device?.identity;
|
||||
if (!identity) {
|
||||
return { status: "no-session" };
|
||||
}
|
||||
if (!force && !PoTokenMinter.shouldRefresh(device)) {
|
||||
return { status: "current" };
|
||||
}
|
||||
|
||||
try {
|
||||
const poToken = await PoTokenMinter.mintPoToken(identity);
|
||||
// The token is valid until the integrity token expires; fall back to a default TTL.
|
||||
const mintedAt = Math.floor(Date.now() / 1000);
|
||||
const expiresAt = PoTokenMinter.integrityTokenExpiresAtMs > 0
|
||||
? Math.floor(PoTokenMinter.integrityTokenExpiresAtMs / 1000)
|
||||
: mintedAt + DEFAULT_POTOKEN_TTL_SECONDS;
|
||||
await PlayletApi.sendPoToken(identity, poToken, mintedAt, expiresAt);
|
||||
return { status: "minted" };
|
||||
} catch (error) {
|
||||
return { status: "failed", error: String(error) };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,411 +0,0 @@
|
||||
import { Innertube, Platform, UniversalCache, type Types } from 'youtubei.js/web';
|
||||
import { getHost } from "lib/Api/Host";
|
||||
import { BG, buildURL, GOOG_API_KEY, type WebPoSignalOutput } from "bgutils-js";
|
||||
import { type BgConfig } from "bgutils-js";
|
||||
import type { VideoInfo } from 'node_modules/youtubei.js/dist/src/parser/youtube';
|
||||
import type { StoryboardData } from 'node_modules/youtubei.js/dist/src/parser/classes/PlayerStoryboardSpec';
|
||||
import type { PlayerLiveStoryboardSpec, PlayerStoryboardSpec } from 'node_modules/youtubei.js/dist/src/parser/nodes';
|
||||
import type { Format } from 'node_modules/youtubei.js/dist/src/parser/misc';
|
||||
|
||||
export class YoutubeJs {
|
||||
static host = () => `http://${getHost()}`
|
||||
|
||||
static innerTube: Innertube;
|
||||
static innerTubePromise: Promise<void>;
|
||||
|
||||
static webPoMinter: BG.WebPoMinter;
|
||||
static webPoMinterPromise: Promise<void>;
|
||||
|
||||
static visitorData?: string = undefined;
|
||||
|
||||
static async fetch(input: RequestInfo | URL, init?: RequestInit) {
|
||||
const method = init?.method
|
||||
? init.method
|
||||
: input instanceof Request
|
||||
? input.method
|
||||
: 'GET';
|
||||
|
||||
const url = typeof input === 'string'
|
||||
? new URL(input)
|
||||
: input instanceof URL
|
||||
? input
|
||||
: new URL(input.url);
|
||||
|
||||
const headers = init?.headers
|
||||
? new Headers(init.headers)
|
||||
: input instanceof Request
|
||||
? input.headers
|
||||
: new Headers();
|
||||
|
||||
const headersObject = {};
|
||||
headers.forEach((value, key) => {
|
||||
headersObject[key] = value;
|
||||
});
|
||||
|
||||
let body = init?.body
|
||||
|
||||
const args = {
|
||||
Method: method,
|
||||
Url: url,
|
||||
Headers: headersObject,
|
||||
Body: body,
|
||||
CacheSeconds: -1,
|
||||
};
|
||||
|
||||
const response = await fetch(`http://${getHost()}/api/innertube/proxy`, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
method: "POST",
|
||||
body: JSON.stringify(args)
|
||||
})
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
return new Response(responseData.body, {
|
||||
status: responseData.status,
|
||||
statusText: `${responseData.status}`,
|
||||
headers: responseData.headers,
|
||||
});
|
||||
}
|
||||
|
||||
static async initVisitorData() {
|
||||
if (YoutubeJs.visitorData) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
const sessionData = await YoutubeJs.getSessionData();
|
||||
if (sessionData.visitorData) {
|
||||
YoutubeJs.visitorData = sessionData.visitorData;
|
||||
return;
|
||||
}
|
||||
|
||||
YoutubeJs.visitorData = await YoutubeJs.generateVisitorData();
|
||||
|
||||
await YoutubeJs.setSessionData({
|
||||
visitorData: YoutubeJs.visitorData,
|
||||
timestamp: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
}
|
||||
|
||||
static async getSessionData() {
|
||||
const response = await fetch(`http://${getHost()}/api/innertube/session`)
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
static async setSessionData(sessionData: any) {
|
||||
await fetch(`http://${getHost()}/api/innertube/session`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(sessionData)
|
||||
});
|
||||
}
|
||||
|
||||
static async getInnertube() {
|
||||
await YoutubeJs.initInnertube();
|
||||
return YoutubeJs.innerTube;
|
||||
}
|
||||
|
||||
static async initInnertube() {
|
||||
if (YoutubeJs.innerTube) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
if (YoutubeJs.innerTubePromise) {
|
||||
return YoutubeJs.innerTubePromise;
|
||||
}
|
||||
|
||||
YoutubeJs.innerTubePromise = new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
this.initJsEvaluator();
|
||||
await YoutubeJs.initVisitorData()
|
||||
YoutubeJs.innerTube = await Innertube.create({
|
||||
fetch: YoutubeJs.fetch,
|
||||
cache: new UniversalCache(true),
|
||||
visitor_data: YoutubeJs.visitorData,
|
||||
});
|
||||
YoutubeJs.innerTubePromise = null;
|
||||
resolve();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
YoutubeJs.innerTube = null;
|
||||
YoutubeJs.innerTubePromise = null;
|
||||
reject(error);
|
||||
}
|
||||
})
|
||||
|
||||
return YoutubeJs.innerTubePromise;
|
||||
}
|
||||
|
||||
static initJsEvaluator() {
|
||||
Platform.shim.eval = async (data: Types.BuildScriptResult, env: Record<string, Types.VMPrimative>) => {
|
||||
return new Function(data.output)();
|
||||
};
|
||||
}
|
||||
|
||||
static async generateVisitorData() {
|
||||
const innertube = await Innertube.create({ retrieve_player: false });
|
||||
const visitorData = innertube.session.context.client.visitorData;
|
||||
if (!visitorData) {
|
||||
throw new Error('Could not get visitor data');
|
||||
}
|
||||
return visitorData;
|
||||
}
|
||||
|
||||
static async initWebPoMinter() {
|
||||
if (YoutubeJs.webPoMinter) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
if (YoutubeJs.webPoMinterPromise) {
|
||||
return YoutubeJs.webPoMinterPromise;
|
||||
}
|
||||
|
||||
YoutubeJs.webPoMinterPromise = new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const requestKey = 'O43z0dpjhgX20SCx4KAo';
|
||||
|
||||
const bgConfig: BgConfig = {
|
||||
fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => YoutubeJs.fetch(input, init),
|
||||
globalObj: globalThis,
|
||||
requestKey,
|
||||
identifier: ''
|
||||
};
|
||||
|
||||
const bgChallenge = await BG.Challenge.create(bgConfig);
|
||||
if (!bgChallenge) {
|
||||
throw new Error('Could not get challenge');
|
||||
}
|
||||
|
||||
const interpreterJavascript = bgChallenge.interpreterJavascript.privateDoNotAccessOrElseSafeScriptWrappedValue;
|
||||
if (interpreterJavascript) {
|
||||
new Function(interpreterJavascript)();
|
||||
} else {
|
||||
throw new Error('Could not load VM');
|
||||
}
|
||||
|
||||
const botguard = await BG.BotGuardClient.create({
|
||||
globalName: bgChallenge.globalName,
|
||||
globalObj: globalThis,
|
||||
program: bgChallenge.program
|
||||
});
|
||||
|
||||
const webPoSignalOutput: WebPoSignalOutput = [];
|
||||
const botguardResponse = await botguard.snapshot({ webPoSignalOutput });
|
||||
|
||||
const integrityTokenResponse = await bgConfig.fetch(buildURL('GenerateIT', true), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json+protobuf',
|
||||
'x-goog-api-key': GOOG_API_KEY,
|
||||
'x-user-agent': 'grpc-web-javascript/0.1'
|
||||
},
|
||||
body: JSON.stringify([requestKey, botguardResponse])
|
||||
});
|
||||
|
||||
const response = await integrityTokenResponse.json() as unknown[];
|
||||
|
||||
if (typeof response[0] !== 'string')
|
||||
throw new Error('Could not get integrity token');
|
||||
|
||||
YoutubeJs.webPoMinter = await BG.WebPoMinter.create({ integrityToken: response[0] }, webPoSignalOutput);
|
||||
YoutubeJs.webPoMinterPromise = null;
|
||||
resolve();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
YoutubeJs.webPoMinter = null;
|
||||
YoutubeJs.webPoMinterPromise = null;
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
return YoutubeJs.webPoMinterPromise;
|
||||
}
|
||||
|
||||
static async generatePoToken(videoId: string) {
|
||||
await YoutubeJs.initWebPoMinter();
|
||||
|
||||
if (!YoutubeJs.webPoMinter) {
|
||||
throw new Error('WebPoMinter is not initialized');
|
||||
}
|
||||
|
||||
return await YoutubeJs.webPoMinter.mintAsWebsafeString(videoId);
|
||||
}
|
||||
|
||||
static async getVideoInfo(videoId: string) {
|
||||
await YoutubeJs.initInnertube();
|
||||
|
||||
const info = await YoutubeJs.innerTube.getBasicInfo(videoId, {
|
||||
client: 'TV',
|
||||
po_token: await YoutubeJs.generatePoToken(videoId),
|
||||
});
|
||||
|
||||
if (info.playability_status.status !== 'OK') {
|
||||
throw new Error(`Video is not playable: ${info.playability_status.status}\nReason: ${info.playability_status.reason}`);
|
||||
}
|
||||
|
||||
// We can't generate a proper dash from live videos.
|
||||
// By returning null, we're telling Playlet to fetch video info itself.
|
||||
if (info.basic_info.is_live) {
|
||||
return null;
|
||||
}
|
||||
|
||||
YoutubeJs.innerTube.session.player.po_token = YoutubeJs.innerTube.session.po_token;
|
||||
|
||||
// Populate a video object that is similar to Invidious format.
|
||||
// Mostly populate only fields we care about, enough to make it work.
|
||||
return {
|
||||
type: "video",
|
||||
title: info.basic_info.title,
|
||||
videoId: info.basic_info.id,
|
||||
videoThumbnails: [],
|
||||
storyboards: YoutubeJs.getStoryboards(info),
|
||||
description: "",
|
||||
published: 0,
|
||||
publishedText: "",
|
||||
keywords: [],
|
||||
viewCount: 0,
|
||||
likeCount: 0,
|
||||
dislikeCount: 0,
|
||||
paid: false,
|
||||
premium: false,
|
||||
isFamilyFriendly: true,
|
||||
allowedRegions: [],
|
||||
genre: "",
|
||||
genreUrl: null,
|
||||
author: info.basic_info.author,
|
||||
authorId: info.basic_info.channel_id,
|
||||
authorUrl: "",
|
||||
authorVerified: false,
|
||||
authorThumbnails: [],
|
||||
subCountText: "",
|
||||
lengthSeconds: info.basic_info.duration,
|
||||
allowRatings: true,
|
||||
rating: 0,
|
||||
isListed: true,
|
||||
liveNow: info.basic_info.is_live,
|
||||
isPostLiveDvr: info.basic_info.is_post_live_dvr,
|
||||
isUpcoming: info.basic_info.is_upcoming,
|
||||
dashUrl: info.streaming_data.dash_manifest_url || "",
|
||||
hlsUrl: info.streaming_data.hls_manifest_url,
|
||||
adaptiveFormats: await YoutubeJs.transformFormats(info.streaming_data?.adaptive_formats),
|
||||
formatStreams: await YoutubeJs.transformFormats(info.streaming_data?.formats),
|
||||
captions: YoutubeJs.getCaptions(info),
|
||||
}
|
||||
}
|
||||
|
||||
static async transformFormats(formats: Format[]) {
|
||||
if (!formats) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Promise.all(formats.map(format =>
|
||||
YoutubeJs.transformStreamFormat(format)
|
||||
));
|
||||
}
|
||||
|
||||
static async transformStreamFormat(format: Format): Promise<any> {
|
||||
const result: any = {
|
||||
init: format.init_range ? `${format.init_range.start}-${format.init_range.end}` : "",
|
||||
index: format.index_range ? `${format.index_range.start}-${format.index_range.end}` : "",
|
||||
bitrate: `${format.bitrate}`,
|
||||
itag: `${format.itag}`,
|
||||
type: format.mime_type,
|
||||
clen: `${format.approx_duration_ms}`,
|
||||
lmt: `${format.last_modified}`,
|
||||
};
|
||||
|
||||
if (format.url || format.signature_cipher || format.cipher) {
|
||||
result.url = await format.decipher(YoutubeJs.innerTube.session.player);
|
||||
}
|
||||
|
||||
if (format.audio_quality) {
|
||||
result.audioQuality = format.audio_quality;
|
||||
}
|
||||
if (format.audio_sample_rate) {
|
||||
result.audioSampleRate = format.audio_sample_rate;
|
||||
}
|
||||
if (format.audio_channels) {
|
||||
result.audioChannels = format.audio_channels;
|
||||
}
|
||||
|
||||
if (format.quality_label) {
|
||||
result.qualityLabel = format.quality_label;
|
||||
}
|
||||
if (format.fps) {
|
||||
result.fps = format.fps;
|
||||
}
|
||||
|
||||
if (format.width) {
|
||||
result.width = format.width;
|
||||
}
|
||||
if (format.height) {
|
||||
result.height = format.height;
|
||||
}
|
||||
if (format.height && format.width) {
|
||||
result.size = `${format.width}x${format.height}`;
|
||||
result.resolution = `${format.height}p`;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static getStoryboards(videoInfo: VideoInfo) {
|
||||
if (!videoInfo.storyboards) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (videoInfo.storyboards.type === 'PlayerLiveStoryboardSpec') {
|
||||
const board = (videoInfo.storyboards as PlayerLiveStoryboardSpec).board
|
||||
return [{
|
||||
templateUrl: board.template_url,
|
||||
width: board.thumbnail_width,
|
||||
height: board.thumbnail_height,
|
||||
count: -1,
|
||||
interval: 5000,
|
||||
storyboardWidth: board.columns,
|
||||
storyboardHeight: board.rows,
|
||||
}];
|
||||
}
|
||||
|
||||
const storyboards = (videoInfo.storyboards as PlayerStoryboardSpec).boards;
|
||||
return storyboards.map((board: StoryboardData) => {
|
||||
return {
|
||||
templateUrl: board.template_url,
|
||||
width: board.thumbnail_width,
|
||||
height: board.thumbnail_height,
|
||||
count: board.thumbnail_count,
|
||||
interval: board.interval,
|
||||
storyboardWidth: board.columns,
|
||||
storyboardHeight: board.rows,
|
||||
storyboardCount: board.storyboard_count
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
static getCaptions(videoInfo: VideoInfo) {
|
||||
if (!videoInfo.captions?.caption_tracks) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return videoInfo.captions.caption_tracks.map(track => {
|
||||
const baseUrl = track.base_url;
|
||||
if (!baseUrl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const queryComponents = new URLSearchParams(baseUrl.split('?')[1]);
|
||||
queryComponents.set('fmt', 'vtt');
|
||||
const modifiedBaseUrl = `${baseUrl.split('?')[0]}?${queryComponents.toString()}`;
|
||||
|
||||
return {
|
||||
label: track.name.toString(),
|
||||
language_code: track.language_code || '',
|
||||
url: modifiedBaseUrl
|
||||
};
|
||||
}).filter(caption => !!caption);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<script lang="ts">
|
||||
import { PlayletApi } from "lib/Api/PlayletApi";
|
||||
import { translate } from "lib/Stores";
|
||||
import { get } from "svelte/store";
|
||||
|
||||
const textSizes = ["text-2xl", "text-lg", "text-base", "text-sm", "text-xs"];
|
||||
|
||||
export let displayText: string = "";
|
||||
// svelte-ignore unused-export-let
|
||||
export let key: string = "";
|
||||
export let description: string = "";
|
||||
export let level: number = 0;
|
||||
|
||||
async function clearPoTokens() {
|
||||
await PlayletApi.clearPoTokens();
|
||||
alert(get(translate)("PoTokens cleared."));
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="m-5">
|
||||
<div class={textSizes[level]}>{$translate(displayText)}</div>
|
||||
<div class="text-xs text-gray-500">{@html $translate(description)}</div>
|
||||
<button class="btn m-1" on:click={clearPoTokens}
|
||||
>{$translate("Clear PoTokens")}</button
|
||||
>
|
||||
</div>
|
||||
@@ -0,0 +1,20 @@
|
||||
<script lang="ts">
|
||||
import { translate } from "lib/Stores";
|
||||
import { ensureDevicePoTokenWithToast } from "lib/ensureDevicePoToken";
|
||||
|
||||
const textSizes = ["text-2xl", "text-lg", "text-base", "text-sm", "text-xs"];
|
||||
|
||||
export let displayText: string = "";
|
||||
// svelte-ignore unused-export-let
|
||||
export let key: string = "";
|
||||
export let description: string = "";
|
||||
export let level: number = 0;
|
||||
</script>
|
||||
|
||||
<div class="m-5">
|
||||
<div class={textSizes[level]}>{$translate(displayText)}</div>
|
||||
<div class="text-xs text-gray-500">{@html $translate(description)}</div>
|
||||
<button class="btn m-1" on:click={() => ensureDevicePoTokenWithToast(true)}
|
||||
>{$translate("Mint PoToken")}</button
|
||||
>
|
||||
</div>
|
||||
@@ -7,6 +7,8 @@
|
||||
import StringControl from "lib/Screens/Settings/SettingControls/StringControl.svelte";
|
||||
import NumberControl from "./SettingControls/NumberControl.svelte";
|
||||
import ClearCacheControl from "./SettingControls/ClearCacheControl.svelte";
|
||||
import ClearPoTokensControl from "./SettingControls/ClearPoTokensControl.svelte";
|
||||
import MintPoTokenControl from "./SettingControls/MintPoTokenControl.svelte";
|
||||
import EditQualityControl from "./SettingControls/EditQualityControl.svelte";
|
||||
import SponsorBlockCategoriesControl from "./SettingControls/SponsorBlockCategoriesControl.svelte";
|
||||
import { translate } from "lib/Stores";
|
||||
@@ -34,6 +36,8 @@
|
||||
const customComponents = {
|
||||
ClearSearchHistoryControl,
|
||||
ClearCacheControl,
|
||||
ClearPoTokensControl,
|
||||
MintPoTokenControl,
|
||||
EditHomeScreenControl,
|
||||
PlayletLibVersionControl,
|
||||
EditQualityControl,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<script lang="ts">
|
||||
import { toastStore, removeToast } from "lib/Toast";
|
||||
|
||||
const alertClass: Record<string, string> = {
|
||||
success: "alert-success",
|
||||
error: "alert-error",
|
||||
info: "alert-info",
|
||||
warning: "alert-warning",
|
||||
};
|
||||
</script>
|
||||
|
||||
<div class="toast toast-end toast-bottom z-50">
|
||||
{#each $toastStore as toast (toast.id)}
|
||||
<div class="alert {alertClass[toast.type] ?? 'alert-info'}">
|
||||
<span>{toast.message}</span>
|
||||
<button
|
||||
class="btn btn-ghost btn-xs"
|
||||
on:click={() => removeToast(toast.id)}>✕</button
|
||||
>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
@@ -0,0 +1,25 @@
|
||||
import { writable } from "svelte/store";
|
||||
|
||||
export type ToastType = "success" | "error" | "info" | "warning";
|
||||
|
||||
export interface Toast {
|
||||
id: number;
|
||||
type: ToastType;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export const toastStore = writable<Toast[]>([]);
|
||||
|
||||
let nextId = 0;
|
||||
|
||||
export function addToast(message: string, type: ToastType = "info", durationMs = 5000) {
|
||||
const id = nextId++;
|
||||
toastStore.update((toasts) => [...toasts, { id, type, message }]);
|
||||
if (durationMs > 0) {
|
||||
setTimeout(() => removeToast(id), durationMs);
|
||||
}
|
||||
}
|
||||
|
||||
export function removeToast(id: number) {
|
||||
toastStore.update((toasts) => toasts.filter((toast) => toast.id !== id));
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
import { playletStateStore, translate } from "lib/Stores";
|
||||
import VideoStartAt from "./VideoStartAt.svelte";
|
||||
import VideoThumbnail from "./VideoThumbnail.svelte";
|
||||
import { YoutubeJs } from "lib/Api/YoutubeJs";
|
||||
|
||||
export let videoId: string | undefined = undefined;
|
||||
export let title: string | undefined = undefined;
|
||||
@@ -58,26 +57,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function playOnTvYtjs() {
|
||||
try {
|
||||
const videoInfo = getVideoInfo() as any;
|
||||
|
||||
// measure length of time it takes to get video info
|
||||
const start = performance.now();
|
||||
const metadata = await YoutubeJs.getVideoInfo(videoId);
|
||||
const end = performance.now();
|
||||
console.log(`Time to get video info: ${end - start}ms`);
|
||||
|
||||
if (metadata) {
|
||||
videoInfo.metadata = metadata;
|
||||
}
|
||||
await PlayletApi.playVideo(videoInfo);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
alert(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function queueOnTv() {
|
||||
try {
|
||||
const videoInfo = getVideoInfo();
|
||||
@@ -168,9 +147,6 @@
|
||||
<button class="btn join-item hover:btn-accent" on:click={playOnTv}>
|
||||
{$translate("Play on %1").replace("%1", tvName)}
|
||||
</button>
|
||||
<button class="btn join-item hover:btn-accent" on:click={playOnTvYtjs}>
|
||||
{$translate("Play on %1").replace("%1", tvName)} (ytjs)
|
||||
</button>
|
||||
<button class="btn join-item hover:btn-accent" on:click={queueOnTv}>
|
||||
{$translate("Queue on %1").replace("%1", tvName)}
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { PoTokenMinter } from "lib/Api/PoTokenMinter";
|
||||
import { addToast } from "lib/Toast";
|
||||
|
||||
// Mints for the current identity if needed, surfacing the outcome as a toast.
|
||||
export async function ensureDevicePoTokenWithToast(force = false) {
|
||||
const result = await PoTokenMinter.ensureDevicePoToken(force);
|
||||
switch (result.status) {
|
||||
case "minted":
|
||||
addToast("PoToken minted on device", "success");
|
||||
break;
|
||||
case "current":
|
||||
addToast("PoToken already up to date on device", "info");
|
||||
break;
|
||||
case "no-session":
|
||||
addToast("No identity available to mint a PoToken yet", "warning");
|
||||
break;
|
||||
case "failed":
|
||||
addToast(`PoToken minting failed: ${result.error}`, "error");
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
Reference in new issue
Block a user