-
Notifications
You must be signed in to change notification settings - Fork 0
/
images-json.mjs
220 lines (156 loc) · 5.44 KB
/
images-json.mjs
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
import { fetch, setGlobalDispatcher, Agent } from 'undici'
import { existsSync } from "node:fs"
import { opendir, readFile, writeFile } from "node:fs/promises"
import path from "node:path"
/** @typedef {{name: string, images: Set<string>}} ImagesObject */
/**
* @typedef {Object} Question
* @property {string} question - The question content.
* @property {string} answer - The answer to the question.
* @property {string} [text] - Additional text content (optional).
* @property {string} [image] - URL of an image associated with the question (optional).
*/
/**
* @typedef {Object} Metadata
* @property {string} title - The title of the cuiz.
* @property {string} [image] - URL of an image associated with the cuiz (optional).
* @property {string} description - Description of the cuiz.
* @property {string} author - The author of the cuiz.
* @property {string} course - The course or category to which the cuiz belongs.
* @property {"easy" | "medium" | "hard"} difficulty - The difficulty level of the cuiz.
*/
/**
* @typedef {Object} Data
* @property {string} [text] - Additional text content (optional).
* @property {string} [image] - URL of an image associated with the cuiz (optional).
* @property {Question[]} questions - Array of questions in the cuiz.
*/
/**
* @typedef {Data & Metadata} Quiz
*/
/**
* @typedef {Record<string, string>} ImageFileContents
*
*/
// set fetch timeout
setGlobalDispatcher(new Agent({ connect: { timeout: 60_000 } }) )
/**
* @param {string} url
* @returns {string}
*/
const parseURL = (url) => (url.endsWith('/') ? url : `${url}/`)
/**
* @param {string} url
* @param {AbortController} controller
* @returns {Promise<string>}
*
*/
const getImageData = async (url, controller) => {
const res = await fetch(url, {
signal: controller?.signal ?? null
})
const blob = await res.blob()
const bufferArray = await blob.arrayBuffer()
const buffer = Buffer.from(bufferArray)
const dataURL = `data:image/png;base64,${buffer.toString("base64")}`
return dataURL
}
/**
* @param {string} relativeUrl
* @returns {Promise<string[]>}
*/
const getSourceFiles = async (relativeUrl) => {
const dir = await opendir(path.resolve(relativeUrl));
/** @type {string[]} */
const files = []
for await (const entry of dir) {
const isValid = entry.isFile() && entry.name.endsWith('.json')
if (isValid) files.push(entry.name)
}
return files
}
/**
* @param {string} fileName
*
*/
const getImagePathsFromJSON = async (fileName) => {
/** @type {ImagesObject} */
const output = {
name: fileName,
images: new Set()
}
const file = await readFile(fileName, { encoding: "utf8" })
/** @type {Quiz} json */
const json = JSON.parse(file)
if ("image" in json) output.images.add(parseURL(json.image))
json.questions.forEach(question => {
if ("image" in question) output.images.add(parseURL(question.image))
})
return output
}
/**
*@param {string} filePath
*@param {string} cacheDirectory
*@returns {string} cacheFileName
*/
const getCacheFileName = (filePath, cacheDirectory) => {
const file = path.parse(filePath)
const fileName = `${file.name.toLowerCase().replace(" ", "-")}${file.ext}`
const cacheFileName = path.resolve(cacheDirectory, fileName)
return cacheFileName
}
/**
* @param {string} cacheFileName
* @param {ImagesObject} imagesData
*/
const modifyCache = async (cacheFileName, imagesData) => {
const cacheExists = existsSync(cacheFileName)
/** @type {Record<string, string>} */
const outputFile = {}
/** @type {Promise<any>[]} */
const promises = []
if (!cacheExists) {
imagesData.images.forEach(image => {
const imagePromise = getImageData(image).then(url => {
outputFile[image] = url
})
promises.push(imagePromise)
})
} else {
const currentImages = await readFile(cacheFileName, { encoding: "utf-8" })
/** @type {ImageFileContents} */
const imageFileContents = JSON.parse(currentImages)
imagesData.images.forEach(image => {
if (image in imageFileContents) {
console.count("cache hit!")
outputFile[image] = imageFileContents[image]
} else {
const imagePromise = getImageData(image).then(url => {
outputFile[image] = url
})
promises.push(imagePromise)
}
})
}
if (promises.length) await Promise.all(promises)
if (!Object.keys(outputFile).length) return
return writeFile(cacheFileName, `${JSON.stringify(outputFile, null)} \n`, { encoding: 'utf8' })
}
const runJob = async () => {
const RELATIVE_PATH = "./src/content/quiz/"
const CACHE_RELATIVE_PATH = "./public/_images/"
const fileNames = await getSourceFiles(RELATIVE_PATH);
/** @type {Promise<ImagesObject>[]} */
const jsonPromises = fileNames.filter(file => !file.startsWith('_')).map(file => {
return new Promise((resolve, reject) => {
const fileName = path.resolve(RELATIVE_PATH, file)
return getImagePathsFromJSON(fileName).then(resolve).catch(reject)
})
})
const filesArray = await Promise.all(jsonPromises)
filesArray.forEach((file) => {
const cacheFileName = getCacheFileName(file.name, CACHE_RELATIVE_PATH)
modifyCache(cacheFileName, file)
})
}
runJob()