-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·217 lines (178 loc) · 6.16 KB
/
index.js
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
const fs = require('fs')
const path = require('path')
const express = require('express')
const sizeOf = require('image-size')
const { AppError } = require('./errors')
const puppeteer = require('puppeteer-core')
const AppConstants = require('./constants')
const { AuthService, FileService } = require('./services')
const { ErrorHandler, FileUploadHandler } = require('./handlers')
const app = express()
app.use(express.json())
app.use((req, res, next) => {
try {
if (
!AuthService.getInstance().isValidRequest(
req.get(AppConstants.Headers.CodelibSecretKey)
)
) {
throw new AppError(
401,
"You don't have permission to perform this operation. Kindly contact your administrator for more details."
)
}
next()
} catch (err) {
const { statusCode, ...others } =
ErrorHandler.getInstance().processError(err)
res.status(statusCode).send(others)
}
})
app.post('/resize', async (req, res) => {
try {
await FileUploadHandler.getInstance(req, res, [
{
name: 'image',
maxCount: 1
}
]).handleFileUpload()
const browserWSEndpoint = process.env[AppConstants.Env.BrowserWSEndpoint]
const templateFilePath = path.join(
__dirname,
'templates',
'ResizeTemplate.html'
)
if (!req.files.image) {
throw new AppError(400, "'image' cannot be empty.")
}
const image = req.files.image[0]
const { width, height } = req.body
if (width) {
if (!AppConstants.NumberRegex.test(width)) {
throw new AppError(400, "'width' should be a number.")
}
} else {
throw new AppError(400, "'width' cannot be empty.")
}
if (height) {
if (!AppConstants.NumberRegex.test(height)) {
throw new AppError(400, "'height' should be a number.")
}
} else {
throw new AppError(400, "'height' cannot be empty.")
}
const fileService = new FileService()
const localFilePath = fileService.createTempFilePath(Date.now() + '-' + image.originalname)
// obtain the size of an image
const dimensions = sizeOf(image.path)
if (width > AppConstants.MaxImageWidth) {
dimensions.width = AppConstants.MaxImageWidth
} else {
dimensions.width = width
}
if (height > AppConstants.MaxImageHeight) {
dimensions.height = AppConstants.MaxImageHeight
} else {
dimensions.height = height
}
let template = fs.readFileSync(templateFilePath, 'utf8')
const imageSrc = await fs.promises.readFile(image.path, 'base64')
const templateData = {
imageSrc,
mountingDivID: AppConstants.MountingDivID,
imageWidth: dimensions.width,
imageHeight: dimensions.height
}
for (const [placeholder, value] of Object.entries(templateData)) {
template = template.replace(new RegExp(placeholder, 'g'), value)
}
const browser = await puppeteer.connect({ browserWSEndpoint })
const page = await browser.newPage()
await page.setContent(template, { waitUntil: 'domcontentloaded' })
await page.waitForSelector(`#${AppConstants.MountingDivID}`)
const element = await page.$(`#${AppConstants.MountingDivID}`)
await element.screenshot({ path: localFilePath, type: 'png' })
await page.close()
res.status(200).download(localFilePath, image.originalname)
} catch (err) {
const { statusCode, ...others } =
ErrorHandler.getInstance().processError(err)
res.status(statusCode).send(others)
}
})
app.post('/compress', async (req, res) => {
try {
await FileUploadHandler.getInstance(req, res, [
{
name: 'image',
maxCount: 1
}
]).handleFileUpload()
const browserWSEndpoint = process.env[AppConstants.Env.BrowserWSEndpoint]
const templateFilePath = path.join(
__dirname,
'templates',
'CompressTemplate.html'
)
if (!req.files.image) {
throw new AppError(400, "'image' cannot be empty.")
}
const image = req.files.image[0]
const compressQuality = req.body.compress_quality
if (compressQuality) {
if (!AppConstants.NumberRegex.test(compressQuality)) {
throw new AppError(400, "'compress_quality' should be a number.")
} else {
if (!(compressQuality > 0 && compressQuality <= 100)) {
throw new AppError(
400,
"'compress_quality' should be in the range between 1 and 100."
)
}
}
} else {
throw new AppError(400, "'compress_quality' cannot be empty.")
}
const fileService = new FileService()
const localFilePath = fileService.createTempFilePath(Date.now() + '-' + image.originalname)
// obtain the size of an image
const dimensions = sizeOf(image.path)
if (dimensions.width > AppConstants.MaxImageWidth) {
dimensions.width = AppConstants.MaxImageWidth
}
if (dimensions.height > AppConstants.MaxImageHeight) {
dimensions.height = AppConstants.MaxImageHeight
}
let template = fs.readFileSync(templateFilePath, 'utf8')
const imageSrc = await fs.promises.readFile(image.path, 'base64')
const templateData = {
imageSrc,
mountingDivID: AppConstants.MountingDivID,
imageWidth: dimensions.width,
imageHeight: dimensions.height,
imageCompressQuality: compressQuality / 100
}
for (const [placeholder, value] of Object.entries(templateData)) {
template = template.replace(new RegExp(placeholder, 'g'), value)
}
const browser = await puppeteer.connect({ browserWSEndpoint })
const page = await browser.newPage()
await page.setContent(template, { waitUntil: 'domcontentloaded' })
await page.waitForSelector(`#${AppConstants.MountingDivID}`)
const element = await page.$(`#${AppConstants.MountingDivID}`)
await element.screenshot({ path: localFilePath, type: 'png' })
await page.close()
res.status(200).download(localFilePath, image.originalname)
} catch (err) {
const { statusCode, ...others } =
ErrorHandler.getInstance().processError(err)
res.status(statusCode).send(others)
}
})
app.all('*', function (_req, res) {
res.status(404).send({
status: 'failure',
message: "We couldn't find the requested url."
})
})
module.exports = app