-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
475 lines (273 loc) · 11.5 KB
/
index.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
/****************************************************************************
* index.js
* openacousticdevices.info
* February 2021
*****************************************************************************/
'use strict';
/* global document */
const electron = require('electron');
const { dialog, getCurrentWindow } = require('@electron/remote');
const nightMode = require('./nightMode.js');
const versionChecker = require('./versionChecker.js');
const uiOutput = require('./uiOutput');
const path = require('path');
const fs = require('fs');
const audiomothUtils = require('audiomoth-utils');
var currentWindow = getCurrentWindow();
const selectionRadios = document.getElementsByName('selection-radio');
const prefixCheckbox = document.getElementById('prefix-checkbox');
const prefixInput = document.getElementById('prefix-input');
const synced192Checkbox = document.getElementById('synced-192-checkbox');
const autoResolveCheckbox = document.getElementById('auto-resolve-checkbox');
const fileLabel = document.getElementById('file-label');
const fileButton = document.getElementById('file-button');
const syncButton = document.getElementById('sync-button');
var files = [];
var syncing = false;
const RESAMPLE_RATE = 192000;
const DEFAULT_SLEEP_AMOUNT = 2000;
function getSelectedRadioValue (radioName) {
return parseInt(document.querySelector('input[name="' + radioName + '"]:checked').value);
}
electron.ipcRenderer.on('night-mode', (e, nm) => {
if (nm !== undefined) {
nightMode.setNightMode(nm);
} else {
nightMode.toggle();
}
});
electron.ipcRenderer.on('poll-night-mode', function () {
electron.ipcRenderer.send('night-mode-poll-reply', nightMode.isEnabled());
});
/* Pause execution */
function sleep (milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
/* Update text on selection button to reflect selection mode (file or folder selection) */
function updateButtonText () {
const selectionType = getSelectedRadioValue('selection-radio');
if (selectionType === 0) {
fileButton.innerText = 'Select Files';
} else {
fileButton.innerText = 'Select Folders';
}
}
/* Disable UI elements in main window while progress bar is open and sync is in progress */
function disableUI () {
fileButton.disabled = true;
syncButton.disabled = true;
selectionRadios[0].disabled = true;
selectionRadios[1].disabled = true;
synced192Checkbox.disabled = true;
autoResolveCheckbox.disabled = true;
uiOutput.disableOutputCheckbox();
uiOutput.disableOutputButton();
prefixCheckbox.disabled = true;
prefixInput.disabled = true;
}
function enableUI () {
fileButton.disabled = false;
syncButton.disabled = false;
selectionRadios[0].disabled = false;
selectionRadios[1].disabled = false;
synced192Checkbox.disabled = false;
autoResolveCheckbox.disabled = false;
uiOutput.enableOutputCheckbox();
uiOutput.enableOutputButton();
prefixCheckbox.disabled = false;
if (prefixCheckbox.checked) {
prefixInput.disabled = false;
}
syncing = false;
}
/* Sync selected files */
function syncFiles () {
if (!files) {
return;
}
let successCount = 0;
let errorCount = 0;
const errors = [];
const errorFiles = [];
let errorFilePath;
let sleepAmount = DEFAULT_SLEEP_AMOUNT;
let successesWithoutError = 0;
const unwrittenErrors = [];
let lastErrorWrite = -1;
let errorFileStream;
for (let i = 0; i < files.length; i++) {
/* If progress bar is closed, the sync task is considered cancelled. This will contact the main thread and ask if that has happened */
const cancelled = electron.ipcRenderer.sendSync('poll-sync-cancelled');
if (cancelled) {
console.log('Sync cancelled.');
enableUI();
return;
}
/* Let the main thread know what value to set the progress bar to */
electron.ipcRenderer.send('set-sync-bar-progress', i, 0);
console.log('Syncing:', files[i]);
console.log('-');
/* Check if the optional prefix/output directory setttings are being used. If left as null, syncer will put file(s) in the same directory as the input with no prefix */
let outputPath = null;
if (uiOutput.isCustomDestinationEnabled()) {
outputPath = uiOutput.getOutputDir();
if (uiOutput.isCreateSubdirectoriesEnabled() && selectionRadios[1].checked) {
const dirnames = path.dirname(files[i]).replace(/\\/g, '/').split('/');
const folderName = dirnames[dirnames.length - 1];
outputPath = path.join(outputPath, folderName);
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath);
}
}
}
const prefix = (prefixCheckbox.checked && prefixInput.value !== '') ? prefixInput.value : null;
const resample = synced192Checkbox.checked;
const autoResolve = autoResolveCheckbox.checked;
const response = audiomothUtils.sync(files[i], outputPath, prefix, resample ? RESAMPLE_RATE : null, autoResolve, (progress) => {
electron.ipcRenderer.send('set-sync-bar-progress', i, progress);
electron.ipcRenderer.send('set-sync-bar-file', i, path.basename(files[i]));
});
if (response.success) {
successCount++;
successesWithoutError++;
if (successesWithoutError >= 10) {
sleepAmount = DEFAULT_SLEEP_AMOUNT;
}
} else {
/* Add error to log file */
unwrittenErrors.push(errorCount);
successesWithoutError = 0;
errorCount++;
errors.push(response.error);
errorFiles.push(files[i]);
electron.ipcRenderer.send('set-sync-bar-error', path.basename(files[i]));
if (errorCount === 1) {
const errorFileLocation = uiOutput.isCustomDestinationEnabled() ? uiOutput.getOutputDir() : path.dirname(errorFiles[0]);
errorFilePath = path.join(errorFileLocation, 'ERRORS.TXT');
errorFileStream = fs.createWriteStream(errorFilePath, {flags: 'a'});
errorFileStream.write('-- Sync --\n');
}
const currentTime = new Date();
const timeSinceLastErrorWrite = currentTime - lastErrorWrite;
if (timeSinceLastErrorWrite > 1000 || lastErrorWrite === -1) {
lastErrorWrite = new Date();
const unwrittenErrorCount = unwrittenErrors.length;
console.log('Writing', unwrittenErrorCount, 'errors');
let fileContent = '';
for (let e = 0; e < unwrittenErrorCount; e++) {
const unwrittenErrorIndex = unwrittenErrors.pop();
fileContent += path.basename(errorFiles[unwrittenErrorIndex]) + ' - ' + errors[unwrittenErrorIndex] + '\n';
}
try {
errorFileStream.write(fileContent);
console.log('Error summary written to ' + errorFilePath);
} catch (err) {
console.error(err);
electron.ipcRenderer.send('set-sync-bar-completed', successCount, errorCount, true);
return;
}
}
sleep(sleepAmount);
sleepAmount = sleepAmount / 2;
}
}
/* If any errors occurred, do a final error write */
const unwrittenErrorCount = unwrittenErrors.length;
if (unwrittenErrorCount > 0) {
console.log('Writing remaining', unwrittenErrorCount, 'errors');
let fileContent = '';
for (let e = 0; e < unwrittenErrorCount; e++) {
const unwrittenErrorIndex = unwrittenErrors.pop();
fileContent += path.basename(errorFiles[unwrittenErrorIndex]) + ' - ' + errors[unwrittenErrorIndex] + '\n';
}
try {
errorFileStream.write(fileContent);
console.log('Error summary written to ' + errorFilePath);
errorFileStream.end();
} catch (err) {
console.error(err);
electron.ipcRenderer.send('set-sync-bar-completed', successCount, errorCount, true);
return;
}
}
/* Notify main thread that sync is complete so progress bar is closed */
electron.ipcRenderer.send('set-sync-bar-completed', successCount, errorCount, false);
}
/* When the progress bar is complete and the summary window at the end has been displayed for a fixed amount of time, it will close and this re-enables the UI */
electron.ipcRenderer.on('sync-summary-closed', enableUI);
/* Update label to reflect new file/folder selection */
function updateInputDirectoryDisplay (directoryArray) {
if (directoryArray.length === 0 || !directoryArray) {
fileLabel.innerHTML = 'No AudioMoth WAV files selected.';
syncButton.disabled = true;
} else {
fileLabel.innerHTML = 'Found ';
fileLabel.innerHTML += directoryArray.length + ' AudioMoth WAV file';
fileLabel.innerHTML += (directoryArray.length === 1 ? '' : 's');
fileLabel.innerHTML += '.';
syncButton.disabled = false;
}
}
/* Reset UI back to default state, clearing the selected files */
function resetUI () {
files = [];
fileLabel.innerHTML = 'No AudioMoth WAV files selected.';
syncButton.disabled = true;
updateButtonText();
}
/* Whenever the file/folder radio button changes, reset the UI */
selectionRadios[0].addEventListener('change', resetUI);
selectionRadios[1].addEventListener('change', resetUI);
/* Select/process file(s) buttons */
fileButton.addEventListener('click', () => {
const fileRegex = audiomothUtils.getFilenameRegex(audiomothUtils.SYNC);
files = uiOutput.selectRecordings(fileRegex);
if (files !== undefined) {
updateInputDirectoryDisplay(files);
updateButtonText();
}
});
syncButton.addEventListener('click', () => {
if (syncing) {
return;
}
syncing = true;
disableUI();
electron.ipcRenderer.send('start-sync-bar', files.length);
setTimeout(syncFiles, 2000);
});
electron.ipcRenderer.on('update-check', function () {
versionChecker.checkLatestRelease(function (response) {
if (response.error) {
console.error(response.error);
dialog.showMessageBox(currentWindow, {
type: 'error',
title: 'Failed to check for updates',
message: response.error
});
return;
}
if (response.updateNeeded === false) {
dialog.showMessageBox(currentWindow, {
type: 'info',
buttons: ['OK'],
title: 'Update not needed',
message: 'Your app is on the latest version (' + response.latestVersion + ').'
});
return;
}
const buttonIndex = dialog.showMessageBoxSync({
type: 'warning',
buttons: ['Yes', 'No'],
title: 'Download newer version',
message: 'A newer version of this app is available (' + response.latestVersion + '), would you like to download it?'
});
if (buttonIndex === 0) {
electron.shell.openExternal('https://www.openacousticdevices.info/gps-sync');
}
});
});