40 lines
1.4 KiB
JavaScript
40 lines
1.4 KiB
JavaScript
|
|
require('dotenv').config();
|
||
|
|
|
||
|
|
const ALLOWED_EXT = ['jpg', 'jpeg', 'png'];
|
||
|
|
|
||
|
|
function extFromUrl(url) {
|
||
|
|
const m = /\.([a-z0-9]+)(\?|$)/i.exec(String(url || ''));
|
||
|
|
return m ? m[1].toLowerCase() : null;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Portiert aus adapters/media.lua IsAllowedExternalUrl
|
||
|
|
function isAllowedExternalUrl(url) {
|
||
|
|
url = String(url || '');
|
||
|
|
if (!/^https:\/\//i.test(url)) return { ok: false, reason: 'url_must_be_https' };
|
||
|
|
if (/^https:\/\/i\.ibb\.co\//i.test(url) || /^https:\/\/ibb\.co\//i.test(url)) return { ok: true };
|
||
|
|
const ext = extFromUrl(url);
|
||
|
|
if (ext && ALLOWED_EXT.includes(ext)) return { ok: true };
|
||
|
|
return { ok: false, reason: 'unsupported_image_url' };
|
||
|
|
}
|
||
|
|
|
||
|
|
// Upload eines Buffers zu imgbb -> { url }
|
||
|
|
async function uploadToImgbb(buffer, filename) {
|
||
|
|
const key = process.env.IMGBB_KEY;
|
||
|
|
if (!key) throw new Error('imgbb_key_missing');
|
||
|
|
const form = new FormData();
|
||
|
|
form.append('image', buffer.toString('base64'));
|
||
|
|
if (filename) form.append('name', filename.replace(/\.[^.]+$/, ''));
|
||
|
|
|
||
|
|
const resp = await fetch(`https://api.imgbb.com/1/upload?key=${encodeURIComponent(key)}`, {
|
||
|
|
method: 'POST',
|
||
|
|
body: form,
|
||
|
|
});
|
||
|
|
const data = await resp.json();
|
||
|
|
if (!data || !data.success || !data.data || !data.data.url) {
|
||
|
|
throw new Error('imgbb_upload_failed');
|
||
|
|
}
|
||
|
|
return { url: data.data.url };
|
||
|
|
}
|
||
|
|
|
||
|
|
module.exports = { isAllowedExternalUrl, uploadToImgbb, ALLOWED_EXT };
|