ytmusic_api_unofficial
Version:
A simple API to get music from YouTube Music
230 lines • 10.5 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_2;
exports.makeUrl = makeUrl;
exports.headerBuilder = headerBuilder;
exports.bodyBuilder = bodyBuilder;
exports.getVisitorData = getVisitorData;
const default_1 = __importStar(require("./default"));
const error_1 = require("./error");
let visitorID = process.env.YT_VISITOR_ID || "";
let context = process.env.YT_USER_CONTEXT || "";
let cookies = process.env.YT_COOKIE || "";
function default_2(url, body = {}, header = {}, option = default_1.options) {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
const headers = yield headerBuilder(header, option);
body = yield bodyBuilder(body, option).catch(reject);
url = makeUrl(url);
fetch(url, {
method: 'POST',
headers: headers,
body: body
}).then((res) => __awaiter(this, void 0, void 0, function* () {
res = yield res.json();
if (res.error)
reject((0, error_1.error)(res.error.code, { message: res.error.message, url: url }));
else
resolve(res);
})).catch((e) => {
reject((0, error_1.error)(1000, e));
});
}));
}
function makeUrl(url, params) {
if (!url.startsWith('http')) {
url = default_1.default.apiUrl + url;
}
if (url.split('?').length <= 1)
url += '?prettyPrint=false&alt=json';
if (params) {
for (const param of params) {
url += `&${param}`;
}
}
return encodeURI(url);
}
function headerBuilder(header, options) {
return __awaiter(this, void 0, void 0, function* () {
const headers = new Headers();
for (const key in default_1.default.header) {
if (default_1.default.header[key]) {
headers.append(key, default_1.default.header[key]);
}
}
for (const key in header) {
if (header[key]) {
headers.append(key, header[key]);
}
}
headers.append('X-Goog-Visitor-Id', yield getVisitorId());
headers.append('cookie', cookies);
return headers;
});
}
function bodyBuilder(body, options_arr) {
return __awaiter(this, void 0, void 0, function* () {
const def_body = default_1.default.body;
yield getVisitorData();
def_body.context = context || def_body.context;
for (const key in options_arr) {
switch (key) {
case "country": {
if (!options_arr.country || options_arr.country === default_1.options.country)
break;
if (!default_1.countriesCodes.includes(options_arr.country.toUpperCase()))
throw (0, error_1.error)(1002, `Available languages codes: ${default_1.countriesCodes.join(", ")}`);
def_body.context.client.hl = options_arr.country.toLowerCase();
def_body.context.client.gl = options_arr.country.toUpperCase();
break;
}
}
}
return JSON.stringify(Object.assign(default_1.default.body, body));
});
}
function addOrReplaceCookie(cookie, value) {
const regex = new RegExp(`(?:^|,\\W)(${cookie})=(.*?);`, 'g');
cookie = cookie.replace(/,\s?/g, '');
cookie = cookie.replace(/;\s?/g, '');
value = value.replace(/,\s?/g, '');
value = value.replace(/;\s?/g, '');
if (cookies.match(regex)) {
cookies = cookies.replace(regex, `$1=${value};`);
}
else {
cookies += `${cookie}=${value};`;
}
}
function getVisitorId() {
return __awaiter(this, void 0, void 0, function* () {
var _a;
try {
if (visitorID || process.env.NODE_ENV !== "production")
return visitorID;
let response = yield (yield fetch('https://music.youtube.com/', {
method: 'GET',
headers: {
'User-Agent': default_1.default.header['User-Agent'],
'cookie': default_1.default.header['cookie'],
'Referer': default_1.default.header['Referer'],
},
})).text();
const matches = response.match(/ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;/);
if (matches && matches.length > 0) {
const ytcfg = JSON.parse(matches[1]);
visitorID = ((_a = ytcfg === null || ytcfg === void 0 ? void 0 : ytcfg.INNERTUBE_CONTEXT) === null || _a === void 0 ? void 0 : _a.client.visitorData) || '';
}
return visitorID;
}
catch (error) {
process.emitWarning(`Failed to get visitor ID: ${error}`, 'uncaughtException');
return visitorID;
}
});
}
function getVisitorData() {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
try {
if (visitorID !== '')
return visitorID;
if (context !== '')
return (_a = context === null || context === void 0 ? void 0 : context.client) === null || _a === void 0 ? void 0 : _a.visitorData;
/********** Init Consent Panel **********/
let init = yield fetch('https://music.youtube.com/', {
method: 'GET',
headers: {
'User-Agent': default_1.default.header['User-Agent']
},
redirect: 'manual',
});
(_d = (_c = (_b = init.headers) === null || _b === void 0 ? void 0 : _b.get('set-cookie')) === null || _c === void 0 ? void 0 : _c.match(/(?:^|,\W)([^;|,]*?)=(.*?);/g)) === null || _d === void 0 ? void 0 : _d.forEach((cookie) => {
addOrReplaceCookie(cookie.split('=')[0], cookie.split('=')[1]);
});
yield fetch(((_e = init === null || init === void 0 ? void 0 : init.headers) === null || _e === void 0 ? void 0 : _e.get('location')) || '', {
method: 'GET',
headers: {
'User-Agent': default_1.default.header['User-Agent'],
'cookie': cookies
},
});
/********** Set No Cookie And Validate User **********/
let saveUser = yield fetch('https://consent.youtube.com/save', {
method: 'POST',
headers: {
'User-Agent': default_1.default.header['User-Agent'],
'cookie': cookies,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'gl=FR&m=0&app=0&pc=ytm&continue=https%3A%2F%2Fmusic.youtube.com%2F%3Fcbrd%3D1&x=6&bl=boq_identityfrontenduiserver_20250309.09_p0&hl=fr&src=1&cm=2&set_eom=true'
});
(_h = (_g = (_f = saveUser.headers) === null || _f === void 0 ? void 0 : _f.get('set-cookie')) === null || _g === void 0 ? void 0 : _g.match(/(?:^|,\W)([^;|,]*?)=(.*?);/g)) === null || _h === void 0 ? void 0 : _h.forEach((cookie) => {
addOrReplaceCookie(cookie.split('=')[0], cookie.split('=')[1]);
});
/********** Get Context **********/
let response = yield (yield fetch('https://music.youtube.com/', {
method: 'GET',
headers: {
'User-Agent': default_1.default.header['User-Agent'],
'cookie': cookies
},
})).text();
const matches = response.match(/ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;/);
if (matches && matches.length > 0) {
const ytcfg = JSON.parse(matches[1]);
context = ytcfg === null || ytcfg === void 0 ? void 0 : ytcfg.INNERTUBE_CONTEXT;
context.client.visitorData = ((_j = ytcfg === null || ytcfg === void 0 ? void 0 : ytcfg.INNERTUBE_CONTEXT) === null || _j === void 0 ? void 0 : _j.client.visitorData) || '';
visitorID = (_k = context === null || context === void 0 ? void 0 : context.client) === null || _k === void 0 ? void 0 : _k.visitorData;
}
return visitorID;
}
catch (error) {
if (process.env.YT_DEBUG_MODE === "true")
console.error(`Failed to get visitor ID: `, error);
return visitorID;
}
});
}
//# sourceMappingURL=request.js.map