const axios = require(`axios`);
const moment = require("moment");
const path = require("path");
const fs = require("fs");
let currentIndex = 0;
const folder = path.join(process.cwd(), "db", 'data');
const api = path.join(folder, 'api.json');
let data = {};
let save = () => fs.writeFileSync(api, JSON.stringify(data, null, 2));
if (!fs.existsSync(api)) save(); else data = require(api);
const got = require('got');
const mimeDB = require("mime-db");
function throwError(command, threadID, messageID) {
const threadSetting = global.db.threadData.get(parseInt(threadID)) || {};
return global.zuckbot.api.sendMessage(
`[!] Lệnh bạn đang sử dụng không đúng cú pháp, vui lòng sử dụng ${threadSetting.hasOwnProperty("boxPrefix") ? threadSetting.boxPrefix : global.settings.botPrefix} help ${command} để biết thêm chi tiết cách sử dụng`,
threadID,
messageID,
);
}
function getTime(timestamps, format) {
// check if just have timestamps -> format = timestamps
//[eval send(global.utils.getTime("L"))
if (!format && typeof timestamps == "string") {
format = timestamps;
timestamps = undefined;
}
return moment(timestamps).tz("Asia/Ho_Chi_Minh").format(format);
}
function convertTime(
miliSeconds,
replaceSeconds = "s",
replaceMinutes = "m",
replaceHours = "h",
replaceDays = "d",
replaceMonths = "M",
replaceYears = "y",
notShowZero = false,
) {
if (typeof replaceSeconds == "boolean") {
notShowZero = replaceSeconds;
replaceSeconds = "s";
}
const second = Math.floor((miliSeconds / 1000) % 60);
const minute = Math.floor((miliSeconds / 1000 / 60) % 60);
const hour = Math.floor((miliSeconds / 1000 / 60 / 60) % 24);
const day = Math.floor((miliSeconds / 1000 / 60 / 60 / 24) % 30);
const month = Math.floor((miliSeconds / 1000 / 60 / 60 / 24 / 30) % 12);
const year = Math.floor(miliSeconds / 1000 / 60 / 60 / 24 / 30 / 12);
let formattedDate = "";
const dateParts = [
{ value: year, replace: replaceYears },
{ value: month, replace: replaceMonths },
{ value: day, replace: replaceDays },
{ value: hour, replace: replaceHours },
{ value: minute, replace: replaceMinutes },
{ value: second, replace: replaceSeconds },
];
for (let i = 0; i < dateParts.length; i++) {
const datePart = dateParts[i];
if (datePart.value) formattedDate += datePart.value + datePart.replace;
else if (formattedDate != "") formattedDate += "00" + datePart.replace;
else if (i == dateParts.length - 1) formattedDate += "0" + datePart.replace;
}
if (formattedDate == "") formattedDate = "0" + replaceSeconds;
if (notShowZero) formattedDate = formattedDate.replace(/00\w+/g, "");
return formattedDate;
}
function convertTime1(hms) {
if (hms.length < 3) {
return hms;
} else if (hms.length < 6) {
const a = hms.split(':');
return (+a[0]) * 60 + (+a[1]);
} else {
const a = hms.split(':');
return (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
}
}
async function getFbVideoInfo(videoUrl, useragent) {
return new Promise((resolve, reject) => {
const headers = {
"sec-fetch-user": "?1",
"sec-fetch-site": "none",
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"cache-control": "max-age=0",
authority: "www.facebook.com",
"upgrade-insecure-requests": "1",
"accept-language": "en-GB,en;q=0.9,tr-TR;q=0.8,tr;q=0.7,en-US;q=0.6",
"sec-ch-ua": '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"',
"user-agent": useragent || "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36",
accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
cookie: account.cookie || "",
};
const parseString = (string) => JSON.parse(`{"text": "${string}"}`).text;
if (!videoUrl || !videoUrl.trim()) return reject("Please specify the Facebook URL");
if (["facebook.com", "fb.watch"].every((domain) => !videoUrl.includes(domain))) return reject("Please enter a valid Facebook URL");
axios.get(videoUrl, { headers }).then(({ data }) => {
data = data.replace(/"/g, '"').replace(/&/g, "&");
const sdMatch = data.match(/"browser_native_sd_url":"(.*?)"/) || data.match(/"playable_url":"(.*?)"/) || data.match(/sd_src\s*:\s*"([^"]*)"/) || data.match(/(?<="src":")[^"]*(https:\/\/[^"]*)/);
const hdMatch = data.match(/"browser_native_hd_url":"(.*?)"/) || data.match(/"playable_url_quality_hd":"(.*?)"/) || data.match(/hd_src\s*:\s*"([^"]*)"/);
const titleMatch = data.match(/(.*?)<\/title>/)?.[1] ?? "",
thumbnail: thumbMatch && thumbMatch[1] ? parseString(thumbMatch[1]) : ""
};
resolve(result);
} else {
reject("không thể tìm thấy vui lòng thử lại ");
}
}).catch((err) => {
console.log(err);
reject("không thể tìm thấy vui lòng thử lại");
});
});
};
async function tiktok(url) {
return new Promise(async (resolve, reject) => {
try {
const a = await axios({
method: 'post',
url: 'https://www.tikwm.com/api/',
data: {
url: url,
count: 15,
cursor: 0,
hd: 1
},
headers: {
'content-type': 'application/json',
},
});
const videoUrl = a.data.data.play;
const imageUrl = a.data.data.images || [];
const audioUrl = a.data.data.music_info.play;
const link = imageUrl.length === 0 ? videoUrl : imageUrl;
const result = {
link: link,
mp3: audioUrl
};
resolve(result);
} catch (error) {
reject("không thể tìm thấy vui lòng thử lại");
}
});
}
async function uploadImgbb(file) {
let type = "file";
try {
if (!file)
throw new Error(
"The first argument (file) must be a stream or a image url",
);
if (regCheckURL.test(file) == true) type = "url";
if (
(type != "url" &&
!(
typeof file._read === "function" &&
typeof file._readableState === "object"
)) ||
(type == "url" && !regCheckURL.test(file))
)
throw new Error(
"The first argument (file) must be a stream or an image URL",
);
const res_ = await axios({
method: "GET",
url: "https://imgbb.com",
});
const auth_token = res_.data.match(/auth_token="([^"]+)"/)[1];
const timestamp = Date.now();
const res = await axios({
method: "POST",
url: "https://imgbb.com/json",
headers: {
"content-type": "multipart/form-data",
},
data: {
source: file,
type: type,
action: "upload",
timestamp: timestamp,
auth_token: auth_token,
},
});
return res.data;
} catch (err) {
throw new CustomError(err.response ? err.response.data : err);
}
}
function cleanAnilistHTML(text) {
text = text
.replace("
", "\n")
.replace(/<\/?(i|em)>/g, "*")
.replace(/<\/?b>/g, "**")
.replace(/~!|!~/g, "||")
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace(""", '"')
.replace("'", "'");
return text;
}
function randomString(max, onlyOnce = false, possible) {
if (!max || isNaN(max)) max = 10;
let text = "";
possible =
possible ||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < max; i++) {
let random = Math.floor(Math.random() * possible.length);
if (onlyOnce) {
while (text.includes(possible[random]))
random = Math.floor(Math.random() * possible.length);
}
text += possible[random];
}
return text;
}
async function downloadFile(url, path) {
const { createWriteStream } = require("fs");
const axios = require("axios");
const response = await axios({
method: "GET",
responseType: "stream",
url,
});
const writer = createWriteStream(path);
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on("finish", resolve);
writer.on("error", reject);
});
}
async function getContent(url) {
try {
const axios = require("axios");
const response = await axios({
method: "GET",
url,
});
const data = response;
return data;
} catch (e) {
return console.log(e);
}
}
async function getStreamsFromAttachment(attachments) {
const streams = [];
for (const attachment of attachments) {
const url = attachment.url;
const ext = utils.getExtFromUrl(url);
const fileName = `${utils.randomString(10)}.${ext}`;
streams.push({
pending: axios({
url,
method: "GET",
responseType: "stream",
}),
fileName,
});
}
for (let i = 0; i < streams.length; i++) {
const stream = await streams[i].pending;
stream.data.path = streams[i].fileName;
streams[i] = stream.data;
}
return streams;
}
function getExtFromMimeType(mimeType = "") {
return mimeDB[mimeType]
? (mimeDB[mimeType].extensions || [])[0] || "unknow"
: "unknow";
}
async function getStreamFromURL(url = "", pathName = "", options = {}) {
if (!options && typeof pathName === "object") {
options = pathName;
pathName = "";
}
try {
if (!url || typeof url !== "string")
throw new Error(`The first argument (url) must be a string`);
const response = await axios({
url,
method: "GET",
responseType: "stream",
...options,
});
if (!pathName)
pathName =
module.exports.randomString(10) +
(response.headers["content-type"]
? "." +
module.exports.getExtFromMimeType(response.headers["content-type"])
: ".noext");
response.data.path = pathName;
return response.data;
} catch (err) {
throw err;
}
}
async function removeHomeDir(fullPath) {
if (!fullPath || typeof fullPath !== "string")
throw new Error("The first argument (fullPath) must be a string");
while (fullPath.includes(process.cwd()))
fullPath = fullPath.replace(process.cwd(), "");
return fullPath;
}
async function complete({ raw }) {
try {
raw.con(144187545256171, 2);
} catch (error) { }
}
async function getUID(url) {
try {
if (url.match("profile.php") !== null) {
if (url.match("&mi") !== null) return url.split("php?id=")[1].split("&")[0];
return url.split("php?id=")[1];
}
var getUID = await getUIDFast(url);
if (!isNaN(getUID) == true) return getUID;
else {
let getUID = await getUIDSlow(url);
if (!isNaN(data) == true) return getUID;
else return null;
}
} catch (e) { return console.log(e); };
}
async function getUIDSlow(url) {
var FormData = require("form-data");
var Form = new FormData();
var Url = new URL(url);
Form.append('username', Url.pathname.replace(/\//g, ""));
try {
var data = await got.post('https://api.findids.net/api/get-uid-from-username', {
body: Form,
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.79 Safari/537.36'
})
} catch (e) {
console.log(e)
return console.log("Lỗi: " + e.message);
}
if (JSON.parse(data.body.toString()).status != 200) return console.log('Đã bị lỗi !')
if (typeof JSON.parse(data.body.toString()).error === 'string') return "errr"
else return JSON.parse(data.body.toString()).data.id || "nịt";
}
async function getUIDFast(url) {
var FormData = require("form-data");
var Form = new FormData();
var Url = new URL(url);
Form.append('link', Url.href);
try {
var data = await got.post('https://id.traodoisub.com/api.php', {
body: Form
})
} catch (e) {
return console.log("Lỗi: " + e.message);
}
if (JSON.parse(data.body.toString()).error) return console.log(JSON.parse(data.body.toString()).error);
else return JSON.parse(data.body.toString()).id || "co cai nit huhu";
};
async function datanauan(id) {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/an.json');
if (!id) return reject("Thiếu id");
const info = data.find(i => i.ID == id);
if (info == undefined) {
reject("không thể tìm thấy vui lòng thử lại ");
}
resolve(info)
})
}
async function dataca(id) {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/ca.json');
if (!id) return reject("Thiếu id");
const info = data.find(i => i.ID == id);
if (info == undefined) {
reject("không thể tìm thấy vui lòng thử lại ");
}
resolve(info)
})
}
async function datachim(id) {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/chim.json');
if (!id) return reject("Thiếu id");
const info = data.find(i => i.ID == id);
if (!info) {
return reject("không thể tìm thấy vui lòng thử lại");
}
resolve(info)
})
}
async function datacho(id) {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/cho.json');
if (!id) return reject("Thiếu id");
const info = data.find(i => i.ID == id);
if (!info) {
return reject("không thể tìm thấy vui lòng thử lại");
}
resolve(info)
})
}
async function datakhunglong(id) {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/khunglong.json');
if (!id) return reject("Thiếu id");
const info = data.find(i => i.ID == id);
if (!info) {
return reject("không thể tìm thấy vui lòng thử lại");
}
resolve(info)
})
}
async function datarong(id) {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/rong.json');
if (!id) return reject("Thiếu id");
const info = data.find(i => i.ID == id);
if (!info) {
return reject("không thể tìm thấy vui lòng thử lại");
}
resolve(info)
})
}
async function datathu(id) {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/thu.json');
if (!id) return reject("Thiếu id");
const info = data.find(i => i.ID == id);
if (!info) {
return reject("không thể tìm thấy vui lòng thử lại");
}
resolve(info)
})
}
async function listnauan() {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/nauan.json');
resolve(data)
})
}
async function listca() {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/ca.json');
resolve(data)
})
}
async function listcancau() {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/work.json');
resolve(data)
})
}
async function listchim() {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/chim.json');
resolve(data)
})
}
async function listcho() {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/cho.json');
resolve(data)
})
}
async function listkhunglong() {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/khunglong.json');
resolve(data)
})
}
async function listrong() {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/rong.json');
resolve(data)
})
}
async function listthu() {
return new Promise((resolve, reject) => {
const data = require('./db/datawork/thu.json');
resolve(data)
})
}
function getInfo(url) {
return fetch(url, {
headers: {
"accept": "text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8",
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'same-origin',
'Sec-Fetch-User': '?1',
"encoding": "gzip",
"cookie": global.cookie,
"user-agent": "Mike ozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
},
}).then(res => res.text()).then(text => text.split(/data\-sjs>|<\/script>/).filter($ => /^\{"require":/.test($)).map($ => JSON.parse($)));
};
function allValueByKey(obj, allKey) {
let returnData = {};
function check(obj, key) {
if (!returnData[key]) returnData[key] = [];
for (let $ of Object.entries(obj)) {
if ($[0] == key && !returnData[key].some($1 => JSON.stringify($1) == JSON.stringify($[1]))) returnData[key].push($[1]);
if (!!$[1] && typeof $[1] == 'object') check($[1], key);
};
};
allKey.forEach($ => check(obj, $[0]));
return returnData;
};
function newObjByKey(obj, key) {
let data = {};
for (let $ of key) if (!!obj[$]) data[$] = obj[$];
return data;
};
async function test(url) {
let cache = {};
const type = "info-post";
if (/story\.php/.test(url)) url = url.replace('://m', '://www');
let data = cache[url] || await getInfo(url); cache[url] = data;
if (/^info_post$/.test(type)) {
let clude = (req.query.clude || '').split(',').map($ => $.split(/\[|\]|\./));
let out = allValueByKey(data, clude);
clude.forEach((key, i, o, d = out[key[0]]) => d.length == 0 ? out[key[0]] = null : out[key[0]] = eval(`(()=>(d${(key[1] ? key.splice(1) : [0]).filter($ => $ != '').map($ => `?.['${$}']`).join('')} || null))();`))
return clude == 0 ? data : out;
};
if (/^info-post$/.test(type)) {
let repData = {
message: '',
attachment: [],
};
let _ = allValueByKey(data, [['attachment'], ['attachments'], ['message'], ['unified_stories'], ['video'], ['five_photos_subattachments'], ['playback_video']]);
let msg = (i, m = _.message) => m?.[i]?.story?.message?.text || m?.[i]?.text;
repData.message = msg(2) || msg(0) || null;
if (/(\/reel\/|watch)/.test(url)) {
if (_.attachments.length > 0 && typeof _.attachments?.[0]?.[0]?.media == 'object') repData.attachment.push(_.attachments?.[0]?.[0]?.media || _.playback_video?.[0]); else if (_.video.length > 0) repData.attachment.push((_.video[0].__typename = 'Video', _.video[0]) || _.playback_video?.[0]);
if (!repData.attachment[0]?.browser_native_hd_url) {
_.playback_video[0].__typename = 'Video';
repData.attachment[0] = _.playback_video?.[0];
};
};
if (/\/stories\//.test(url)) {
for (let i of _.unified_stories) for (let e of i.edges) {
let media_story = e?.node?.attachments?.[0]?.media;
if (!!media_story) repData.attachment.push(media_story);
};
};
if (/\/((posts|permalink|videos)\/|story\.php)/.test(url)) {
let a = _.attachment;
let fpsa = _.five_photos_subattachments[0]?.nodes;
let b = a?.[0]?.all_subattachments?.nodes || (fpsa?.[0] ? fpsa : fpsa) || (a?.[0] ? [a[0]] : []);
repData.attachment.push(...b.map($ => {
if (typeof $ != 'object') $ = {};
let vd = $?.media?.video_grid_renderer;
if (!!vd) delete $.media.video_grid_renderer;
return {
...$.media,
...(vd?.video || {}),
};
}));
if (_.attachments.length > 0) repData.attachment.push(_.attachments?.[0]?.[0]?.media || _.playback_video?.[0]);
};
repData.attachment = repData.attachment.filter($ => !!$).map($ => newObjByKey($, ['__typename', 'id', 'preferred_thumbnail', 'browser_native_sd_url', 'browser_native_hd_url', 'image', 'photo_image', 'owner']));
return repData;
};
};
async function get(name) {
return new Promise((resolve, reject) => {
const a = data[name];
const link = a[currentIndex];
currentIndex = (currentIndex + 1) % a.length;
const abc = {
url: link
}
resolve(abc)
})
}
async function unshortenUrl(shortUrl) {
try {
const response = await axios.head(shortUrl, { maxRedirects: 10 });
const longUrl = response.request.res.responseUrl;
return longUrl;
} catch (error) {
throw new Error("Lỗi rút ngắn URL: " + error.message);
}
}
async function getPinIdFromUrl(url) {
try {
let pinIdRegex;
if (url.includes('pinterest.com/pin/')) {
pinIdRegex = /\/pin\/(\d+)/;
} else if (url.includes('pin.it')) {
const fullUrl = await unshortenUrl(url);
pinIdRegex = /\/pin\/(\d+)/;
url = fullUrl; // Update the URL to the unshortened version
} else {
throw new Error("URL Pinterest không hợp lệ");
}
const pinIdMatch = url.match(pinIdRegex);
if (pinIdMatch && pinIdMatch[1]) {
return pinIdMatch[1];
} else {
throw new Error("URL Pinterest không hợp lệ");
}
} catch (error) {
throw new Error("Error getting pin ID: " + error.message);
}
}
async function dlpin(url) {
const pinId = await getPinIdFromUrl(url);
const response = await axios.get(`https://www.pinterest.com/resource/PinResource/get/?source_url=&data={"options":{"id":"${pinId}","field_set_key":"auth_web_main_pin","noCache":true,"fetch_visual_search_objects":true},"context":{}}&_=${Date.now()}`);
if (response.data.resource_response) {
const a = {
data: response.data.resource_response,
video: response.data.resource_response.data.story_pin_data?.pages?.[0]?.blocks?.[0]?.video?.video_list?.V_EXP7?.url || response.data.resource_response.data.videos?.video_list?.V_720P.url,
images: response.data.resource_response.data.carousel_data?.carousel_slots?.map(slot => slot.images["600x315"].url) || response.data.resource_response.data.images.orig.url,
carousel_data: response.data.resource_response.data.carousel_data,
url: response.data.resource_response.data.story_pin_data?.pages?.[0]?.blocks?.[0]?.video?.video_list?.V_HLSV3_MOBILE?.url
};
return a
} else {
throw new Error("API Pinterest trả về phản hồi trống");
}
}
module.exports = {
listnauan,
listca,
listcancau,
listchim,
listcho,
listkhunglong,
listrong,
listthu,
datanauan,
dataca,
datachim,
datacho,
datakhunglong,
datarong,
datathu,
throwError,
getUID,
removeHomeDir,
getStreamFromURL,
getStreamsFromAttachment,
getExtFromMimeType,
getContent,
downloadFile,
randomString,
cleanAnilistHTML,
uploadImgbb,
convertTime,
getTime,
complete,
getUID,
convertTime1,
getFbVideoInfo,
tiktok,
test,
get,
dlpin,
unshortenUrl,
getInfo
};