-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.js
900 lines (821 loc) · 31.5 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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
var alma = require ('almarestapi-lib');
var fs = require('fs');
var pdf = require('html-pdf');
const temp = require('temp');
const {app, BrowserWindow, dialog, Menu} = require('electron');
const edge = require('electron-edge-js');
//const { printFile } = require('./lib/print');
const printer = require('node-native-printer');
const ipcMain = require('electron').ipcMain;
const log = require('electron-log');
const {autoUpdater} = require('electron-updater');
const defaultBorder = ".4" //This was the hardcoded default pre-2.0.0-beta-03
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'silly';
let timer;
let userLogFile;
let userConfigFile;
let globalLogFile;
let globalConfigFile;
let logFile = "";
let configFile;
let configSettings;
let pdfOptions;
let printOptions;
let mainWindow;
let almaPrinters;
let almaPrinterQueues;
let localPrinterList;
let almaPrinterProfiles;
let useAlmaPrinters;
let mode;
let lastAlmaPrinter = 0;
let useLandscape = false;
let useColor = false;
let useLocalPrinter;
let menuOffset = 0;
let printouts;
//For classic printing using the browser window
let printDocs;
let docIndex = 0;
let total_document_count = 0;
let notPrinting = true;
let paused = true;
let testDate = null;
let libraryHours = null;
let usingGlobalConfig = true;
const getPrinterQueues = async (type, offset) =>
await alma.getp(`/conf/printers?printout_queue=${type}&limit=100&offset=${offset}`);
const getPrintouts = async (printer_id = useAlmaPrinters, limit = 100) =>
await alma.getp(`/task-lists/printouts?status=Pending${printer_id}&limit=${limit}`);
const markAsPrinted = async id =>
await alma.postp(`/task-lists/printouts/${id}?op=mark_as_printed`, {});
const getLibraryHours = async (libraryCode, getDate) =>
await alma.getp(`/conf/libraries/${libraryCode}/open-hours?from=${getDate}&to=${getDate}`);
const viaBrowserSortPrintouts = async () => await printDocs.printout.sort ((a, b) => {
if (a.date < b.date) {
return -1;
}
})
const viaPDFSortPrintouts = async () => await printouts.printout.sort ((a, b) => {
if (a.date < b.date) {
return -1;
}
})
const htmlToPdf = html => {
const pdfFile = pdf.create(html, pdfOptions);
return new Promise( (resolve, reject) => {
pdfFile.toFile(temp.path({suffix: '.pdf'}), (err, res) => {
if (err) reject(err);
else resolve(res);
});
})
}
const printDocumentsViaBrowser = async () => {
console.log ('Entered printDocumentsViaBrowser');
clearTimeout(timer);
mainWindow.loadURL('File://' + __dirname + '\\docsRetrieving.html');
try {
printDocs = await getPrintouts();
total_record_count = printDocs.total_record_count;
docIndex = 0;
console.log ('Back from getDocuments; total_record_count = ' + total_record_count);
if (total_record_count > 0) {
viaBrowserSortPrintouts (); //GitHub issue #10
notPrinting = false;
console.log ('Load first document');
mainWindow.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(printDocs.printout[docIndex].letter));
}
else {
notPrinting = true;
if (configSettings.interval == 0) {
mainWindow.loadURL('File://' + __dirname + '\\docsPrintedManual.html');
//Don't set a timer....requests are done manually
return;
}
else {
mainWindow.loadURL('File://' + __dirname + '\\docsPrintedInterval.html');
console.log ('No docs at all..set the timer');
timer = setTimeout(getDocumentsTimerController, configSettings.interval * 60000);
}
}
}
catch (e) {
notPrinting = true;
WriteLog ('Error retrieving documents from Alma: ' + e.message + '. Will try again.');
console.log ('Error retrieving documents from Alma: ' + e.message);
if (configSettings.interval == 0) {
mainWindow.loadURL('File://' + __dirname + '\\docsRetrievalErrorManual.html');
//Don't set a timer....requests are done manually
return;
}
else {
mainWindow.loadURL('File://' + __dirname + '\\docsRetrievalErrorInterval.html');
timer = setTimeout(getDocumentsTimerController, configSettings.interval * 60000);
}
}
}
const printDocumentsViaPDF = async () => {
console.log ('Entered printDocumentsViaPDF');
clearTimeout(timer);
console.log ('Timer cleared...ready to getPrintouts');
console.log ('almaPrinters = ' + useAlmaPrinters);
if (!service) {
mainWindow.loadURL('File://' + __dirname + '\\docsRetrieving.html');
}
try {
printouts = await getPrintouts();
console.log ('Back from getPrintouts');
}
catch (e) {
WriteLog ('Service: Error retrieving documents from Alma: ' + e.message + '. Reset timer to try again.');
console.log ('set timer to get next batch of documents to print');
timer = setTimeout(getDocumentsTimerController, configSettings.interval * 60000);
return;
}
let total_record_count = printouts.total_record_count;
if (total_record_count > 0)
viaPDFSortPrintouts (); //GitHub issue #10
if (total_record_count && !service) {
mainWindow.loadURL('File://' + __dirname + '\\docsPrinting.html');
}
while (total_record_count) {
console.log ("Get Printouts number to print = " + total_record_count);
for (const printout of printouts.printout) {
try {
console.log ("Should we get local printer settings? lastAlmaPrinter = " + lastAlmaPrinter + ", next Alma Printer = " + printout.printer.value);
if (lastAlmaPrinter != printout.printer.value) {
getLocalPrinter(printout.printer.value);
}
let filename = (await htmlToPdf(printout.letter)).filename;
//await printFile(filename)
console.log ("Service printer = " + printer.getCurrentPrinter());
await printer.print (filename, printOptions)
fs.unlinkSync(filename);
WriteLog ('Printed document ' + printout.id + ' on ' + useLocalPrinter + '.' );
/* Post File */
await markAsPrinted(printout.id);
console.log('printed file', printout.id)
}
catch (e) {
WriteLog ('Service: Printing document ' + printout.id + ' failed on ' + printout.printer.value + '. Skipping to next document.' );
WriteLog ('Service: Print error ' + e.message);
console.error('Error', e);
}
}
try {
printouts = await getPrintouts();
total_record_count = printouts.total_record_count;
if (total_record_count > 0)
viaPDFSortPrintouts (); //GitHub issue #10
}
catch (e) {
WriteLog ('Service: Error retrieving documents from Alma: ' + e.message + '. Reset timer to try again.');
console.log ('set timer to get next batch of documents to print');
timer = setTimeout(getDocumentsTimerController, configSettings.interval * 60000);
return;
}
}
if (!service) {
if (configSettings.interval == 0) {
mainWindow.loadURL('File://' + __dirname + '\\docsPrintedManual.html');
//Don't set a timer....requests are done manually
return;
}
else {
mainWindow.loadURL('File://' + __dirname + '\\docsPrintedInterval.html');
}
}
console.log ('set timer to get next batch of documents to print');
timer = setTimeout(getDocumentsTimerController, configSettings.interval * 60000);
}
const getAlmaPrinters = async () => {
//Get Alma printers in groups to fix GitHub issue #35.
let nextBatch;
almaPrinterQueues = await getPrinterQueues('true', 0);
let total_alma_printers = almaPrinterQueues.total_record_count;
let current_printer_count = almaPrinterQueues.printer.length;
while (total_alma_printers > current_printer_count) {
nextBatch = await getPrinterQueues('true', current_printer_count);
for (const printer of nextBatch.printer) {
almaPrinterQueues.printer.splice(almaPrinterQueues.printer.length, 0, printer);
}
current_printer_count = current_printer_count + nextBatch.printer.length;
}
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', function() {
console.log ("app ready!!!!!");
createWindow();
})
// Main line ***************
//Set up macOS-specific stuff
const isMac = process.platform === 'darwin';
console.log ('isMac = ' + isMac);
if (isMac) {
menuOffset = 1;
}
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
console.log ("!!!!!!!!!Duplicate instance!!!!!!!!!")
app.quit();
}
else {
app.on('second-instance', (event, commandLine, workingDirectory) => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore()
mainWindow.focus()
}
})
}
console.log ('Arguments = ' + process.argv);
let setup = process.argv.indexOf('setup')==-1?false:true;
console.log ('setup = ' + setup);
let service = process.argv.indexOf('service')==-1?false:true;
console.log ('service = ' + service);
// Force service to true for testing service functionality
//service = true;
success = initConfiguration();
if (!success && !setup) {
console.log ("Config not found and no setup argument -> switch to setup!");
setup = true;
}
if (!setup) {
if (configSettings.almaPrinterProfiles == undefined) {
console.log ("Alma printer profiles not defined -> switch to setup!")
setup = true;
}
else if (configSettings.almaPrinterProfiles.length == 0) {
console.log ("Alma printer profiles length = 0 -> switch to setup!")
setup = true;
}
}
//if (setup) {
console.log ("Getting Alma Print Queues");
getAlmaPrinters();
console.log ("Back from getAlmaPrinters()");
//}
function createWindow () {
if (setup || !service) {
mainWindow = new BrowserWindow({
width: 600,
height: 625,
show: true,
title: "Alma Print Daemon 2.2.0",
webPreferences: {
//preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true
}
})
mainWindow.webContents.on('did-finish-load', () => {
if (paused || notPrinting) {
if (usingGlobalConfig && (mainWindow.title.indexOf("Using") == -1)) {
mainWindow.title = mainWindow.title + ": Using Global Configuration";
}
return;
}
console.log ('Document loaded...print it. Document id = ' + printDocs.printout[docIndex].id);
if (lastAlmaPrinter != printDocs.printout[docIndex].printer.value) {
getLocalPrinter(printDocs.printout[docIndex].printer.value);
}
mainWindow.webContents.print({silent: true, landscape: useLandscape, color: useColor, deviceName: useLocalPrinter}, (success, errorType) => {
if (!success) {
//Checking success here should work, according to Electron doc...but doesn't...at least not for "invalid deviceName" error.
console.log ('Printing document failed on ' + useLocalPrinter + ' with error ' + errorType + '. Skipping to next document.');
WriteLog ('Failed printing document on ' + useLocalPrinter + ' with error ' + errorType + '. Skipping to next document.' );
//Printing failed. Don't mark document as printed....but continue to next document; it might use a different printer that doesn't generate an error
}
else {
//Success printing...mark document as printed.
console.log ('Successfully printed document; calling markAsPrinted');
WriteLog ('Successfully printed document ' + printDocs.printout[docIndex].id + ' on ' + useLocalPrinter + '.' );
markAsPrinted(printDocs.printout[docIndex].id);
}
docIndex++;
let haveDocument = true;
if (printDocs.printout[docIndex] === undefined) {
console.log ('printDocs.printout[docIndex] undefined...stop processing batch!');
haveDocument = false;
}
if (docIndex < total_record_count && haveDocument) {
console.log ('More docs....load next one: ' + docIndex);
mainWindow.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(printDocs.printout[docIndex].letter));
}
else {
notPrinting = true;
if (configSettings.interval == 0) {
mainWindow.loadURL('File://' + __dirname + '\\docsPrintedManual.html');
//Don't set a timer....requests are done manually
return;
}
else {
mainWindow.loadURL('File://' + __dirname + '\\docsPrintedInterval.html');
console.log ('No more docs...set the timer');
timer = setTimeout(getDocumentsTimerController, configSettings.interval * 60000);
}
}
})
})
//mainWindow.webContents.openDevTools();
if (setup) {
WriteLog ('Started with SETUP parameter....create mainWindow');
//WriteLog ('Try to load configWindow.html');
mainWindow.loadURL('File://' + __dirname + '\\configWindow.html');
//WriteLog ('After trying to load configWindow.html');
localPrinterList = mainWindow.webContents.getPrinters();
//console.log (localPrinterList);
mainWindow.webContents.on('did-finish-load', () => {
//console.log ('did-finish-load for configWindow');
//console.log ('Send saved settings to configWindow');
mainWindow.webContents.send('send-settings', configSettings);
//console.log ('Send local printers to configWindow');
mainWindow.webContents.send('local-printers', localPrinterList);
//console.log ('Send alma printers to configWindow');
//console.log (almaPrinterQueues);
mainWindow.webContents.send('alma-printers', almaPrinterQueues);
})
}
else if (!service) {
//If manual requesting...
if (configSettings.interval == 0) {
mainWindow.loadURL('File://' + __dirname + '\\docsPrintedManual.html');
}
else {
//If autoStart enabled, start printing
if (configSettings.autoStart == 'true') {
console.log ("Start printing since autoStart = true");
paused = false;
printDocumentsViaBrowser();
}
else {
//Wait for user to start printing
console.log ("Start in paused mode since autoStart = false");
paused = true;
mainWindow.loadURL('File://' + __dirname + '\\docsPrintIntervalPaused.html');
}
}
}
setMenus();
mainWindow.on('close', () => {
app.quit();
})
}
else {
console.log ("Start printing as a service");
//If the interval isn't set, set it to default of 2 minutes
if (configSettings.interval == 0) {
configSettings.interval = 2;
}
printDocumentsViaPDF();
}
}
//Function to control getting documents when the timer hits
const getDocumentsTimerController = async () => {
let daemonActive = true;
console.log ('Timer triggered');
//libraryOpen = await checkLibraryHours();
daemonActive = checkActiveHours();
if (daemonActive) {
if (service)
printDocumentsViaPDF();
else
printDocumentsViaBrowser();
} else {
console.log ('Not during active hours...set timer');
timer = setTimeout(getDocumentsTimerController, configSettings.interval * 60000);
if (!service) {
mainWindow.loadURL('File://' + __dirname + '\\docsPrintSleeping.html');
}
}
}
function checkActiveHours() {
var currentdate = new Date();
let timePad = currentdate.getHours() < 10 ? '0' : '';
let timePad2 = currentdate.getMinutes() < 10 ? '0' : '';
var checkTime = timePad + currentdate.getHours() + ":"
+ timePad2 + currentdate.getMinutes();
if (checkTime >= configSettings.fromTime && checkTime <= configSettings.untilTime) {
console.log ('Daemon active time!');
return true;
} else {
console.log ('Daemon inactive time!');
return false;
}
}
const checkLibraryHours = async () => {
//Check date and time to see if library is open. If not, do not bother requesting documents.
var currentdate = new Date();
let monthPad = currentdate.getMonth()+1 < 10 ? '0' : '';
let datePad = currentdate.getDate() < 10 ? '0' : '';
var checkDate = currentdate.getFullYear() + "-"
+ monthPad + (currentdate.getMonth() + 1 ) + "-"
+ datePad + currentdate.getDate();
let timePad = currentdate.getHours() < 10 ? '0' : '';
let timePad2 = currentdate.getMinutes() < 10 ? '0' : '';
var checkTime = timePad + currentdate.getHours() + ":"
+ timePad2 + currentdate.getMinutes();
if (testDate !== checkDate) {
libraryHours = await getLibraryHours('MAIN', checkDate);
console.log ('Library hours: ' + JSON.stringify(libraryHours));
testDate = checkDate;
}
for (let i = 0; i < libraryHours.day[0].hour.length; i++) {
if (checkTime >= libraryHours.day[0].hour[i].from && checkTime <= libraryHours.day[0].hour[i].to) {
console.log ('Library is open!');
return true;
} else{
console.log ('Library is closed!');
return false;
}
}
//If we got here, assume no library hours set and library is open
return true;
}
//Function to read config file and set options accordingly
function initConfiguration() {
let configExists = true;
let configData;
let d = new Date();
let year, month, day;
year = d.getUTCFullYear();
month = ('0' + (d.getUTCMonth() + 1)).slice(-2);
day = ('0' + d.getUTCDate()).slice(-2);
//Check for global configuration file
globalConfigFile = app.getPath("exe");
let lastSlash = globalConfigFile.lastIndexOf("\\");
globalConfigFile = globalConfigFile.substring(0, lastSlash);
globalConfigFile = globalConfigFile + "\\globalConfiguration.json";
console.log ("Checking for global configuration file: " + globalConfigFile);
try {
let globalConfigData = fs.readFileSync(globalConfigFile);
const globalConfigJSON = globalConfigData.toString('utf8');
let globalConfigSettings = JSON.parse(globalConfigJSON);
globalConfigFile = globalConfigSettings.globalConfigPath;
globalLogPath = globalConfigFile;
globalConfigFile = globalConfigFile + "\\alma-print-config.json"
globalLogFile = globalLogPath + "\\alma-print-daemon." + year + "-" + month + "-" + day + '.log';
console.log ('Looks like we think we have a global configuration.');
console.log ('globalConfigFile: ' + globalConfigFile);
console.log ('globalLogFile: ' + globalLogFile);
}
catch (e) {
usingGlobalConfig = false;
globalConfigFile = "";
globalConfigPath = "";
}
userConfigFile = app.getPath("userData") + "\\alma-print-config.json";
userLogFile = app.getPath("userData") + "\\alma-print-daemon." + year + "-" + month + "-" + day + '.log';
try {
logFile = globalLogFile;
//See if global config exists
configData = fs.readFileSync(globalConfigFile);
configFile = globalConfigFile;
}
catch (e) {
usingGlobalConfig = false;
logFile = userLogFile;
//No global config....check if user config
try {
configData = fs.readFileSync(userConfigFile);
configFile = userConfigFile;
}
//No user config....force configuration
catch (ee) {
configFile = userConfigFile; //assume user config
configExists = false;
configData = "{\"region\": \"ap\",\"apiKey\": \"\",\"interval\": \"5\",\"autoStart\": \"false\",\"almaPrinterProfiles\": []}";
configSettings = JSON.parse(configData);
let message = 'Please set your configuration options in ' + configFile;
WriteLog(message);
return false;
//app.quit();
}
}
WriteLog ('Global config file: ' + globalConfigFile);
WriteLog ('User config file: ' + userConfigFile);
WriteLog ('Global log file: ' + globalLogFile);
WriteLog ('User log file: ' + userLogFile);
WriteLog ('Using global config = ' + usingGlobalConfig);
WriteLog ('Using config file ' + configFile);
WriteLog ('Using log file: ' + logFile);
if (configExists) {
const configJSON = configData.toString('utf8');
configSettings = JSON.parse(configJSON);
if (configSettings["almaPrinter"]) {
console.log ('Config file must be converted!');
convertConfigFile(configJSON);
console.log ("Back from converting config file");
fs.writeFileSync(configFile, JSON.stringify(configSettings));
configData = fs.readFileSync(configFile);
}
else {
console.log ('Config file already converted!');
}
if (configSettings.fromTime == undefined)
configSettings.fromTime = "00:00";
if (configSettings.untilTime == undefined)
configSettings.untilTime = "24:00"
console.log('Region = ' + configSettings.region);
console.log('API Key = ' + configSettings.apiKey);
console.log('Interval = ' + configSettings.interval);
console.log('Auto Start = ' + configSettings.autoStart);
console.log('Print Daemon Active Hours = ' + configSettings.fromTime + ' to ' + configSettings.untilTime);
console.log('Alma Printer Profiles = ' + JSON.stringify(configSettings.almaPrinterProfiles));
console.log ('Writing config values to log');
let d = new Date();
WriteLog ('******************************************************');
WriteLog ('Alma Print Daemon/Service startup at ' + d.toISOString() + '.');
WriteLog ('Configuration Parameters:');
WriteLog ('Region = ' + configSettings.region);
//WriteLog ('API Key = ' + configSettings.apiKey);
WriteLog ('API Key = hidden');
WriteLog ('Interval (minutes) = ' + configSettings.interval);
WriteLog('Auto Start = ' + configSettings.autoStart);
WriteLog('Print Daemon Active Hours = ' + configSettings.fromTime + ' to ' + configSettings.untilTime);
WriteLog('Alma Printer Profiles = ' + JSON.stringify(configSettings.almaPrinterProfiles));
//printer.setPrinter(configSettings.localPrinter);
printer.setPrinter('Microsoft Print to PDF');
//printer.setPrinter('Generic / Text Only');
if (configSettings.almaPrinterProfiles.length > 0) {
useAlmaPrinters = '&printer_id=';
for (let i = 0; i < configSettings.almaPrinterProfiles.length; i++) {
if (i > 0) {
useAlmaPrinters = useAlmaPrinters + ","
}
useAlmaPrinters = useAlmaPrinters + configSettings.almaPrinterProfiles[i].almaPrinter;
}
}
process.env.ALMA_APIKEY = configSettings.apiKey;
process.env.ALMA_APIPATH = 'https://api-' + configSettings.region + '.hosted.exlibrisgroup.com/almaws/v1';
//WriteLog ("from initConfiguration, setting API_KEY = " + process.env.ALMA_APIKEY);
//WriteLog ("from initConfiguration, setting APIPATH = " + process.env.ALMA_APIPATH);
alma.setOptions (process.env.ALMA_APIKEY, process.env.ALMA_APIPATH);
return true;
}
else {
return false;
//WriteLog ('Alma Print Service configuration file does not exist; writing base config. Please edit with correct values.');
configData = "{\"region\": \"enter region here\",\"apiKey\": \"enter APIKEY here\",\"almaPrinter\": \"enter Alma Printer IDs here\",\"localPrinter\": \"enter local printer name here\",\"interval\": \"10\",\"orientation\": \"portrait\",\"tempDir\": \"c:\\\\temp\",\"batchSize\": \"100\"}";
fs.writeFileSync(configFile, configData);
}
}
//Function to write log messages
function WriteLog(message) {
let d = new Date();
try {
fs.appendFileSync(logFile, d.toISOString() + ": " + message + "\n");
}
catch (e) {
let options = {
type: 'error',
buttons: ['OK'],
title: 'Could not write to log',
};
options.message = 'An error occurred trying to write to the log file.\r\n' + e.message;
if (!service) {
//alert ('An error occurred trying to write to the log file.\r\n' + e.message);
}
}
}
//Catch 'save-settings' from renderer
ipcMain.on('save-settings', function(e, configString){
console.log ('from renderer: user saved settings = ' + configString);
// Write JSON Alma config file
try {
fs.writeFileSync(configFile, configString);
}
catch (e) {
let options = {
type: 'error',
buttons: ['OK'],
title: 'Save Configuration Error',
};
options.message = 'An error occurred trying to save the configuration.\r\nYou most likely do not have permissions.\r\nReverting to previous settings.\r\n' + e.message;
dialog.showMessageBox (mainWindow, options);
}
//configWindow.close();
//Reset last Alma Printer used as settings for that printer may have changed
lastAlmaPrinter = 0;
// quit and relaunch app to make new settings effective
//app.relaunch();
//app.quit();
//Reload configuration
initConfiguration();
if (almaPrinterQueues == undefined) {
console.log ('Just saved settings - get alma printer queues, if necessary');
getAlmaPrinters();
}
setup = false;
//...and resume printing
if (configSettings.interval == 0) {
mainWindow.loadURL('File://' + __dirname + '\\docsPrintedManual.html');
}
else {
getDocumentsTimerController();
//if (service)
// printDocumentsViaPDF();
//else
// printDocumentsViaBrowser();
}
})
//Catch "Print now" from renderer
ipcMain.on('print-now', function (e){
console.log('from renderer: user clicked print now');
paused = false;
//Has a UI, so print via browser
printDocumentsViaBrowser(0);
})
//Catch "Continue printing" from renderer
ipcMain.on('print-continue', function(e) {
console.log('from renderer: user clicked continue printing');
setup = false;
paused = false;
//Has a UI, so print via browser
getDocumentsTimerController();
//printDocumentsViaBrowser();
})
//Catch "Pause printing" from renderer
ipcMain.on('print-pause', function (e){
console.log('from renderer: user clicked pause printing');
//clear the timer since user has paused printing
clearTimeout (timer);
paused = true;
mainWindow.loadURL('File://' + __dirname + '\\docsPrintIntervalPaused.html');
})
ipcMain.on('display-config', function (e){
displayConfigPage();
})
ipcMain.on('check-for-update', function (e){
checkForSoftwareUpdate();
})
ipcMain.on('restart_app', () => {
autoUpdater.quitAndInstall();
});
autoUpdater.on('update-available', () => {
mainWindow.webContents.send('update_available');
});
autoUpdater.on('update-downloaded', () => {
mainWindow.webContents.send('update_downloaded');
});
autoUpdater.on('update-not-available', () => {
mainWindow.webContents.send('update_not_available');
});
function getLocalPrinter(almaPrinter) {
let i, pageOptions;
console.log ("in getLocalPrinter");
//Save last Alma printer so we don't come here to get local printer settings for each document if not necessary
lastAlmaPrinter = almaPrinter;
for (i = 0; configSettings.almaPrinterProfiles.length; i++) {
if (configSettings.almaPrinterProfiles[i].almaPrinter == almaPrinter) {
useColor = configSettings.almaPrinterProfiles[i].color == 'true'?true:false;
useLocalPrinter = decodeURIComponent(configSettings.almaPrinterProfiles[i].localPrinter);
if (configSettings.almaPrinterProfiles[i].orientation == "landscape") {
useLandscape = true;
}
else {
useLandscape = false;
}
break;
}
}
let letterFormat, borderUnits, borderTop, borderRight, borderBottom, borderLeft, customHeight, customWidth;
if (configSettings.almaPrinterProfiles[i].letterFormat == undefined)
letterFormat = 'Letter';
else
letterFormat = configSettings.almaPrinterProfiles[i].letterFormat;
if (configSettings.almaPrinterProfiles[i].borderUnits == undefined)
borderUnits = "in";
else
borderUnits = configSettings.almaPrinterProfiles[i].borderUnits;
borderTop = setBorderValue(configSettings.almaPrinterProfiles[i].borderTop) + borderUnits;
borderRight = setBorderValue(configSettings.almaPrinterProfiles[i].borderRight) + borderUnits;
borderBottom = setBorderValue(configSettings.almaPrinterProfiles[i].borderBottom) + borderUnits;
borderLeft = setBorderValue(configSettings.almaPrinterProfiles[i].borderLeft) + borderUnits;
customHeight = configSettings.almaPrinterProfiles[i].pageHeight + borderUnits;
customWidth = configSettings.almaPrinterProfiles[i].pageWidth + borderUnits;
if (letterFormat == 'Custom')
pdfOptions = {
height: customHeight,
width: customWidth,
border: {
top: borderTop,
right: borderRight,
bottom: borderBottom,
left: borderLeft
},
script: 'lib\\pdf_a4_portrait.js',
phantomPath: 'lib\\phantomjs.exe'
};
else
pdfOptions = {
format: letterFormat,
orientation: configSettings.almaPrinterProfiles[i].orientations,
border: {
top: borderTop,
right: borderRight,
bottom: borderBottom,
left: borderLeft
},
script: 'lib\\pdf_a4_portrait.js',
phantomPath: 'lib\\phantomjs.exe'
};
console.log ('pdfOptions = ' + JSON.stringify(pdfOptions));
printOptions = {
"landscape": useLandscape,
"color": useColor
}
printer.setPrinter (useLocalPrinter);
console.log ("Local printer settings: useLandscape = " + useLandscape + " useColor = " + useColor + " useLocalPrinter = " + useLocalPrinter);
}
function setBorderValue (value) {
if (value == undefined)
return defaultBorder;
else if (isNaN(value))
return defaultBorder;
else
return value;
}
function displayConfigPage() {
//clear timer so request isn't trigered.
clearTimeout(timer);
//switch to SETUP mode
setup = true;
//WriteLog ('Try to load configWindow.html');
mainWindow.loadURL('File://' + __dirname + '\\configWindow.html');
//WriteLog ('After trying to load configWindow.html');
localPrinterList = mainWindow.webContents.getPrinters();
//console.log (localPrinterList);
mainWindow.webContents.on('did-finish-load', () => {
if (setup) {
//console.log ('did-finish-load for configWindow');
//console.log ('Send saved settings to configWindow');
mainWindow.webContents.send('send-settings', configSettings);
//console.log ('Send local printers to configWindow');
mainWindow.webContents.send('local-printers', localPrinterList);
//console.log ('Send alma printers to configWindow');
//WriteLog('In displayConfigPage, on-did-finish-load, sending Alma Printer Queues = ' + JSON.stringify(almaPrinterQueues));
mainWindow.webContents.send('alma-printers', almaPrinterQueues);
mainWindow.webContents.send('global-config-flag', usingGlobalConfig);
}
})
}
function checkForSoftwareUpdate() {
autoUpdater.allowPrerelease = false;
autoUpdater.checkForUpdatesAndNotify();
}
function convertConfigFile() {
var jsonPrinterProfileObj;
var almaPrinterProfiles = [];
for (let i = 0; i < configSettings.almaPrinter.length; i++) {
//Build Alma Printer Profile for each almaPrinter
jsonPrinterProfileObj = {almaPrinter: configSettings.almaPrinter[i], localPrinter: configSettings.localPrinter, orientation: configSettings.orientation, color: "true"};
almaPrinterProfiles[i] = jsonPrinterProfileObj;
}
delete configSettings['almaPrinter'];
delete configSettings['localPrinter'];
delete configSettings['orientation'];
configSettings.almaPrinterProfiles = almaPrinterProfiles;
console.log ("New config file = " + JSON.stringify(configSettings));
}
function setMenus(){
console.log ('in setMenus');
if (isMac) {
mainMenuTemplate.unshift ({
label: app.name,
submenu: [
{role: 'about'},
{type: 'separator'},
{role: 'services', submenu: []},
{type: 'separator'},
{role: 'hide'},
{role: 'hideothers'},
{role: 'unhide'},
{type: 'separator'},
{role: 'quit'}
]
})
}
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
Menu.setApplicationMenu (mainMenu);
}
const mainMenuTemplate = [
{
label:'File',
visible: true,
submenu:[
{
label: 'Exit',
accelerator: process.platform == 'darwin' ? 'Command+Q' : 'Alt+F4',
click(){
app.quit();
}
}
],
},
{
label: 'Edit',
role: 'editMenu'
}
]