File size: 4,379 Bytes
8c53df2
095af13
59f11b4
095af13
 
 
 
 
8c53df2
095af13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59f11b4
095af13
 
 
 
 
 
 
 
 
 
8c53df2
 
 
 
 
 
 
 
 
59f11b4
8c53df2
 
 
 
 
 
 
 
 
 
095af13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c53df2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
095af13
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
const fs = require('fs')
const os = require('os')
// const uuid = require('uuid')
const bytes = require('bytes')
const sharp = require('sharp')
const morgan = require('morgan')
const express = require('express')
const PDFDocument = require('pdfkit')
const playwright = require('playwright-extra')

const app = express()
app.set('json spaces', 4)
app.use(morgan('dev'))
app.use(express.json())

app.all('/', (req, res) => {
	const status = {}
	const used = process.memoryUsage()
	for (let key in used) status[key] = formatSize(used[key])
	
	const totalmem = os.totalmem()
	const freemem = os.freemem()
	status.memoryUsage = `${formatSize(totalmem - freemem)} / ${formatSize(totalmem)}`
	
	res.json({
		creator: '@rippanteq7',
		message: 'Hello World',
		uptime: new Date(process.uptime() * 1000).toUTCString().split(' ')[4],
		status
	})
})

app.post('/imagetopdf', async (req, res) => {
	try {
		console.log(req.body)
		const { images } = req.body
		if (!images) return res.json({ success: false, message: 'Required an array image url' })
		
		const buffer = await toPDF(images)
		res.setHeader('Content-Disposition', `attachment; filename=${Math.random().toString(36).slice(2)}.pdf`)
		res.setHeader('Content-Type', 'application/pdf')
		res.setHeader('Content-Length', buffer.byteLength)
		res.send(buffer)
	} catch (e) {
		console.log(e)
		e = String(e)
		res.json({ error: true, message: e === '[object Object]' ? 'Internal Server Error' : e })
	}
})

app.all('/tgstogif', async (req, res) => {
	if (!['GET', 'POST'].includes(req.method)) return res.status(405).end()
	try {
		let tgsUrl = req.query.url
		if (req.method === 'POST') tgsUrl = req.body.url
		if (!tgsUrl) return res.json({ success: false, message: 'Required parameter url' })
		if (!tgsUrl.endsWith('.tgs')) return res.json({ success: false, message: 'Invalid tgs url' })
		
		const buffer = await tgsToGif(tgsUrl)
		res.setHeader('Content-Disposition', `attachment; filename=${Math.random().toString(36).slice(2)}.gif`)
		res.setHeader('Content-Type', 'image/gif')
		res.setHeader('Content-Length', buffer.byteLength)
		res.send(buffer)
	} catch (e) {
		console.log(e)
		e = String(e)
		res.json({ error: true, message: e === '[object Object]' ? 'Internal Server Error' : e })
	}
})

const PORT = process.env.PORT || 7860
app.listen(PORT, () => console.log('App running on port', PORT))

function formatSize(num) {
	return bytes.format(+num || 0, { unitSeparator: ' ' })
}

function toPDF(urls) {
	return new Promise(async (resolve, reject) => {
		try {
			if (!Array.isArray(urls)) urls = [urls]
			const doc = new PDFDocument({ margin: 0, size: 'A4' })
			const buffers = []
			
			const promises = urls.map(async (url, index) => {
				const response = await fetch(url, { headers: { referer: url }})
				if (!response.ok) return
				
				const type = response.headers.get('content-type')
				if (!/image/.test(type)) return reject(`Invalid Type: ${type}`)
				
				let buffer = Buffer.from(await response.arrayBuffer())
				if (/gif|webp/.test(type)) buffer = await sharp(buffer).png().toBuffer()
				
				doc.image(buffer, 0, 0, { fit: [595.28, 841.89], align: 'center', valign: 'center' })
				if (urls.length !== index + 1) doc.addPage()
			})
			
			await Promise.all(promises)
			
			doc.on('data', (chunk) => buffers.push(chunk))
			doc.on('end', () => resolve(Buffer.concat(buffers)))
			doc.on('error', reject)
			doc.end()
		} catch (e) {
			console.log(e)
			reject(e)
		}
	})
}

async function tgsToGif(url) {
	let browser
	try {
		browser = await playwright['chromium'].launch({
			headless: true,
			executablePath: '/usr/bin/chromium',
			args: ['--no-sandbox']
		})
		
		const page = await browser.newPage()
		await page.goto('https://www.emojibest.com/tgs-to-gif')
		
		const arrayBuffer = await (await fetch(url)).arrayBuffer()
		await page.setInputFiles('.el-upload__input', {
			name: 'file.tgs', buffer: Buffer.from(arrayBuffer)
		})
		
		const [download] = await Promise.all([
			page.waitForEvent('download'),
			page.click('.el-button.el-button--primary.el-button--mini'),
			page.click('.el-button.el-button--success.el-button--mini')
		])
		
		const filePath = await download.path()
		const fileBuffer = await fs.promises.readFile(filePath)
		await fs.promises.unlink(filePath)
		
		return fileBuffer
	} catch (e) {
		throw e
	} finally {
		if (browser) await browser?.close?.()
	}
}