1
0
Fork 0
mirror of https://github.com/wukko/cobalt.git synced 2025-03-29 21:01:37 +01:00
cobalt/src/modules/processing/services/youtube.js

245 lines
7.7 KiB
JavaScript
Raw Normal View History

import { Innertube, Session } from 'youtubei.js';
import { env } from '../../config.js';
import { cleanString } from '../../sub/utils.js';
import { fetch } from 'undici'
2024-06-08 09:30:12 +00:00
import { getCookie, updateCookieValues } from '../cookie/manager.js'
const ytBase = Innertube.create().catch(e => e);
const codecMatch = {
2023-02-26 22:49:25 +06:00
h264: {
codec: "avc1",
aCodec: "mp4a",
container: "mp4"
},
av1: {
codec: "av01",
aCodec: "mp4a",
container: "mp4"
},
vp9: {
codec: "vp9",
aCodec: "opus",
container: "webm"
}
}
const transformSessionData = (cookie) => {
if (!cookie)
return;
2024-07-10 14:13:56 +00:00
const values = { ...cookie.values() };
const REQUIRED_VALUES = [
'access_token', 'refresh_token',
2024-07-10 14:13:56 +00:00
'client_id', 'client_secret'
];
if (REQUIRED_VALUES.some(x => typeof values[x] !== 'string')) {
return;
}
2024-07-10 14:13:56 +00:00
if (values.expires) {
values.expiry_date = values.expires;
delete values.expires;
} else if (!values.expiry_date) {
return;
}
return values;
}
const cloneInnertube = async (customFetch) => {
const innertube = await ytBase;
if (innertube instanceof Error) {
throw innertube;
}
const session = new Session(
innertube.session.context,
innertube.session.key,
innertube.session.api_version,
innertube.session.account_index,
innertube.session.player,
undefined,
customFetch ?? innertube.session.http.fetch,
innertube.session.cache
);
2024-06-08 09:30:12 +00:00
const cookie = getCookie('youtube_oauth');
const oauthData = transformSessionData(cookie);
if (!session.logged_in && oauthData) {
await session.oauth.init(oauthData);
session.logged_in = true;
}
if (session.logged_in) {
2024-07-10 14:13:56 +00:00
if (session.oauth.shouldRefreshToken()) {
await session.oauth.refreshAccessToken();
}
const cookieValues = cookie.values();
const oldExpiry = new Date(cookieValues.expiry_date);
const newExpiry = new Date(session.oauth.oauth2_tokens.expiry_date);
2024-06-08 09:30:12 +00:00
if (oldExpiry.getTime() !== newExpiry.getTime()) {
updateCookieValues(cookie, {
2024-07-10 14:13:56 +00:00
...session.oauth.client_id,
...session.oauth.oauth2_tokens,
expiry_date: newExpiry.toISOString()
2024-06-08 09:30:12 +00:00
});
}
}
const yt = new Innertube(session);
return yt;
}
2023-02-26 22:49:25 +06:00
export default async function(o) {
const yt = await cloneInnertube(
(input, init) => fetch(input, { ...init, dispatcher: o.dispatcher })
);
let info, isDubbed, format = o.format || "h264";
let quality = o.quality === "max" ? "9000" : o.quality; // 9000(p) - max quality
2024-04-27 18:05:43 +06:00
function qual(i) {
if (!i.quality_label) {
return;
}
return i.quality_label.split('p')[0].split('s')[0]
}
2023-02-26 22:49:25 +06:00
try {
info = await yt.getBasicInfo(o.id, yt.session.logged_in ? 'ANDROID' : 'IOS');
} catch(e) {
if (e?.message === 'This video is unavailable') {
return { error: 'ErrorCouldntFetch' };
} else {
return { error: 'ErrorCantConnectToServiceAPI' };
}
2023-02-26 22:49:25 +06:00
}
if (!info) return { error: 'ErrorCantConnectToServiceAPI' };
const playability = info.playability_status;
if (playability.status === 'LOGIN_REQUIRED') {
if (playability.reason.endsWith('bot')) {
return { error: 'ErrorYTLogin' }
}
if (playability.reason.endsWith('age')) {
return { error: 'ErrorYTAgeRestrict' }
}
}
if (playability.status === "UNPLAYABLE" && playability.reason.endsWith('request limit.')) {
return { error: 'ErrorYTRateLimit' }
}
if (playability.status !== 'OK') return { error: 'ErrorYTUnavailable' };
2023-02-26 22:49:25 +06:00
if (info.basic_info.is_live) return { error: 'ErrorLiveVideo' };
2024-04-27 18:05:43 +06:00
// return a critical error if returned video is "Video Not Available"
// or a similar stub by youtube
if (info.basic_info.id !== o.id) {
return {
error: 'ErrorCantConnectToServiceAPI',
critical: true
}
}
let bestQuality, hasAudio;
const filterByCodec = (formats) => formats.filter(e =>
e.mime_type.includes(codecMatch[format].codec) || e.mime_type.includes(codecMatch[format].aCodec)
2023-08-23 01:03:31 +06:00
).sort((a, b) => Number(b.bitrate) - Number(a.bitrate));
let adaptive_formats = filterByCodec(info.streaming_data.adaptive_formats);
if (adaptive_formats.length === 0 && format === "vp9") {
format = "h264"
adaptive_formats = filterByCodec(info.streaming_data.adaptive_formats)
}
bestQuality = adaptive_formats.find(i => i.has_video && i.content_length);
hasAudio = adaptive_formats.find(i => i.has_audio && i.content_length);
if (bestQuality) bestQuality = qual(bestQuality);
if (!bestQuality && !o.isAudioOnly || !hasAudio) return { error: 'ErrorYTTryOtherCodec' };
if (info.basic_info.duration > env.durationLimit) return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
2024-01-31 17:10:02 +06:00
let checkBestAudio = (i) => (i.has_audio && !i.has_video),
audio = adaptive_formats.find(i => checkBestAudio(i) && !i.is_dubbed);
2023-02-26 22:49:25 +06:00
if (o.dubLang) {
2023-10-15 22:13:01 +06:00
let dubbedAudio = adaptive_formats.find(i =>
2024-01-31 17:10:02 +06:00
checkBestAudio(i) && i.language === o.dubLang && i.audio_track && !i.audio_track.audio_is_default
2023-10-15 22:13:01 +06:00
);
2023-02-26 22:49:25 +06:00
if (dubbedAudio) {
audio = dubbedAudio;
isDubbed = true
}
}
let fileMetadata = {
title: cleanString(info.basic_info.title.trim()),
artist: cleanString(info.basic_info.author.replace("- Topic", "").trim()),
}
if (info.basic_info.short_description && info.basic_info.short_description.startsWith("Provided to YouTube by")) {
let descItems = info.basic_info.short_description.split("\n\n");
2023-08-20 18:16:00 +06:00
fileMetadata.album = descItems[2];
fileMetadata.copyright = descItems[3];
if (descItems[4].startsWith("Released on:")) {
2023-08-20 18:16:00 +06:00
fileMetadata.date = descItems[4].replace("Released on: ", '').trim()
}
}
let filenameAttributes = {
service: "youtube",
id: o.id,
title: fileMetadata.title,
author: fileMetadata.artist,
youtubeDubName: isDubbed ? o.dubLang : false
}
if (hasAudio && o.isAudioOnly) return {
type: "render",
isAudioOnly: true,
urls: audio.decipher(yt.session.player),
filenameAttributes: filenameAttributes,
fileMetadata: fileMetadata,
bestAudio: format === "h264" ? 'm4a' : 'opus'
}
2023-10-17 16:48:51 +00:00
const matchingQuality = Number(quality) > Number(bestQuality) ? bestQuality : quality,
checkSingle = i => qual(i) === matchingQuality && i.mime_type.includes(codecMatch[format].codec),
checkRender = i => qual(i) === matchingQuality && i.has_video && !i.has_audio;
let match, type, urls;
if (!o.isAudioOnly && !o.isAudioMuted && format === 'h264') {
match = info.streaming_data.formats.find(checkSingle);
type = "bridge";
urls = match?.decipher(yt.session.player);
}
const video = adaptive_formats.find(checkRender);
if (!match && video) {
match = video;
type = "render";
urls = [video.decipher(yt.session.player), audio.decipher(yt.session.player)];
}
2023-02-26 22:49:25 +06:00
if (match) {
filenameAttributes.qualityLabel = match.quality_label;
filenameAttributes.resolution = `${match.width}x${match.height}`;
filenameAttributes.extension = codecMatch[format].container;
filenameAttributes.youtubeFormat = format;
return {
2024-01-31 17:10:02 +06:00
type,
urls,
filenameAttributes,
fileMetadata
}
}
2023-02-26 22:49:25 +06:00
return { error: 'ErrorYTTryOtherCodec' }
}