File size: 10,248 Bytes
91d2cae
 
 
 
 
 
 
 
 
 
2558d03
 
 
 
 
 
91d2cae
 
 
 
fdf2e1b
 
 
 
 
 
 
 
 
91d2cae
 
 
fdf2e1b
 
 
 
 
 
 
 
 
 
91d2cae
 
 
fdf2e1b
 
 
 
 
 
 
 
 
 
91d2cae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdf2e1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91d2cae
 
 
fdf2e1b
 
 
 
 
 
 
 
 
 
 
 
 
91d2cae
fdf2e1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91d2cae
 
fdf2e1b
 
91d2cae
fdf2e1b
 
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
const axios = require('axios');
const cheerio = require('cheerio');
const express = require("express");
const path = require("path");
const os = require("os");
const fs = require("fs");
const PORT = process.env.PORT || 7860;
const app = express();

const tempDir = path.join(os.tmpdir(), "temp");

// Create temp directory if it doesn't exist
if (!fs.existsSync(tempDir)) {
  fs.mkdirSync(tempDir, { recursive: true });
}

app.use('/temp', express.static(tempDir));
app.use(express.json());

app.get("/", (req, res) => {
  res.type("json");
  const keluaran = {
    success: true,
    author: "Nex",
    data: {
      igdl: "/igdl"
    },
  };
  res.send(keluaran);
});

async function downloadImage(url) {
  try {
    const response = await axios.get(url, { responseType: 'arraybuffer' });
    const randomCode = Math.random().toString(36).substring(7);
    const imagePath = `downloaded_image_${randomCode}.png`;
    fs.writeFileSync(path.join(tempDir, "/" + imagePath), Buffer.from(response.data, 'binary'));
    return imagePath;
  } catch (error) {
    console.error('Error downloading image:', error.message);
    throw error;
  }
}

async function downloadVideo(url) {
  try {
    const response = await axios.get(url, { responseType: 'arraybuffer' });
    const randomCode = Math.random().toString(36).substring(7);
    const videoPath = `downloaded_video_${randomCode}.mp4`;
    fs.writeFileSync(path.join(tempDir, "/" + videoPath), Buffer.from(response.data, 'binary'));
    return videoPath;
  } catch (error) {
    console.error('Error downloading video:', error.message);
    throw error;
  }
}

const generateRandomIP = () => {
	const octet = () => Math.floor(Math.random() * 256);
	return `${octet()}.${octet()}.${octet()}.${octet()}`;
};

const getMimeTypeFromUrl = async (url) => {
	try {
		const headers = {
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
			'Accept': '*/*',
			'User-Agent': 'Mozilla/5.0 (Linux; Android 12; SM-S908B Build/SP1A.210812.016; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/99.0.4844.58 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/357.0.0.23.115;]',
			'Referer': 'https://igdownloader.app/en',
			'X-Forwarded-For': generateRandomIP()
		};

		const response = await axios.head(url, {
			headers
		});
		const contentTypeHeader = response.headers['content-type'];
		const [mediaType] = contentTypeHeader.split('/');
		return mediaType;
	} catch (error) {
		console.error('Error while fetching media type:', error.message);
		return undefined;
	}
};

const checkMediaType = (url) => {
	const supportedImageExtensions = ['jpg', 'jpeg', 'png', 'webp', 'heic'];
	const supportedVideoExtensions = ['mp4'];
	const fileExtension = url.toLowerCase();
	if (supportedImageExtensions.includes(fileExtension)) {
		return 'image';
	} else if (supportedVideoExtensions.includes(fileExtension)) {
		return 'video';
	} else {
		return 'unknown';
	}
};


/*
IGDL IGDL IGDL IGDL IGDL IGDL
IGDL IGDL IGDL IGDL IGDL IGDL
*/

async function igdl1(url) {
	try {
		const apiEndpoint = 'https://v3.igdownloader.app/api/ajaxSearch';
		const requestOptions = {
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
				'Accept': '*/*',
				'User-Agent': 'Mozilla/5.0 (Linux; Android 12; SM-S908B Build/SP1A.210812.016; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/99.0.4844.58 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/357.0.0.23.115;]',
				'Referer': 'https://igdownloader.app/en',
				'X-Forwarded-For': generateRandomIP()
			},
		};
		const postData = `recaptchaToken=&q=${encodeURIComponent(url)}&t=media&lang=en`;
		const response = await axios.post(apiEndpoint, postData, requestOptions);
		const $ = cheerio.load(response.data.data);
		const downloadLinks = $('div.download-items__btn > a');
		const hrefArray = {
			title: null,
			urls: []
		}
		await Promise.all(downloadLinks.map(async (index, element) => {
			const href = $(element).attr('href');
			const media_type = await getMimeTypeFromUrl(href);
			let type;
			if (typeof media_type === 'undefined') {
				type = "video";
			} else {
				type = media_type;
			}
			hrefArray.urls.push({
				url: href,
				type: type
			});
		}));
		return hrefArray;
	} catch (error) {
		console.error('Instagram Downloader 1 - Error:', error.message);
		return null;
	}
}

