-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathCompendium2Module.js
More file actions
337 lines (303 loc) · 13.6 KB
/
Compendium2Module.js
File metadata and controls
337 lines (303 loc) · 13.6 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
export class Compendium2Module {
/**
* Async for each loop
*
* @param {array} array - Array to loop through
* @param {function} callback - Function to apply to each array item loop
*/
static async asyncForEach(array, callback) {
for (let index = 0; index < array.length; index += 1) {
await callback(array[index], index, array)
}
}
/**
* @param {Object} formData The jQuery selector for the dialog
* @returns {boolean} If there are any invalid fields.
*/
static validateFields(formData) {
let valid = true
let id = formData.id
if (id.length > 0 && id.match(/[^a-z\d\-_]/)) {
valid = false
ui.notifications.error(game.i18n.localize("compendium2module.errors.id"), {permanent: true})
}
if (Object.keys(Object.fromEntries(Object.entries(formData).filter(([key, value]) => key.startsWith("compendium") && value))).length === 0) {
valid = false
ui.notifications.error(game.i18n.localize("compendium2module.errors.compendiums"), {permanent: true})
}
return valid
}
/**
* @param {string} moduleId The module ID
* @param {string} moduleJSON The content for the module.json file
* @param {{data: {string: string}, images: string[]}} dbData The data for the compendiums that are included with the module
* @param {FormApplication} formApplication
* @param {boolean} saveToFile If the module should be saved to the local file system
* @param {boolean} includeURLImages If images hosted at URLs should be included or filtered out
*/
static async generateZIP(moduleId, moduleJSON, dbData, formApplication, saveToFile, includeURLImages) {
let zip = new JSZip()
let parentDir = zip.folder(moduleId)
parentDir.file("module.json", moduleJSON)
let packsDirectory = parentDir.folder("packs")
for (let key of Object.keys(dbData.data)) {
packsDirectory.file(`${key}.db`, dbData.data[key])
}
if (dbData.images.length > 0) {
ui.notifications.info(game.i18n.localize("compendium2module.assets.start"))
let assets = parentDir.folder("assets")
let request
let imageContent
// This will be used to map image URLs back to URL.pathname. This is important because the full URL shouldn't be recreated in the module's assets folder
let urlPathMap = {}
await this.asyncForEach(dbData.images.filter((value => {
try {
const imgURL = new URL(value)
if (includeURLImages) {
urlPathMap[value] = imgURL.pathname
return true;
}
return false
} catch (e) {
return true
}
})), async (image) => {
try {
request = await fetch(image)
if (!request.ok) {
ui.notifications.warn(game.i18n.localize("compendium2module.assets.notFound").replace("<filename>", image))
return
}
imageContent = await request.blob()
let imageDest = decodeURI(image)
if (includeURLImages && urlPathMap[image]) {
imageDest = decodeURI(urlPathMap[imageDest])
}
assets.file(imageDest, imageContent)
} catch (e) {
ui.notifications.warn(game.i18n.localize("compendium2module.assets.notFound").replace("<filename>", image))
}
})
ui.notifications.info(game.i18n.localize("compendium2module.assets.finish"))
}
zip.generateAsync(
{
type : "blob",
platform: "UNIX"
}
).then(async content => {
if (saveToFile) {
let moduleDir = `compendium2module/${moduleId}`
try {
await FilePicker.createDirectory('data', 'compendium2module')
} catch (e) {
// Ignore
}
try {
await FilePicker.createDirectory('data', `compendium2module/${moduleId}`)
} catch (e) {
// Ignore
}
await FilePicker.upload('data', moduleDir, new File([new Blob([moduleJSON], {type: "application/json"})], "module.json"), {}, {notify: false})
await FilePicker.upload('data', moduleDir, new File([new Blob([content], {type: "application/zip"})], "module-zip.txt"), {}, {notify: false})
let dialog = $('.compendium2moduleDialog')
let manifestLink = dialog.find('input.manifestLink')
const resourcePath = await this.getResourcePath();
manifestLink.val(new URL(`${resourcePath}/compendium2module/${moduleId}/module.json`).href)
dialog.find('button#cancel').html(`<i class='fas fa-ban'></i>${game.i18n.localize('compendium2module.edit.close')}`)
let generateButton = dialog.find('button#generate')
let generateButtonIcon = generateButton.find('i')
generateButtonIcon.addClass("fa-save")
generateButtonIcon.removeClass("fa-cog fa-spin")
generateButton.removeClass("disabled")
generateButton.attr("disabled", false)
} else {
saveDataToFile(content, "application/zip", `${moduleId}.zip`)
formApplication.close({force: true}).then()
}
ui.notifications.info(game.i18n.localize("compendium2module.info.moduleFinished"))
})
}
/**
* @param {Document[]} compendiumData
* @param {string[]} imagePaths
* @returns {string[]}
*/
static collectImagePathsFromCompendium(compendiumData, imagePaths) {
let path = ''
for (let compendiumEntry of compendiumData) {
path = compendiumEntry.img
if (!imagePaths.includes(path)) {
imagePaths.push(path)
}
if (compendiumEntry.type === "character") {
path = compendiumEntry.prototypeToken.texture.src
if (!imagePaths.includes(path)) {
imagePaths.push(path)
}
}
}
return imagePaths
}
/**
* @param {Document[]} documents
* @param {string} moduleId
* @param {boolean} includeImages
* @param {boolean} includeURLImages
* @param {string[]} images
* @returns {{images: string[], data: string}}
*/
static transformCompendiumData(documents, moduleId, includeImages, includeURLImages, images = []) {
images = includeImages ? Compendium2Module.collectImagePathsFromCompendium(documents, images) : images
let documentData = []
documents.forEach(d => {
let json = d.toJSON()
if (includeImages) {
try {
const imgURL = new URL(json.img)
if (includeURLImages) {
json.img = `modules/${moduleId}/assets/${imgURL.pathname}`
}
} catch (e) {
json.img = `modules/${moduleId}/assets/${json.img}`
}
if (json.type === "character") {
try {
const imgURL = new URL(json.prototypeToken.texture.src)
if (includeURLImages) {
json.prototypeToken.texture.src = `modules/${moduleId}/assets/${imgURL.pathname}`
}
} catch (e) {
json.prototypeToken.texture.src = `modules/${moduleId}/assets/${json.prototypeToken.texture.src}`
}
}
}
documentData.push(json)
})
return {
"data" : documentData.map(p => JSON.stringify(p)).join("\n"),
"images": images
}
}
// noinspection JSCheckFunctionSignatures
/**
* @param {CompendiumCollection[]} compendiums
* @param {boolean} isSingleCompendium
* @param {Object} overrideData
* @param {FormApplication} formApplication
* @returns {Promise<void>}
*/
static async generateRequiredFilesForCompendium(compendiums, isSingleCompendium, overrideData, formApplication) {
let now = Date.now().toString()
let moduleOptions = {
"id" : overrideData.id.length > 0 ? overrideData.id : game.i18n.localize("compendium2module.data.generatedId").replace("<timestamp>", now),
"authors" : [{
"name" : overrideData.author.length > 0 ? overrideData.author : game.user.name,
"email": "",
"url" : ""
}],
"version" : overrideData.version.length > 0 ? overrideData.version : "1.0.0",
"displayName" : overrideData.displayName.length > 0 ? overrideData.displayName : (isSingleCompendium ? compendiums[0].metadata.label : `Generated Module #${now}`),
"includeImages": overrideData.includeImages,
"saveToFile" : overrideData.saveToFile,
"includeURLImages" : overrideData.includeURLImages
}
let manifestURL, downloadURL
if (moduleOptions.saveToFile) {
const resourcePath = await this.getResourcePath();
manifestURL = (new URL(`${resourcePath}/compendium2module/${moduleOptions.id}/module.json`)).href
downloadURL = (new URL(`${resourcePath}/compendium2module/${moduleOptions.id}/module-zip.txt`)).href
} else {
manifestURL = ""
downloadURL = ""
}
let packs = []
let dbData = {
"images": [],
"data" : {}
}
let metadata
let documents
let images = []
let transformedData
let packName
for (let compendium of compendiums) {
metadata = compendium.metadata
if (isSingleCompendium || overrideData[`compendium|${metadata.packageName}|${metadata.name}`] === true) {
packName = `${metadata.packageName}-${metadata.name}-${now}`
packs.push({
"type" : metadata.type,
"label" : metadata.label,
"module": moduleOptions.id,
"path" : `packs/${packName}.db`,
"name" : `${packName}`,
"system": game.system.id
})
documents = await compendium.getDocuments()
transformedData = Compendium2Module.transformCompendiumData(documents, moduleOptions.id, moduleOptions.includeImages, moduleOptions.includeURLImages, images)
images = transformedData.images
dbData.data[packName] = transformedData.data
}
}
let moduleJSON = {
"name" : moduleOptions.id,
"title" : moduleOptions.displayName,
"description" : game.i18n.localize("compendium2module.json.description").replace("<displayName>", moduleOptions.displayName),
"version" : moduleOptions.version,
"library" : "false",
"manifestPlusVersion": moduleOptions.version,
"compatibility" : {
"minimum" : 10,
"verified": parseInt(game.version),
"maximum" : parseInt(game.version) + 1
},
"authors" : moduleOptions.authors,
"packs" : packs,
"manifest" : manifestURL,
"download" : downloadURL
}
dbData.images = images
ui.notifications.info(game.i18n.localize("compendium2module.info.dataCollected"))
// noinspection JSCheckFunctionSignatures
return Compendium2Module.generateZIP(moduleOptions.id, JSON.stringify(moduleJSON, null, 4), dbData, formApplication, moduleOptions.saveToFile, moduleOptions.includeURLImages)
}
/**
* @param {Event} event
*/
static async copyToClipboard(event) {
let linkElement = $(event.target).parent().find("input#manifestLink")
if (navigator.clipboard) {
await navigator.clipboard.writeText(linkElement.val())
ui.notifications.info("Copied to clipboard!")
} else {
linkElement.focus()
linkElement.select()
try {
// noinspection JSDeprecatedSymbols
let success = document.execCommand("copy")
if (success) {
ui.notifications.info("Copied to clipboard!")
} else {
ui.notifications.error("Failed to copy to clipboard!")
}
} catch (e) {
console.error(e)
ui.notifications.error("Failed to copy to clipboard!")
}
}
}
/**
* Return a path where resources will be hosted, usually the world host.
* Hosting providers or integrations may specify a different path.
* @returns {Promise<string>} path
* @private
*/
static async getResourcePath() {
let path = window.location.origin;
// If running on The Forge, link to user's Assets Library
if (typeof ForgeVTT !== "undefined" && ForgeVTT.usingTheForge) {
path = ForgeVTT.ASSETS_LIBRARY_URL_PREFIX + await ForgeAPI.getUserId();
}
return path;
}
}