poke/src/libpoketube/libpoketube-fetcher.js

63 lines
1.5 KiB
JavaScript
Raw Normal View History

2023-03-12 07:38:21 +01:00
const { curly } = require('node-libcurl');
const { toJson } = require('xml2json');
const fetch = require("node-fetch");
2022-03-02 21:05:55 +01:00
2023-03-12 07:38:21 +01:00
const youtubeUrl = 'https://www.youtube.com/watch?v=';
const dislikeApi = 'https://p.poketube.fun/api?v=';
const newApiUrl = 'https://inner-api.poketube.fun/api/player';
2023-02-25 18:47:28 +01:00
const parseXml = async (videoId, headers) => {
2023-03-04 15:08:54 +01:00
try {
2023-03-12 07:38:21 +01:00
var { data } = await curly.get(`${newApiUrl}?v=${videoId}`, {
httpHeader: Object.entries(headers).map(([k, v]) => `${k}: ${v}`)
});
const json = toJson(data);
2023-03-04 15:08:54 +01:00
return getJson(json);
} catch (error) {
console.error(`Error parsing XML: ${error}`);
return null;
}
2023-02-25 18:47:28 +01:00
};
2022-12-21 16:42:06 +01:00
2023-03-12 07:38:21 +01:00
2023-02-25 18:47:28 +01:00
const getJson = (str) => {
try {
return JSON.parse(str);
} catch {
return null;
2022-03-06 14:53:46 +01:00
}
2023-02-25 18:47:28 +01:00
};
2022-07-10 22:52:00 +02:00
2023-03-12 07:38:21 +01:00
2023-03-04 15:08:54 +01:00
const getEngagementData = async (videoId) => {
2023-02-28 15:12:57 +01:00
const apiUrl = `${dislikeApi}${videoId}`;
const fallbackUrl = `https://p.poketube.fun/${apiUrl}`;
try {
const engagement = await fetch(apiUrl).then((res) => res.json());
return engagement.data;
2023-02-28 15:12:57 +01:00
} catch {
try {
const engagement = await fetch(fallbackUrl).then((res) => res.json());
return engagement;
} catch {
return;
}
}
2023-02-25 18:47:28 +01:00
};
2022-12-20 14:38:25 +01:00
2023-02-28 15:12:57 +01:00
2023-02-25 18:47:28 +01:00
const getPokeTubeData = async (videoId) => {
const headers = {};
const videoData = await parseXml(videoId, headers);
2023-03-04 15:08:54 +01:00
const engagement = await getEngagementData(videoId);
2022-12-20 14:38:25 +01:00
2023-02-25 18:47:28 +01:00
return {
video: videoData,
2022-12-20 11:59:28 +01:00
engagement,
2023-02-25 18:47:28 +01:00
videoUrlYoutube: `${youtubeUrl}${videoId}`,
};
};
2023-02-25 18:47:28 +01:00
2023-03-12 07:38:21 +01:00
module.exports = getPokeTubeData;