poke/src/libpoketube/libpoketube-core.js
2025-09-01 22:30:15 +02:00

183 lines
5.0 KiB
JavaScript

/**
* Poke is a Free/Libre youtube front-end !
*
* This file is Licensed under LGPL-3.0-or-later. Poketube itself is GPL, Only this file is LGPL.
* See a copy here: https://www.gnu.org/licenses/lgpl-3.0.txt
* Please don't remove this comment while sharing this code.
*/
const getdislikes = require("../libpoketube/libpoketube-dislikes.js");
const getColors = require("get-image-colors");
const config = require("../../config.json");
class InnerTubePokeVidious {
constructor(config) {
this.config = config;
this.cache = {};
this.language = "hl=en-US";
this.param = "2AMB";
this.param_legacy = "CgIIAdgDAQ%3D%3D";
this.apikey = "AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8";
this.ANDROID_API_KEY = "AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w";
this.ANDROID_APP_VERSION = "20.20.41";
this.ANDROID_VERSION = "16";
this.useragent =
config.useragent ||
"PokeTube/2.0.0 (GNU/Linux; Android 14; Trisquel 11; poketube-vidious; like FreeTube)";
this.INNERTUBE_CONTEXT_CLIENT_VERSION = "1";
this.region = "region=US";
this.sqp =
"-oaymwEbCKgBEF5IVfKriqkDDggBFQAAiEIYAXABwAEG&rs=AOn4CLBy_x4UUHLNDZtJtH0PXeQGoRFTgw";
}
getJson(str) {
try {
return JSON.parse(str);
} catch {
return null;
}
}
checkUnexistingObject(obj) {
return obj && "authorId" in obj;
}
async getYouTubeApiVideo(f, v, contentlang, contentregion) {
const { fetch } = await import("undici");
if (!v) {
this.initError("Missing video ID", null);
return { error: true, message: "No video ID provided" };
}
if (this.cache[v] && Date.now() - this.cache[v].timestamp < 3600000) {
return this.cache[v].result;
}
const headers = {
"User-Agent": this.useragent,
};
const fetchWithRetry = async (url, options = {}, retries = 3) => {
let lastError;
for (let attempt = 0; attempt < retries; attempt++) {
try {
const res = await fetch(url, {
...options,
headers: {
...options.headers,
...headers,
},
});
if (res.ok) {
return res;
}
if ((res.status >= 500 || res.status === 429) && attempt < retries - 1) {
this.initError(`Retrying fetch for ${url}`, res.status);
continue;
}
return res;
} catch (err) {
lastError = err;
this.initError(`Fetch error for ${url}`, err);
if (attempt < retries - 1) {
continue;
} else {
throw lastError;
}
}
}
};
try {
const [invComments, videoInfo] = await Promise.all([
fetchWithRetry(
`${this.config.invapi}/comments/${v}?hl=${contentlang}&region=${contentregion}&h=${btoa(
Date.now()
)}`
).then((res) => res?.text()),
fetchWithRetry(
`${this.config.invapi}/videos/${v}?hl=${contentlang}&region=${contentregion}&h=${btoa(
Date.now()
)}`
).then((res) => res?.text()),
]);
const comments = this.getJson(invComments);
const vid = this.getJson(videoInfo);
if (!vid) {
this.initError("Video info missing/unparsable", v);
return {
error: true,
message: "Sorry nya, we couldn't find any information about that video qwq",
};
}
if (this.checkUnexistingObject(vid)) {
let fe = { engagement: null };
try {
fe = await getdislikes(v);
} catch (err) {
this.initError("Dislike API error", err);
}
let color = "#0ea5e9";
let color2 = "#111827";
try {
const palette = await getColors(
`https://i.ytimg.com/vi/${v}/hqdefault.jpg?sqp=${this.sqp}`
);
if (Array.isArray(palette) && palette[0] && palette[1]) {
color = palette[0].hex();
color2 = palette[1].hex();
}
} catch (err) {
this.initError("Thumbnail color extraction error", err);
}
this.cache[v] = {
result: {
vid,
comments,
channel_uploads: " ",
engagement: fe.engagement,
wiki: "",
desc: "",
color,
color2,
},
timestamp: Date.now(),
};
return this.cache[v].result;
} else {
this.initError("Invalid video object (missing authorId)", vid);
}
} catch (error) {
this.initError("Error getting video", error);
}
}
isvalidvideo(v) {
if (v != "assets" && v != "cdn-cgi" && v != "404") {
return /^([a-zA-Z0-9_-]{11})$/.test(v);
}
return false;
}
initError(context, error) {
console.log("[LIBPT CORE ERROR]", context, error?.stack || error || "");
}
}
const pokeTubeApiCore = new InnerTubePokeVidious({
invapi: "https://invid-api.poketube.fun/bHj665PpYhUdPWuKPfZuQGoX/api/v1",
useragent: config.useragent,
});
module.exports = pokeTubeApiCore;