-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqrcode.js
More file actions
105 lines (91 loc) · 3.28 KB
/
Copy pathqrcode.js
File metadata and controls
105 lines (91 loc) · 3.28 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
import fs from "fs"
import path from "path"
import os from "os"
// ======================
// QR CODE GENERATOR MODULE
// ======================
// Permanent base media directory and qrcode folder (per request)
const BASE_MEDIA_DIR = path.join(path.sep, "HASYIM56")
const QRCODE_FOLDER = path.join(BASE_MEDIA_DIR, "qrcode")
// Ensure qrcode folder exists (best-effort)
try {
if (!fs.existsSync(BASE_MEDIA_DIR)) {
fs.mkdirSync(BASE_MEDIA_DIR, { recursive: true })
}
if (!fs.existsSync(QRCODE_FOLDER)) {
fs.mkdirSync(QRCODE_FOLDER, { recursive: true })
}
} catch (e) {
// best-effort; do not alter behavior if cannot create
console.warn("[QRCODE] Failed to ensure permanent qrcode folder:", e?.message || e)
}
/**
* Generate QR Code from text or URL using external API
* @param {string} data - Text or URL to encode
* @returns {Promise<Object>} - Response object with QR Code data
*/
export const generateQRCode = async (data) => {
if (!data || typeof data !== "string" || data.trim().length === 0) {
throw new Error("Data tidak boleh kosong")
}
try {
console.log(`[QRCODE] Generating QR Code for: ${data}`)
const response = await fetch("https://h56-qr-generator-api.netlify.app/api/qr_scan", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
data: data.trim(),
}),
})
if (!response.ok) {
throw new Error(`API Error: ${response.status} ${response.statusText}`)
}
const result = await response.json()
// Validate response structure
if (!result.success || !result.qr_data_url) {
throw new Error("Invalid API response: missing qr_data_url")
}
// Save a copy of the QR image to permanent qrcode folder (non-intrusive: does not change return value)
try {
const dataUrl = result.qr_data_url
const commaIndex = dataUrl.indexOf(",")
if (commaIndex > -1) {
const meta = dataUrl.slice(0, commaIndex)
const base64String = dataUrl.slice(commaIndex + 1)
const buffer = Buffer.from(base64String, "base64")
const filename = `qrcode_${Date.now()}_${Math.random().toString(36).slice(2, 8)}.png`
const filepath = path.join(QRCODE_FOLDER, filename)
try {
fs.writeFileSync(filepath, buffer)
console.log(`[QRCODE] Saved QR image to: ${filepath}`)
} catch (writeErr) {
console.warn("[QRCODE] Failed to save QR image copy:", writeErr?.message || writeErr)
}
}
} catch (saveErr) {
console.warn("[QRCODE] Non-fatal: failed to write QR copy:", saveErr?.message || saveErr)
}
console.log(`[QRCODE] QR Code generated successfully`)
return result
} catch (err) {
console.error("[QRCODE] Error generating QR Code:", err.message)
throw new Error(`Gagal generate QR Code: ${err.message}`)
}
}
/**
* Convert Base64 Data URL to Buffer
* @param {string} dataUrl - Base64 data URL from API
* @returns {Buffer} - Image buffer
*/
export const base64ToBuffer = (dataUrl) => {
if (!dataUrl.startsWith("data:image/")) {
throw new Error("Invalid data URL format")
}
const base64String = dataUrl.split(",")[1]
if (!base64String) {
throw new Error("Cannot extract base64 data from data URL")
}
return Buffer.from(base64String, "base64")
}