File size: 10,943 Bytes
d6a14cd
 
 
 
 
 
 
 
6199537
d6a14cd
 
 
 
 
 
6199537
 
 
 
 
 
 
 
 
d6a14cd
6199537
d6a14cd
 
 
 
 
 
 
 
 
6199537
d6a14cd
 
 
6199537
d6a14cd
 
 
 
 
 
 
 
 
 
6199537
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6a14cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6199537
d6a14cd
 
 
 
6199537
 
 
 
 
 
d6a14cd
6199537
 
 
d6a14cd
6199537
 
 
d6a14cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6199537
 
 
d6a14cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6199537
 
 
 
d6a14cd
6199537
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6a14cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6199537
 
 
 
 
 
 
 
 
 
 
 
 
d6a14cd
 
 
 
 
 
 
 
 
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
import bytes from 'bytes'
import cp from 'child_process'
import express from 'express'
import favicon from 'serve-favicon'
import fs from 'fs'
import morgan from 'morgan'
import os from 'os'
import path from 'path'
import playwright from 'playwright'
import PDFDocument from 'pdfkit'
import sharp from 'sharp'
import util from 'util'
import yts from 'yt-search'

const utils = {
	getBrowser: (...opts) => playwright.chromium.launch({
		args: [
			'--incognito', '--single-process',
			'--no-sandbox', '--no-zygote', '--no-cache'
		],
		executablePath: process.env.CHROME_BIN,
		headless: true,
		...opts
	}),
	// from https://github.com/petersolopov/carbonara
	fetchCarbonaraAPI: async (code, opts = {}) => {
		let resp = await utils.fetchPOST('https://carbonara.solopov.dev/api/cook', JSON.stringify({ code, ...opts }), {
			headers: { 'Content-Type': 'application/json' }
		})
		if (!resp.ok) {
			let content = resp.headers.get('content-type')
			if (/json$/.test(content)) {
				let json = await resp.json()
				throw json.error || 'An error occurred'
			}
			throw resp.statusText
		}
		
		let img = await resp.arrayBuffer()
		const output = `${tmpDir}/${utils.randomName('.png')}`
		await fs.promises.writeFile(output, Buffer.from(img))
		return output
	},
	fetchCobaltAPI: async (url, opts = {}) => (
		await utils.fetchPOST('https://cobalt-7.kwiatekmiki.com/api/json', JSON.stringify({ url, ...opts }), {
			headers: { Accept: 'application/json', 'Content-Type': 'application/json' }
		})
	).json(),
	fetchPOST: (url, body, opts = {}) => fetch(url, { method: 'POST', body, ...opts }),
	formatSize: (n) => bytes(+n, { unitSeparator: ' ' }),
	generateBrat: async (text) => {
		const browser = await utils.getBrowser()
		try {
			const page = await browser.newPage()
			await page.goto('https://www.bratgenerator.com/')
			await page.click('#toggleButtonWhite')
			await page.locator('#textInput').fill(text)
			const output = `${tmpDir}/${utils.randomName('.jpg')}`
			const ss = await page.locator('#textOverlay')
				.screenshot({ path: output })
			return output
		} catch (e) {
			throw e
		} finally {
			await browser.close()
		}
	},
	getError: (e) => String(e).startsWith('[object ') ? 'Internal Server Error' : String(e),
	isBase64: (str) => {
		try {
			return btoa(atob(str)) === str
		} catch {
			return false
		}
	},
	isTrue: (str) => [true, 'true'].includes(str),
	randomIP: () => [...new Array(4)].map(() => ~~(Math.random() * 256)).join('.'),
	randomName: (str = '') => (Math.random().toString(36).slice(2) + str),
	toPDF: (urls, opts = {}) => new Promise(async (resolve, reject) => {
		try {
			const doc = new PDFDocument({ margin: 0, size: 'A4' })
			const buffs = []
				
			for (let x = 0; x < urls.length; x++) {
				if (!/https?:\/\//.test(urls[x])) continue
				const url = new URL(urls[x])
				let image = await fetch(url.toString(), { headers: { referer: url.origin } })
				if (!image.ok) continue
				
				const type = image.headers.get('content-type')
				if (!/image/.test(type)) continue
				image = Buffer.from(await image.arrayBuffer())
				if (/(gif|webp)$/.test(type)) image = await sharp(image).png().toBuffer()
				
				doc.image(image, 0, 0, { fit: [595.28, 841.89], align: 'center', valign: 'center', ...opts })
				if (urls.length != x + 1) doc.addPage()
			}
			
			doc.on('data', (chunk) => buffs.push(chunk))
			doc.on('end', () => resolve(Buffer.concat(buffs)))
			doc.on('error', (err) => reject(err))
			doc.end()
		} catch (e) {
			console.log(e)
			reject(e)
		}
	}),
	// from https://github.com/Nurutomo/wabot-aq/blob/master/lib/y2mate.js#L15
	ytIdRegex: /(?:http(?:s|):\/\/|)(?:(?:www\.|)?youtube(?:\-nocookie|)\.com\/(?:shorts\/)?(?:watch\?.*(?:|\&)v=|embed\/|live\/|v\/)?|youtu\.be\/)([-_0-9A-Za-z]{11})/,
}

const app = express()
const tmpDir = os.tmpdir()

app.set('json spaces', 4)
app.use(express.json({ limit: '200mb' }))
app.use(express.urlencoded({ extended: true, limit: '200mb' }))
app.use(favicon(path.join(import.meta.dirname, 'favicon.ico')))
app.use(morgan('combined'))

app.use((req, __, next) => {
	// clear tmp
	for (let file of fs.readdirSync(tmpDir)) {
		file = `${tmpDir}/${file}`
		const stat = fs.statSync(file)
		const exp = Date.now() - stat.mtimeMs >= 1000 * 60 * 30
		if (stat.isFile() && exp) {
			console.log('Deleted file', file)
			fs.unlinkSync(file)
		}
	}
	req.allParams = Object.assign(req.query, req.body)
	req.headers['User-Agent'] = 'WhatsApp/1.2.3'
	next()
})

app.use('/file', express.static(tmpDir))

app.all('/', (_, res) => {
	const status = {}
	status['diskUsage'] = cp.execSync('du -sh').toString().split('M')[0] + ' MB'
	
	const used = process.memoryUsage()
	for (let x in used) status[x] = utils.formatSize(used[x])
	
	const totalmem = os.totalmem()
	const freemem = os.freemem()
	status['memoryUsage'] = `${utils.formatSize(totalmem - freemem)} / ${utils.formatSize(totalmem)}`
	
	res.json({
		message: 'Hello World!',
		uptime: new Date(process.uptime() * 1000).toUTCString().split(' ')[4],
		status
	})
})

app.all(/^\/(brat|carbon)/, async (req, res) => {
	if (!['GET', 'POST'].includes(req.method)) return res.status(405).json({ success: false, message: 'Method Not Allowed' })
	
	try {
		const obj = req.allParams
		const isBrat = req.params[0] === 'brat'
		if (isBrat && !obj.text) {
			return res.status(400).json({ success: false, message: 'Required parameter \'text\'' })
		} else if (!isBrat && !(obj.code || obj.text)) {
			return res.status(400).json({ success: false, message: 'Required parameter \'code\'' })
		}
		
		const image = isBrat ?
			await utils.generateBrat(obj.text) :
			utils.fetchCarbonaraAPI(obj.code || obj.text, obj)
		const resultUrl = `https://${req.hostname}/${image.replace(tmpDir, 'file')}`
		utils.isTrue(obj.json) ?
			res.json({ success: true, result: resultUrl }) :
		res[utils.isTrue(obj.raw) ? 'send' : 'redirect'](resultUrl)
	} catch (e) {
		console.log(e)
		res.status(500).json({ error: true, message: utils.getError(e) })
	}
})

app.all('/topdf', async (req, res) => {
	if (req.method !== 'POST') return res.status(405).json({ success: false, message: 'Method Not Allowed' })
	
	try {
		const { images: urls, json, raw } = req.body
		if (!urls) return res.status(400).json({ success: false, message: 'Payload \'images\' requires an array of urls' })
		if (!Array.isArray(urls)) urls = [urls]
		
		const bufferPDF = await utils.toPDF(urls)
		if (!bufferPDF.length) return res.status(400).json({ success: false, message: 'Can\'t convert to pdf' })
		
		const fileName = utils.randomName('.pdf')
		await fs.promises.writeFile(`${tmpDir}/${fileName}`, bufferPDF)
		
		const resultUrl = `https://${req.hostname}/file/${fileName}`
		utils.isTrue(json) ?
			res.json({ success: true, result: resultUrl }) :
		res[utils.isTrue(raw) ? 'send' : 'redirect'](resultUrl)
	} catch (e) {
		console.log(e)
		res.status(500).json({ error: true, message: utils.getError(e) })
	}
})

app.all(/^\/webp2(gif|mp4|png)/, async (req, res) => {
	if (req.method !== 'POST') return res.status(405).json({ success: false, message: 'Method Not Allowed' })
	
	try {
		const { file, json, raw } = req.body
		if (!file) return res.status(400).json({ success: false, message: 'Payload \'file\' requires base64 string' })
		if (!utils.isBase64(file)) return res.status(400).json({ success: false, message: 'Invalid base64 format' })
		
		const type = req.params[0]
		if (type === 'png') {
			const fileName = utils.randomName('.png')
			const fileBuffer = await sharp(Buffer.from(file, 'base64')).png().toBuffer()
			await fs.promises.writeFile(`${tmpDir}/${fileName}`, fileBuffer)
			
			const resultUrl = `https://${req.hostname}/file/${fileName}`
			utils.isTrue(json) ?
				res.json({ success: true, result: resultUrl }) :
			res[utils.isTrue(raw) ? 'send' : 'redirect'](resultUrl)
			return
		}
		
		const fileName = utils.randomName('.webp')
		const filePath = `${tmpDir}/${fileName}`
		await fs.promises.writeFile(filePath, Buffer.from(file, 'base64'))
		
		const exec = util.promisify(cp.exec).bind(cp)
		await exec(`convert ${filePath} ${filePath.replace('webp', 'gif')}`)
		
		let resultUrl
		if (type === 'gif') resultUrl = `https://${req.hostname}/file/${fileName.replace('webp', 'gif')}`
		else {
			await exec(`ffmpeg -i ${filePath.replace('webp', 'gif')} -movflags faststart -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" ${filePath.replace('webp', 'mp4')}`)
			resultUrl = `https://${req.hostname}/file/${fileName.replace('webp', 'mp4')}`
		}
		
		utils.isTrue(json) ?
			res.json({ success: true, result: resultUrl }) :
		res[utils.isTrue(raw) ? 'send' : 'redirect'](resultUrl)
	} catch (e) {
		console.log(e)
		res.status(500).json({ error: true, message: utils.getError(e) })
	}
})

// /yt /yt/dl /yt/download /yt/search /youtube/dl /youtube/download /youtube/search
app.all(/^\/y(outube|t)(\/(d(ownload|l)|search)?)?/, async (req, res) => {
	if (!['GET', 'POST'].includes(req.method)) return res.status(405).json({ success: false, message: 'Method Not Allowed' })
	
	try {
		const type = req.params[2]
		const obj = req.allParams
		if (type === 'search') {
			if (!obj.query) return res.status(400).json({ success: false, message: 'Required parameter \'query\'' })
			
			const result = await yts(obj)
			if (!(result.all?.length || result?.url)) return res.status(400).json({ success: false, message: 'Video unavailable' })
			
			res.json({ success: true, result })
			return
		} else if (['dl', 'download'].includes(type)) {
			if (!obj.url) return res.status(400).json({ success: false, message: 'Required parameter \'url\'' })
			if (!utils.ytIdRegex.test(obj.url)) return res.status(400).json({ success: false, message: 'Invalid url' })
			
			const payload = obj
			if (obj.type === 'audio') {
				payload.isAudioOnly = true
				// payload.audioBitrate = obj.quality || '128'
			} else {
				payload.vQuality = obj.quality || '720'
			}
			// nembak lagi woila
			const result = await utils.fetchCobaltAPI(obj.url, payload)
			if (result.status === 'error') return res.status(400).json({ success: false, message: 'An error occurred' })
			res.redirect(result.url)
			return
		}
	
		if (!obj.query) return res.status(400).json({ success: false, message: 'Required parameter \'query\'' })
		
		let result = await yts(utils.ytIdRegex.test(obj.query) ? { videoId: utils.ytIdRegex.exec(obj.query)[1] } : obj.query)
		result = result.videos ? result.videos[0] : result
		if (!result?.url) return res.status(400).json({ success: false, message: 'Video unavailable' })
		
		const dlUrl = `https://${req.hostname}/yt/dl?url=${result.url}`
		const download = { audio: `${dlUrl}&type=audio`, video: `${dlUrl}&type=video` }
		res.json({
			success: true,
			result: { ...result, download }
		})
	} catch (e) {
		console.log(e)
		res.status(500).json({ error: true, message: utils.getError(e) })
	}
})

// app.use((req, res, next) => {})

app.listen(7860, () => console.log('App running on port 7860'))