-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.ts
1068 lines (969 loc) · 38.1 KB
/
main.ts
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
import {app, BrowserWindow, dialog, globalShortcut, ipcMain, shell} from "electron"
import Store from "electron-store"
import {autoUpdater} from "electron-updater"
import * as localShortcut from "electron-shortcuts"
import fs from "fs"
import imageSize from "image-size"
import path from "path"
import process from "process"
import "./dev-app-update.yml"
import pack from "./package.json"
import functions from "./structures/functions"
import imagemin from "imagemin"
import imageminMozjpeg from "imagemin-mozjpeg"
import imageminGifsicle from "imagemin-gifsicle"
import imageminWebp from "imagemin-webp"
import imageminPngquant from "imagemin-pngquant"
import imagesMeta from "images-meta"
import phash from "sharp-phash"
import dist from "sharp-phash/distance"
import sharp from "sharp"
// @ts-ignore
import Helvetica from "pdfkit/js/data/Helvetica.afm"
import PDFDocument from "@react-pdf/pdfkit"
import child_process from "child_process"
import mkvExtractor from "mkv-subtitle-extractor"
import srt2vtt from "srt-to-vtt"
import ass2srt from "ass-to-srt"
import util from "util"
const exec = util.promisify(child_process.exec)
require("@electron/remote/main").initialize()
process.setMaxListeners(0)
let window: Electron.BrowserWindow | null
let preview: Electron.BrowserWindow | null
let popplerPath = undefined as any
if (process.platform === "darwin") popplerPath = path.join(app.getAppPath(), "../../poppler/mac/bin/pdfimages")
if (process.platform === "win32") popplerPath = path.join(app.getAppPath(), "../../poppler/windows/bin/pdfimages.exe")
if (!fs.existsSync(popplerPath)) popplerPath = undefined
let pnmPath = undefined as any
if (process.platform === "darwin") pnmPath = path.join(app.getAppPath(), "../../poppler/mac/bin/pnmtojpeg")
if (process.platform === "win32") pnmPath = path.join(app.getAppPath(), "../../poppler/windows/bin/pnmtojpeg.exe")
autoUpdater.autoDownload = false
const store = new Store()
const history: Array<{id: number, source: string, dest?: string}> = []
const active: Array<{id: number, source: string, dest: string, action: null | "stop"}> = []
const queue: Array<{started: boolean, info: any}> = []
const removeDoubles = async (images: string[], dontProcessAll?: boolean) => {
images = images.sort(new Intl.Collator(undefined, {numeric: true, sensitivity: "base"}).compare)
let doubleImages: string[] = []
let widthMap = {} as any
for (let i = 0; i < images.length; i++) {
const metadata = await sharp(images[i], {limitInputPixels: false}).metadata()
const width = metadata.width || 0
if (widthMap[width]) {
widthMap[width] += 1
} else {
widthMap[width] = 1
}
}
let commonWidth = 0
let freq = 0
for (let i = 0; i < Object.keys(widthMap).length; i++) {
const key = Object.keys(widthMap)[i]
const value = Object.values(widthMap)[i]
if (freq < Number(value)) {
freq = Number(value)
commonWidth = Number(key)
}
}
for (let i = 0; i < images.length; i++) {
const metadata = await sharp(images[i], {limitInputPixels: false}).metadata()
const width = metadata.width || 0
if (width > commonWidth * 1.5) {
doubleImages.push(images[i])
}
}
// If all images have the same width, treat all of them as doubles
if (!doubleImages.length) {
if (!dontProcessAll) doubleImages = images
}
for (let i = 0; i < doubleImages.length; i++) {
const metadata = await sharp(doubleImages[i], {limitInputPixels: false}).metadata()
const width = metadata.width || 0
const height = metadata.height || 0
const newWidth = Math.floor(width / 2)
const page1 = `${path.dirname(doubleImages[i])}/${path.basename(doubleImages[i], path.extname(doubleImages[i]))}.1${path.extname(doubleImages[i])}`
const page2 = `${path.dirname(doubleImages[i])}/${path.basename(doubleImages[i], path.extname(doubleImages[i]))}.2${path.extname(doubleImages[i])}`
await sharp(doubleImages[i], {limitInputPixels: false})
.extract({left: newWidth, top: 0, width: newWidth, height: height})
.toFile(page1)
await sharp(doubleImages[i], {limitInputPixels: false})
.extract({left: 0, top: 0, width: newWidth, height: height})
.toFile(page2)
}
const promiseArray: any[] = []
for (let i = 0; i < doubleImages.length; i++) {
promiseArray.push(new Promise<void>((resolve) => {
fs.unlink(doubleImages[i], () => resolve())
}))
}
await Promise.all(promiseArray)
}
ipcMain.handle("remove-duplicate-subs", async (event, files: string[]) => {
for (let i = 0; i < files.length; i++) {
const content = fs.readFileSync(files[i]).toString().split("\n")
let obj = {} as any
for (let j = 0; j < content.length; j++) {
if (!Number.isNaN(Number(content[j][0]))) {
if (obj[content[j]]) continue
obj[content[j]] = content[j+1]
}
}
let newContent = "WEBVTT\n\n"
for (let j = 0; j < Object.keys(obj).length; j++) {
const key = Object.keys(obj)[j]
const value = Object.values(obj)[j]
newContent += `${key}\n${value}\n\n`
}
fs.writeFileSync(files[i], newContent)
}
shell.openPath(path.dirname(files[0]))
})
const ppmToJpeg = async (files: string[]) => {
const pnmtojpeg = pnmPath ? pnmPath : "pnmtojpeg"
for (let i = 0; i < files.length; i++) {
await exec(`"${pnmtojpeg}" "${files[i]}" > "${path.dirname(files[i])}/${path.basename(files[i], path.extname(files[i]))}.jpg"`)
}
const promiseArray: any[] = []
for (let i = 0; i < files.length; i++) {
promiseArray.push(new Promise<void>((resolve) => {
fs.unlink(files[i], () => resolve())
}))
}
await Promise.all(promiseArray)
}
const subToVtt = async (subtitles: string[]): Promise<any> => {
const srtSubs = [] as string[]
for (let i = 0; i < subtitles.length; i++) {
await new Promise<void>((resolve, reject) => {
if (path.extname(subtitles[i]) === ".ass") {
const vtt = functions.ass2vtt(fs.readFileSync(subtitles[i]).toString())
const vttDest = `${path.dirname(subtitles[i])}/${path.basename(subtitles[i], path.extname(subtitles[i]))}.vtt`
fs.writeFileSync(vttDest, vtt)
return resolve()
}
const readStream = fs.createReadStream(subtitles[i])
if (path.extname(subtitles[i]) === ".srt") readStream.pipe(srt2vtt())
const writeStream = fs.createWriteStream(`${path.dirname(subtitles[i])}/${path.basename(subtitles[i], path.extname(subtitles[i]))}.vtt`)
readStream.pipe(writeStream)
.on("error", (e) => console.log(e))
.on("end", () => resolve())
.on("finish", () => resolve())
})
}
const promiseArray: any[] = []
for (let i = 0; i < subtitles.length; i++) {
promiseArray.push(new Promise<void>((resolve) => {
fs.unlink(subtitles[i], () => resolve())
}))
}
await Promise.all(promiseArray)
if (srtSubs.length) {
return subToVtt(srtSubs)
}
}
const extractSubtitles = async (videos: string[]) => {
for (let i = 0; i < videos.length; i++) {
await mkvExtractor(videos[i])
}
const promiseArray: any[] = []
for (let i = 0; i < videos.length; i++) {
promiseArray.push(new Promise<void>((resolve) => {
fs.unlink(videos[i], () => resolve())
}))
}
await Promise.all(promiseArray)
}
ipcMain.handle("extract-subtitles", async (event, files: string[]) => {
const directories = files.filter((f) => fs.lstatSync(f).isDirectory())
const videos = files.filter((f) => path.extname(f).toLowerCase() === ".mkv")
const subtitles = files.filter((f) => path.extname(f).toLowerCase() === ".srt" || path.extname(f).toLowerCase() === ".ass")
let openDir = ""
for (let i = 0; i < directories.length; i++) {
const dir = directories[i]
let files = fs.readdirSync(dir).map((i) => path.join(dir, i))
let videos = files.filter((f) => path.extname(f).toLowerCase() === ".mkv")
let subs = files.filter((f) => path.extname(f).toLowerCase() === ".srt" || path.extname(f).toLowerCase() === ".ass")
if (videos.length) {
await extractSubtitles(videos)
let files = fs.readdirSync(dir).map((i) => path.join(dir, i))
let subs = files.filter((f) => path.extname(f).toLowerCase() === ".srt" || path.extname(f).toLowerCase() === ".ass")
await subToVtt(subs)
}
if (subs.length) {
await subToVtt(subs)
}
try {
fs.rmdirSync(dir)
} catch (e) {
console.log(e)
}
if (!openDir) openDir = directories[0]
}
if (videos.length) {
await extractSubtitles(videos)
let subs = fs.readdirSync(path.dirname(videos[0])).map((i) => path.join(path.dirname(videos[0]), i))
subs = subs.filter((f) => path.extname(f).toLowerCase() === ".srt" || path.extname(f).toLowerCase() === ".ass")
await subToVtt(subs)
if (!openDir) openDir = videos[0]
}
if (subtitles.length) {
await subToVtt(subtitles)
if (!openDir) openDir = subtitles[0]
}
shell.openPath(path.dirname(openDir))
})
ipcMain.handle("rename", async (event, files: string[]) => {
const directoryName = path.basename(path.dirname(files[0]))
const fileNames = files.map((f) => path.basename(f, path.extname(f)))
let renamed = false
for (let i = 0; i < fileNames.length; i++) {
const regex = new RegExp(`(?<=${directoryName}) (.*?) (?=.)`, "gi")
const bit = fileNames[i].match(regex)?.[0].trim()
if (!bit) continue
let newFilename = ""
if (/\d+/.test(bit)) {
newFilename = `${directoryName} ${Number(bit.match(/\d+/)?.[0])}`
} else {
let badBit = false
for (let j = 0; j < fileNames.length; j++) {
const testBit = fileNames[j].match(regex)?.[0].trim()
if (`${directoryName} ${bit}` === `${directoryName} ${testBit}`) badBit = true
}
if (badBit) break
newFilename = `${directoryName} ${bit}`
}
const newPath = path.join(path.dirname(files[i]), `${newFilename}${path.extname(files[i])}`)
fs.renameSync(files[i], newPath)
renamed = true
}
if (!renamed) {
files = files.sort(new Intl.Collator(undefined, {numeric: true, sensitivity: "base"}).compare)
for (let i = 0; i < files.length; i++) {
const newPath = path.join(path.dirname(files[i]), `${directoryName} ${i + 1}${path.extname(files[i])}`)
fs.renameSync(files[i], newPath)
}
}
shell.openPath(path.dirname(files[0]))
})
const extractCover = async (dir: string, images: string[]) => {
images = images.sort(new Intl.Collator(undefined, {numeric: true, sensitivity: "base"}).compare)
fs.writeFileSync(`${path.dirname(dir)}/${path.basename(dir, path.extname(dir))}.jpg`, fs.readFileSync(images[0]))
const promiseArray: any[] = []
for (let i = 0; i < images.length; i++) {
promiseArray.push(new Promise<void>((resolve) => {
fs.unlink(images[i], () => resolve())
}))
}
await Promise.all(promiseArray)
}
const createPDF = async (dir: string, images: string[]) => {
images = images.sort(new Intl.Collator(undefined, {numeric: true, sensitivity: "base"}).compare)
const pdf = new PDFDocument({autoFirstPage: false})
pdf.pipe(fs.createWriteStream(`${path.dirname(dir)}/${path.basename(dir, path.extname(dir))}.pdf`))
for (let i = 0; i < images.length; i++) {
const image = pdf.openImage(images[i])
pdf.addPage({size: [image.width, image.height]})
pdf.image(image, 0, 0)
}
const promiseArray: any[] = []
for (let i = 0; i < images.length; i++) {
promiseArray.push(new Promise<void>((resolve) => {
fs.unlink(images[i], () => resolve())
}))
}
await Promise.all(promiseArray)
pdf.end()
}
ipcMain.handle("pdf-cover", async (event, files: string[]) => {
const directories = files.filter((f) => fs.lstatSync(f).isDirectory())
const PDFs = files.filter((f) => path.extname(f) === ".pdf")
const images = files.filter((f) => path.extname(f).toLowerCase() === ".jpg" || path.extname(f).toLowerCase() === ".png" || path.extname(f).toLowerCase() === ".jpeg")
let openDir = ""
for (let i = 0; i < PDFs.length; i++) {
const dir = path.dirname(PDFs[i])
const saveFilename = path.basename(PDFs[i], path.extname(PDFs[i]))
const savePath = path.join(dir, saveFilename)
if (!fs.existsSync(savePath)) fs.mkdirSync(savePath)
const pdfimages = popplerPath ? popplerPath : "pdfimages"
exec(`cd "${savePath}" && "${pdfimages}" -png -j -q "${PDFs[i]}" "${saveFilename}"`)
.then(async () => {
fs.unlinkSync(PDFs[i])
let images = fs.readdirSync(savePath).map((i) => path.join(savePath, i))
images = images.filter((f) => path.extname(f).toLowerCase() === ".jpg" || path.extname(f).toLowerCase() === ".png" || path.extname(f).toLowerCase() === ".jpeg")
await extractCover(savePath, images)
try {
fs.rmdirSync(savePath)
} catch (e) {
console.log(e)
}
})
.catch((e) => window?.webContents.send("debug", e))
if (!openDir) openDir = PDFs[0]
}
for (let i = 0; i < directories.length; i++) {
const dir = directories[i]
let images = fs.readdirSync(dir).map((i) => path.join(dir, i))
images = images.filter((f) => path.extname(f).toLowerCase() === ".jpg" || path.extname(f).toLowerCase() === ".png" || path.extname(f).toLowerCase() === ".jpeg")
await removeDoubles(images, true)
if (!openDir) openDir = images[0]
}
if (images.length) {
await removeDoubles(images)
if (!openDir) openDir = images[0]
}
shell.openPath(path.dirname(openDir))
})
ipcMain.handle("pdf", async (event, files: string[]) => {
const directories = files.filter((f) => fs.lstatSync(f).isDirectory())
const PDFs = files.filter((f) => path.extname(f) === ".pdf")
const images = files.filter((f) => path.extname(f).toLowerCase() === ".jpg" || path.extname(f).toLowerCase() === ".png" || path.extname(f).toLowerCase() === ".jpeg")
const PPM = files.filter((f) => path.extname(f).toLowerCase() === ".ppm")
if (PPM.length) {
await ppmToJpeg(PPM)
return shell.openPath(path.dirname(PPM[0]))
}
let openDir = ""
for (let i = 0; i < directories.length; i++) {
const dir = directories[i]
let images = fs.readdirSync(dir).map((i) => path.join(dir, i))
images = images.filter((f) => path.extname(f).toLowerCase() === ".jpg" || path.extname(f).toLowerCase() === ".png" || path.extname(f).toLowerCase() === ".jpeg")
await createPDF(dir, images)
try {
fs.rmdirSync(dir)
} catch (e) {
console.log(e)
}
if (!openDir) openDir = directories[0]
}
for (let i = 0; i < PDFs.length; i++) {
const dir = path.dirname(PDFs[i])
const saveFilename = path.basename(PDFs[i], path.extname(PDFs[i]))
const savePath = path.join(dir, saveFilename)
if (!fs.existsSync(savePath)) fs.mkdirSync(savePath)
const pdfimages = popplerPath ? popplerPath : "pdfimages"
exec(`cd "${savePath}" && "${pdfimages}" -j -q "${PDFs[i]}" "${saveFilename}"`)
.then(() => fs.unlinkSync(PDFs[i]))
.catch((e) => window?.webContents.send("debug", e))
if (!openDir) openDir = PDFs[0]
}
if (images.length) {
await createPDF(images[0], images)
if (!openDir) openDir = images[0]
}
shell.openPath(path.dirname(openDir))
})
ipcMain.handle("multi-open", async (event, type?: string) => {
let title = "Convert or Extract PDF"
let button = "Convert"
if (type === "cover") title = "PDF or Image Directory Cover"
if (type === "rename") {
title = "Rename by Directory"
button = "Rename"
}
if (type === "subs") {
title = "Convert to VTT Subtitles"
button = "Convert"
}
if (!window) return
const result = await dialog.showOpenDialog(window, {
properties: ["openFile", "openDirectory", "multiSelections"],
buttonLabel: button,
title
})
return result.filePaths
})
const subFiles = (directory: string) => {
let files: string[] = []
let directories: string[] = []
let dirFiles = fs.readdirSync(directory).map((f) => `${directory}/${f}`)
dirFiles = dirFiles.sort(new Intl.Collator(undefined, {numeric: true, sensitivity: "base"}).compare)
for (let i = 0; i < dirFiles.length; i++) {
if (fs.lstatSync(dirFiles[i]).isDirectory()) {
directories.push(dirFiles[i])
const sub = subFiles(dirFiles[i])
files.push(...sub.files)
directories.push(...sub.directories)
} else {
files.push(dirFiles[i])
}
}
return {files, directories}
}
ipcMain.handle("flatten", async (event, directory: string) => {
const {files, directories} = subFiles(directory)
let conflict = false
loop1:
for (let i = 0; i < files.length; i++) {
let newName = path.basename(files[i])
for (let j = 0; j < files.length; j++) {
if (`${path.dirname(files[i])}/${path.basename(files[i])}` === `${path.dirname(files[j])}/${path.basename(files[j])}`) continue
let checkName = path.basename(files[j])
if (newName === checkName) {
conflict = true
break loop1
}
}
}
let renameIndex = 0
for (let i = 0; i < files.length; i++) {
let newName = `${directory}/${path.basename(files[i])}`
if (conflict) newName = `${directory}/${renameIndex}_${path.basename(files[i])}`
fs.renameSync(files[i], newName)
renameIndex++
}
for (let i = 0; i < directories.length; i++) {
fs.rmdirSync(directories[i])
}
shell.openPath(directory)
})
ipcMain.handle("flatten-directory", async () => {
if (!window) return
const result = await dialog.showOpenDialog(window, {
properties: ["openDirectory"],
buttonLabel: "Flatten",
title: "Flatten Directory"
})
return result.filePaths[0]
})
ipcMain.handle("zoom-out", () => {
preview?.webContents.send("zoom-out")
})
ipcMain.handle("zoom-in", () => {
preview?.webContents.send("zoom-in")
})
const openPreview = async () => {
if (!preview) {
preview = new BrowserWindow({width: 800, height: 600, minWidth: 720, minHeight: 450, frame: false, backgroundColor: "#181818", center: false, webPreferences: {nodeIntegration: true, contextIsolation: false}})
await preview.loadFile(path.join(__dirname, "preview.html"))
require("@electron/remote/main").enable(preview.webContents)
preview?.on("closed", () => {
preview = null
})
} else {
if (preview.isMinimized()) preview.restore()
preview.focus()
}
}
ipcMain.handle("preview-realtime", async (event, info: any) => {
preview?.webContents.send("update-buffer-realtime", info)
})
ipcMain.handle("preview", async (event, info: any) => {
await openPreview()
preview?.webContents.send("update-buffer", info)
})
ipcMain.handle("on-drop", async (event, files: any) => {
window?.webContents.send("on-drop", files)
})
const getDimensions = (path: string) => {
try {
const dimensions = imageSize(path)
return {width: dimensions.width ?? 0, height: dimensions.height ?? 0}
} catch {
return {width: 0, height: 0}
}
}
ipcMain.handle("get-dimensions", async (event, path: string) => {
return getDimensions(path)
})
ipcMain.handle("delete-duplicates", async () => {
const hashMap = new Map()
for (let i = 0; i < history.length; i++) {
const source = history[i].source
if (fs.existsSync(source)) {
try {
const hash = await phash(fs.readFileSync(source))
let dupeArray = []
let found = false
hashMap.forEach((value, key) => {
if (dist(key, hash) < 5) {
dupeArray = functions.removeDuplicates([...value, source])
hashMap.set(key, dupeArray)
found = true
}
})
if (!found) {
dupeArray = [source]
hashMap.set(hash, dupeArray)
}
} catch {
continue
}
}
}
hashMap.forEach(async (value: string[]) => {
if (value.length > 1) {
let arr = []
for (let i = 0; i < value.length; i++) {
const {width, height} = getDimensions(value[i])
const id = history.find((h) => h.source === value[i])?.id
arr.push({id, width, height, source: value[i]})
}
arr = arr.sort((a, b) => a.width - b.width)
while (arr.length > 1) {
const val = arr.shift()
let counter = 1
let error = true
while (error && counter < 20) {
await functions.timeout(100)
try {
fs.unlinkSync(val?.source!)
error = false
} catch {
// ignore
}
counter++
}
window?.webContents.send("deleted-source", {id: val?.id})
}
}
})
})
ipcMain.handle("close-conversion", async (event, id: number) => {
let index = history.findIndex((h) => h.id === id)
if (index !== -1) history.splice(index, 1)
})
ipcMain.handle("delete-conversion", async (event, id: number) => {
let dest = ""
let source = ""
let index = active.findIndex((a) => a.id === id)
if (index !== -1) {
active[index].action = "stop"
dest = active[index].dest
source = active[index].source
} else {
index = history.findIndex((a) => a.id === id)
if (index !== -1) {
dest = history[index].dest as string
source = history[index].source
}
}
if (dest) {
let counter = 1
let error = true
while (error && counter < 20) {
await functions.timeout(100)
try {
fs.unlinkSync(dest)
error = false
} catch {
// ignore
}
counter++
}
return true
}
return false
})
const nextQueue = async (info: any) => {
const index = active.findIndex((a) => a.id === info.id)
if (index !== -1) active.splice(index, 1)
const settings = store.get("settings", {}) as any
let qIndex = queue.findIndex((q) => q.info.id === info.id)
if (qIndex !== -1) {
queue.splice(qIndex, 1)
let concurrent = 1 // Number(settings?.queue)
if (Number.isNaN(concurrent) || concurrent < 1) concurrent = 1
if (active.length < concurrent) {
const next = queue.find((q) => !q.started)
if (next) {
await compress(next.info)
}
}
}
}
const compress = async (info: any) => {
let qIndex = queue.findIndex((q) => q.info.id === info.id)
if (qIndex !== -1) queue[qIndex].started = true
const options = {
quality: Number(info.quality),
overwrite: info.overwrite,
ignoreBelow: info.ignoreBelow,
resizeWidth: Number(info.resizeWidth),
resizeHeight: Number(info.resizeHeight),
percentage: info.percentage,
keepRatio: info.keepRatio,
rename: info.rename,
format: info.format,
progressive: info.progressive
}
window?.webContents.send("conversion-started", {id: info.id})
const fileSize = functions.parseFileSize(info.fileSize)
const ignoredSize = functions.parseFileSize(options.ignoreBelow)
if (fileSize < ignoredSize) {
window?.webContents.send("conversion-finished", {id: info.id, output: info.source, skipped: true})
return nextQueue(info)
}
const {width, height} = functions.parseNewDimensions(info.width, info.height, options.resizeWidth, options.resizeHeight, options.percentage, options.keepRatio)
if (!fs.existsSync(info.dest)) fs.mkdirSync(info.dest, {recursive: true})
let dest = await functions.parseDest(info.source, info.dest, options.rename, options.format, width, height, options.overwrite)
const historyIndex = history.findIndex((h) => h.id === info.id)
if (historyIndex !== -1) history[historyIndex].dest = dest
const activeIndex = active.findIndex((a) => a.id === info.id)
if (activeIndex !== -1) active[activeIndex].dest = dest
let meta = []
let output = ""
let buffer = fs.readFileSync(info.source)
try {
let inMime = "image/jpeg"
if (path.extname(info.source) === ".png") inMime = "image/png"
meta = imagesMeta.readMeta(buffer, inMime)
for (let i = 0; i < meta.length; i++) {
if (typeof meta[i].value !== "string") meta[i].value = ""
meta[i].value = meta[i].value.replaceAll("UNICODE", "").replaceAll(/\u0000/g, "")
}
} catch {}
try {
const sourceExt = path.extname(info.source).replaceAll(".", "")
const ext = path.extname(dest).replaceAll(".", "")
const resizeCondition = options.keepRatio ? (options.percentage ? options.resizeWidth !== 100 : true) : (options.percentage ? (options.resizeWidth !== 100 && options.resizeHeight !== 100) : true)
let isAnimated = sourceExt === "gif"
if (sourceExt === "webp") {
isAnimated = functions.isAnimatedWebp(buffer)
}
if (ext === "gif") {
if (resizeCondition) {
if (process.platform === "win32") {
const {frameArray, delayArray} = await functions.getGIFFrames(info.source)
const newFrameArray = [] as Buffer[]
for (let i = 0; i < frameArray.length; i++) {
const newFrame = await sharp(frameArray[i], {limitInputPixels: false})
.resize(width, height, {fit: "fill"})
.toBuffer()
newFrameArray.push(newFrame)
}
buffer = await functions.encodeGIF(newFrameArray, delayArray, width, height)
} else {
buffer = await sharp(buffer, {animated: true, limitInputPixels: false}).resize(width, height, {fit: "fill"}).gif().toBuffer()
}
if (options.quality !== 100) {
buffer = await imagemin.buffer(buffer, {plugins: [
imageminGifsicle({optimizationLevel: 3})
]})
}
} else {
if (options.quality !== 100) {
buffer = await imagemin([info.source], {plugins: [
imageminGifsicle({optimizationLevel: 3})
]}).then((i: any) => i[0].data)
}
}
} else {
if (resizeCondition) {
buffer = await sharp(buffer, {animated: true, limitInputPixels: false}).resize(width, height, {fit: "fill"}).toBuffer()
}
let s = sharp(buffer, {animated: true, limitInputPixels: false})
if (ext === "jpg" || ext === "jpeg") s.jpeg({optimiseScans: options.progressive, quality: options.quality, trellisQuantisation: true})
if (ext === "png") s.png({quality: options.quality})
if (ext === "webp") s.webp({quality: options.quality})
if (ext === "avif") s.avif({quality: options.quality})
if (ext === "jxl") s.jxl({quality: options.quality})
if (ext === "gif") s.gif()
buffer = await s.toBuffer()
if (options.quality < 95) {
if (!isAnimated && ext !== "avif" && ext !== "jxl") {
buffer = await imagemin.buffer(buffer, {plugins: [
imageminMozjpeg({quality: options.quality}),
imageminPngquant(),
imageminWebp({quality: options.quality}),
imageminGifsicle({optimizationLevel: 3})
]})
}
}
}
fs.writeFileSync(options.overwrite ? info.source : dest, buffer)
if (options.overwrite) {
fs.renameSync(info.source, dest)
}
output = dest
if (meta?.length) {
let outMime = "image/jpeg"
if (path.extname(output) === ".png") outMime = "image/png"
let metaBuffer = imagesMeta.writeMeta(fs.readFileSync(output), outMime, meta, "buffer")
fs.writeFileSync(output, metaBuffer)
}
window?.webContents.send("conversion-finished", {id: info.id, output, buffer, fileSize: Buffer.byteLength(buffer)})
return nextQueue(info)
} catch (error) {
console.log(error)
window?.webContents.send("conversion-finished", {id: info.id, output: info.source, skipped: true})
return nextQueue(info)
}
}
ipcMain.handle("compress", async (event, info: any, startAll: boolean) => {
const qIndex = queue.findIndex((q) => q.info.id === info.id)
if (qIndex === -1) queue.push({info, started: false})
if (startAll) {
const settings = store.get("settings", {}) as any
let concurrent = 1 // Number(settings?.queue)
if (Number.isNaN(concurrent) || concurrent < 1) concurrent = 1
if (active.length < concurrent) {
active.push({id: info.id, source: info.source, dest: "", action: null})
await compress(info)
}
} else {
active.push({id: info.id, source: info.source, dest: "", action: null})
await compress(info)
}
})
ipcMain.handle("compress-realtime", async (event, info: any) => {
const options = {
quality: Number(info.quality),
overwrite: info.overwrite,
ignoreBelow: info.ignoreBelow,
resizeWidth: Number(info.resizeWidth),
resizeHeight: Number(info.resizeHeight),
percentage: info.percentage,
keepRatio: info.keepRatio,
rename: info.rename,
format: info.format,
progressive: info.progressive
}
const fileSize = functions.parseFileSize(info.fileSize)
const ignoredSize = functions.parseFileSize(options.ignoreBelow)
if (fileSize < ignoredSize) {
return {buffer: info.source, fileSize}
}
const {width, height} = functions.parseNewDimensions(info.width, info.height, options.resizeWidth, options.resizeHeight, options.percentage, options.keepRatio)
const dest = await functions.parseDest(info.source, info.dest, "{name}", options.format, width, height, options.overwrite)
let buffer = fs.readFileSync(info.source)
try {
const sourceExt = path.extname(info.source).replaceAll(".", "")
const ext = path.extname(dest).replaceAll(".", "")
const resizeCondition = options.keepRatio ? (options.percentage ? options.resizeWidth !== 100 : true) : (options.percentage ? (options.resizeWidth !== 100 && options.resizeHeight !== 100) : true)
let isAnimated = sourceExt === "gif"
if (sourceExt === "webp") {
isAnimated = functions.isAnimatedWebp(buffer)
}
if (ext === "gif") {
if (resizeCondition) {
if (process.platform === "win32") {
const {frameArray, delayArray} = await functions.getGIFFrames(info.source)
const newFrameArray = [] as Buffer[]
for (let i = 0; i < frameArray.length; i++) {
const newFrame = await sharp(frameArray[i], {limitInputPixels: false})
.resize(width, height, {fit: "fill"})
.toBuffer()
newFrameArray.push(newFrame)
}
buffer = await functions.encodeGIF(newFrameArray, delayArray, width, height)
} else {
buffer = await sharp(buffer, {animated: true, limitInputPixels: false}).resize(width, height, {fit: "fill"}).gif().toBuffer()
}
if (options.quality !== 100) {
buffer = await imagemin.buffer(buffer, {plugins: [
imageminGifsicle({optimizationLevel: 3})
]})
}
} else {
if (options.quality !== 100) {
buffer = await imagemin([info.source], {plugins: [
imageminGifsicle({optimizationLevel: 3})
]}).then((i: any) => i[0].data)
}
}
} else {
if (resizeCondition) {
buffer = await sharp(buffer, {animated: true, limitInputPixels: false}).resize(width, height, {fit: "fill"}).toBuffer()
}
let s = sharp(buffer, {animated: true, limitInputPixels: false})
if (ext === "jpg" || ext === "jpeg") s.jpeg({optimiseScans: options.progressive, quality: options.quality})
if (ext === "png") s.png({quality: options.quality})
if (ext === "webp") s.webp({quality: options.quality})
if (ext === "avif") s.avif({quality: options.quality})
if (ext === "jxl") s.jxl({quality: options.quality})
if (ext === "gif") s.gif()
buffer = await s.toBuffer()
if (options.quality < 95) {
if (!isAnimated && ext !== "avif" && ext !== "jxl") {
buffer = await imagemin.buffer(buffer, {plugins: [
imageminMozjpeg({quality: options.quality}),
imageminPngquant(),
imageminWebp({quality: options.quality}),
imageminGifsicle({optimizationLevel: 3})
]})
}
}
}
return {buffer, fileSize: Buffer.byteLength(buffer)}
} catch (error) {
console.log(error)
return {buffer: info.source, fileSize}
}
})
ipcMain.handle("update-concurrency", async (event, concurrent) => {
if (Number.isNaN(concurrent) || concurrent < 1) concurrent = 1
let counter = active.length
while (counter < concurrent) {
const next = queue.find((q) => !q.started)
if (next) {
counter++
await compress(next.info)
} else {
break
}
}
})
ipcMain.handle("move-queue", async (event, id: number) => {
const settings = store.get("settings", {}) as any
let concurrent = 1 // Number(settings?.queue)
if (Number.isNaN(concurrent) || concurrent < 1) concurrent = 1
if (id) {
let qIndex = queue.findIndex((q) => q.info.id === id)
if (qIndex !== -1) queue.splice(qIndex, 1)
}
if (active.length < concurrent) {
const next = queue.find((q) => !q.started)
if (next) {
await compress(next.info)
}
}
})
ipcMain.handle("update-color", (event, color: string) => {
window?.webContents.send("update-color", color)
})
ipcMain.handle("init-settings", () => {
return store.get("settings", null)
})
ipcMain.handle("store-settings", (event, settings) => {
const prev = store.get("settings", {}) as object
store.set("settings", {...prev, ...settings})
})
ipcMain.handle("get-theme", () => {
return store.get("theme", "light")
})
ipcMain.handle("save-theme", (event, theme: string) => {
store.set("theme", theme)
})
ipcMain.handle("install-update", async (event) => {
if (process.platform === "darwin") {
const update = await autoUpdater.checkForUpdates()
const url = `${pack.repository.url}/releases/download/v${update.updateInfo.version}/${update.updateInfo.files[0].url}`
await shell.openExternal(url)
app.quit()
} else {
await autoUpdater.downloadUpdate()
autoUpdater.quitAndInstall()
}
})
ipcMain.handle("check-for-updates", async (event, startup: boolean) => {
window?.webContents.send("close-all-dialogs", "version")
const update = await autoUpdater.checkForUpdates()
const newVersion = update.updateInfo.version
if (pack.version === newVersion) {
if (!startup) window?.webContents.send("show-version-dialog", null)
} else {
window?.webContents.send("show-version-dialog", newVersion)
}
})
ipcMain.handle("open-location", async (event, location: string) => {
if (!fs.existsSync(location)) return
if (fs.statSync(location).isDirectory()) {
shell.openPath(path.normalize(location))
} else {
shell.showItemInFolder(path.normalize(location))
}
})
ipcMain.handle("start-all", () => {
window?.webContents.send("start-all")
})
ipcMain.handle("clear-all", () => {
window?.webContents.send("clear-all")
})
ipcMain.handle("add-files", (event, files: string[], identifers: number[]) => {
for (let i = 0; i < files.length; i++) {
history.push({id: identifers[i], source: files[i]})
}
window?.webContents.send("add-files", files, identifers)
})
ipcMain.handle("add-file-id", (event, file: string, pos: number, id: number) => {
history.push({id, source: file})
window?.webContents.send("add-file-id", file, pos, id)
})
ipcMain.handle("add-file", (event, file: string, pos: number) => {
window?.webContents.send("add-file", file, pos)
})
ipcMain.handle("select-files", async () => {
if (!window) return
const files = await dialog.showOpenDialog(window, {
filters: [
{name: "All Files", extensions: ["*"]},
{name: "Images", extensions: ["png", "jpg", "jpeg", "webp", "avif", "tiff"]},
{name: "GIF", extensions: ["gif"]}
],
properties: ["multiSelections", "openFile", "openDirectory"]
})
const filePaths = files.filePaths
if (filePaths.length === 1) {
if (fs.lstatSync(filePaths[0]).isDirectory()) {
return fs.readdirSync(filePaths[0]).map((f) => `${filePaths[0]}/${f}`)
}
}
return filePaths
})
ipcMain.handle("get-downloads-folder", async () => {
if (store.has("downloads")) {
return store.get("downloads")