This commit is contained in:
Flummi
2021-04-17 10:43:23 +02:00
parent d553e71b50
commit 65454961ce
54 changed files with 1996 additions and 25454 deletions

5
src/inc/config.mjs Normal file
View File

@ -0,0 +1,5 @@
import _config from "../../config.json";
let config = JSON.parse(JSON.stringify(_config));
export default config;

View File

@ -1,3 +1,21 @@
const epochs = [
["year", 31536000],
["month", 2592000],
["day", 86400],
["hour", 3600],
["minute", 60],
["second", 1]
];
const getDuration = timeAgoInSeconds => {
for(let [name, seconds] of epochs) {
const interval = ~~(timeAgoInSeconds / seconds);
if(interval >= 1) return {
interval: interval,
epoch: name
};
}
};
export default new class {
formatSize(size, i = ~~(Math.log(size) / Math.log(1024))) {
return (size / Math.pow(1024, i)).toFixed(2) * 1 + " " + ["B", "kB", "MB", "GB", "TB"][i];
@ -5,4 +23,8 @@ export default new class {
calcSpeed(b, s) {
return (Math.round((b * 8 / s / 1e6) * 1e4) / 1e4);
}
timeAgo(date) {
const { interval, epoch } = getDuration(~~((new Date() - new Date(date)) / 1e3));
return `${interval} ${epoch}${interval === 1 ? "" : "s"} ago`;
}
};

114
src/inc/routes/apiv2.mjs Normal file
View File

@ -0,0 +1,114 @@
import router from "../router.mjs";
import sql from "../sql.mjs";
import { parse } from "url";
import cfg from "../../../config.json";
import { mimes, queries } from "./inc/apiv2.mjs";
router.get("/api/v2", (req, res) => {
res.end("api lol");
});
router.get(/^\/api\/v2\/random(\/user\/.+|\/image|\/video|\/audio)?$/, async (req, res) => {
const args = [];
let q = queries.random.main;
if(req.url.split[3] === "user") {
q += queries.random.where("username like ?");
args.push(req.url.split[4] || "flummi");
}
else
q += queries.random.where(mimes[req.url.split[3]] ? mimes[req.url.split[3]].map(mime => `mime = "${mime}"`).join(" or ") : null);
try {
const rows = await sql.query(q, args);
res
.writeHead(200, { "Content-Type": "application/json" })
.end(JSON.stringify(rows.length > 0 ? rows[0] : []), "utf-8");
} catch(err) {
res
.writeHead(500)
.end(JSON.stringify(err), "utf-8");
}
});
router.get("/api/v2/p", async (req, res) => {
let id = parseInt(req.url.qs.id) || 99999999;
const eps = Math.min(parseInt(req.url.qs.eps) || 100, 200);
let [ order, trend ] = req.url.qs.order === "asc" ? [ "asc", ">" ] : [ "desc", "<" ];
try {
const tmp = (await sql.query("select min(id) as min, max(id) as max from items limit 1"))[0];
if((id - 1 + eps) > tmp.max) {
id = tmp.max;
[ order, trend ] = [ "desc", "<=" ];
}
if((id + 1 - eps) < tmp.min) {
id = tmp.min;
[ order, trend ] = [ "asc", ">=" ];
}
const rows = await sql.query(queries.p(trend, order), [ id, eps ]);
const items = {
items: rows,
first: rows[0].id,
last: rows[rows.length - 1].id,
newest: tmp.max,
oldest: tmp.min
};
res
.writeHead(200, { "Content-Type": "application/json" })
.end(JSON.stringify(items), "utf-8");
} catch(err) {
console.error(err);
res
.writeHead(500)
.end(JSON.stringify(err), "utf-8");
}
});
router.get(/^\/api\/v2\/p\/([0-9]+)/, async (req, res) => { // legacy
let eps = 100;
let id = +req.url.split[3];
const query = await sql.query("select * from items where id < ? order by id desc limit ?", [ id, eps ]);
const items = {
items: query,
last: query[query.length - 1].id
};
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(items), "utf-8");
});
router.get(/^\/api\/v2\/item\/[0-9]+$/, async (req, res) => {
try {
const rows = await sql.query(queries.item, Array(3).fill(req.url.split[3]));
res.reply({
type: "application/json",
body: JSON.stringify(rows?.shift() || [])
});
} catch(err) {
res.reply({
code: 500,
body: JSON.stringify(err)
});
}
});
router.get(/^\/api\/v2\/user\/.*(\/[0-9]+)?$/, async (req, res) => { // auf qs umstellen
const user = req.url.split[3];
const eps = Math.min(req.url.split[4] || 50, 50);
try {
const rows = await sql.query(queries.user, [ user, eps ]);
res.reply({
type: "application/json",
body: JSON.stringify(rows.length > 0 ? rows : [])
});
} catch(err) {
res.reply({
code: 500,
body: JSON.stringify(err)
});
}
});

View File

@ -0,0 +1,18 @@
export const mimes = {
image: [ "image/png", "image/gif", "image/jpeg" ],
video: [ "video/webm", "video/mp4", "video/quicktime" ],
audio: [ "audio/mpeg", "audio/flac", "audio/x-flac", "audio/ogg" ]
};
export const queries = {
random: {
main: "select id, mime, size, username, userchannel, usernetwork, stamp, dest, src from items ",
where: where => `${where?`where ${where}`:""} order by rand() limit 1`
},
item: "select id, mime, dest, size, src, stamp, userchannel, username, usernetwork, "
+ "(select id from items where id = (select min(id) from items where id > ?)) as next, "
+ "(select id from items where id = (select max(id) from items where id < ?)) as prev "
+ "from items where items.id = ? limit 1",
p: (trend, order) => `select id, mime from items where id ${trend} ? order by id ${order} limit ?`,
user: "select id, mime, size, src, stamp, userchannel, username, usernetwork from items where username = ? limit ?"
};

View File

@ -1,6 +1,12 @@
export const queries = {
item: "select items.*, "
+ "(select id from items where id = (select min(id) from items where id > ?)) as next, "
+ "(select id from items where id = (select max(id) from items where id < ?)) as prev "
+ "from items where items.id = ? limit 1"
export const mimes = {
image: [ "image/png", "image/gif", "image/jpeg" ],
video: [ "video/webm", "video/mp4", "video/quicktime" ],
audio: [ "audio/mpeg", "audio/flac", "audio/x-flac", "audio/ogg" ]
};
export const queries = {
random: {
main: "select id, mime, size, username, userchannel, usernetwork, stamp, dest, src from items ",
where: where => `${where?`where ${where}`:""} order by rand() limit 1`
}
};

View File

@ -2,22 +2,28 @@ import router from "../router.mjs";
import cfg from "../../../config.json";
import url from "url";
import fs from "fs";
import { queries } from "./inc/index.mjs";
import { mimes } from "./inc/index.mjs";
import sql from "../sql.mjs";
import lib from "../lib.mjs";
import tpl from "../tpl.mjs";
tpl.readdir("views");
router.get(/\/(p\/\d+)?$/, async (req, res) => {
router.get(/^\/(audio\/?|image\/?|video\/?)?(p\/\d+)?$/, async (req, res) => {
try {
const total = (await sql.query("select count(*) as total from items"))[0].total;
const limit = 299;
const pages = +Math.ceil(total / limit);
const page = Math.min(pages, +req.url.split[1] || 1);
const offset = (page - 1) * limit;
let mime = false;
let q = false;
if(['audio', 'image', 'video'].includes(req.url.split[0])) {
mime = req.url.split[0];
q = " where " + (mimes[mime] ? mimes[mime].map(_mime => `mime = "${_mime}"`).join(" or ") : null);
}
const query = await sql.query("select id, mime from items order by id desc limit ?, ?", [ offset, limit ]);
const total = (await sql.query("select count(*) as total from items" + (mime ? q : "")))[0].total;
const pages = +Math.ceil(total / cfg.websrv.eps);
const page = Math.min(pages, +req.url.split[mime ? 2 : 1] || 1);
const offset = (page - 1) * cfg.websrv.eps;
const query = await sql.query(`select id, mime from items ${mime ? q : ""} order by id desc limit ?, ?`, [ offset, cfg.websrv.eps ]);
let cheat = [];
for(let i = Math.max(1, page - 3); i <= Math.min(page + 3, pages); i++)
@ -37,28 +43,50 @@ router.get(/\/(p\/\d+)?$/, async (req, res) => {
next: (page < pages) ? page + 1 : null,
page: page,
cheat: cheat,
link: "/p/"
link: `/${mime ? mime + "/" : ""}p/`
},
last: query[query.length - 1].id
last: query[query.length - 1].id,
filter: mime ? mime : undefined
};
res.reply({ body: tpl.render("views/index", data) });
} catch(err) {
res.reply({ body: "error :(" });
console.log(err);
res.reply({ body: "sorry bald wieder da lol :(" });
}
});
router.get(/^\/([0-9]+)$/, async (req, res) => {
const query = (await sql.query(queries.item, Array(3).fill(req.url.split[0])))?.shift();
const qmax = (await sql.query("select id from items order by id desc limit 1"))[0].id;
router.get(/^\/((audio\/|video\/|image\/)?[0-9]+)$/, async (req, res) => {
let id = false;
let mime = false;
let q = false;
if(['audio', 'video', 'image'].includes(req.url.split[0])) {
mime = req.url.split[0];
id = +req.url.split[1];
q = mimes[mime] ? mimes[mime].map(_mime => `mime = "${_mime}"`).join(" or ") : null;
}
else
id = +req.url.split[0];
const query = (await sql.query(`select items.* from items where items.id = ? ${mime ? "and ("+q+")" : ""} limit 1`, [ id ]))?.shift();
if(!query?.id)
return res.redirect("/404");
let cheat = [];
for(let i = Math.min(query.id + 3, qmax); i >= Math.max(1, query.id - 3); i--)
cheat.push(i);
const tags = (await sql.query(`select tags.tag from tags_assign left join tags on tags.id = tags_assign.tag_id where tags_assign.item_id = ?`, [ id ]));
const qmin = (await sql.query(`select id from items ${mime ? "where "+q : ""} order by id asc limit 1`))[0].id;
const qmax = (await sql.query(`select id from items ${mime ? "where "+q : ""} order by id desc limit 1`))[0].id;
const qnext = (await sql.query(`select id from items where id > ? ${mime ? "and ("+q+")" : ""} order by id asc limit 3`, [ id ])).reverse();
const qprev = (await sql.query(`select id from items where id < ? ${mime ? "and ("+q+")" : ""} order by id desc limit 3`, [ id ]));
const cheat = qnext.concat([{ id: id }].concat(qprev)).map(e => +e.id);
const next = qnext[qnext.length - 1] ? qnext[qnext.length - 1].id : false;
const prev = qprev[0] ? qprev[0].id : false;
const data = {
user: {
name: query.username,
@ -72,23 +100,24 @@ router.get(/^\/([0-9]+)$/, async (req, res) => {
short: url.parse(query.src).hostname,
},
thumbnail: `${cfg.websrv.paths.thumbnails}/${query.id}.png`,
coverart: `${cfg.websrv.paths.coverarts}/${query.id}.png`,
dest: `${cfg.websrv.paths.images}/${query.dest}`,
mime: query.mime,
size: lib.formatSize(query.size),
timestamp: new Date(query.stamp * 1000).toISOString()
timestamp: lib.timeAgo(new Date(query.stamp * 1000).toISOString()),
tags: tags
},
next: query.next ? query.next : null,
prev: query.prev ? query.prev : null,
title: `${query.id} - f0ck.me`,
pagination: {
start: qmax,
end: 1,
prev: query.id + 1,
next: Math.max(query.id - 1, 1),
end: qmin,
prev: next,
next: prev,
page: query.id,
cheat: cheat,
link: "/"
}
link: `/${mime ? mime + "/" : ""}`
},
filter: mime ? mime : undefined
};
res.reply({ body: tpl.render("views/item", data) });
});
@ -96,7 +125,3 @@ router.get(/^\/([0-9]+)$/, async (req, res) => {
router.get(/^\/(contact|help|about)$/, (req, res) => {
res.reply({ body: tpl.render(`views/${req.url.split[0]}`) });
});
router.get("/random", async (req, res) => {
res.redirect("/" + (await sql.query("select id from items order by rand() limit 1"))[0].id)
});

19
src/inc/routes/random.mjs Normal file
View File

@ -0,0 +1,19 @@
import router from "../router.mjs";
import { mimes, queries } from "./inc/index.mjs";
import sql from "../sql.mjs";
router.get(/^\/random(\/image|\/video|\/audio)?$/, async (req, res) => {
const args = [];
let q = queries.random.main;
q += queries.random.where(mimes[req.url.split[1]] ? mimes[req.url.split[1]].map(mime => `mime = "${mime}"`).join(" or ") : null);
try {
const rows = await sql.query(q, args);
res.redirect(`/${req.url.split[1] ? req.url.split[1] + "/" : ""}${rows[0].id}`);
} catch(err) {
res
.writeHead(500)
.end(JSON.stringify(err), "utf-8");
}
});

View File

@ -15,3 +15,8 @@ router.static({
dir: path.resolve() + "/public/t",
route: /^\/t\//
});
router.static({
dir: path.resolve() + "/public/ca",
route: /^\/ca\//
});

51
src/inc/routes/tags.mjs Normal file
View File

@ -0,0 +1,51 @@
import router from "../router.mjs";
import sql from "../sql.mjs";
import tpl from "../tpl.mjs";
tpl.readdir("views");
router.get(/^\/tags(\/\w+)?/, async (req, res) => {
try {
const tag = req.url;
console.log(tag);
return res.reply({ body: "wip" });
const total = (await sql.query("select count(*) as total from items" + (mime ? q : "")))[0].total;
const limit = 299;
const pages = +Math.ceil(total / limit);
const page = Math.min(pages, +req.url.split[mime ? 2 : 1] || 1);
const offset = (page - 1) * limit;
const query = await sql.query(`select id, mime from items ${mime ? q : ""} order by id desc limit ?, ?`, [ offset, limit ]);
let cheat = [];
for(let i = Math.max(1, page - 3); i <= Math.min(page + 3, pages); i++)
cheat.push(i);
query.forEach(e => {
if(!fs.existsSync(`public/t/${e.id}.png`))
fs.copyFileSync("public/s/img/broken.png", `public/t/${e.id}.png`);
});
const data = {
items: query,
pagination: {
start: 1,
end: pages,
prev: (page > 1) ? page - 1 : null,
next: (page < pages) ? page + 1 : null,
page: page,
cheat: cheat,
link: `/${mime ? mime + "/" : ""}p/`
},
last: query[query.length - 1].id,
filter: mime ? mime : undefined
};
res.reply({ body: tpl.render("views/index", data) });
} catch(err) {
console.log(err);
res.reply({ body: "sorry bald wieder da lol :(" });
}
});

View File

@ -1,5 +1,6 @@
import fs from "fs";
import path from "path";
import cfg from "./config.mjs";
export default new class {
#templates = {};
@ -10,15 +11,18 @@ export default new class {
[ "elseif", t => `}else if(${t.slice(6).trim()}){` ],
[ "else", () => "}else{" ],
[ "/if", () => "}" ],
[ "include", (t, data) => `html+='${this.render(t.slice(7).trim(), data)}';` ],
[ "include", (t, data) => `html+='${this.render(cfg.websrv.cache ? t.slice(7).trim() : `views/${t.slice(7).trim()}`, data)}';` ],
[ "=", t => `html+=${t.slice(1).trim()};` ]
];
readdir(dir, root = dir, rel = dir.replace(`${root}/`, "")) {
for(const d of fs.readdirSync(`${path.resolve()}/${dir}`))
d.endsWith(".html")
? this.#templates[`${rel}/${d.split(".")[0]}`] = fs.readFileSync(`${dir}/${d}`, "utf-8").replace(/\'/g, "\\'")
? this.#templates[`${rel}/${d.split(".")[0]}`] = this.readtpl(dir, d)
: this.readdir(`${dir}/${d}`, root);
}
readtpl(dir, d) {
return fs.readFileSync(`${dir}/${d}`, "utf-8").replace(/\'/g, "\\'");
}
forEach(o, f) {
if(Array.isArray(o))
o.forEach(f);
@ -28,7 +32,7 @@ export default new class {
throw new Error(`${o} is not a iterable object`);
}
render(tpl, data = {}, f) {
return new Function("util", "data", "let html = \"\";with(data){" + this.#templates[tpl]
return new Function("util", "data", "let html = \"\";with(data){" + (cfg.websrv.cache ? this.#templates[tpl] : this.readtpl(path.resolve(), `${tpl}.html`))
.trim()
.replace(/[\n\r]/g, "")
.split(/{{\s*([^}]+)\s*}}/)

View File

@ -1,5 +1,6 @@
import { promises as fs } from "fs";
import cfg from "../../../config.json";
import { exec } from "child_process";
import cfg from "../../inc/config.mjs";
import sql from "../sql.mjs";
import lib from "../lib.mjs";
@ -27,13 +28,25 @@ export default async bot => {
case "thumb":
const rows = await sql.query("select id from items");
const dir = (await fs.readdir("./public/t")).filter(d => d.endsWith(".png")).map(e => +e.split(".")[0]);
const tmp = [];
for(let row of rows) {
for(let row of rows)
!dir.includes(row.id) ? tmp.push(row.id) : null;
}
e.reply(`${tmp.length}, ${rows.length}, ${dir.length}`);
break;
case "cache":
cfg.websrv.cache = !cfg.websrv.cache;
return e.reply(`Cache is ${cfg.websrv.cache ? "enabled" : "disabled"}`);
break;
case "uptime":
exec('sudo systemctl status f0ck', (err, stdout) => {
if(!err)
return e.reply(stdout.split('\n')[2].trim().replace("Active: active (running)", "i'm active"));
});
break;
case "restart":
e.reply("hay hay patron, hemen!");
exec("sudo systemctl restart f0ck");
break;
default:
return;
}

View File

@ -19,9 +19,8 @@ export default async bot => {
f: e => {
const links = e.message.match(regex)?.filter(link => !link.includes("f0ck.me")) || [];
if(e.photo) {
if(e.photo)
links.push(e.photo);
}
if(links.length === 0)
return false;
@ -32,7 +31,7 @@ export default async bot => {
if(!e.channel.includes("f0ck") && !e.message.match(/(!|-)f0ck/i))
return false;
//e.reply(`parsing ${links.length} link${links.length > 1 ? "s" : ""}...`);
console.log(`parsing ${links.length} link${links.length > 1 ? "s" : ""}...`);
links.forEach(async link => {
// check repost (link)
@ -43,28 +42,41 @@ export default async bot => {
// generate uuid
const uuid = (await sql.query("select left(uuid(), 8) as uuid"))[0].uuid;
const maxfilesize = ( getLevel(e.user).level > 50 ? cfg.main.maxfilesize * 2.5 : cfg.main.maxfilesize ) / 1024;
const maxfilesize = (getLevel(e.user).level > 50 ? cfg.main.maxfilesize * 2.5 : cfg.main.maxfilesize) / 1024;
let meta;
// read metadata
try {
meta = JSON.parse((await exec(`youtube-dl -f "bestvideo[ext=mp4,filesize<${maxfilesize}k]+bestaudio/best" --skip-download --dump-json "${link}"`)).stdout);
meta = JSON.parse((await exec(`youtube-dl -f "bestvideo[ext=mp4,filesize<${maxfilesize}k][width<2000][height<=1200]+bestaudio[ext=m4a,filesize<${maxfilesize}k]/bestvideo[width<2000][height<=1200]+bestaudio/best[width<2000][height<=1200]/best" --skip-download --dump-json "${link}"`)).stdout);
//meta = JSON.parse((await exec(`youtube-dl -f "bestvideo[ext=mp4,filesize<${maxfilesize}k]+bestaudio/best" --skip-download --dump-json "${link}"`)).stdout);
}
catch(e) {
catch(err) {
e.reply("666 - kein b0ck!");
console.error(err);
return;
}
let filename = `${uuid}.${meta.ext}`;
e.reply(`downloading ${uuid}...`);
//e.reply(`downloading ${uuid}...`);
e.reply(`[charging the f0cker] downloading: ${uuid}.${meta.ext}`);
// download data
const start = new Date();
let source;
if(meta.ext === "mp4")
source = (await exec(`youtube-dl "${link}" --max-filesize ${maxfilesize}k -f "bestvideo[ext=mp4,filesize<${maxfilesize}k]+bestaudio/best" --merge-output-format mp4 -o ./tmp/${filename}`)).stdout.trim();
else
source = (await exec(`youtube-dl "${link}" --max-filesize ${maxfilesize}k -f "bestvideo[ext=mp4,filesize<${maxfilesize}k]+bestaudio/best" -o ./tmp/${filename}`)).stdout.trim();
if(meta.ext === "mp4") {
//source = (await exec(`youtube-dl "${link}" --max-filesize ${maxfilesize}k -f "bestvideo[ext=mp4,filesize<${maxfilesize}k]+bestaudio/best" --merge-output-format mp4 -o ./tmp/${filename}`)).stdout.trim();
source = (await exec(`youtube-dl "${link}" --max-filesize ${maxfilesize}k -f "bestvideo[ext=mp4,filesize<${maxfilesize}k][width<2000][height<=1200]+bestaudio[ext=m4a,filesize<${maxfilesize}k]/bestvideo[width<2000][height<=1200]+bestaudio/best[width<2000][height<=1200]/best" --merge-output-format mp4 -o ./tmp/${filename}`)).stdout.trim();
console.log("mp4 lol");
}
else {
//source = (await exec(`youtube-dl "${link}" --max-filesize ${maxfilesize}k -f "bestvideo[filesize<${maxfilesize}k][width<2000][height<=1200]+bestaudio[ext=${meta.ext},filesize<${maxfilesize}k]/bestvideo[width<2000][height<=1200]+bestaudio/best[ext=${meta.ext},width<2000][height<=1200]/best" --merge-output-format ${meta.ext} -o ./tmp/${filename}`)).stdout.trim();
source = (await exec(`youtube-dl "${link}" --max-filesize ${maxfilesize}k -f "bestvideo[filesize<${maxfilesize}k][width<2000][height<=1200][ext=${meta.ext}]+bestaudio[filesize<${maxfilesize}k][ext=${meta.ext}]/best" -o ./tmp/${filename}`)).stdout.trim();
//source = (await exec(`youtube-dl "${link}" --max-filesize ${maxfilesize}k -f "bestvideo[ext=mp4,filesize<${maxfilesize}k][width<2000][height<=1200]+bestaudio[ext=m4a,filesize<${maxfilesize}k]/bestvideo[width<2000][height<=1200]+bestaudio/best[width<2000][height<=1200]/best" -o ./tmp/${filename}`)).stdout.trim();
//source = (await exec(`youtube-dl "${link}" --max-filesize ${maxfilesize}k -f "bestvideo[ext=mp4,filesize<${maxfilesize}k]+bestaudio/best" -o ./tmp/${filename}`)).stdout.trim();
console.log("alles andere lol");
}
console.log(source);
if(source.match(/larger than/))
return e.reply("too large lol");
@ -116,17 +128,27 @@ export default async bot => {
);
// generate thumbnail
let thumb_orig = (await exec(`youtube-dlc -f "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best" --get-thumbnail "${link}"`)).stdout.trim();
if(!thumb_orig.startsWith("http")) {
if(mime.startsWith("image") && mime !== "image/gif")
thumb_orig = `./public/b/${filename}`;
else if(!mime.startsWith("audio")) {
await exec(`ffmpegthumbnailer -i./public/b/${filename} -s1024 -o./tmp/${insertq.insertId}`);
thumb_orig = `./tmp/${insertq.insertId}`;
try {
let thumb_orig = (await exec(`youtube-dl -f "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best" --get-thumbnail "${link}"`)).stdout.trim();
if(!thumb_orig.startsWith("http")) {
if(mime.startsWith("image") && mime !== "image/gif")
thumb_orig = `./public/b/${filename}`;
else if(!mime.startsWith("audio")) {
await exec(`ffmpegthumbnailer -i./public/b/${filename} -s1024 -o./tmp/${insertq.insertId}`);
thumb_orig = `./tmp/${insertq.insertId}`;
}
else if(mime.startsWith("audio")) {
await exec(`ffmpeg -i ./public/b/${filename} -update 1 -map 0:v -map 0:1 -c copy ./tmp/${insertq.insertId}.png`)
await exec(`cp ./tmp/${insertq.insertId}.png ./public/ca/${insertq.insertId}.png`)
thumb_orig = `./tmp/${insertq.insertId}.png`;
}
}
await exec(`convert "${thumb_orig}" -resize "200x200^" -gravity center -crop 128x128+0+0 +repage ./public/t/${insertq.insertId}.png`);
await fs.promises.unlink(`./tmp/${insertq.insertId}`).catch(_=>{});
} catch(err) {
e.reply("\x033>no thumb lol");
console.error(err);
}
await exec(`convert "${thumb_orig}" -resize "200x200^" -gravity center -crop 128x128+0+0 +repage ./public/t/${insertq.insertId}.png`);
await fs.promises.unlink(`./tmp/${insertq.insertId}`).catch(_=>{});
let speed = lib.calcSpeed(size, end);
speed = !Number.isFinite(speed) ? "yes" : `${speed.toFixed(2)} Mbit/s`;

118
src/inc/trigger/tags.mjs Normal file
View File

@ -0,0 +1,118 @@
import sql from "../sql.mjs";
import cfg from "../config.mjs";
import { getLevel } from "../admin.mjs";
const queries = {
getTags: "select tags.id, tags.tag from tags_assign left join tags on tags.id = tags_assign.tag_id where tags_assign.item_id = ?",
assignTag: "insert into tags_assign (tag_id, item_id, prefix) values (?, ?, ?)"
};
const getTags = async itemid => {
return await sql.query(queries.getTags, [ itemid ]);
};
export default async bot => {
return [{
name: "tags show",
call: /^\!tags show \d+$/i,
active: true,
level: 100,
f: async e => {
const id = +e.args[1];
if(!id)
return e.reply("lol no");
const tags = await getTags(id).map(t => t.tag);
if(tags.length === 0)
return e.reply(`item ${cfg.main.url}/${id} has no tags!`);
return e.reply(`item ${cfg.main.url}/${id} is tagged as: ${tags.join(', ')}`);
}
}, {
name: "tags add",
call: /^\!tags add \d+ .*/i,
active: true,
level: 100,
f: async e => {
const id = +e.args[1];
if(!id)
return e.reply("lol no");
const tags = (await getTags(id)).map(t => t.tag);
const newtags = (e.message.includes(",")
? e.args.splice(2).join(" ").trim().split(",")
: e.args.splice(2)).filter(t => !tags.includes(t) && t.length > 0);
if(newtags.length === 0)
return e.reply("no (new) tags provided");
await Promise.all(newtags.map(async ntag => {
try {
let tagid;
const tag_exists = (await sql.query(`select id, tag from tags where tag = ?`, [ ntag ]));
if(tag_exists.length === 0) // create new tag
tagid = (await sql.query("insert into tags (tag) values (?)", [ ntag ])).insertId;
else
tagid = tag_exists[0].id;
return await sql.query(queries.assignTag, [ tagid, id, `${e.user.prefix}${e.channel}` ]);
} catch(err) {
console.error(err);
}
}));
const ntags = (await getTags(id)).map(t => t.tag);
if(ntags.length === 0)
return e.reply(`item ${cfg.main.url}/${id} has no tags!`);
return e.reply(`item ${cfg.main.url}/${id} is now tagged as: ${ntags.join(', ')}`);
}
}, {
name: "tags remove",
call: /^\!tags remove \d+ .*/i,
active: true,
level: 100,
f: async e => {
const id = +e.args[1];
if(!id)
return e.reply("lol no");
const tags = await getTags(id);
const removetags = (e.message.includes(",")
? e.args.splice(2).join(" ").trim().split(",")
: e.args.splice(2)).filter(t => t.length > 0);
if(removetags.length === 0)
return e.reply("no tags provided");
const res = await Promise.all(removetags.map(async rtag => {
const tagid = tags.filter(t => t.tag === rtag)[0]?.id ?? null;
if(!tagid || tagid?.length === 0) {
return {
success: false,
tag: rtag,
msg: "tag is not assigned"
};
}
let q;
if(getLevel(e.user).level > 50)
q = !!(await sql.query("delete from tags_assign where tag_id = ? and item_id = ? limit 1", [ tagid, id ])).affectedRows;
else
q = !!(await sql.query("delete from tags_assign where tag_id = ? and item_id = ? and prefix = ? limit 1", [ tagid, id, `${e.user.prefix}${e.channel}` ])).affectedRows;
return {
success: q,
tag: rtag,
tagid: tagid
};
}));
e.reply(JSON.stringify(res));
const ntags = (await getTags(id)).map(t => t.tag);
if(ntags.length === 0)
return e.reply(`item ${cfg.main.url}/${id} has no tags!`);
return e.reply(`item ${cfg.main.url}/${id} is now tagged as: ${ntags.join(', ')}`);
}
}]
};