forked from sircharlo/meeting-media-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmedia-updater.js
2114 lines (2109 loc) · 110 KB
/
media-updater.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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fadeDelay = 200,
axios = require("axios"),
escape = require("escape-html"),
i18n = require("i18n"),
log = {
debug: function() {
let now = + new Date();
if (!logOutput.debug[now]) logOutput.debug[now] = [];
logOutput.debug[now].push(arguments);
if (logLevel == "debug") console.log.apply(console,arguments);
},
error: function() {
let now = + new Date();
if (!logOutput.error[now]) logOutput.error[now] = [];
logOutput.error[now].push(arguments);
console.error.apply(console,arguments);
},
info: function() {
let now = + new Date();
if (!logOutput.info[now]) logOutput.info[now] = [];
logOutput.info[now].push(arguments);
console.info.apply(console,arguments);
},
warn: function() {
let now = + new Date();
if (!logOutput.warn[now]) logOutput.warn[now] = [];
logOutput.warn[now].push(arguments);
console.warn.apply(console,arguments);
},
},
net = require("net"),
os = require("os"),
path = require("path"),
remote = require("@electron/remote"),
{shell} = require("electron"),
$ = require("jquery");
function checkInternet(online) {
if (online) {
overlay(true, "cog fa-spin");
require("electron").ipcRenderer.send("autoUpdate");
} else {
overlay(true, "wifi", "circle-notch fa-spin text-danger");
setTimeout(updateOnlineStatus, 4000);
}
}
i18n.configure({
directory: path.join(__dirname, "locales"),
defaultLocale: "en",
updateFiles: false,
retryInDefaultLocale: true
});
const updateOnlineStatus = async () => checkInternet((await isReachable("www.jw.org", 443)));
updateOnlineStatus();
require("electron").ipcRenderer.on("overlay", (event, message) => overlay(true, message[0], message[1]));
require("electron").ipcRenderer.on("macUpdate", () => {
$("#bg-mac-update").fadeIn(fadeDelay);
$("#btn-settings").addClass("in-danger");
$("#version").addClass("btn-danger in-danger").removeClass("btn-light").find("i").remove().end().prepend("<i class='fas fa-hand-point-right'></i> ").append(" <i class='fas fa-hand-point-left'></i>").click(function() {
shell.openExternal("https://github.com/sircharlo/jw-meeting-media-fetcher/releases/latest");
});
});
require("electron").ipcRenderer.on("goAhead", () => {
goAhead();
});
const aspect = require("aspectratio"),
bootstrap = require("bootstrap"),
currentAppVersion = "v" + remote.app.getVersion(),
dayjs = require("dayjs"),
ffmpeg = require("fluent-ffmpeg"),
fs = require("graceful-fs"),
fullHd = [1920, 1080],
glob = require("glob"),
isImage = require("is-image"),
isVideo = require("is-video"),
hme = require("h264-mp4-encoder"),
datetime = require("flatpickr"),
sizeOf = require("image-size"),
sqljs = require("sql.js"),
v8 = require("v8"),
{XMLParser} = require("fast-xml-parser"),
zipper = require("adm-zip");
const bugUrl = () => "https://github.com/sircharlo/jw-meeting-media-fetcher/issues/new?labels=bug,from-app&title=ISSUE DESCRIPTION HERE&body=" + encodeURIComponent("### Describe the bug\nA clear and concise description of what the bug is.\n\n### To Reproduce\nSteps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Do '....'\n4. See error\n\n### Expected behavior\nA clear and concise description of what you expected to happen.\n\n### Screenshots\nIf possible, add screenshots to help explain your problem.\n\n### System specs\n- " + os.type() + " " + os.release() + "\n- JWMMF v" + remote.app.getVersion() + "\n\n### Additional context\nAdd any other context about the problem here.\n" + (prefs ? "\n### Anonymized `prefs.json`\n```\n" + JSON.stringify(Object.fromEntries(Object.entries(prefs).map(entry => {
if ((entry[0].startsWith("congServer") || entry[0] == "localOutputPath") && entry[1]) entry[1] = "***";
return entry;
})), null, 2) + "\n```" : "") + (logOutput.error && logOutput.error.length >0 ? "\n### Full error log\n```\n" + JSON.stringify(logOutput.error, null, 2) + "\n```" : "") + "\n").replace(/\n/g, "%0D%0A");
dayjs.extend(require("dayjs/plugin/isoWeek"));
dayjs.extend(require("dayjs/plugin/isBetween"));
dayjs.extend(require("dayjs/plugin/isSameOrBefore"));
dayjs.extend(require("dayjs/plugin/customParseFormat"));
dayjs.extend(require("dayjs/plugin/duration"));
var baseDate = dayjs().startOf("isoWeek"),
cancelSync = false,
currentStep,
datepickers,
downloadStats = {},
dryrun = false,
ffmpegIsSetup = false,
jsonLangs = {},
jwpubDbs = {},
logLevel = "info",
logOutput = {
error: {},
warn: {},
info: {},
debug: {}
},
meetingMedia,
modal = new bootstrap.Modal(document.getElementById("staticBackdrop"), {
backdrop: "static",
keyboard: false
}),
now = dayjs().hour(0).minute(0).second(0).millisecond(0),
paths = {
app: remote.app.getPath("userData")
},
pendingMusicFadeOut = {},
perfStats = {},
prefs = {},
tempMediaArray = [],
totals = {},
webdavIsAGo = false,
stayAlive;
paths.langs = path.join(paths.app, "langs.json");
paths.lastRunVersion = path.join(paths.app, "lastRunVersion.json");
paths.prefs = path.join(paths.app, "prefs.json");
datepickers = datetime(".timePicker", {
enableTime: true,
noCalendar: true,
dateFormat: "H:i",
time_24hr: true,
minuteIncrement: 15,
minTime: "06:00",
maxTime: "22:00",
onClose: function() {
var initiatorEl = $($(this)[0].element);
$("#" + initiatorEl.data("target")).val(initiatorEl.val()).change();
}
});
function goAhead() {
if (fs.existsSync(paths.prefs)) {
try {
prefs = JSON.parse(fs.readFileSync(paths.prefs));
} catch (err) {
notifyUser("error", "errorInvalidPrefs", null, true, err, true);
}
prefsInitialize();
}
getInitialData();
dateFormatter();
$("#overlaySettings input:not(.timePicker), #overlaySettings select").on("change", function() {
if ($(this).prop("tagName") == "INPUT") {
if ($(this).prop("type") == "checkbox") {
prefs[$(this).prop("id")] = $(this).prop("checked");
} else if ($(this).prop("type") == "radio") {
prefs[$(this).closest("div").prop("id")] = $(this).closest("div").find("input:checked").val();
} else if ($(this).prop("type") == "text" || $(this).prop("type") == "password" || $(this).prop("type") == "hidden" || $(this).prop("type") == "range") {
prefs[$(this).prop("id")] = $(this).val();
}
} else if ($(this).prop("tagName") == "SELECT") {
prefs[$(this).prop("id")] = $(this).find("option:selected").val();
}
if ($(this).prop("id") == "congServer" && $(this).val() == "") $("#congServerPort, #congServerUser, #congServerPass, #congServerDir, #webdavFolderList").val("").empty().change();
if ($(this).prop("id").includes("cong")) webdavSetup();
if ($(this).prop("id") == "localAppLang") setAppLang();
if ($(this).prop("id") == "lang") setMediaLang();
if ($(this).prop("id").includes("cong") || $(this).prop("name").includes("Day")) {
rm([paths.media]);
$(".alertIndicators i").addClass("far fa-circle").removeClass("fas fa-check-circle");
}
validateConfig(true);
});
}
function additionalMedia() {
perf("additionalMedia", "start");
currentStep = "additionalMedia";
return new Promise((resolve)=>{
$("#chooseMeeting").empty();
for (var meeting of [prefs.mwDay, prefs.weDay]) {
let meetingDate = baseDate.add(meeting, "d").format("YYYY-MM-DD");
$("#chooseMeeting").append("<input type='radio' class='btn-check' name='chooseMeeting' id='" + meetingDate + "' autocomplete='off'><label class='btn btn-outline-dark' for='" + meetingDate + "'" + (Object.prototype.hasOwnProperty.call(meetingMedia, meetingDate) ? "" : " style='display: none;'") + ">" + meetingDate + "</label>");
}
$(".relatedToUpload, .relatedToUploadType").fadeTo(fadeDelay, 0);
$("#btnCancelUpload").fadeOut(fadeDelay);
$("#btnDoneUpload").unbind("click").on("click", function() {
toggleScreen("overlayUploadFile");
$("#chooseMeeting input:checked, #chooseUploadType input:checked").prop("checked", false);
$("#fileList, #filePicker, #jwpubPicker, .enterPrefixInput").val("").empty().change();
$("#chooseMeeting .active, #chooseUploadType .active").removeClass("active");
removeEventListeners();
perf("additionalMedia", "stop");
resolve();
}).fadeIn(fadeDelay);
toggleScreen("overlayUploadFile");
});
}
function addMediaItemToPart (date, paragraph, media) {
if (!meetingMedia[date]) meetingMedia[date] = [];
if (meetingMedia[date].filter(part => part.title == paragraph).length === 0) {
meetingMedia[date].push({
title: paragraph,
media: []
});
}
media.folder = date;
meetingMedia[date].find(part => part.title == paragraph).media.push(media);
meetingMedia[date] = meetingMedia[date].sort((a, b) => a.title > b.title && 1 || -1);
}
function rm(toDelete) {
if (!Array.isArray(toDelete)) toDelete = [toDelete];
for (var fileOrDir of toDelete) {
fs.rmSync(fileOrDir, {
recursive: true,
force: true
});
}
}
function convertPdf(mediaFile) {
return new Promise((resolve)=>{
var pdfjsLib = require("pdfjs-dist/build/pdf.js");
pdfjsLib.GlobalWorkerOptions.workerSrc = require("pdfjs-dist/build/pdf.worker.entry.js");
pdfjsLib.getDocument({
url: mediaFile,
verbosity: 0
}).promise.then(async function(pdf) {
for (var pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
await convertPdfPage(mediaFile, pdf, pageNum);
}
await rm(mediaFile);
}).catch((err) => {
notifyUser("warn", "warnPdfConversionFailure", path.basename(mediaFile), true, err);
}).then(() => {
resolve();
});
});
}
function convertPdfPage(mediaFile, pdf, pageNum) {
return new Promise((resolve)=>{
pdf.getPage(pageNum).then(function(page) {
$("body").append("<div id='pdf' style='display: none;'>");
$("div#pdf").append("<canvas id='pdfCanvas'></canvas>");
let scale = fullHd[1] / page.getViewport({scale: 1}).height * 2;
var canvas = $("#pdfCanvas")[0];
let ctx = canvas.getContext("2d");
ctx.imageSmoothingEnabled = false;
canvas.height = fullHd[1] * 2;
canvas.width = page.getViewport({scale: scale}).width;
page.render({
canvasContext: ctx,
viewport: page.getViewport({scale: scale})
}).promise.then(function() {
fs.writeFileSync(path.join(path.dirname(mediaFile), path.basename(mediaFile, path.extname(mediaFile)) + "-" + String(pageNum).padStart(2, "0") + ".png"), new Buffer(canvas.toDataURL().replace(/^data:image\/\w+;base64,/, ""), "base64"));
$("div#pdf").remove();
resolve();
});
});
});
}
function convertSvg(mediaFile) {
return new Promise((resolve)=>{
$("body").append("<div id='svg'>");
$("div#svg").append("<img id='svgImg'>").append("<canvas id='svgCanvas'></canvas>");
$("img#svgImg").on("load", function() {
let canvas = $("#svgCanvas")[0],
image = $("img#svgImg")[0];
image.height = fullHd[1] * 2;
canvas.height = image.height;
canvas.width = image.width;
let canvasContext = canvas.getContext("2d");
canvasContext.fillStyle = "white";
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
canvasContext.imageSmoothingEnabled = true;
canvasContext.imageSmoothingQuality = "high";
canvasContext.drawImage(image, 0, 0);
fs.writeFileSync(path.join(path.dirname(mediaFile), path.basename(mediaFile, path.extname(mediaFile)) + ".png"), new Buffer(canvas.toDataURL().replace(/^data:image\/\w+;base64,/, ""), "base64"));
rm(mediaFile);
$("div#svg").remove();
return resolve();
});
$("img#svgImg").on("error", function() {
notifyUser("warn", "warnSvgConversionFailure", path.basename(mediaFile), true);
return resolve();
});
$("img#svgImg").prop("src", mediaFile);
});
}
async function convertUnusableFiles() {
for (let pdfFile of glob.sync(path.join(paths.media, "*", "*pdf"))) {
await convertPdf(pdfFile);
}
for (let svgFile of glob.sync(path.join(paths.media, "*", "*svg"))) {
await convertSvg(svgFile);
}
}
function createMediaNames() {
perf("createMediaNames", "start");
for (var h = 0; h < Object.values(meetingMedia).length; h++) { // meetings
var meeting = Object.values(meetingMedia)[h];
for (var i = 0; i < meeting.length; i++) { // parts
for (var j = 0; j < meeting[i].media.length; j++) { // media
meeting[i].media[j].safeName = (i + 1).toString().padStart(2, "0") + "-" + (j + 1).toString().padStart(2, "0");
if (meeting[i].media[j].filesize) {
meeting[i].media[j].safeName = sanitizeFilename(meeting[i].media[j].safeName + " - " + ((meeting[i].media[j].queryInfo.TargetParagraphNumberLabel ? meeting[i].media[j].queryInfo.TargetParagraphNumberLabel + "- " : "")) + meeting[i].media[j].title + path.extname((meeting[i].media[j].url ? meeting[i].media[j].url : meeting[i].media[j].filepath)));
} else {
continue;
}
}
}
}
log.debug(Object.entries(meetingMedia).map(meeting => { meeting[1] = meeting[1].filter(mediaItem => mediaItem.media.length > 0).map(item => item.media).flat(); return meeting; }));
perf("createMediaNames", "stop");
}
function createVideoSync(mediaFile){
let outputFilePath = path.format({ ...path.parse(mediaFile), base: undefined, ext: ".mp4" });
return new Promise((resolve)=>{
try {
if (path.extname(mediaFile).includes("mp3")) {
ffmpegSetup().then(function () {
ffmpeg(mediaFile).on("end", function() {
rm(mediaFile);
return resolve();
}).on("error", function(err) {
notifyUser("warn", "warnMp4ConversionFailure", path.basename(mediaFile), true, err, true);
return resolve();
}).noVideo().save(path.join(outputFilePath));
});
} else {
let convertedImageDimensions = [],
imageDimesions = sizeOf(mediaFile);
if (imageDimesions.orientation && imageDimesions.orientation >= 5) [imageDimesions.width, imageDimesions.height] = [imageDimesions.height, imageDimesions.width];
convertedImageDimensions = aspect.resize(imageDimesions.width, imageDimesions.height, (fullHd[1] / fullHd[0] > imageDimesions.height / imageDimesions.width ? (imageDimesions.width > fullHd[0] ? fullHd[0] : imageDimesions.width) : null), (fullHd[1] / fullHd[0] > imageDimesions.height / imageDimesions.width ? null : (imageDimesions.height > fullHd[1] ? fullHd[1] : imageDimesions.height)));
$("body").append("<div id='convert' style='display: none;'>");
$("div#convert").append("<img id='imgToConvert'>").append("<canvas id='imgCanvas'></canvas>");
hme.createH264MP4Encoder().then(function (encoder) {
$("img#imgToConvert").on("load", function() {
var canvas = $("#imgCanvas")[0],
image = $("img#imgToConvert")[0];
encoder.quantizationParameter = 10;
image.width = convertedImageDimensions[0];
image.height = convertedImageDimensions[1];
encoder.width = canvas.width = (image.width % 2 ? image.width - 1 : image.width);
encoder.height = canvas.height = (image.height % 2 ? image.height - 1 : image.height);
encoder.initialize();
canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
encoder.addFrameRgba(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data);
encoder.finalize();
fs.writeFileSync(outputFilePath, encoder.FS.readFile(encoder.outputFilename));
encoder.delete();
$("div#convert").remove();
rm(mediaFile);
return resolve();
});
$("img#imgToConvert").on("error", function(err) {
notifyUser("warn", "warnMp4ConversionFailure", path.basename(mediaFile), true, err, true);
$("div#convert").remove();
return resolve();
});
$("img#imgToConvert").prop("src", mediaFile);
});
}
} catch (err) {
notifyUser("warn", "warnMp4ConversionFailure", path.basename(mediaFile), true, err, true);
return resolve();
}
});
}
function dateFormatter() {
let locale = prefs.localAppLang ? prefs.localAppLang : "en";
try {
if (locale !== "en") require("dayjs/locale/" + locale);
} catch(err) {
log.warn("%c[locale] Date locale " + locale + " not found, falling back to 'en'");
}
$(".today").removeClass("today");
for (var d = 0; d < 7; d++) {
$("#day" + d + " .dayLongDate .dayOfWeek").text(baseDate.clone().add(d, "days").locale(locale).format("ddd"));
$("#day" + d + " .dayLongDate .dayOfWeekLong").text(baseDate.clone().add(d, "days").locale(locale).format("dddd"));
$("#day" + d + " .dayLongDate .dateOfMonth .date").text(baseDate.clone().add(d, "days").locale(locale).format("DD"));
$("#day" + d + " .dayLongDate .dateOfMonth .month").text(baseDate.clone().add(d, "days").locale(locale).format("MMM"));
$("#mwDay label:eq(" + d + ")").text(baseDate.clone().add(d, "days").locale(locale).format("dd"));
$("#weDay label:eq(" + d + ")").text(baseDate.clone().add(d, "days").locale(locale).format("dd"));
let meetingInPast = baseDate.clone().add(d, "days").isBefore(now);
$("#day" + d).toggleClass("alert-secondary", meetingInPast).toggleClass("alert-primary", !meetingInPast).find("i").toggle(!meetingInPast);
if (baseDate.clone().add(d, "days").isSame(now)) $("#day" + d).addClass("today");
}
}
const delay = s => new Promise(res => {
setTimeout(res, s * 1000);
let secsRemaining = s;
$("button .action-countdown").html(secsRemaining);
const timeinterval = setInterval(function() {
secsRemaining--;
if (secsRemaining < 1) {
secsRemaining = "";
$("button .action-countdown").html();
clearInterval(timeinterval);
}
$("button .action-countdown").html(secsRemaining);
}, 1000);
$("#bottomIcon button").on("click", function() {
window[$(this).attr("class").split(" ").filter(el => el.includes("btn-action-")).join(" ").split("-").splice(2).join("-").toLowerCase().replace(/([-_][a-z])/g, group => group.toUpperCase().replace("-", "").replace("_", ""))] = true;
clearInterval(timeinterval);
overlay(false);
});
});
function disableGlobalPref([pref, value]) {
let row = $("#" + pref).closest("div.row");
if (row.find(".settingLocked").length === 0) row.find("label").first().prepend($("<span class='badge bg-warning me-1 rounded-pill settingLocked text-black i18n-title' data-bs-toggle='tooltip'><i class='fa-lock fas'></i></span>").attr("title", i18n.__("settingLocked")).tooltip());
row.addClass("text-muted disabled").find("#" + pref + ", #" + pref + " input, input[data-target=" + pref + "]").addClass("forcedPref").prop("disabled", true);
log.info("%c[enforcedPrefs] [" + pref + "] " + value, "background-color: #FCE4EC; color: #AD1457;");
}
function displayMusicRemaining() {
let timeRemaining;
if (prefs.enableMusicFadeOut && pendingMusicFadeOut.endTime >0) {
let rightNow = dayjs();
timeRemaining = (dayjs(pendingMusicFadeOut.endTime).isAfter(rightNow) ? dayjs(pendingMusicFadeOut.endTime).diff(rightNow) : 0);
} else {
timeRemaining = (isNaN($("#meetingMusic")[0].duration) ? 0 : ($("#meetingMusic")[0].duration - $("#meetingMusic")[0].currentTime) * 1000);
}
$("#musicRemaining").text(dayjs.duration(timeRemaining, "ms").format((timeRemaining >= 3600000 ? "HH:" : "") + "mm:ss"));
}
async function downloadIfRequired(file) {
file.downloadRequired = true;
file.localDir = file.pub ? path.join(paths.pubs, file.pub, file.issue) : path.join(paths.media, file.folder);
file.localFile = path.join(file.localDir, file.pub ? path.basename(file.url) : file.safeName);
if (fs.existsSync(file.localFile)) file.downloadRequired = file.filesize !== fs.statSync(file.localFile).size;
if (file.downloadRequired) {
mkdirSync(file.localDir);
fs.writeFileSync(file.localFile, new Buffer((await request(file.url, {isFile: true})).data));
downloadStat("jworg", "live", file);
} else {
downloadStat("jworg", "cache", file);
}
if (path.extname(file.localFile) == ".jwpub") await new zipper((await new zipper(file.localFile).readFile("contents"))).extractAllTo(file.localDir);
}
function downloadStat(origin, source, file) {
if (!downloadStats[origin]) downloadStats[origin] = {};
if (!downloadStats[origin][source]) downloadStats[origin][source] = [];
downloadStats[origin][source].push(file);
}
function enablePreviouslyForcedPrefs() {
$("div.row.text-muted.disabled").removeClass("text-muted disabled").find(".forcedPref").prop("disabled", false).removeClass("forcedPref");
$("div.row .settingLocked").remove();
}
async function enforcePrefs() {
paths.forcedPrefs = path.posix.join(prefs.congServerDir, "forcedPrefs.json");
let forcedPrefs = await getForcedPrefs();
if (Object.keys(forcedPrefs).length > 0) {
let previousPrefs = v8.deserialize(v8.serialize(prefs));
Object.assign(prefs, forcedPrefs);
if (JSON.stringify(previousPrefs) !== JSON.stringify(prefs)) {
setMediaLang();
validateConfig(true);
prefsInitialize();
}
for (var pref of Object.entries(forcedPrefs)) {
disableGlobalPref(pref);
}
} else {
enablePreviouslyForcedPrefs(true);
}
}
async function executeDryrun(persistantOverlay) {
await overlay(true, "cog fa-spin");
await startMediaSync(true);
if (!persistantOverlay) await overlay(false);
}
async function executeStatement(db, statement) {
var vals = await db.exec(statement)[0],
valObj = [];
if (vals) {
for (var v = 0; v < vals.values.length; v++) {
valObj[v] = {};
for (var c = 0; c < vals.columns.length; c++) {
valObj[v][vals.columns[c]] = vals.values[v][c];
}
}
}
log.debug({statement: statement, valObj: valObj});
return valObj;
}
async function ffmpegSetup() {
if (!ffmpegIsSetup) {
var osType = os.type();
var targetOs;
if (osType == "Windows_NT") {
targetOs = "win-64";
} else if (osType == "Darwin") {
targetOs = "osx-64";
} else {
targetOs = "linux-64";
}
var ffmpegVersion = (await request("https://api.github.com/repos/vot/ffbinaries-prebuilt/releases/latest")).data.assets.filter(a => a.name.includes(targetOs) && a.name.includes("ffmpeg"))[0];
var ffmpegZipPath = path.join(paths.app, "ffmpeg", "zip", ffmpegVersion.name);
if (!fs.existsSync(ffmpegZipPath) || fs.statSync(ffmpegZipPath).size !== ffmpegVersion.size) {
await rm([path.join(paths.app, "ffmpeg", "zip")]);
mkdirSync(path.join(paths.app, "ffmpeg", "zip"));
fs.writeFileSync(ffmpegZipPath, new Buffer((await request(ffmpegVersion.browser_download_url, {isFile: true})).data));
}
var zip = new zipper(ffmpegZipPath);
var zipEntry = zip.getEntries().filter((x) => !x.entryName.includes("MACOSX"))[0];
var ffmpegPath = path.join(path.join(paths.app, "ffmpeg", zipEntry.entryName));
if (!fs.existsSync(ffmpegPath) || fs.statSync(ffmpegPath).size !== zipEntry.header.size) {
zip.extractEntryTo(zipEntry.entryName, path.join(paths.app, "ffmpeg"), true, true);
}
try {
fs.accessSync(ffmpegPath, fs.constants.X_OK);
} catch (err) {
fs.chmodSync(ffmpegPath, "777");
}
ffmpeg.setFfmpegPath(ffmpegPath);
ffmpegIsSetup = true;
}
}
async function getCongMedia() {
perf("getCongMedia", "start");
updateTile("specificCong", "warning", "fas fa-circle-notch fa-spin");
try {
for (let congSpecificFolder of (await webdavLs(path.posix.join(prefs.congServerDir, "Media")))) {
let isMeetingDate = dayjs(congSpecificFolder.basename, "YYYY-MM-DD").isValid() && dayjs(congSpecificFolder.basename, "YYYY-MM-DD").isBetween(baseDate, baseDate.clone().add(6, "days"), null, "[]") && now.isSameOrBefore(dayjs(congSpecificFolder.basename, "YYYY-MM-DD"));
let isRecurring = congSpecificFolder.basename == "Recurring";
if (isMeetingDate || isRecurring) {
for (let remoteFile of (await webdavLs(path.posix.join(prefs.congServerDir, "Media", congSpecificFolder.basename)))) {
let congSpecificFile = {
"title": "Congregation-specific",
media: [{
safeName: remoteFile.basename,
congSpecific: true,
filesize: remoteFile.size,
folder: congSpecificFolder.basename,
url: remoteFile.filename
}]
};
if (!meetingMedia[congSpecificFolder.basename]) meetingMedia[congSpecificFolder.basename] = [];
meetingMedia[congSpecificFolder.basename].push(congSpecificFile);
if (isRecurring) {
for (var meeting of Object.keys(meetingMedia)) {
if (dayjs(meeting, "YYYY-MM-DD").isValid()) {
var repeatFile = v8.deserialize(v8.serialize(congSpecificFile));
repeatFile.media[0].recurring = true;
repeatFile.media[0].folder = meeting;
meetingMedia[meeting].push(repeatFile);
}
}
}
}
}
}
for (var hiddenFilesFolder of (await webdavLs(path.posix.join(prefs.congServerDir, "Hidden"))).filter(hiddenFilesFolder => dayjs(hiddenFilesFolder.basename, "YYYY-MM-DD").isValid() && dayjs(hiddenFilesFolder.basename, "YYYY-MM-DD").isBetween(baseDate, baseDate.clone().add(6, "days"), null, "[]") && now.isSameOrBefore(dayjs(hiddenFilesFolder.basename, "YYYY-MM-DD"))).sort((a, b) => (a.basename > b.basename) ? 1 : -1)) {
for (var hiddenFile of await webdavLs(path.posix.join(prefs.congServerDir, "Hidden", hiddenFilesFolder.basename))) {
var hiddenFileLogString = "background-color: #d6d8d9; color: #1b1e21;";
if (meetingMedia[hiddenFilesFolder.basename]) {
meetingMedia[hiddenFilesFolder.basename].filter(part => part.media.filter(mediaItem => mediaItem.safeName == hiddenFile.basename).map(function (mediaItem) {
mediaItem.hidden = true;
hiddenFileLogString = "background-color: #fff3cd; color: #856404;";
}));
}
log.info("%c[hiddenMedia] [" + hiddenFilesFolder.basename + "] " + hiddenFile.basename, hiddenFileLogString);
}
}
} catch (err) {
notifyUser("error", "errorGetCongMedia", null, true, err, true);
updateTile("specificCong", "danger", "fas fa-times-circle");
}
perf("getCongMedia", "stop");
}
async function getDbFromJwpub(pub, issue, localpath) {
try {
var SQL = await sqljs();
if (localpath) {
var jwpubContents = await new zipper(localpath).readFile("contents");
var tempDb = new SQL.Database(await new zipper(jwpubContents).readFile((await new zipper(jwpubContents).getEntries()).filter(entry => path.extname(entry.name) == ".db")[0].entryName));
var jwpubInfo = (await executeStatement(tempDb, "SELECT UniqueEnglishSymbol, IssueTagNumber FROM Publication"))[0];
pub = jwpubInfo.UniqueEnglishSymbol.replace(/[0-9]/g, "");
issue = jwpubInfo.IssueTagNumber;
if (!jwpubDbs[pub]) jwpubDbs[pub] = {};
jwpubDbs[pub][issue] = tempDb;
} else {
if (!jwpubDbs[pub]) jwpubDbs[pub] = {};
if (!jwpubDbs[pub][issue]) {
var jwpub = (await getMediaLinks(pub, null, issue, "JWPUB"))[0];
jwpub.pub = pub;
jwpub.issue = issue;
await downloadIfRequired(jwpub);
jwpubDbs[pub][issue] = new SQL.Database(fs.readFileSync(glob.sync(path.join(paths.pubs, jwpub.pub, jwpub.issue, "*.db"))[0]));
}
}
return jwpubDbs[pub][issue];
} catch (err) {
notifyUser("warn", "errorJwpubDbFetch", pub + " - " + issue, false, err, true);
}
}
async function getDocumentExtract(db, docId) {
var extractMultimediaItems = [];
for (var extractItem of (await executeStatement(db, "SELECT DocumentExtract.BeginParagraphOrdinal,DocumentExtract.EndParagraphOrdinal,DocumentExtract.DocumentId,Extract.RefMepsDocumentId,Extract.RefPublicationId,Extract.RefMepsDocumentId,UniqueEnglishSymbol,IssueTagNumber,Extract.RefBeginParagraphOrdinal,Extract.RefEndParagraphOrdinal FROM DocumentExtract INNER JOIN Extract ON DocumentExtract.ExtractId = Extract.ExtractId INNER JOIN RefPublication ON Extract.RefPublicationId = RefPublication.RefPublicationId INNER JOIN Document ON DocumentExtract.DocumentId = Document.DocumentId WHERE DocumentExtract.DocumentId = " + docId + " AND NOT UniqueEnglishSymbol = 'sjj' AND NOT UniqueEnglishSymbol = 'mwbr' " + (prefs.excludeTh ? "AND NOT UniqueEnglishSymbol = 'th' " : "") + "ORDER BY DocumentExtract.BeginParagraphOrdinal"))) {
var extractDb = await getDbFromJwpub(extractItem.UniqueEnglishSymbol.replace(/[0-9]/g, ""), extractItem.IssueTagNumber);
if (extractDb) {
extractMultimediaItems = extractMultimediaItems.concat((await getDocumentMultimedia(extractDb, null, extractItem.RefMepsDocumentId)).filter(extractMediaFile => {
if (extractMediaFile.queryInfo.tableQuestionIsUsed && !extractMediaFile.queryInfo.TargetParagraphNumberLabel) extractMediaFile.BeginParagraphOrdinal = extractMediaFile.queryInfo.NextParagraphOrdinal;
if (extractMediaFile.BeginParagraphOrdinal && extractItem.RefBeginParagraphOrdinal && extractItem.RefEndParagraphOrdinal) {
return extractItem.RefBeginParagraphOrdinal <= extractMediaFile.BeginParagraphOrdinal && extractMediaFile.BeginParagraphOrdinal <= extractItem.RefEndParagraphOrdinal;
} else {
return true;
}
}).map(extractMediaFile => {
extractMediaFile.BeginParagraphOrdinal = extractItem.BeginParagraphOrdinal;
return extractMediaFile;
}));
}
}
return extractMultimediaItems;
}
async function getDocumentMultimedia(db, destDocId, destMepsId, memOnly) {
let tableMultimedia = ((await executeStatement(db, "SELECT * FROM sqlite_master WHERE type='table' AND name='DocumentMultimedia'")).length === 0 ? "Multimedia" : "DocumentMultimedia");
let keySymbol = (await executeStatement(db, "SELECT UniqueEnglishSymbol FROM Publication"))[0].UniqueEnglishSymbol.replace(/[0-9]*/g, "");
let issueTagNumber = (await executeStatement(db, "SELECT IssueTagNumber FROM Publication"))[0].IssueTagNumber;
let targetParagraphNumberLabelExists = (await executeStatement(db, "PRAGMA table_info('Question')")).map(item => item.name).includes("TargetParagraphNumberLabel");
let suppressZoomExists = (await executeStatement(db, "PRAGMA table_info('Multimedia')")).map(item => item.name).includes("SuppressZoom");
let multimediaItems = [];
if (!(keySymbol == "lffi" && prefs.excludeLffi && prefs.excludeLffiImages)) for (var multimediaItem of (await executeStatement(db, "SELECT " + tableMultimedia + ".DocumentId, " + tableMultimedia + ".MultimediaId, " + (tableMultimedia == "DocumentMultimedia" ? tableMultimedia + ".BeginParagraphOrdinal, " + tableMultimedia + ".EndParagraphOrdinal, Multimedia.KeySymbol, Multimedia.MultimediaId," + (suppressZoomExists ? " Multimedia.SuppressZoom," : "") + " Multimedia.MepsDocumentId AS MultiMeps, Document.MepsDocumentId, Multimedia.Track, Multimedia.IssueTagNumber, " : "Multimedia.CategoryType, ") + (targetParagraphNumberLabelExists && tableMultimedia == "DocumentMultimedia" ? "Question.TargetParagraphNumberLabel, " : "") + "Multimedia.MimeType, Multimedia.DataType, Multimedia.MajorType, Multimedia.FilePath, Multimedia.Label, Multimedia.Caption, Multimedia.CategoryType FROM " + tableMultimedia + (tableMultimedia == "DocumentMultimedia" ? " INNER JOIN Multimedia ON Multimedia.MultimediaId = " + tableMultimedia + ".MultimediaId" : "") + " INNER JOIN Document ON " + tableMultimedia + ".DocumentId = Document.DocumentId " + (targetParagraphNumberLabelExists && tableMultimedia == "DocumentMultimedia" ? "LEFT JOIN Question ON Question.DocumentId = " + tableMultimedia + ".DocumentId AND Question.TargetParagraphOrdinal = " + tableMultimedia + ".BeginParagraphOrdinal " : "") + "WHERE " + (destDocId || destDocId === 0 ? tableMultimedia + ".DocumentId = " + destDocId : "Document.MepsDocumentId = " + destMepsId) + " AND (" + (keySymbol !== "lffi" || !prefs.excludeLffi ? "(Multimedia.MimeType LIKE '%video%' OR Multimedia.MimeType LIKE '%audio%')" : "") + (keySymbol !== "lffi" || (!prefs.excludeLffi && !prefs.excludeLffiImages) ? " OR " : "") + (keySymbol !== "lffi" || !prefs.excludeLffiImages ? "(Multimedia.MimeType LIKE '%image%' AND Multimedia.CategoryType <> 6 AND Multimedia.CategoryType <> 9 AND Multimedia.CategoryType <> 10 AND Multimedia.CategoryType <> 25)" : "") + ")" + (suppressZoomExists ? " AND Multimedia.SuppressZoom <> 1" : "") + (tableMultimedia == "DocumentMultimedia" ? " GROUP BY " + tableMultimedia + ".MultimediaId ORDER BY BeginParagraphOrdinal" : "")))) {
if (targetParagraphNumberLabelExists) {
let paragraphNumber = await executeStatement(db, "SELECT TargetParagraphNumberLabel From Question WHERE DocumentId = " + multimediaItem.DocumentId + " AND TargetParagraphOrdinal = " + multimediaItem.BeginParagraphOrdinal);
if (paragraphNumber.length === 1) Object.assign(multimediaItem, paragraphNumber[0]);
if ((await executeStatement(db, "SELECT COUNT(*) as Count FROM Question"))[0].Count > 0) {
multimediaItem.tableQuestionIsUsed = true;
let nextParagraphQuery = await executeStatement(db, "SELECT TargetParagraphNumberLabel, TargetParagraphOrdinal From Question WHERE DocumentId = " + multimediaItem.DocumentId + " AND TargetParagraphOrdinal > " + multimediaItem.BeginParagraphOrdinal + " LIMIT 1");
if (nextParagraphQuery.length > 0) multimediaItem.NextParagraphOrdinal = nextParagraphQuery[0].TargetParagraphOrdinal;
}
}
try {
if ((multimediaItem.MimeType.includes("audio") || multimediaItem.MimeType.includes("video"))) {
var json = {
queryInfo: multimediaItem,
BeginParagraphOrdinal: multimediaItem.BeginParagraphOrdinal
};
Object.assign(json, (await getMediaLinks(multimediaItem.KeySymbol, multimediaItem.Track, multimediaItem.IssueTagNumber, null, multimediaItem.MultiMeps))[0]);
multimediaItems.push(json);
} else {
if (multimediaItem.KeySymbol == null) {
multimediaItem.KeySymbol = keySymbol;
multimediaItem.IssueTagNumber = issueTagNumber;
if (!memOnly) multimediaItem.LocalPath = path.join(paths.pubs, multimediaItem.KeySymbol, multimediaItem.IssueTagNumber, multimediaItem.FilePath);
}
multimediaItem.FileName = sanitizeFilename((multimediaItem.Caption.length > multimediaItem.Label.length ? multimediaItem.Caption : multimediaItem.Label), true);
var picture = {
BeginParagraphOrdinal: multimediaItem.BeginParagraphOrdinal,
title: multimediaItem.FileName,
queryInfo: multimediaItem
};
if (!memOnly) {
picture.filepath = multimediaItem.LocalPath;
picture.filesize = fs.statSync(multimediaItem.LocalPath).size;
}
multimediaItems.push(picture);
}
} catch (err) {
notifyUser("warn", "errorJwpubMediaExtract", keySymbol + " - " + issueTagNumber, false, err, true);
}
}
return multimediaItems;
}
async function getForcedPrefs() {
let forcedPrefs = {};
if (await webdavExists(paths.forcedPrefs)) {
try {
forcedPrefs = (await request("https://" + prefs.congServer + ":" + prefs.congServerPort + paths.forcedPrefs, {
webdav: true,
noCache: true
})).data;
} catch(err) {
notifyUser("error", "errorForcedSettingsEnforce", null, true, err);
}
}
return forcedPrefs;
}
async function getInitialData() {
await getJwOrgLanguages();
await getLocaleLanguages();
await setAppLang();
await updateCleanup();
await setMediaLang();
await webdavSetup();
let configIsValid = validateConfig();
$("#version").html("JWMMF " + escape(currentAppVersion));
$("#day" + prefs.mwDay + ", #day" + prefs.weDay).addClass("meeting");
if (os.platform() == "linux") $(".notLinux").prop("disabled", true);
$("#baseDate button, #baseDate .dropdown-item:eq(0)").text(baseDate.format("YYYY-MM-DD") + " - " + baseDate.clone().add(6, "days").format("YYYY-MM-DD")).val(baseDate.format("YYYY-MM-DD"));
$("#baseDate .dropdown-item:eq(0)").addClass("active");
for (var a = 1; a <= 4; a++) {
$("#baseDate .dropdown-menu").append("<button class='dropdown-item' value='" + baseDate.clone().add(a, "week").format("YYYY-MM-DD") + "'>" + baseDate.clone().add(a, "week").format("YYYY-MM-DD") + " - " + baseDate.clone().add(a, "week").add(6, "days").format("YYYY-MM-DD") + "</button>");
}
if (prefs.autoStartSync && configIsValid) {
await overlay(true, "hourglass-start", "pause", "cancel-sync");
await delay(5);
if (!cancelSync) $("#mediaSync").click();
}
overlay(false, (prefs.autoStartSync && configIsValid ? "hourglass-start" : null));
}
async function getJwOrgLanguages(forceRefresh) {
if ((!fs.existsSync(paths.langs)) || (!prefs.langUpdatedLast) || dayjs(prefs.langUpdatedLast).isBefore(now.subtract(3, "months")) || forceRefresh) {
let cleanedJwLangs = (await request("https://www.jw.org/en/languages/")).data.languages.filter(lang => lang.hasWebContent).map(lang => ({
name: lang.name,
langcode: lang.langcode,
symbol: lang.symbol,
vernacularName: lang.vernacularName
}));
fs.writeFileSync(paths.langs, JSON.stringify(cleanedJwLangs, null, 2));
prefs.langUpdatedLast = dayjs();
validateConfig(true);
jsonLangs = cleanedJwLangs;
} else {
jsonLangs = JSON.parse(fs.readFileSync(paths.langs));
}
for (var lang of jsonLangs) {
$("#lang").append($("<option>", {
value: lang.langcode,
text: lang.vernacularName + " (" + lang.name + ")"
}));
}
$("#lang").val(prefs.lang).select2();
}
function getLocaleLanguages() {
for (var localeLang of fs.readdirSync(path.join(__dirname, "locales")).map(file => file.replace(".json", ""))) {
let localeLangMatches = jsonLangs.filter(item => item.symbol === localeLang);
$("#localAppLang").append($("<option>", {
value: localeLang,
text: (localeLangMatches.length === 1 ? localeLangMatches[0].vernacularName + " (" + localeLangMatches[0].name + ")" : localeLang)
}));
}
$("#localAppLang").val(prefs.localAppLang);
}
async function getMediaLinks(pub, track, issue, format, docId) {
let mediaFiles = [];
if (prefs.lang && prefs.maxRes) {
try {
if (pub === "w" && parseInt(issue) >= 20080101 && issue.slice(-2) == "01") pub = "wp";
let requestUrl = "https://b.jw-cdn.org/apis/pub-media/GETPUBMEDIALINKS?output=json" + (docId ? "&docid=" + docId : "&pub=" + pub + (track ? "&track=" + track : "") + (issue ? "&issue=" + issue : "")) + (format ? "&fileformat=" + format : "") + "&langwritten=" + prefs.lang;
let result = (await request(requestUrl)).data;
log.debug(pub, track, issue, format, docId, requestUrl);
if (result && result.length > 0 && result[0].status && result[0].status == 404 && pub && track) {
requestUrl = "https://b.jw-cdn.org/apis/pub-media/GETPUBMEDIALINKS?output=json" + "&pub=" + pub + "m" + "&track=" + track + (issue ? "&issue=" + issue : "") + (format ? "&fileformat=" + format : "") + "&langwritten=" + prefs.lang;
result = (await request(requestUrl)).data;
log.debug(pub + "m", track, issue, format, docId, requestUrl);
}
if (result && result.files) {
let mediaFileCategories = Object.values(result.files)[0];
mediaFiles = mediaFileCategories[("MP4" in mediaFileCategories ? "MP4" : Object.keys(mediaFileCategories)[0])].filter(({label}) => label.replace(/\D/g, "") <= prefs.maxRes.replace(/\D/g, ""));
let map = new Map(mediaFiles.map(item => [item.title, item]));
for (let item of mediaFiles) {
let {label, subtitled} = map.get(item.title);
if ((item.label.replace(/\D/g, "") - label.replace(/\D/g, "") || subtitled - item.subtitled) > 0) map.set(item.title, item);
}
mediaFiles = Array.from(map.values(), ({title, file: {url}, filesize, duration, trackImage}) => ({title, url, filesize, duration, trackImage})).map(item => {
item.trackImage = item.trackImage.url;
return item;
});
for (var item of mediaFiles) {
if (item.duration >0 && !item.trackImage) {
item.trackImage = await getMediaThumbnail(pub, track, issue, format, docId);
}
}
}
} catch(err) {
notifyUser("warn", "infoPubIgnored", pub + " - " + track + " - " + issue + " - " + format, false, err);
}
}
log.debug(mediaFiles);
return mediaFiles;
}
async function getMediaThumbnail(pub, track, issue, format, docId) {
let thumbnail = "";
if (issue) issue = issue.toString().replace(/(\d{6})00$/gm, "$1");
let result = (await request("https://b.jw-cdn.org/apis/mediator/v1/media-items/" + prefs.lang + "/" + (docId ? "docid-" + docId + "_1": "pub-" + [pub, issue, track].filter(Boolean).join("_")) + "_VIDEO")).data;
if (result && result.media && result.media.length > 0 && result.media[0].images.wss.sm) thumbnail = result.media[0].images.wss.sm;
return thumbnail;
}
async function getMwMediaFromDb() {
var mwDate = baseDate.clone().add(prefs.mwDay, "days").format("YYYY-MM-DD");
if (now.isSameOrBefore(dayjs(mwDate))) {
updateTile("day" + prefs.mwDay, "warning", "fas fa-circle-notch fa-spin");
try {
var issue = baseDate.format("YYYYMM") + "00";
if (parseInt(baseDate.format("M")) % 2 === 0) issue = baseDate.clone().subtract(1, "months").format("YYYYMM") + "00";
var db = await getDbFromJwpub("mwb", issue);
var docId = (await executeStatement(db, "SELECT DocumentId FROM DatedText WHERE FirstDateOffset = " + baseDate.format("YYYYMMDD") + ""))[0].DocumentId;
(await getDocumentMultimedia(db, docId)).map(video => {
addMediaItemToPart(mwDate, video.BeginParagraphOrdinal, video);
});
(await getDocumentExtract(db, docId)).map(extract => {
addMediaItemToPart(mwDate, extract.BeginParagraphOrdinal, extract);
});
for (var internalRef of (await executeStatement(db, "SELECT DocumentInternalLink.DocumentId AS SourceDocumentId, DocumentInternalLink.BeginParagraphOrdinal, Document.DocumentId FROM DocumentInternalLink INNER JOIN InternalLink ON DocumentInternalLink.InternalLinkId = InternalLink.InternalLinkId INNER JOIN Document ON InternalLink.MepsDocumentId = Document.MepsDocumentId WHERE DocumentInternalLink.DocumentId = " + docId + " AND Document.Class <> 94"))) {
(await getDocumentMultimedia(db, internalRef.DocumentId)).map(internalRefMediaFile => {
addMediaItemToPart(mwDate, internalRef.BeginParagraphOrdinal, internalRefMediaFile);
});
}
updateTile("day" + prefs.mwDay, "success", "fas fa-check-circle");
} catch(err) {
notifyUser("error", "errorGetMwMedia", null, true, err, true);
updateTile("day" + prefs.mwDay, "danger", "fas fa-times-circle");
}
}
}
function getPrefix() {
let prefix = $(".enterPrefixInput").map(function() {
return $(this).val();
}).toArray().join("").trim();
for (var a0 = 0; a0 <= 4; a0++) {
if ($("#enterPrefix-" + a0).val().length > 0) {
for (var a1 = a0 + 1; a1 <= 5; a1++) {
$("#enterPrefix-" + a1).prop("disabled", false);
}
} else {
for (var a2 = a0 + 1; a2 <= 5; a2++) {
$("#enterPrefix-" + a2).val("").prop("disabled", true);
}
}
}
$(".enterPrefixInput").each(function() {
$(this).fadeTo(fadeDelay, !$(this).prop("disabled"));
});
$("#enterPrefix-" + prefix.length).focus();
if (prefix.length % 2) prefix = prefix + 0;
if (prefix.length > 0) prefix = prefix.match(/.{1,2}/g).join("-");
return prefix;
}
function setAppLang() {
i18n.setLocale(prefs.localAppLang ? prefs.localAppLang : "en");
$("[data-i18n-string]").each(function() {
$(this).html(i18n.__($(this).data("i18n-string")));
});
$(".i18n-title").attr("title", i18n.__("settingLocked")).tooltip("dispose").tooltip();
dateFormatter();
}
async function getWeMediaFromDb() {
var weDate = baseDate.clone().add(prefs.weDay, "days").format("YYYY-MM-DD");
if (now.isSameOrBefore(dayjs(weDate))) {
updateTile("day" + prefs.weDay, "warning", "fas fa-circle-notch fa-spin");
try {
var issue = baseDate.clone().subtract(8, "weeks").format("YYYYMM") + "00";
var db = await getDbFromJwpub("w", issue);
var weekNumber = (await executeStatement(db, "SELECT FirstDateOffset FROM DatedText")).findIndex(weekItem => dayjs(weekItem.FirstDateOffset.toString(), "YYYYMMDD").isBetween(baseDate, baseDate.clone().add(6, "days"), null, "[]"));
if (weekNumber < 0) {
issue = baseDate.clone().subtract(9, "weeks").format("YYYYMM") + "00";
db = await getDbFromJwpub("w", issue);
weekNumber = (await executeStatement(db, "SELECT FirstDateOffset FROM DatedText")).findIndex(weekItem => dayjs(weekItem.FirstDateOffset.toString(), "YYYYMMDD").isBetween(baseDate, baseDate.clone().add(6, "days"), null, "[]"));
}
if (weekNumber < 0) throw("No WE meeting date found!");
var docId = (await executeStatement(db, "SELECT Document.DocumentId FROM Document WHERE Document.Class=40 LIMIT 1 OFFSET " + weekNumber))[0].DocumentId;
for (var picture of (await executeStatement(db, "SELECT DocumentMultimedia.MultimediaId,Document.DocumentId, Multimedia.CategoryType,Multimedia.KeySymbol,Multimedia.Track,Multimedia.IssueTagNumber,Multimedia.MimeType, DocumentMultimedia.BeginParagraphOrdinal,Multimedia.FilePath,Label,Caption, Question.TargetParagraphNumberLabel FROM DocumentMultimedia INNER JOIN Document ON Document.DocumentId = DocumentMultimedia.DocumentId INNER JOIN Multimedia ON DocumentMultimedia.MultimediaId = Multimedia.MultimediaId LEFT JOIN Question ON Question.DocumentId = DocumentMultimedia.DocumentId AND Question.TargetParagraphOrdinal = DocumentMultimedia.BeginParagraphOrdinal WHERE Document.DocumentId = " + docId + " AND Multimedia.CategoryType <> 9"))) {
var LocalPath = path.join(paths.pubs, "w", issue, picture.FilePath);
var FileName = sanitizeFilename((picture.Caption.length > picture.Label.length ? picture.Caption : picture.Label), true);
var pictureObj = {
title: FileName,
filepath: LocalPath,
filesize: fs.statSync(LocalPath).size,
queryInfo: picture
};
addMediaItemToPart(weDate, picture.BeginParagraphOrdinal, pictureObj);
}
var qrySongs = await executeStatement(db, "SELECT * FROM Multimedia INNER JOIN DocumentMultimedia ON Multimedia.MultimediaId = DocumentMultimedia.MultimediaId WHERE DataType = 2 ORDER BY BeginParagraphOrdinal LIMIT 2 OFFSET " + weekNumber * 2);
for (var song = 0; song < qrySongs.length; song++) {
let songJson = await getMediaLinks(qrySongs[song].KeySymbol, qrySongs[song].Track);
if (songJson.length > 0) {
songJson[0].queryInfo = qrySongs[song];
addMediaItemToPart(weDate, song * 1000, songJson[0]);
} else {
notifyUser("error", "errorGetWeMedia", null, true, songJson, true);
}
}
updateTile("day" + prefs.weDay, "success", "fas fa-check-circle");
} catch(err) {
notifyUser("error", "errorGetWeMedia", null, true, err, true);
updateTile("day" + prefs.weDay, "danger", "fas fa-times-circle");
}
}
}
function isReachable(hostname, port) {
return new Promise(resolve => {
try {
let client = net.createConnection(port, hostname);
client.setTimeout(3000);
client.on("timeout", () => {
client.destroy("Timeout: " + hostname + ":" + port);
});
client.on("connect", function() {
client.destroy();
resolve(true);
});
client.on("error", function(err) {
notifyUser("error", "errorSiteCheck", hostname + ":" + port, false, err);
resolve(false);
});
} catch(err) {
resolve(false);
}
});
}
function mkdirSync(dirPath) {
try {
fs.mkdirSync(dirPath, {
recursive: true
});
} catch (err) {
if (err.code !== "EEXIST") throw err;
}
}
async function mp4Convert() {
perf("mp4Convert", "start");
updateStatus("microchip");
updateTile("mp4Convert", "warning", "fas fa-circle-notch fa-spin");
await convertUnusableFiles();
var filesToProcess = glob.sync(path.join(paths.media, "*", "*"), {
ignore: path.join(paths.media, "*", "*.mp4")
});
totals.mp4Convert = {
total: filesToProcess.length,
current: 1
};
progressSet(totals.mp4Convert.current, totals.mp4Convert.total, "mp4Convert");
for (var mediaFile of filesToProcess) {
await createVideoSync(mediaFile);
totals.mp4Convert.current++;
progressSet(totals.mp4Convert.current, totals.mp4Convert.total, "mp4Convert");
}
updateStatus("photo-video");
updateTile("mp4Convert", "success", "fas fa-check-circle");
perf("mp4Convert", "stop");
}
function notifyUser(type, message, fileOrUrl, persistent, errorFedToMe, action) {
let icon;
switch (type) {
case "error":
icon = "fa-exclamation-circle text-danger";
break;
case "warn":
icon = "fa-exclamation-circle text-warning";
break;
default:
icon = "fa-info-circle text-primary";
}
if (fileOrUrl) fileOrUrl = escape(fileOrUrl);
if (["error", "warn"].includes(type)) log[type](fileOrUrl ? fileOrUrl : "", errorFedToMe ? errorFedToMe : "");
type = i18n.__(type);
let thisBugUrl = bugUrl() + (errorFedToMe ? encodeURIComponent("\n### Error details\n```\n" + JSON.stringify(errorFedToMe, Object.getOwnPropertyNames(errorFedToMe), 2) + "\n```\n").replace(/\n/g, "%0D%0A") : "");
$("#toastContainer").append($("<div class='toast' role='alert' data-bs-autohide='" + !persistent + "' data-bs-delay='10000'><div class='toast-header'><i class='fas " + icon + "'></i><strong class='me-auto ms-2'>" + type + "</strong><button type='button' class='btn-close' data-bs-dismiss='toast'></button></div><div class='toast-body'><p>" + i18n.__(message) + "</p>" + (fileOrUrl ? "<code>" + fileOrUrl + "</code>" : "") + (action ? "<div class='mt-2 pt-2 border-top'><button type='button' class='btn btn-primary btn-sm toast-action' " + (action ? "data-toast-action-url='" + escape((action && action.url ? action.url : thisBugUrl)) + "'" :"") + ">" + i18n.__(action && action.desc ? action.desc : "reportIssue") + "</button></div>" : "") + "</div></div>").toast("show"));
}
function overlay(show, topIcon, bottomIcon, action) {
return new Promise((resolve) => {
if (!show) {
if (!topIcon || (topIcon && $("#overlayMaster i.fa-" + topIcon).length > 0)) $("#overlayMaster").stop().fadeOut(fadeDelay, () => resolve());
} else {
if ($("#overlayMaster #topIcon i.fa-" + topIcon).length === 0) $("#overlayMaster #topIcon i").removeClass().addClass("fas fa-fw fa-" + topIcon);
$("#overlayMaster #bottomIcon i").removeClass();
if (bottomIcon) {
$("#overlayMaster #bottomIcon i").addClass("fas fa-fw fa-" + bottomIcon + (action ? " " + action : "")).unwrap("button");
$("#overlayMaster #bottomIcon button .action-countdown").html();
if (action) $("#overlayMaster #bottomIcon i").next("span").addBack().wrapAll("<button type='button' class='btn btn-danger btn-action-" + action + " position-relative'></button>");
}
$("#overlayMaster").stop().fadeIn(fadeDelay, () => resolve());
}
});
}
function perf(func, op) {
if (!perfStats[func]) perfStats[func] = {};
perfStats[func][op] = performance.now();
}
function perfPrint() {
for (var perfItem of Object.entries(perfStats).sort((a, b) => a[1].stop - b[1].stop)) {
log.info("%c[perf] [" + perfItem[0] + "] " + (perfItem[1].stop - perfItem[1].start).toFixed(1) + "ms", "background-color: #e2e3e5; color: #41464b;");
}
for (let downloadSource of Object.entries(downloadStats)) {
log.info("%c[perf] [" + downloadSource[0] + "Fetch] " + Object.entries(downloadSource[1]).sort((a,b) => a[0].localeCompare(b[0])).map(downloadOrigin => "from " + downloadOrigin[0] + ": " + (downloadOrigin[1].map(source => source.filesize).reduce((a, b) => a + b, 0) / 1024 / 1024).toFixed(1) + "MB").join(", "), "background-color: #fbe9e7; color: #000;");
}
}
function prefsInitialize() {
for (var pref of ["localAppLang", "lang", "mwDay", "weDay", "autoStartSync", "autoRunAtBoot", "autoQuitWhenDone", "localOutputPath", "enableMp4Conversion", "congServer", "congServerPort", "congServerUser", "congServerPass", "autoOpenFolderWhenDone", "localAdditionalMediaPrompt", "maxRes", "enableMusicButton", "enableMusicFadeOut", "musicFadeOutTime", "musicFadeOutType", "mwStartTime", "weStartTime", "excludeTh", "excludeLffi", "excludeLffiImages"]) {
if (!(Object.keys(prefs).includes(pref)) || !prefs[pref]) prefs[pref] = null;
}
for (let field of ["localAppLang", "lang", "localOutputPath", "congServer", "congServerUser", "congServerPass", "congServerPort", "congServerDir", "musicFadeOutTime", "mwStartTime", "weStartTime"]) {
$("#" + field).val(prefs[field]);
}
for (let timeField of ["mwStartTime", "weStartTime"]) {
$(".timePicker").filter("[data-target='" + timeField + "']").val($("#" + timeField).val());
}
for (let dtPicker of datepickers) {
dtPicker.setDate($(dtPicker.element).val());
}
for (let checkbox of ["autoStartSync", "autoRunAtBoot", "enableMp4Conversion", "autoQuitWhenDone", "autoOpenFolderWhenDone", "localAdditionalMediaPrompt", "enableMusicButton", "enableMusicFadeOut", "excludeTh", "excludeLffi", "excludeLffiImages"]) {
$("#" + checkbox).prop("checked", prefs[checkbox]);
}
for (let radioSel of ["mwDay", "weDay", "maxRes", "musicFadeOutType"]) {
$("#" + radioSel + " input[value=" + prefs[radioSel] + "]").prop("checked", true);
}
}
function progressSet(current, total, blockId) {