API / features /upscale.js
Puruu Puruu
8065f56
/*
* Lokasi: /features/upscale.js
* Versi: v1
*/
const axios = require('axios');
const FormData = require('form-data');
const crypto = require('crypto');
async function sendCallback(url, payload) {
try {
await axios.post(url, payload, { headers: { 'Content-Type': 'application/json' } });
} catch (error) {
console.error('Callback failed:', error.message);
}
}
module.exports = async function(req, res) {
const { imageUrl, scale, jobId, callbackUrl, callbackKey } = req.body;
if (!imageUrl || !jobId || !callbackUrl || !callbackKey) {
return res.status(400).json({ error: 'Missing required parameters.' });
}
res.status(202).json({ message: 'Job accepted and is being processed.' });
try {
const username = `${crypto.randomBytes(8).toString('hex')}_aiimglarger`;
const imageResponse = await axios.get(imageUrl, { responseType: 'arraybuffer' });
const imageBuffer = imageResponse.data;
const imageName = imageUrl.split('/').pop().split('?')[0] || 'temp.jpg';
const formData = new FormData();
formData.append('type', 0);
formData.append('username', username);
formData.append('scaleRadio', (scale || 4).toString());
formData.append('file', imageBuffer, { filename: imageName, contentType: 'image/jpeg' });
const uploadResponse = await axios.post('https://photoai.imglarger.com/api/PhoAi/Upload', formData, {
headers: { ...formData.getHeaders(), 'User-Agent': 'Dart/3.5 (dart:io)', 'Accept-Encoding': 'gzip' },
});
const { code } = uploadResponse.data.data;
const pollParams = { code, type: 0, username, scaleRadio: (scale || 4).toString() };
let statusData = null;
for (let i = 0; i < 100; i++) {
const statusResponse = await axios.post('https://photoai.imglarger.com/api/PhoAi/CheckStatus', JSON.stringify(pollParams), {
headers: { 'User-Agent': 'Dart/3.5 (dart:io)', 'Accept-Encoding': 'gzip', 'Content-Type': 'application/json' },
});
statusData = statusResponse.data.data;
if (statusData.status === 'success') break;
if (statusData.status === 'failed') throw new Error('Upscaling process failed on the external server.');
await new Promise(r => setTimeout(r, 2000));
}
if (statusData?.status === 'success' && statusData?.downloadUrls?.[0]) {
await sendCallback(callbackUrl, {
jobId,
callbackKey,
status: 'success',
result: { url: statusData.downloadUrls[0] },
});
} else {
throw new Error('Failed to get the upscaled image after multiple checks.');
}
} catch (e) {
await sendCallback(callbackUrl, {
jobId,
callbackKey,
status: 'failed',
result: { error: e.message || 'An unknown error occurred during upscaling.' },
});
}
};