-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.js
500 lines (461 loc) · 13.6 KB
/
main.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
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
const {
app,
BrowserWindow,
ipcMain,
dialog,
Menu,
shell,
} = require("electron");
const path = require("path");
const fs = require("fs");
const _ = require("lodash");
const logger = require("./munch/logger.js");
// immediately clear the log file
logger.clear();
// Load environment variables
const isDevelopment = process.env.NODE_ENV === "DEV";
const memoryCap = process.env.MEMORY ? process.env.MEMORY : "6144";
// add electron switches
app.commandLine.appendSwitch("trace-warnings");
app.commandLine.appendSwitch("unhandled-rejections", "strict");
app.commandLine.appendSwitch("js-flags", `--max-old-space-size=${memoryCap} --expose-gc`);
// Keep a global reference of the window object
let mainWindow;
if (isDevelopment) {
require("electron-reload")(__dirname);
logger.warn("DEVELOPMENT ENVIRONMENT");
}
const isMac = process.platform === "darwin";
const ddb = require("./munch/data/ddb.js");
const { Adventure } = require("./munch/adventure/Adventure.js");
const { Config } = require("./munch/adventure/Config.js");
const yargs = require("yargs/yargs");
const { hideBin } = require("yargs/helpers");
const pargs = yargs(hideBin(process.argv));
const { autoUpdater } = require("electron-updater");
let allBooks = true;
const configDir = app.getPath("userData");
const menuTemplate = [
// { role: 'appMenu' }
...(isMac
? [
{
label: app.name,
submenu: [
{ role: "about" },
{ type: "separator" },
{ role: "services" },
{ type: "separator" },
{ role: "hide" },
{ role: "hideothers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" },
],
},
]
: []),
// { role: 'fileMenu' }
{
label: "File",
submenu: [
{
label: "Reset config",
click: async () => {
const configFile = path.join(configDir, "config.json");
logger.info(configFile);
if (fs.existsSync(configFile)) fs.unlinkSync(configFile);
},
},
{
label: "Reset generated ids",
click: async () => {
const lookupPathV3 = path.join(configDir, "lookup.json");
logger.info(lookupPathV3);
if (fs.existsSync(lookupPathV3)) fs.unlinkSync(lookupPathV3);
const lookupPathV4 = path.join(configDir, "lookup4.json");
logger.info(lookupPathV4);
if (fs.existsSync(lookupPathV4)) fs.unlinkSync(lookupPathV4);
},
},
{
label: "Remove downloaded files",
click: async () => {
const downloadPath = path.join(configDir, "content");
logger.info(downloadPath);
if (fs.existsSync(downloadPath)) {
fs.rm(downloadPath, { recursive: true }, (err) => {
if (err) {
throw err;
}
});
}
const buildPath = path.join(configDir, "build");
logger.info(buildPath);
if (fs.existsSync(buildPath)) {
fs.rm(buildPath, { recursive: true }, (err) => {
if (err) {
throw err;
}
});
}
const metaPath = path.join(configDir, "meta");
logger.info(metaPath);
if (fs.existsSync(metaPath)) {
fs.rm(metaPath, { recursive: true }, (err) => {
if (err) {
throw err;
}
});
}
},
},
isMac ? { role: "close" } : { role: "quit" },
],
},
// { role: 'viewMenu' }
{
label: "View",
submenu: [
{ role: "reload" },
{ role: "forceReload" },
{ role: "toggleDevTools" },
{ type: "separator" },
{ role: "resetZoom" },
{ role: "zoomIn" },
{ role: "zoomOut" },
{ type: "separator" },
{ role: "togglefullscreen" },
],
},
// { role: 'windowMenu' }
{
label: "Window",
submenu: [
{ role: "minimize" },
{ role: "zoom" },
...(isMac
? [
{ type: "separator" },
{ role: "front" },
{ type: "separator" },
{ role: "window" },
]
: [{ role: "close" }]),
],
},
{
role: "help",
submenu: [
{
label: "Config location",
click: async () => {
const configFile = path.join(configDir, "config.json");
logger.info(configDir);
if (fs.existsSync(configFile)) {
shell.showItemInFolder(configFile);
} else {
shell.showItemInFolder(configDir);
}
},
},
{
label: "Log file location",
click: async () => {
const logFolder = isMac
? "~/Library/Logs/ddb-adventure-muncher/"
: path.join(configDir, "logs");
const logFile = path.join(logFolder, "main.log");
logger.info(logFolder);
if (fs.existsSync(logFile)) {
shell.showItemInFolder(logFile);
} else {
shell.showItemInFolder(logFolder);
}
},
},
{
label: "Scene status page",
click: async () => {
await shell.openExternal(
"https://docs.ddb.mrprimate.co.uk/status.html"
);
},
},
{
label: "Icon attribution",
click: async () => {
await shell.openExternal(
"https://iconarchive.com/show/role-playing-icons-by-chanut/Adventure-Map-icon.html"
);
},
},
{
label: "Software license",
click: async () => {
await shell.openExternal("https://opensource.org/licenses/MIT");
},
},
{
label: "Source code",
click: async () => {
await shell.openExternal(
"https://github.com/MrPrimate/ddb-adventure-muncher"
);
},
},
{
label: `Version: ${app.getVersion()}`,
},
],
},
];
async function downloadBooks(config) {
const noCheck = process.env.DDB_NO_CHECK === "true" || config.data.ddbNoCheck;
const availableBooks = await ddb.listBooks(config.data.cobalt, noCheck);
// logger.info(bookIds)
for (let i = 0; i < availableBooks.length; i++) {
process.stdout.write(`Downloading ${availableBooks[i].book.description}`);
await config.loadBook(availableBooks[i].bookCode);
process.stdout.write(`Download for ${availableBooks[i].book.description} complete`);
}
}
async function generateAdventure(options, returnFuncs) {
options.version = app.getVersion();
options.returns = returnFuncs;
options.configDir = configDir;
// return new Promise((resolve) => {
const config = new Config(options);
await config.loadBook(options.bookCode);
const overrides = isDevelopment
? {}
: {
templateDir: path.join(process.resourcesPath, "content", "templates")
};
const adventure = new Adventure(config, overrides);
adventure.processAdventure();
}
function checkAuth() {
return new Promise((resolve) => {
const config = new Config({configDir});
ddb.getUserData(config.data.cobalt).then((userData) => {
if (userData.error || !userData.userDisplayName) {
process.stdout.write("Authentication failure, please check your cobalt token\n");
process.exit(0);
} else {
resolve(config);
}
});
});
}
function commandLine() {
const args = pargs
.usage("./$0 <command> [options]")
.option("show-owned-books", {
alias: "o",
describe: "Show only owned books, not shared.",
})
.command("version", "Version information")
.alias("v", "version")
.command("list", "List books")
.alias("l", "list")
.command(
"download",
"Download all the book files you have access to. This does not process the book, just downloads for later use."
)
.alias("d", "download")
.command("generate", "Generate content for specified book.")
.alias("g", "generate")
.nargs("g", 1)
.command("config", "Load a config file into the importer.")
.alias("c", "config")
.nargs("c", 1)
.example(
"$0 generate lmop",
"Generate import file for Lost Mines of Phandelver"
)
.help("help")
.locale("en").argv;
return new Promise((resolve) => {
if (args["show-owned-books"]) {
process.stdout.write("Owned books mode activated\n");
allBooks = false;
}
if (args.config) {
const options = {
externalConfigFile: args.config,
configDir,
};
new Config(options);
process.stdout.write(`Loaded ${args.config}\n`);
process.exit(0);
} else if (args.list) {
checkAuth().then((config) => {
ddb.listBooks(config.data.cobalt).then((books) => {
books.forEach((book) => {
process.stdout.write(`${book.bookCode} : ${book.book.description}\n`);
});
process.exit(0);
});
});
} else if (args.download) {
checkAuth().then((config) => {
downloadBooks(config).then(() => {
process.stdout.write("Downloads finished\n");
process.exit(0);
});
});
} else if (args.generate) {
checkAuth().then(() => {
generateAdventure(args.generate);
});
} else if (args.help) {
// eslint-disable-next-line no-undef
process.stdout.write(options.help());
process.exit(0);
} else if (args.version) {
process.stdout.write(`${app.getVersion()}\n`);
process.exit(0);
} else {
resolve(true);
}
});
}
function loadMainWindow() {
commandLine();
let iconLocation = isDevelopment
? path.join(__dirname, "build", "icon.png")
: path.join(process.resourcesPath, "content", "icon.png");
mainWindow = new BrowserWindow({
width: 800,
height: 1000,
icon: iconLocation,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
},
});
// Emitted when the window is closed.
mainWindow.on("closed", function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
if (isDevelopment) {
mainWindow.webContents.openDevTools();
}
// eslint-disable-next-line no-unused-vars
ipcMain.on("loadConfig", (event, args) => {
logger.info("Loading config for UI");
dialog
.showOpenDialog(mainWindow, {
properties: ["openFile", "createDirectory"],
filters: [{ name: "JSON", extensions: ["json"] }],
})
.then((result) => {
if (!result.canceled) {
const options = {
externalConfigFile: result.filePaths[0],
configDir,
};
console.debug("Loading config", options);
const config = new Config(options);
mainWindow.webContents.send("config", config);
}
});
});
// eslint-disable-next-line no-unused-vars
ipcMain.on("outputDir", (event, args) => {
logger.info("Setting output dir for UI");
dialog
.showOpenDialog(mainWindow, {
properties: ["openDirectory", "createDirectory"],
})
.then((result) => {
if (!result.canceled) {
// options.bookCode, options.externalConfigFile, options.outputDirPath
const options = {
outputDirPath: result.filePaths[0],
configDir,
};
const config = new Config(options);
mainWindow.webContents.send("directoryConfig", config);
}
});
});
// eslint-disable-next-line no-unused-vars
ipcMain.on("books", (event, config) => {
logger.info("Fetching books for UI");
ddb.listBooks(config.data.cobalt, allBooks, config.data.ddbNoCheck).then((books) => {
books = _.orderBy(books, ["book.description"], ["asc"]);
mainWindow.webContents.send("books", books);
});
});
// eslint-disable-next-line no-unused-vars
ipcMain.on("user", (event, config) => {
logger.info("Getting User for UI");
ddb.getUserData(config.data.cobalt).then((userData) => {
mainWindow.webContents.send("user", userData);
});
});
const returnAdventure = (adventure) => {
const data = {
success: true,
message: `Successfully generated ${adventure.bookCode}.fvttadv`,
data: [],
ddbVersions: adventure.config.ddbVersions,
};
const targetAdventureZip = path.join(
adventure.config.outputDirEnv,
`${adventure.bookCode}.fvttadv`
);
logger.info(`Adventure generated to ${targetAdventureZip}`);
try {
mainWindow.webContents.send("generate", data);
} catch (err) {
logger.error(err);
logger.error(err.stack);
}
};
const statusMessage = (message) => {
try {
console.warn(message);
mainWindow.webContents.send("stateMessage", message);
} catch (err) {
logger.error(err);
logger.error(err.stack);
}
};
ipcMain.on("generate", (event, data) => {
const returnFuncs = {
returnAdventure: returnAdventure,
statusMessage: statusMessage,
};
generateAdventure(data, returnFuncs);
});
mainWindow.loadFile(path.join(__dirname, "renderer", "index.html"));
mainWindow.webContents.once("did-finish-load", () => {
logger.info("Init config to ", configDir);
const config = new Config({configDir});
mainWindow.webContents.send("config", config);
});
}
function prepare() {
commandLine().then(() => {
autoUpdater.checkForUpdatesAndNotify();
loadMainWindow();
});
}
app.on("ready", prepare);
app.on("window-all-closed", () => {
if (!isMac) {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
loadMainWindow();
}
});