-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
317 lines (271 loc) · 9.25 KB
/
Copy pathindex.js
File metadata and controls
317 lines (271 loc) · 9.25 KB
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
const express = require('express');
const QRCode = require('qrcode');
const sharp = require('sharp');
const app = express();
app.use(express.json({ limit: '1mb' }));
const PORT = process.env.PORT || 3201;
// Rate limiting
const rateLimit = new Map();
const RATE_LIMIT = 300;
function checkRate(ip) {
const now = Date.now();
const entry = rateLimit.get(ip) || { count: 0, reset: now + 3600000 };
if (now > entry.reset) {
entry.count = 0;
entry.reset = now + 3600000;
}
entry.count++;
rateLimit.set(ip, entry);
return entry.count <= RATE_LIMIT;
}
app.use((req, res, next) => {
const ip = req.ip || req.connection.remoteAddress;
if (!checkRate(ip)) {
return res.status(429).json({ error: 'Rate limit exceeded. 300 requests/hour.' });
}
next();
});
// POST /generate — Generate QR code
app.post('/generate', async (req, res) => {
try {
const {
data,
size = 300,
format = 'png',
errorCorrection = 'M',
darkColor = '#000000',
lightColor = '#ffffff',
margin = 4,
logo,
} = req.body;
if (!data || typeof data !== 'string') {
return res.status(400).json({ error: 'Provide "data" (string) in request body' });
}
if (data.length > 4000) {
return res.status(400).json({ error: 'Data too long. Max 4000 characters.' });
}
const validSizes = size >= 50 && size <= 2000;
if (!validSizes) {
return res.status(400).json({ error: 'Size must be between 50 and 2000 pixels.' });
}
const ecLevel = ['L', 'M', 'Q', 'H'].includes(errorCorrection) ? errorCorrection : 'M';
const qrOptions = {
errorCorrectionLevel: ecLevel,
width: size,
margin,
color: {
dark: darkColor,
light: lightColor,
},
};
if (format === 'svg') {
const svg = await QRCode.toString(data, { ...qrOptions, type: 'svg' });
res.setHeader('Content-Type', 'image/svg+xml');
return res.send(svg);
}
let qrBuffer = await QRCode.toBuffer(data, { ...qrOptions, type: 'png' });
// If logo provided (base64), overlay it in the center
if (logo) {
try {
const logoBuffer = Buffer.from(logo, 'base64');
const logoSize = Math.round(size * 0.2);
const resizedLogo = await sharp(logoBuffer)
.resize(logoSize, logoSize, { fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 1 } })
.png()
.toBuffer();
const padding = 4;
const bgSize = logoSize + padding * 2;
const bg = await sharp({
create: { width: bgSize, height: bgSize, channels: 4, background: { r: 255, g: 255, b: 255, alpha: 1 } },
})
.composite([{ input: resizedLogo, left: padding, top: padding }])
.png()
.toBuffer();
const offset = Math.round((size - bgSize) / 2);
qrBuffer = await sharp(qrBuffer)
.composite([{ input: bg, left: offset, top: offset }])
.png()
.toBuffer();
} catch {
// If logo processing fails, return QR without logo
}
}
if (format === 'webp') {
qrBuffer = await sharp(qrBuffer).webp({ quality: 90 }).toBuffer();
res.setHeader('Content-Type', 'image/webp');
} else if (format === 'jpeg' || format === 'jpg') {
qrBuffer = await sharp(qrBuffer).jpeg({ quality: 90 }).toBuffer();
res.setHeader('Content-Type', 'image/jpeg');
} else {
res.setHeader('Content-Type', 'image/png');
}
const base64 = qrBuffer.toString('base64');
res.json({
image: `data:image/${format === 'svg' ? 'svg+xml' : format};base64,${base64}`,
size,
format,
dataLength: data.length,
errorCorrection: ecLevel,
});
} catch (err) {
res.status(500).json({ error: 'QR generation failed', details: err.message });
}
});
// POST /generate/image — Return raw image (not base64 JSON)
app.post('/generate/image', async (req, res) => {
try {
const {
data,
size = 300,
format = 'png',
errorCorrection = 'M',
darkColor = '#000000',
lightColor = '#ffffff',
margin = 4,
} = req.body;
if (!data || typeof data !== 'string') {
return res.status(400).json({ error: 'Provide "data" (string) in request body' });
}
const ecLevel = ['L', 'M', 'Q', 'H'].includes(errorCorrection) ? errorCorrection : 'M';
const qrOptions = {
errorCorrectionLevel: ecLevel,
width: Math.min(Math.max(size, 50), 2000),
margin,
color: { dark: darkColor, light: lightColor },
};
if (format === 'svg') {
const svg = await QRCode.toString(data, { ...qrOptions, type: 'svg' });
res.setHeader('Content-Type', 'image/svg+xml');
return res.send(svg);
}
let buffer = await QRCode.toBuffer(data, { ...qrOptions, type: 'png' });
if (format === 'webp') {
buffer = await sharp(buffer).webp().toBuffer();
res.setHeader('Content-Type', 'image/webp');
} else if (format === 'jpeg' || format === 'jpg') {
buffer = await sharp(buffer).jpeg().toBuffer();
res.setHeader('Content-Type', 'image/jpeg');
} else {
res.setHeader('Content-Type', 'image/png');
}
res.send(buffer);
} catch (err) {
res.status(500).json({ error: 'QR generation failed', details: err.message });
}
});
// POST /batch — Generate multiple QR codes
app.post('/batch', async (req, res) => {
try {
const { items, size = 200, format = 'png' } = req.body;
if (!Array.isArray(items) || items.length === 0) {
return res.status(400).json({ error: 'Provide "items" array with data strings' });
}
if (items.length > 20) {
return res.status(400).json({ error: 'Maximum 20 items per batch.' });
}
const results = await Promise.all(
items.map(async (item) => {
const data = typeof item === 'string' ? item : item.data;
if (!data) return { error: 'Missing data', input: item };
const buffer = await QRCode.toBuffer(data, {
errorCorrectionLevel: 'M',
width: Math.min(Math.max(size, 50), 1000),
margin: 4,
type: 'png',
});
const base64 = buffer.toString('base64');
return {
data,
image: `data:image/png;base64,${base64}`,
};
})
);
res.json({ count: results.length, results });
} catch (err) {
res.status(500).json({ error: 'Batch generation failed', details: err.message });
}
});
// POST /decode — Decode QR code from base64 image (placeholder — needs jsQR)
// Future enhancement
// GET /wifi — Generate WiFi QR code
app.post('/wifi', async (req, res) => {
try {
const { ssid, password, encryption = 'WPA', hidden = false, size = 300 } = req.body;
if (!ssid) {
return res.status(400).json({ error: 'Provide "ssid" (network name)' });
}
const enc = ['WPA', 'WEP', 'nopass'].includes(encryption) ? encryption : 'WPA';
const wifiString = `WIFI:T:${enc};S:${ssid};P:${password || ''};H:${hidden ? 'true' : 'false'};;`;
const buffer = await QRCode.toBuffer(wifiString, {
errorCorrectionLevel: 'H',
width: Math.min(Math.max(size, 50), 2000),
margin: 4,
type: 'png',
});
const base64 = buffer.toString('base64');
res.json({
image: `data:image/png;base64,${base64}`,
wifiString,
ssid,
encryption: enc,
});
} catch (err) {
res.status(500).json({ error: 'WiFi QR generation failed', details: err.message });
}
});
// POST /vcard — Generate vCard QR code
app.post('/vcard', async (req, res) => {
try {
const { name, phone, email, company, title, url, size = 300 } = req.body;
if (!name) {
return res.status(400).json({ error: 'Provide "name" at minimum' });
}
const parts = name.split(' ');
const lastName = parts.length > 1 ? parts.pop() : '';
const firstName = parts.join(' ');
let vcard = `BEGIN:VCARD\nVERSION:3.0\nN:${lastName};${firstName}\nFN:${name}`;
if (phone) vcard += `\nTEL:${phone}`;
if (email) vcard += `\nEMAIL:${email}`;
if (company) vcard += `\nORG:${company}`;
if (title) vcard += `\nTITLE:${title}`;
if (url) vcard += `\nURL:${url}`;
vcard += '\nEND:VCARD';
const buffer = await QRCode.toBuffer(vcard, {
errorCorrectionLevel: 'M',
width: Math.min(Math.max(size, 50), 2000),
margin: 4,
type: 'png',
});
const base64 = buffer.toString('base64');
res.json({
image: `data:image/png;base64,${base64}`,
vcard,
});
} catch (err) {
res.status(500).json({ error: 'vCard QR generation failed', details: err.message });
}
});
// Health check
app.get('/', (req, res) => {
res.json({
name: 'QR Code Generator API',
version: '1.0.0',
endpoints: [
'POST /generate - Generate QR code (returns base64 JSON)',
'POST /generate/image - Generate QR code (returns raw image)',
'POST /batch - Generate multiple QR codes (max 20)',
'POST /wifi - Generate WiFi network QR code',
'POST /vcard - Generate contact vCard QR code',
],
options: {
formats: ['png', 'svg', 'webp', 'jpeg'],
sizes: '50-2000px',
errorCorrection: 'L, M, Q, H',
customColors: 'darkColor, lightColor (hex)',
logoOverlay: 'base64 logo image (on /generate)',
},
});
});
app.listen(PORT, () => {
console.log(`QR Code Generator API running on port ${PORT}`);
});