youtube: add support for using OAuth2 tokens

This commit is contained in:
dumbmoron 2024-06-08 09:18:29 +00:00
parent 7fb2e6d8d9
commit 46274c8da0
No known key found for this signature in database
2 changed files with 62 additions and 1 deletions

View file

@ -24,6 +24,26 @@ const codecMatch = {
}
}
const transformSessionData = (cookie) => {
if (!cookie)
return;
const values = cookie.values();
const REQUIRED_VALUES = [
'access_token', 'refresh_token',
'client_id', 'client_secret',
'expires'
];
if (REQUIRED_VALUES.some(x => typeof values[x] !== 'string')) {
return;
}
return {
...values,
expires: new Date(values.expires),
};
}
const cloneInnertube = async (customFetch) => {
const innertube = await ytBase;
if (innertube instanceof Error) {
@ -41,6 +61,17 @@ const cloneInnertube = async (customFetch) => {
innertube.session.cache
);
const oauthData = transformSessionData(getCookie('youtube_oauth'));
if (!session.logged_in && oauthData) {
await session.oauth.init(oauthData);
session.logged_in = true;
}
if (session.logged_in) {
await session.oauth.refreshIfRequired();
}
const yt = new Innertube(session);
return yt;
}
@ -62,7 +93,7 @@ export default async function(o) {
}
try {
info = await yt.getBasicInfo(o.id, 'IOS');
info = await yt.getBasicInfo(o.id, yt.session.logged_in ? 'ANDROID' : 'IOS');
} catch(e) {
if (e?.message === 'This video is unavailable') {
return { error: 'ErrorCouldntFetch' };

View file

@ -0,0 +1,30 @@
import { Innertube } from 'youtubei.js';
const bail = (...msg) => (console.error(...msg), process.exit(1));
const tube = await Innertube.create();
tube.session.once(
'auth-pending',
({ verification_url, user_code }) => console.log(
`Open ${verification_url} in a browser and enter ${user_code} when asked for the code.`
)
);
tube.session.once('auth-error', (err) => bail('An error occurred:', err));
tube.session.once('auth', ({ status, credentials, ...rest }) => {
if (status !== 'SUCCESS') {
bail('something went wrong', rest);
}
console.log(credentials);
console.log(
JSON.stringify(
Object.entries(credentials)
.map(([k, v]) => `${k}=${v instanceof Date ? v.toISOString() : v}`)
.join('; ')
)
);
});
await tube.session.signIn();