async function igdl2(url) {
	const apiEndpoint = 'https://snapinst.com/api/convert';

	const requestData = {
		url,
		ts: Date.now(),
		_ts: Date.now() - 106169240745,
		_tsc: 0,
		_s: 'b4d95f81de50ed9cace0103923a25dd2f57b2a76c142d82ac78a963f1274a1e1',
	};

	const headers = {
		'Accept': 'application/json, text/plain, */*',
		'Content-Type': 'application/json',
		'X-XSRF-TOKEN': 'eyJpdiI6InZ3aU9SVG41enJWOUljS3hIUnpsd3c9PSIsInZhbHVlIjoiakFHQjcrVjNMQm1wZ2xrcmF6NGdOSjdTUFp0ZTNFNXpCZ0tcL3VaNmFaN09TSVl2QzFZVndTVmxLUFo2QVVuYnpcL2JDdVwvc29sdHB6XC9jSzY2aURYMDdzcmd4TWVHUjZzWHpHZXEySXJMb0UwN3dqbUFDRlZFTXFxU2E4U2hOUzg5IiwibWFjIjoiNGQyYjBjYWNhNGQwMWUwZWE4YWM1MzdkMWJlYmRkYzBkOTMyZDZjNWVhNjE3MzAxOWMwNTM2OTJiOTM0ZjMwNyJ9',
		'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36',
		'Referer': 'https://snapinst.com/',
	};

	try {
		const response = await axios.post(apiEndpoint, requestData, {
			headers
		});
		const resultArray = [];

		const transformedData = {
			title: response.data[0].meta.title,
			urls: response.data.map(item => item.url.map(urlInfo => ({
				url: urlInfo.url,
				type: checkMediaType(urlInfo.type)
			})))
		};

		return transformedData;
	} catch (error) {
		console.error('Instagram Downloader 2 - Error:', error.message);
		return null;
	}
}


async function igdl3(url) {
	const apiEndpoint = 'https://co.wuk.sh/api/json';

	const requestData = {
		url,
		aFormat: 'mp3',
		filenamePattern: 'classic',
		dubLang: false,
		vQuality: '720',
	};

	const headers = {
		'Accept': 'application/json',
		'Content-Type': 'application/json',
		'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36',
		'Referer': 'https://cobalt.tools/',
	};

	try {
		const response = await axios.post(apiEndpoint, requestData, {
			headers
		});
		var result = response.data;
		let array_res = {
			title: null,
			urls: []
		}
		if (result.status === "redirect") {
			let media_type = await getMimeTypeFromUrl(result.url)
			array_res.urls.push({
				url: result.url,
				type: media_type
			})
		} else if (result.status === "picker") {
			for (let i = 0; i < result.picker.length; i++) {
				let media_type = await getMimeTypeFromUrl(result.picker[i].url)
				array_res.urls.push({
					url: result.picker[i].url,
					type: media_type
				})
			}
		}
		return array_res;
	} catch (error) {
		console.error('Instagram Downloader 3 - Error:', error.message);
		return null;
	}
};

async function igdl4(url) {
	try {
		const apiEndpoint = 'https://v3.saveig.app/api/ajaxSearch';
		const requestOptions = {
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
				'Accept': '*/*',
				'User-Agent': 'Mozilla/5.0 (Linux; Android 12; SM-S908B Build/SP1A.210812.016; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/99.0.4844.58 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/357.0.0.23.115;]',
				'Referer': 'https://saveig.app/en',
			},
		};
		const postData = `recaptchaToken=&q=${encodeURIComponent(url)}&t=media&lang=en`;
		const response = await axios.post(apiEndpoint, postData, requestOptions);
		const $ = cheerio.load(response.data.data);
		const downloadLinks = $('div.download-items__btn > a');
		const hrefArray = {
			title: null,
			urls: []
		}
		await Promise.all(downloadLinks.map(async (index, element) => {
			const href = $(element).attr('href');
			const media_type = await getMimeTypeFromUrl(href);
			let type;
			if (typeof media_type === 'undefined') {
				type = "video";
			} else {
				type = media_type;
			}
			hrefArray.urls.push({
				url: href,
				type: type
			});
		}));
		return hrefArray;
	} catch (error) {
		console.error('Instagram Downloader 4 - Error:', error.message);
		return null;
	}
}

const getInstagramDownloadLinks = async (url) => {
  let result = await igdl1(url);
  if (!result) {
    result = await igdl2(url);
  }
  if (!result) {
    result = await igdl3(url);
  }
  if (!result) {
    result = await igdl4(url);
  }
  if (!result) {
    result = {
      message: "all server error"
    };
  }
  return result;
};

app.get('/igdl', async (req, res) => {
  try {
    const { url } = req.query;
    if (!url) {
      return res.status(400).json({ error: 'Parameter url is required' });
    }
    if (!/https?:\/\/(www\.)?instagram\.com\/(p|reel|tv)/.test(url)) {
      return res.status(400).json({ error: "Example: https://www.instagram.com/p/Cz1fTwMJFpx/?igsh=MXRrY2g4eWNucGoyZg==" });
    }
    let result = await getInstagramDownloadLinks(url);
    let result_upload = { 
      title: result?.title || 'untitled',
      media: []
    }

    for (let item of result.urls) {
      if (item.type === "image") {
        let unduh = await downloadImage(item.url);
        result_upload.media.push({ type: item.type, path: unduh, url_path: `http://${process.env.SPACE_HOST}/temp/${path.basename(unduh)}` });
      } else if (item.type === "video") { 
        let unduh = await downloadVideo(item.url);
        result_upload.media.push({ type: item.type, path: unduh, url_path: `http://${process.env.SPACE_HOST}/temp/${path.basename(unduh)}` });
      }
    }
    
    res.json(result_upload);
    
    for (let item of result_upload.media) {
      try {
        await new Promise(resolve => setTimeout(resolve, 10 * 60 * 1000)); // 10 minutes
        await fs.unlink(item.path);
        console.log(`File ${item.path} deleted.`);
      } catch (error) {
        console.error(`Error deleting file ${item.path}:`, error);
      }
    }
  } catch (error) {
    console.error('Error processing request:', error);
    res.status(500).json({ error: 'Failed to process request\n' + error});
  }
});


const hostname = `http://${process.env.SPACE_HOST}`;  // Ganti dengan host yang sesuai
app.listen(PORT, () => {
  console.log(`Server is running on http://${hostname}:${PORT}`);
});