File size: 5,016 Bytes
520ddc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const https = require('https');
const FormData = require('form-data');

const UPLOAD_URL = 'https://api.unblurimage.ai/api/common/upload/upload-image';
const CREATE_JOB_URL = 'https://api.unblurimage.ai/api/imgupscaler/v1/ai-image-upscaler-v2/create-job';
const PRODUCT_SERIAL = '79661c82d918475e7458944c2f66857e';
const TMP_DIR = '/tmp/upscaler';

const axiosInstance = axios.create({
  timeout: 60000,
  httpsAgent: new https.Agent({
    rejectUnauthorized: false,
  }),
});

function ensureTmpDir() {
  if (!fs.existsSync(TMP_DIR)) {
    fs.mkdirSync(TMP_DIR, { recursive: true });
  }
}

async function downloadImage(imageUrl) {
  const response = await axiosInstance.get(imageUrl, {
    responseType: 'arraybuffer',
  });
  return Buffer.from(response.data);
}

function saveImageToTmp(imageBuffer) {
  ensureTmpDir();
  const fileName = `image_${Date.now()}_${Math.random().toString(36).substr(2, 9)}.jpg`;
  const filePath = path.join(TMP_DIR, fileName);
  fs.writeFileSync(filePath, imageBuffer);
  return filePath;
}

function deleteFileAfterDelay(filePath, delayMs = 10000) {
  setTimeout(() => {
    try {
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    } catch (error) {
      console.error(`Failed to delete file ${filePath}:`, error.message);
    }
  }, delayMs);
}

async function uploadImage(filePath) {
  const imageBuffer = fs.readFileSync(filePath);
  const fileName = path.basename(filePath);
  const contentType = 'image/jpeg';
  
  const form = new FormData();
  form.append('file_name', fileName);
  form.append('file', imageBuffer, fileName);

  const uploadResponse = await axiosInstance.post(UPLOAD_URL, form, {
    headers: {
      ...form.getHeaders(),
      'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Mobile Safari/537.36',
    },
  });

  if (uploadResponse.data.code !== 100000) {
    throw new Error(`Upload failed: ${uploadResponse.data.message.en}`);
  }

  const uploadUrl = uploadResponse.data.result.url;

  await axiosInstance.put(uploadUrl, imageBuffer, {
    headers: {
      'Content-Type': contentType,
      'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Mobile Safari/537.36',
    },
  });

  return {
    url: uploadUrl.split('?')[0],
  };
}

async function createJob(imageUrl, upscaleLevel) {
  const form = new FormData();
  form.append('original_image_url', imageUrl);
  form.append('upscale_type', upscaleLevel.toString());

  const response = await axiosInstance.post(CREATE_JOB_URL, form, {
    headers: {
      ...form.getHeaders(),
      'Product-Serial': PRODUCT_SERIAL,
      'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Mobile Safari/537.36',
    },
  });

  if (response.data.code !== 100000) {
    throw new Error(`Job creation failed: ${response.data.message.en}`);
  }

  return response.data.result;
}

async function upscaleImage(imageUrl, scaleNumber) {
  let tmpFilePath = null;
  
  try {
    if (!imageUrl) {
      throw new Error('Image URL is required');
    }

    if (![2, 4, 8, 16].includes(scaleNumber)) {
      throw new Error('Scale number must be 2, 4, 8, or 16');
    }

    const imageBuffer = await downloadImage(imageUrl);
    tmpFilePath = saveImageToTmp(imageBuffer);
    
    const uploadResult = await uploadImage(tmpFilePath);
    const result = await createJob(uploadResult.url, scaleNumber);
    
    deleteFileAfterDelay(tmpFilePath, 10000);
    
    return result;
  } catch (error) {
    if (tmpFilePath && fs.existsSync(tmpFilePath)) {
      fs.unlinkSync(tmpFilePath);
    }
    throw error;
  }
}

const handler = async (req, res) => {
  try {
    const { image_url, scale, key } = req.query;

    if (!image_url) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameter: image_url'
      });
    }

    if (!scale) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameter: scale'
      });
    }

    const scaleNum = parseInt(scale);
    if (![2, 4, 8, 16].includes(scaleNum)) {
      return res.status(400).json({
        success: false,
        error: 'Scale must be 2, 4, 8, or 16'
      });
    }

    const result = await upscaleImage(image_url, scaleNum);

    return res.json({
      author: "Herza",
      success: true,
      data: result
    });

  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      timestamp: new Date().toISOString()
    });
  }
};

module.exports = {
  name: 'Image Upscaler',
  description: 'Upscale images to 2x, 4x, 8x, or 16x resolution',
  type: 'GET',
  routes: ['api/tools/upscale'],
  tags: ['image', 'upscale', 'enhancement'],
  parameters: ['image_url', 'scale', 'key'],
  limit: 5,
  enabled: true,
  main: ['tools'],
  handler
};