f0ckv2/src/inc/trigger/parser_new.mjs
2018-09-03 21:03:58 +02:00

114 lines
3.7 KiB
JavaScript

import { cfg } from "../cfg";
import sql from "../sql";
import * as lib from "./inc/parser";
import fs from "fs";
import fetch from "node-fetch";
import { promisify } from "util";
import { execFile as ef } from "child_process";
const execFile = promisify(ef);
const bin = process.cwd() + "/bin/youtube-dl";
const b = process.cwd() + "/b";
const _args = [ "--dump-json" ];
const regex = /https?:\/\/[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?/gi;
export default bot => {
bot._trigger.set("parser", new bot.trigger({
call: regex,
f: e => {
if(e.channel !== "#kbot-dev" && !e.message.match(/(!|-)f0ck/i))
return;
if(e.message.match(/(!|-)ignore/))
return e.reply("ignored");
const tmp = e.message.match(regex); // get links
Promise.all(tmp.map(link => execFile(bin, [...[link], ..._args])))
.then(data => data.map(d => JSON.parse(d.stdout)))
.then(d => d.map(data => data.direct ? {
thumbnail: "",
link: data.url,
file: data.title,
format: [{
ext: data.ext,
note: "direct",
url: data.url,
size: 0,
rsize: 0
}]
} : {
thumbnail: data.thumbnail,
link: data.webpage_url,
file: data.id,
format: data.formats
.filter(f => {
if(f.hasOwnProperty("fragments"))
return false;
if(!["webm", "mp4", "mp3"].includes(f.ext))
return false;
if(f.filesize > cfg.main.maxFileSize.val && f.ext !== "mp3")
return false;
if(/playlist/i.test(f.url))
return false;
if(e.self.debug)
e.reply(`${f.ext} - ${f.url} - ${f.format}`);
return f;
})
.splice(-1, 1)
.map(f => ({
ext: f.ext,
note: f.format_note,
url: f.url,
size: lib.formatSize(f.filesize),
rsize: f.filesize
}))
}))
.then(d => d.map(data => {
if(data.format.length === 0)
return e.reply("no filters found, f0ck! D:");
fetch(data.format[0].url, { size: cfg.main.maxFileSize.val })
.then(res => {
const uuid = lib.getUUID();
const file = `${b}/${uuid}.${data.format[0].ext}`;
const dest = fs.createWriteStream(file);
res.body.pipe(dest);
let t;
dest.on("open", () => {
e.reply(`downloading ${data.file}...`);
t = setInterval(() => {
const size = fs.statSync(file).size;
if(size >= cfg.main.maxFileSize.val) {
e.reply(`file too large lol! D: (${lib.formatSize(size)})`);
res.body.unpipe(dest);
dest.destroy();
fs.unlinkSync(file);
clearInterval(t);
t = false;
}
else {
if(e.self.debug)
e.reply(`${data.file}: ${lib.formatSize(size)}`);
}
}, 2000);
});
dest.on("close", blah => {
if(t) {
clearInterval(t);
e.reply(`gef0ckt lol: ${data.file} -> ${uuid}.${data.format[0].ext}, ~${lib.formatSize(fs.statSync(file).size)}`);
}
else {
// recursive
}
});
})
.catch(err => {
console.error(err);
});
}))
.catch(err => e.reply(JSON.stringify(err))
);
}
}));
};