forked from SchneeHertz/exhentai-manga-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1047 lines (950 loc) · 32.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
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 { app, BrowserWindow, ipcMain, session, dialog, shell, screen, Menu, clipboard, nativeImage } = require('electron')
const path = require('path')
const fs = require('fs')
const { brotliDecompress } = require('zlib')
const { promisify, format } = require('util')
const _ = require('lodash')
const { nanoid } = require('nanoid')
const sharp = require('sharp')
const { exec } = require('child_process')
const { createHash } = require('crypto')
const sqlite3 = require('sqlite3')
const { open } = require('sqlite')
const fetch = require('node-fetch')
const { HttpsProxyAgent } = require('https-proxy-agent')
const windowStateKeeper = require('electron-window-state')
const express = require('express')
const { prepareMangaModel, prepareMetadataModel } = require('./modules/database')
const { prepareTemplate } = require('./modules/prepare_menu.js')
const { getBookFilelist, geneCover, getImageListByBook, deleteImageFromBook } = require('./fileLoader/index.js')
const { STORE_PATH, TEMP_PATH, COVER_PATH, VIEWER_PATH, prepareSetting, prepareCollectionList, preparePath } = require('./modules/init_folder_setting.js')
preparePath()
let setting = prepareSetting()
let collectionList = prepareCollectionList()
const Manga = prepareMangaModel(path.join(STORE_PATH, './database.sqlite'))
let metadataSqliteFile
if (setting.metadataPath) {
metadataSqliteFile = path.join(setting.metadataPath, './metadata.sqlite')
} else {
metadataSqliteFile = path.join(STORE_PATH, './metadata.sqlite')
}
let Metadata = prepareMetadataModel(metadataSqliteFile)
const getColumns = async (sequelize, tableName) => {
const query = `PRAGMA table_info(${tableName})`
const [results] = await sequelize.query(query)
return results.map(column => column.name)
}
;(async () => {
const columns = await getColumns(Manga.sequelize, 'Mangas')
if (['hiddenBook', 'readCount'].some(c => !columns.includes(c))) {
await Manga.sync({ alter: true })
} else {
await Manga.sync()
}
await Metadata.sync()
})()
const logFile = fs.createWriteStream(path.join(STORE_PATH, 'log.txt'), { flags: 'w' })
const logStdout = process.stdout
console.log = (...message) => {
logFile.write(format(...message) + '\n')
logStdout.write(format(...message) + '\n')
}
process
.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason)
})
.on('uncaughtException', err => {
console.log(err, 'Uncaught Exception thrown')
process.exit(1)
})
const sendMessageToWebContents = (message) => {
console.log(message)
mainWindow.webContents.send('send-message', message)
}
let mainWindow
let screenWidth
let sendImageLock = false
const createWindow = () => {
const mainWindowState = windowStateKeeper({
defaultWidth: 1560,
defaultHeight: 1000
})
const win = new BrowserWindow({
'x': mainWindowState.x,
'y': mainWindowState.y,
'width': mainWindowState.width,
'height': mainWindowState.height,
webPreferences: {
webSecurity: app.isPackaged ? true : false,
preload: path.join(__dirname, 'preload.js')
},
show: false
})
mainWindowState.manage(win)
if (app.isPackaged) {
win.loadFile('dist/index.html')
} else {
win.loadURL('http://localhost:5374')
}
win.setMenuBarVisibility(false)
win.setAutoHideMenuBar(true)
const menu = Menu.buildFromTemplate(prepareTemplate(win))
Menu.setApplicationMenu(menu)
win.webContents.on('did-finish-load', () => {
const name = require('./package.json').name
const version = require('./package.json').version
win.setTitle(name + ' ' + version)
})
win.once('ready-to-show', () => {
win.show()
})
return win
}
app.commandLine.appendSwitch('js-flags', '--max-old-space-size=65536')
// app.disableHardwareAcceleration()
app.whenReady().then(async () => {
const primaryDisplay = screen.getPrimaryDisplay()
screenWidth = Math.floor(primaryDisplay.workAreaSize.width * primaryDisplay.scaleFactor)
mainWindow = createWindow()
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
mainWindow = createWindow()
}
})
app.on('ready', async () => {
if (setting.proxy) {
await session.defaultSession.setProxy({
mode: 'fixed_servers',
proxyRules: setting.proxy
})
}
// session.defaultSession.loadExtension(path.join(__dirname, './devtools'))
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
process.on('exit', () => {
app.quit()
})
// base function
const loadBookListFromBrFile = async () => {
try {
const buffer = await fs.promises.readFile(path.join(STORE_PATH, 'bookList.json.br'))
const decodeBuffer = await promisify(brotliDecompress)(buffer)
return JSON.parse(decodeBuffer.toString())
} catch {
return JSON.parse(await fs.promises.readFile(path.join(STORE_PATH, 'bookList.json'), { encoding: 'utf-8' }))
}
}
const loadLegecyBookListFromFile = async () => {
const bookList = await loadBookListFromBrFile()
try {
shell.trashItem(path.join(STORE_PATH, 'bookList.json.br'))
shell.trashItem(path.join(STORE_PATH, 'bookList.json'))
} catch {
console.log('Remove Legecy BookList Failed')
}
return bookList
}
const loadBookListFromDatabase = async () => {
let bookList = await Manga.findAll()
bookList = bookList.map(b => b.toJSON())
if (_.isEmpty(bookList)) {
bookList = await loadLegecyBookListFromFile()
await saveBookListToDatabase(bookList)
}
let metadataList = await Metadata.findAll()
metadataList = metadataList.map(m => m.toJSON())
const bookListLength = bookList.length
for (let i = 0; i < bookListLength; i++) {
const book = bookList[i]
const findMetadata = metadataList.find(m => m.hash === book.hash)
if (findMetadata) {
Object.assign(book, findMetadata)
} else {
setProgressBar((i + 1) / bookListLength)
await Metadata.upsert(book)
}
}
setProgressBar(-1)
return bookList
}
const saveBookListToDatabase = async (data) => {
console.log('Empty Exist BookList and Saved New BookList')
await Manga.destroy({ truncate: true })
await Manga.bulkCreate(data)
}
const saveBookToDatabase = async (book) => {
await Manga.update(book, { where: { id: book.id } })
await Metadata.upsert(book)
console.log(`Saved ${book.title}`)
}
const setProgressBar = (progress) => {
mainWindow.setProgressBar(progress)
mainWindow.webContents.send('send-action', {
action: 'send-progress',
progress
})
}
const clearFolder = async (Folder) => {
try {
await fs.promises.rm(Folder, { recursive: true, force: true })
await fs.promises.mkdir(Folder, { recursive: true })
} catch (err) {
console.log(err)
}
}
// library and metadata
ipcMain.handle('load-book-list', async (event, scan) => {
if (scan) {
sendMessageToWebContents('Start loading library')
const bookList = await Manga.findAll({ raw: true })
bookList.forEach(b => b.exist = false)
let list = await getBookFilelist(setting.library)
if (!_.isEmpty(setting.excludeFile)) {
let excludeRe
try {
excludeRe = new RegExp(setting.excludeFile)
list = _.filter(list, file => !excludeRe.test(file.filepath))
} catch {
console.log('Illegal regular expressions')
}
}
const listLength = list.length
sendMessageToWebContents(`Load ${listLength} book from library`)
for (let i = 0; i < listLength; i++) {
try {
const { filepath, type } = list[i]
const foundData = bookList.find(b => b.filepath === filepath)
if (foundData === undefined) {
const id = nanoid()
const { targetFilePath, coverPath, pageCount, bundleSize, mtime, coverHash } = await geneCover(filepath, type)
if (targetFilePath && coverPath) {
const hash = createHash('sha1').update(fs.readFileSync(targetFilePath)).digest('hex')
const newBook = {
title: path.basename(filepath),
coverPath,
hash,
filepath,
type,
id,
pageCount,
bundleSize,
mtime: mtime.toJSON(),
coverHash,
status: 'non-tag',
exist: true,
date: Date.now()
}
await Manga.create(newBook)
bookList.push(newBook)
}
} else {
foundData.exist = true
foundData.coverPath = path.join(COVER_PATH, path.basename(foundData.coverPath))
}
if ((i + 1) % 50 === 0) {
setProgressBar(i / listLength)
await clearFolder(TEMP_PATH)
}
} catch (e) {
sendMessageToWebContents(`Load ${list[i].filepath} failed because ${e}, ${i + 1} of ${listLength}`)
}
}
await clearFolder(TEMP_PATH)
const existData = bookList.filter(b => b.exist === true)
try {
const coverList = await fs.promises.readdir(COVER_PATH)
const existCoverList = existData.map(b => b.coverPath)
const removeCoverList = _.difference(coverList.map(p => path.join(COVER_PATH, p)), existCoverList)
for (const coverPath of removeCoverList) {
await fs.promises.rm(coverPath)
}
} catch (err) {
console.log(err)
}
const removeData = bookList.filter(b => b.exist === false)
for (const book of removeData) {
await Manga.destroy({ where: { id: book.id } })
}
setProgressBar(-1)
}
return await loadBookListFromDatabase()
})
ipcMain.handle('force-gene-book-list', async (event, arg) => {
await Manga.destroy({ truncate: true })
await clearFolder(TEMP_PATH)
await clearFolder(COVER_PATH)
sendMessageToWebContents('Start loading library')
let list = await getBookFilelist(setting.library)
if (!_.isEmpty(setting.excludeFile)) {
let excludeRe
try {
excludeRe = new RegExp(setting.excludeFile)
list = _.filter(list, file => !excludeRe.test(file.filepath))
} catch {
console.log('Illegal regular expressions')
}
}
const listLength = list.length
sendMessageToWebContents(`Load ${listLength} book from library`)
for (let i = 0; i < listLength; i++) {
try {
const { filepath, type } = list[i]
const id = nanoid()
const { targetFilePath, coverPath, pageCount, bundleSize, mtime, coverHash } = await geneCover(filepath, type)
if (targetFilePath && coverPath) {
const hash = createHash('sha1').update(fs.readFileSync(targetFilePath)).digest('hex')
await Manga.create({
title: path.basename(filepath),
coverPath,
hash,
filepath,
type,
id,
pageCount,
bundleSize,
mtime: mtime.toJSON(),
coverHash,
status: 'non-tag',
date: Date.now()
})
}
if ((i + 1) % 50 === 0) await clearFolder(TEMP_PATH)
setProgressBar(i / listLength)
} catch (e) {
sendMessageToWebContents(`Load ${list[i].filepath} failed because ${e}, ${i + 1} of ${listLength}`)
}
}
await clearFolder(TEMP_PATH)
setProgressBar(-1)
return await loadBookListFromDatabase()
})
ipcMain.handle('patch-local-metadata', async (event, arg) => {
const bookList = await loadBookListFromDatabase()
const bookListLength = bookList.length
await clearFolder(TEMP_PATH)
await clearFolder(COVER_PATH)
for (let i = 0; i < bookListLength; i++) {
try {
const book = bookList[i]
let { filepath, type } = book
if (!type) type = 'archive'
const { targetFilePath, coverPath, pageCount, bundleSize, mtime, coverHash } = await geneCover(filepath, type)
if (targetFilePath && coverPath) {
const hash = createHash('sha1').update(fs.readFileSync(targetFilePath)).digest('hex')
_.assign(book, { type, coverPath, hash, pageCount, bundleSize, mtime: mtime.toJSON(), coverHash })
await saveBookToDatabase(book)
}
if ((i + 1) % 50 === 0) await clearFolder(TEMP_PATH)
setProgressBar(i / bookListLength)
} catch (e) {
sendMessageToWebContents(`Patch ${bookList[i].filepath} failed because ${e}`)
}
}
await clearFolder(TEMP_PATH)
setProgressBar(-1)
return bookList
})
ipcMain.handle('patch-local-metadata-by-book', async (event, book) => {
let { filepath, type } = book
if (!type) type = 'archive'
try {
const { targetFilePath, coverPath, pageCount, bundleSize, mtime, coverHash } = await geneCover(filepath, type)
if (targetFilePath && coverPath) {
const hash = createHash('sha1').update(fs.readFileSync(targetFilePath)).digest('hex')
await clearFolder(TEMP_PATH)
return Promise.resolve({ coverPath, hash, pageCount, bundleSize, mtime: mtime.toJSON(), coverHash })
}
} catch (e) {
sendMessageToWebContents(`Patch ${book.filepath} failed because ${e}`)
await clearFolder(TEMP_PATH)
return Promise.reject()
}
})
ipcMain.handle('get-ex-webpage', async (event, { url, cookie }) => {
if (setting.proxy) {
return await fetch(url, {
headers: {
Cookie: cookie
},
agent: new HttpsProxyAgent(setting.proxy)
})
.then(res => {
return res.text()
})
.catch(e => {
sendMessageToWebContents(`Get ex page failed because ${e}`)
})
} else {
return await fetch(url, {
headers: {
Cookie: cookie
}
})
.then(res => {
return res.text()
})
.catch(e => {
sendMessageToWebContents(`Get ex page failed because ${e}`)
})
}
})
ipcMain.handle('post-data-ex', async (event, { url, data, cookie }) => {
if (setting.proxy) {
return await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
Cookie: cookie,
'Content-Type': 'application/json'
},
agent: new HttpsProxyAgent(setting.proxy)
})
.then(res => {
return res.text()
})
.catch(e => {
sendMessageToWebContents(`Get ex data failed because ${e}`)
})
} else {
return await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
Cookie: cookie,
'Content-Type': 'application/json'
}
})
.then(res => {
return res.text()
})
.catch(e => {
sendMessageToWebContents(`Get ex data failed because ${e}`)
})
}
})
ipcMain.handle('save-book', async (event, book) => {
return await saveBookToDatabase(book)
})
// home
ipcMain.handle('get-folder-tree', async (event, bookList) => {
const folderList = [...new Set(bookList.map(b => path.dirname(b.filepath)))]
const librarySplitPathsLength = setting.library.split(path.sep).length - 1
const bookPathSplitList = folderList.sort().map(fp => fp.split(path.sep).slice(librarySplitPathsLength))
const folderTreeObject = {}
for (const folders of bookPathSplitList) {
_.set(folderTreeObject, folders.map(f => '_' + f), {})
}
const resolveTree = (preRoot, tree, initFolder) => {
_.forIn(tree, (node, label) => {
const trueLabel = label.slice(1)
if (_.isEmpty(node)) {
preRoot.push({
label: trueLabel,
folderPath: [...initFolder, trueLabel].slice(1).join(path.sep),
})
} else {
preRoot.push({
label: trueLabel,
folderPath: [...initFolder, trueLabel].slice(1).join(path.sep),
children: resolveTree([], node, [...initFolder, trueLabel]),
})
}
})
return preRoot
}
return resolveTree([], folderTreeObject, [])
})
ipcMain.handle('load-collection-list', async (event, arg) => {
return collectionList
})
ipcMain.handle('save-collection-list', async (event, list) => {
collectionList = list
return await fs.promises.writeFile(path.join(STORE_PATH, 'collectionList.json'), JSON.stringify(list, null, ' '), { encoding: 'utf-8' })
})
// detail
ipcMain.handle('open-url', async (event, url) => {
shell.openExternal(url)
})
ipcMain.handle('show-file', async (event, filepath) => {
shell.showItemInFolder(filepath)
})
ipcMain.handle('use-new-cover', async (event, filepath) => {
const copyTempCoverPath = path.join(TEMP_PATH, nanoid(8) + path.extname(filepath))
const coverPath = path.join(COVER_PATH, nanoid() + path.extname(filepath))
try {
await fs.promises.copyFile(filepath, copyTempCoverPath)
await sharp(copyTempCoverPath, { failOnError: false })
.resize(500, 707, {
fit: 'contain',
background: '#303133'
})
.toFile(coverPath)
return coverPath
} catch (e) {
sendMessageToWebContents(`Generate cover from ${filepath} failed because ${e}`)
}
})
ipcMain.handle('open-local-book', async (event, filepath) => {
exec(`${setting.imageExplorer} "${filepath}"`)
})
ipcMain.handle('delete-local-book', async (event, filepath) => {
if (filepath.startsWith(setting.library)) {
await Manga.destroy({ where: { filepath: filepath } })
return shell.trashItem(filepath)
}
})
// viewer
ipcMain.handle('load-manga-image-list', async (event, book) => {
await clearFolder(VIEWER_PATH)
const { filepath, type, id: bookId } = book
const list = await getImageListByBook(filepath, type)
sendImageLock = true
;(async () => {
// 384 is the default 4K screen width divided by the default number of thumbnail columns
const thumbnailWidth = _.isFinite(screenWidth / setting.thumbnailColumn) ? Math.floor(screenWidth / setting.thumbnailColumn) : 384
const widthLimit = _.isNumber(setting.widthLimit) ? Math.ceil(setting.widthLimit) : screenWidth
for (let index = 1; index <= list.length; index++) {
if (sendImageLock) {
let imageFilepath = list[index - 1]
const extname = path.extname(imageFilepath)
if (imageFilepath.search(/[%#]/) >= 0 || type === 'folder') {
const newFilepath = path.join(VIEWER_PATH, `rename_${nanoid(8)}${extname}`)
await fs.promises.copyFile(imageFilepath, newFilepath)
imageFilepath = newFilepath
}
let { width, height } = await sharp(imageFilepath, { failOnError: false }).metadata()
if (widthLimit !== 0 && width > widthLimit) {
height = Math.floor(height * (widthLimit / width))
width = widthLimit
const resizedFilepath = path.join(VIEWER_PATH, `resized_${nanoid(8)}.jpg`)
switch (extname) {
case '.gif':
break
default:
await sharp(imageFilepath, { failOnError: false })
.resize({ width })
.toFile(resizedFilepath)
imageFilepath = resizedFilepath
break
}
}
const filename = path.basename(list[index - 1])
mainWindow.webContents.send('manga-image', {
id: `${bookId}_${index}`,
index,
filename,
filepath: imageFilepath,
width, height
})
;(async () => {
let thumbnailPath = path.join(VIEWER_PATH, `thumb_${nanoid(8)}.jpg`)
switch (extname) {
case '.gif':
thumbnailPath = imageFilepath
break
default:
await sharp(imageFilepath, { failOnError: false })
.resize({ width: thumbnailWidth })
.toFile(thumbnailPath)
break
}
mainWindow.webContents.send('manga-thumbnail-image', {
id: `${bookId}_${index}`,
index,
filename,
filepath: imageFilepath,
thumbnailPath,
})
})()
}
}
})()
return list
})
ipcMain.handle('release-sendimagelock', () => {
sendImageLock = false
})
ipcMain.handle('delete-image', async (event, filename, filepath, type) => {
return await deleteImageFromBook(filename, filepath, type)
})
// setting
ipcMain.handle('select-folder', async (event, title) => {
const result = await dialog.showOpenDialog(mainWindow, {
title,
properties: ['openDirectory']
})
if (!result.canceled) {
return result.filePaths[0]
} else {
return undefined
}
})
ipcMain.handle('select-file', async (event, title) => {
const result = await dialog.showOpenDialog(mainWindow, {
title,
properties: ['openFile']
})
if (!result.canceled) {
return result.filePaths[0]
} else {
return undefined
}
})
ipcMain.handle('load-setting', async (event, arg) => {
return setting
})
ipcMain.handle('save-setting', async (event, receiveSetting) => {
if (receiveSetting.proxy) {
await session.defaultSession.setProxy({
mode: 'fixed_servers',
proxyRules: receiveSetting.proxy
})
}
if (receiveSetting.metadataPath !== setting.metadataPath) {
Metadata = prepareMetadataModel(path.join(receiveSetting.metadataPath, './metadata.sqlite'))
await Metadata.sync()
}
if (receiveSetting.enabledLANBrowsing !== setting.enabledLANBrowsing) {
if (receiveSetting.enabledLANBrowsing) {
enableLANBrowsing()
} else {
if (LANBrowsingInstance?.listening) {
LANBrowsingInstance.close(() => {
sendMessageToWebContents('LAN browsing closed')
})
}
}
}
setting = receiveSetting
return await fs.promises.writeFile(path.join(STORE_PATH, 'setting.json'), JSON.stringify(setting, null, ' '), { encoding: 'utf-8' })
})
ipcMain.handle('export-database', async (event, folder) => {
await fs.promises.copyFile(path.join(STORE_PATH, 'collectionList.json'), path.join(folder, 'collectionList.json'))
await fs.promises.copyFile(metadataSqliteFile, path.join(folder, 'metadata.sqlite'))
})
ipcMain.handle('import-database', async (event, arg) => {
const { collectionListPath, metadataSqlitePath } = arg
await Metadata.sequelize.close()
await fs.promises.copyFile(collectionListPath, path.join(STORE_PATH, 'collectionList.json'))
await fs.promises.copyFile(metadataSqlitePath, metadataSqliteFile)
app.relaunch()
app.exit(0)
})
ipcMain.handle('import-sqlite', async (event, bookList) => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile']
})
if (!result.canceled) {
const db = await open({
filename: result.filePaths[0],
driver: sqlite3.Database
})
try {
const re = /'/g
const bookListLength = bookList.length
for (let i = 0; i < bookListLength; i++) {
const book = bookList[i]
if (book.status !== 'tagged') {
const metadata = await db.get('SELECT * FROM gallery WHERE thumb LIKE ?', `%${book.coverHash}%`)
if (metadata) {
metadata.tags = {
language: metadata.language ? JSON.parse(metadata.language.replace(re, '\"')) : undefined,
parody: metadata.parody ? JSON.parse(metadata.parody.replace(re, '\"')) : undefined,
character: metadata.character ? JSON.parse(metadata.character.replace(re, '\"')) : undefined,
group: metadata.group ? JSON.parse(metadata.group.replace(re, '\"')) : undefined,
artist: metadata.artist ? JSON.parse(metadata.artist.replace(re, '\"')) : undefined,
male: metadata.male ? JSON.parse(metadata.male.replace(re, '\"')) : undefined,
female: metadata.female ? JSON.parse(metadata.female.replace(re, '\"')) : undefined,
mixed: metadata.mixed ? JSON.parse(metadata.mixed.replace(re, '\"')) : undefined,
other: metadata.other ? JSON.parse(metadata.other.replace(re, '\"')) : undefined,
cosplayer: metadata.cosplayer ? JSON.parse(metadata.cosplayer.replace(re, '\"')) : undefined,
rest: metadata.rest ? JSON.parse(metadata.rest.replace(re, '\"')) : undefined,
}
metadata.filecount = +metadata.filecount
metadata.rating = +metadata.rating
metadata.posted = +metadata.posted
metadata.filesize = +metadata.filesize
metadata.url = `https://exhentai.org/g/${metadata.gid}/${metadata.token}/`
_.assign(book, _.pick(metadata, ['tags', 'title', 'title_jpn', 'filecount', 'rating', 'posted', 'filesize', 'category', 'url']), { status: 'tagged' })
await saveBookToDatabase(book)
}
setProgressBar(i / bookListLength)
}
}
await db.close()
setProgressBar(-1)
} catch (e) {
console.log(e)
await db.close()
}
return {
success: true,
bookList
}
} else {
return {
success: false
}
}
})
// tools
ipcMain.handle('set-progress-bar', async (event, progress) => {
setProgressBar(progress)
})
ipcMain.handle('get-locale', async (event, arg) => {
return app.getLocale()
})
ipcMain.handle('copy-image-to-clipboard', async (event, filepath) => {
clipboard.writeImage(nativeImage.createFromPath(filepath))
})
ipcMain.handle('copy-text-to-clipboard', async (event, text) => {
clipboard.writeText(text)
})
ipcMain.handle('read-text-from-clipboard', async () => {
return clipboard.readText()
})
ipcMain.handle('update-window-title', async (event, title) => {
const name = require('./package.json').name
const version = require('./package.json').version
if (title) {
mainWindow.setTitle(name + ' ' + version + ' | ' + title)
} else {
mainWindow.setTitle(name + ' ' + version)
}
})
ipcMain.handle('switch-fullscreen', async (event, arg) => {
mainWindow.setFullScreen(!mainWindow.isFullScreen())
})
ipcMain.on('get-path-sep', async (event, arg) => {
event.returnValue = path.sep
})
// 初始化Express
const LANBrowsing = express()
const port = 23786
// 设置静态文件夹
const staticFilePath = path.resolve(STORE_PATH, 'public')
fs.mkdirSync(staticFilePath, { recursive: true })
LANBrowsing.use('/static', express.static(staticFilePath))
let mangas = []
// 格式化标签
const formatTags = (tags) => {
return Object.entries(tags)
.map(([key, values]) => values.map(value => `${key}:${value}`).join(', '))
.join(', ')
}
LANBrowsing.get('/api/search', async (req, res) => {
try {
const filter = req.query.filter || ''
const start = parseInt(req.query.start) || 0
// 读取并搜索数据库
mangas = await loadBookListFromDatabase()
let filterMangas
if (filter) {
filterMangas = mangas.filter(manga => {
return JSON.stringify(_.pick(manga, ['title', 'title_jpn', 'status', 'category', 'filepath', 'url', 'pageDiff'])).toLowerCase().includes(filter.toLowerCase())
|| formatTags(manga.tags).toLowerCase().includes(filter.toLowerCase())
})
} else {
filterMangas = mangas
}
filterMangas = filterMangas.toSorted((a, b) => new Date(b.mtime) - new Date(a.mtime))
// 格式化响应数据
const responseData = filterMangas.slice(start, start + 100).map(manga => ({
arcid: manga.hash,
extension: path.extname(manga.filepath),
filename: path.basename(manga.filepath),
isnew: 'true',
lastreadtime: 0,
pagecount: manga.pageCount,
progress: 0,
size: manga.filesize,
summary: null,
tags: manga.tags ? formatTags(manga.tags) : '',
title: `${manga.title_jpn && manga.title ? `${manga.title_jpn} || ${manga.title}` : manga.title}`
}))
res.json({
data: responseData,
draw: 0,
recordsFiltered: responseData.length,
recordsTotal: filterMangas.length
})
} catch (error) {
res.status(500).send(error.message)
}
})
LANBrowsing.get('/api/search/random', async (req, res) => {
try {
// 从数据库中随机获取指定数量的 Manga 记录
const count = parseInt(req.query.count, 10) || 1
const randomMangas = _.sampleSize(await loadBookListFromDatabase(), count)
const responseData = randomMangas.map(manga => ({
arcid: manga.hash,
extension: path.extname(manga.filepath),
filename: path.basename(manga.filepath),
isnew: 'true',
lastreadtime: 0,
pagecount: manga.pageCount,
progress: 0,
size: manga.filesize,
summary: null,
tags: manga.tags ? formatTags(manga.tags) : '',
title: `${manga.title_jpn && manga.title ? `${manga.title_jpn} || ${manga.title}` : manga.title}`
}))
res.json({
data: responseData
})
} catch (error) {
console.error('Failed to fetch random Manga:', error)
res.status(500).send('Internal Server Error')
}
})
LANBrowsing.get('/api/archives/:hash/metadata', async (req, res) => {
try {
const mangaHash = req.params.hash
// 从数据库找到对应的漫画
if (_.isEmpty(mangas)) mangas = await loadBookListFromDatabase()
const manga = await mangas.find(manga => manga.hash === mangaHash)
if (!manga) {
return res.status(404).send('Manga not found')
}
// 构造响应数据
const responseMetadata = {
arcid: manga.hash,
extension: path.extname(manga.filepath),
filename: path.basename(manga.filepath),
isnew: 'true',
lastreadtime: 0,
pagecount: manga.pageCount,
progress: 0,
size: manga.filesize,
summary: null,
tags: manga.tags ? formatTags(manga.tags) : '',
title: `${manga.title_jpn && manga.title ? `${manga.title_jpn} || ${manga.title}` : manga.title}`
}
res.json(responseMetadata)
} catch (error) {
res.status(500).send(error.message)
}
})
// 处理封面图片请求
LANBrowsing.get('/api/archives/:hash/thumbnail', async (req, res) => {
const hash = req.params.hash
const manga = await Manga.findOne({where: {hash: hash}})
if (!manga || !manga.coverPath) {
return res.status(404).send('Cover not found')
}
const coverFilePath = path.join(staticFilePath, path.basename(manga.coverPath))
await fs.promises.copyFile(manga.coverPath, coverFilePath)
if (fs.existsSync(coverFilePath)) {
res.sendFile(coverFilePath)
} else {
res.status(404).send('Cover file not found')
}
})
let existBook = {
hash: null,
imageList: []
}
// 处理章节列表请求
LANBrowsing.get('/api/archives/:hash/files', async (req, res) => {
try {
const mangaHash = req.params.hash
// 从数据库找到对应的漫画
const manga = await Manga.findOne({where: {hash: mangaHash}})
if (!manga) {
return res.status(404).send('Manga not found')
}
await clearFolder(VIEWER_PATH)
await clearFolder(staticFilePath)
const imageList = await getImageListByBook(manga.filepath, manga.type)
existBook = {
hash: manga.hash,
imageList: imageList
}
// 构造响应数据
const responseFiles = {
job: Date.now(), // 示例中的 job 可以是一个随机数或时间戳
pages: imageList.map((file, index) => `/api/archives/${manga.hash}/page?path=${index + 1}`)
}
res.json(responseFiles)
} catch (error) {
res.status(500).send(error.message)
}
})
// 处理章节图片请求
LANBrowsing.get('/api/archives/:hash/page', async (req, res) => {
const hash = req.params.hash
const page = parseInt(req.query.path, 10)
if (isNaN(page) || page < 1) {
return res.status(400).send('Invalid page number')
}
const manga = await Manga.findOne({where: {hash: hash}})
if (!manga || !manga.filepath) {
return res.status(404).send('File not found')
}
// 获取章节图片列表
try {
let imageList
if (manga.hash === existBook.hash) {
imageList = existBook.imageList
} else {
await clearFolder(VIEWER_PATH)
await clearFolder(staticFilePath)
imageList = await getImageListByBook(manga.filepath, manga.type)
existBook.hash = manga.hash
existBook.imageList = imageList
}
const imageFilePath = imageList[page - 1]
if (!imageFilePath) {
return res.status(404).send('Image not found')
}
// 重命名并复制图片文件到静态文件夹
const imageFileName = `${manga.hash}_${page}${path.extname(imageFilePath)}`