/** * ImgBB Image Uploader with Custom Expiration Duration * Reverse-Engineered from https://id.imgbb.com/ * * @author Vamz Spectre (https://vamxapi.my.id) * * Download: * curl -sL "https://code.vamxapi.my.id/snippet/raw/imgbb-uploader" -o imgbb-uploader.js * * Usage: * node imgbb-uploader.js "https://avatars.githubusercontent.com/u/10137?v=4" 5m * node imgbb-uploader.js "./gambar.png" 1d * node imgbb-uploader.js "https://avatars.githubusercontent.com/u/10137?v=4" never */ const https = require("https"); const fs = require("fs"); const path = require("path"); const EXPIRATION_MAP = { never: "", "0": "", "5m": "PT5M", "5min": "PT5M", "15m": "PT15M", "15min": "PT15M", "30m": "PT30M", "30min": "PT30M", "1h": "PT1H", "3h": "PT3H", "6h": "PT6H", "12h": "PT12H", "1d": "P1D", "2d": "P2D", "3d": "P3D", "4d": "P4D", "5d": "P5D", "6d": "P6D", "1w": "P1W", "2w": "P2W", "3w": "P3W", "1mo": "P1M", "2mo": "P2M", "3mo": "P3M", "4mo": "P4M", "5mo": "P5M", "6mo": "P6M", "1month": "P1M", "2months": "P2M", "3months": "P3M", "4months": "P4M", "5months": "P5M", "6months": "P6M", }; /** * Normalisasi opsi durasi ke format kode ISO 8601 yang diterima ImgBB * @param {string} exp */ function normalizeExpiration(exp) { if (!exp) return ""; const clean = String(exp).trim().toLowerCase(); if (EXPIRATION_MAP[clean] !== undefined) return EXPIRATION_MAP[clean]; const upper = String(exp).trim().toUpperCase(); if (Object.values(EXPIRATION_MAP).includes(upper)) return upper; return ""; } /** * Mengambil session cookie dan auth_token dari halaman utama ImgBB */ function getSessionAndToken() { return new Promise((resolve, reject) => { https .get( "https://id.imgbb.com/", { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Accept-Language": "id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7", }, }, (res) => { let data = ""; const cookies = (res.headers["set-cookie"] || []).map((c) => c.split(";")[0]).join("; "); res.on("data", (chunk) => (data += chunk)); res.on("end", () => { const match = data.match(/PF\.obj\.config\.auth_token\s*=\s*"([^"]+)"/); if (!match) return reject(new Error("Gagal mengambil auth_token dari ImgBB.")); resolve({ authToken: match[1], cookies }); }); } ) .on("error", reject); }); } /** * Fungsi utama upload gambar ke ImgBB * @param {string|Buffer} input URL gambar publik, file path lokal, atau Buffer * @param {object} options * @param {string} options.expiration Durasi simpan: 5m, 15m, 30m, 1h, 1d, 1w, 1mo, atau never (default: "") * @param {string} options.filename Nama file kustom (opsional) */ async function uploadImgbb(input, options = {}) { if (!input) { throw new Error("Input gambar wajib diberikan (URL, path file, atau Buffer)."); } const { authToken, cookies } = await getSessionAndToken(); const rawExp = options.expiration || options.durasi || ""; const expCode = normalizeExpiration(rawExp); const isUrl = typeof input === "string" && /^https?:\/\//i.test(input); const boundary = "----WebKitFormBoundary" + Math.random().toString(36).substring(2); const parts = []; const addField = (name, val) => { parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${val}\r\n`)); }; addField("action", "upload"); addField("auth_token", authToken); if (expCode) { addField("expiration", expCode); } if (isUrl) { addField("type", "url"); addField("source", input); } else { addField("type", "file"); let fileBuffer; let fileName = options.filename || "image.png"; if (Buffer.isBuffer(input)) { fileBuffer = input; } else if (typeof input === "string" && fs.existsSync(input)) { fileBuffer = fs.readFileSync(input); fileName = path.basename(input); } else { throw new Error(`Path file tidak ditemukan atau format tidak valid: ${input}`); } const fileHeader = Buffer.from( `--${boundary}\r\nContent-Disposition: form-data; name="source"; filename="${fileName}"\r\nContent-Type: application/octet-stream\r\n\r\n` ); parts.push(fileHeader); parts.push(fileBuffer); parts.push(Buffer.from("\r\n")); } parts.push(Buffer.from(`--${boundary}--\r\n`)); const fullBody = Buffer.concat(parts); return new Promise((resolve, reject) => { const req = https.request( "https://id.imgbb.com/json", { method: "POST", headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", Referer: "https://id.imgbb.com/", Accept: "application/json", Cookie: cookies, "Content-Type": `multipart/form-data; boundary=${boundary}`, "Content-Length": fullBody.length, }, }, (res) => { let body = ""; res.on("data", (c) => (body += c)); res.on("end", () => { try { const json = JSON.parse(body); if (json.status_code !== 200 || !json.image) { return reject(new Error(json.error?.message || json.status_txt || "Gagal mengunggah gambar ke ImgBB.")); } const img = json.image; resolve({ status: true, directUrl: img.url, viewerUrl: img.url_viewer, deleteUrl: img.delete_url, thumbUrl: img.thumb?.url || img.display_url, filename: img.filename, size: img.size_formatted || `${img.size} bytes`, width: img.width, height: img.height, expirationSeconds: img.expiration, expirationCode: expCode || "never", raw: img, }); } catch (e) { reject(new Error("Respon tidak valid dari ImgBB: " + body.slice(0, 100))); } }); } ); req.on("error", reject); req.write(fullBody); req.end(); }); } // CLI Runner Support if (require.main === module) { (async () => { try { const input = process.argv[2] || "https://avatars.githubusercontent.com/u/10137?v=4"; const expiration = process.argv[3] || "never"; const res = await uploadImgbb(input, { expiration }); console.log(JSON.stringify(res, null, 2)); } catch (err) { console.error(JSON.stringify({ status: false, error: err.message }, null, 2)); process.exit(1); } })(); } module.exports = { uploadImgbb, normalizeExpiration, EXPIRATION_MAP, };