-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
744 lines (677 loc) · 24.1 KB
/
main.js
File metadata and controls
744 lines (677 loc) · 24.1 KB
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
/* eslint-disable prefer-destructuring,no-loop-func,no-shadow,no-use-before-define,no-param-reassign,global-require,import/no-extraneous-dependencies,camelcase */
// ==Headers==
// @Name: main
// @Description: 浏览comic
// @Version: 1.0.1120
// @Author: dodying
// @Created: 2020-01-28 21:26:56
// @Modified: 2024-02-15 21:09:56
// @Namespace: https://github.com/dodying/Nodejs
// @SupportURL: https://github.com/dodying/Nodejs/issues
// @Require: fs-extra,electron,electron-reload,mysql2,jszip
// ==/Headers==
// 设置
const debug = process.env.DEBUG || false;
let windowHistory = [];
const windows = {};
let config = {};
let store = {};
let tray = null;
// let isQuiting = false;
let connection = null;
let connectionLastTime = null;
const connectionTimeout = 5 * 60 * 1000;
const lastConnection = {
info: {},
result: [],
};
let connecting = false;
const columns = {
path: 'text', // 路径
size: 'int unsigned', // 文件大小
artist: 'varchar(511)', // 作者
title: 'varchar(511)', // 英文标题
title_main: 'varchar(511)', // 英文标题的主要部分
title_number: 'varchar(511)', // 英文标题的数字部分
title_jpn: 'varchar(511)', // 日文标题
title_jpn_main: 'varchar(511)', // 日文标题的主要部分
title_jpn_number: 'varchar(511)', // 日文标题的数字部分
category: 'varchar(20)', // 类别
web: 'varchar(50)', // 网址
language: 'varchar(2)', // 语言
pages: 'int unsigned', // 页数
time_upload: 'datetime', // 上传时间 '2020-01-02 21:14:16.000'
uploader: 'varchar(40)', // 上传者
rating: 'float unsigned', // 评分
favorited: 'int unsigned', // 收藏人数
time_download: 'datetime', // 下载时间
tags: 'json', // 标签
};
// 导入原生模块
const path = require('path');
const cp = require('child_process');
// 导入第三方模块
const fse = require('fs-extra');
const {
app, BrowserWindow, ipcMain, Menu, shell, Tray,
} = require('electron');
if (debug) require('electron-reload')(path.join(__dirname, 'src'));
const mysql = require('mysql2/promise');
const JSZip = require('jszip');
const walkEverything = require('../_lib/walkEverything');
const waitInMs = require('../_lib/waitInMs');
const parseInfo = require('./js/parseInfo');
const getTitleMain = require('./js/getTitleMain');
const mainTag = 'language,artist,group,parody,character,cosplayer,female,male,mixed,other,reclass,temp'.split(',');
// Function
const openWindow = (url) => {
if (!url.match(/^https?:/)) url = path.resolve(__dirname, url);
console.debug('open', url);
let win, id;
return new Promise((resolve, reject) => {
win = new BrowserWindow({
width: 800,
height: 600,
show: false,
// autoHideMenuBar: true,
// darkTheme: true,
frame: false,
icon: './src/icon.png',
webPreferences: {
nodeIntegration: true,
},
});
id = win.id;
windows[id] = win;
windows[id].on('maximize', () => {
if (resolve) resolve(id);
resolve = null;
});
if (config.alwaysMaximize) {
windows[id].on('unmaximize', () => {
windows[id].maximize();
});
windows[id].on('restore', () => {
windows[id].maximize();
});
}
if (config.hideOnMinimize) {
windows[id].on('minimize', () => {
windows[id].hide();
rebuildTrayMenu();
});
}
windows[id].once('ready-to-show', () => {
windows[id].show();
if (resolve) resolve(id);
resolve = null;
});
windows[id].on('closed', () => {
delete windows[id];
win = null;
for (let i = 0; i < windowHistory.length; i++) {
const id = windowHistory[i];
if (id in windows) {
if (!windows[id].isVisible()) continue;
windows[id].show();
break;
} else {
windowHistory.splice(0, 1);
i = i - 1;
}
}
});
windows[id].on('focus', () => {
windowHistory.unshift(id);
windowHistory = Array.from(new Set(windowHistory));
});
windows[id].loadURL(url);
windows[id].maximize();
if (debug) windows[id].openDevTools();
});
};
const createConnection = async (obj) => {
/* eslint-disable no-unmodified-loop-condition */
while (connecting) {
await waitInMs(200);
}
connecting = true;
let isInfoSame = lastConnection.info.host === obj.host;
isInfoSame = isInfoSame && lastConnection.info.user === obj.user;
isInfoSame = isInfoSame && lastConnection.info.password === obj.password;
if (lastConnection.result[1] === 1 && isInfoSame && new Date().getTime() - connectionLastTime < connectionTimeout) {
connecting = false;
return lastConnection.result;
}
lastConnection.info = {
host: obj.host,
user: obj.user,
password: obj.password,
};
console.log('re-connection');
try {
if (connection && connection.end && typeof connection.end === 'function') connection.end();
} catch (error) {
console.log({ err: error, msg: error.message });
}
try {
const { database, ...objLeft } = obj;
connection = await mysql.createConnection({
host: obj.host,
user: obj.user,
password: obj.password,
keepAliveInitialDelay: 10000,
enableKeepAlive: true,
dateStrings: true,
// timezone: '+00:00',
...objLeft,
});
connection.on('error', (err) => {
if (['PROTOCOL_CONNECTION_LOST'].includes(err.code)) {
createConnection(obj);
} else {
console.log('Database error:', { err });
}
});
connectionLastTime = new Date().getTime();
} catch (error) {
if (error.message.match('Too many connections')) {
connecting = false;
return createConnection(obj);
}
console.log({ err: error, msg: error.message });
connection = null;
connecting = false;
connectionLastTime = null;
return ['Connection Failed, please check info', -1];
}
const [rows] = await connection.query('SHOW DATABASES');
if (rows.filter((i) => i.Database === obj.database).length) {
await connection.query(`USE ${obj.database}`);
connecting = false;
return ['Connection Success, and you can update', 1];
}
connecting = false;
connectionLastTime = null;
return ['Connection Success, but you need to init', 0];
};
const updateTableFiles = async (obj) => {
console.log('database-update');
console.time('walk');
const filesLocal = await walkEverything('file: <ext:cbz|ext:zip>', {
root: obj.libraryFolder,
fullpath: false,
});
console.timeEnd('walk');
console.time('query');
const [rows] = await connection.query('select path from files');
const filesDatabase = rows.map((i) => i.path);
console.timeEnd('query');
console.debug('Total Files:\t', filesLocal.length, '\nExisted Files:\t', filesDatabase.length);
const filesLocalUpperCase = filesLocal.map((i) => i.toUpperCase());
const filesDatabaseUpperCase = filesDatabase.map((i) => i.toUpperCase());
const filesDeleted = filesDatabase.filter((i) => !filesLocalUpperCase.includes(i.toUpperCase()));
const filesNew = filesLocal.filter((i) => !filesDatabaseUpperCase.includes(i.toUpperCase()));
console.debug('New Files\t', filesNew.length, '\nDeleted Files:\t', filesDeleted.length);
console.time('INSERT INTO');
const column = Object.keys(columns);
let queryString = `INSERT INTO files (${column.join(', ')}) values `;
let arr = [];
for (const file of filesNew) {
if (arr.length >= 100) {
const arr1 = arr.map((i) => `(${i.map((j) => (j === 'NULL' ? 'NULL' : mysql.escape(j))).join(', ')})`).join(',\n');
await connection.query(queryString + arr1);
arr = [];
}
const fullpath = path.join(obj.libraryFolder, file);
const { size } = fse.statSync(fullpath);
// 读取数据
const targetData = fse.readFileSync(fullpath);
const jszip = new JSZip();
let zip;
try {
zip = await jszip.loadAsync(targetData);
} catch (error) {
// console.error(`Error:\t无法读取文件 "${file}"`)
const title = path.parse(fullpath).name;
arr.push([
file, size, 'NULL',
title, ...getTitleMain(title),
title, ...getTitleMain(title),
...'1'.repeat(column.length - 9).split('').map((i) => 'NULL'),
]);
continue;
}
// 查看列表
const fileList = Object.keys(zip.files);
// 检测有无info.txt
if (fileList.filter((item) => item.match(/(^|\/)info\.txt$/)).length === 0) {
console.warn('压缩档内不存在info.txt: ', file);
continue;
}
// 读取info.txt
const infoFile = fileList.find((item) => item.match(/(^|\/)info\.txt$/));
const data = await zip.files[infoFile].async('text');
const info = parseInfo(data);
//
const tags = {};
for (const i of mainTag) {
if (i in info) tags[i] = info[i];
}
// eslint-disable-next-line no-nested-ternary
let artist = tags.artist ? tags.artist : tags.group ? tags.group : [];
artist = artist.map((i) => i.split('|')[0].trim()).sort().slice(0, 3).join(', ');
arr.push([
file, size, artist,
info.title, ...getTitleMain(info.title),
info.jTitle, ...getTitleMain(info.jTitle),
info.Category, info.web, info.lang,
Number.isNaN(parseInt(info.length, 10)) ? 0 : parseInt(info.length, 10),
info.Posted, info.Uploader,
Number.isNaN(parseFloat(info.Rating)) ? 0 : parseFloat(info.Rating),
Number.isNaN(parseInt(info.Favorited, 10)) ? 0 : parseInt(info.Favorited, 10),
info.downloadTime,
JSON.stringify(tags),
]);
}
if (arr.length) {
arr = arr.map((i) => `(${i.map((j) => (j === 'NULL' ? 'NULL' : mysql.escape(j))).join(', ')})`).join(',\n');
await connection.query(queryString + arr);
}
console.timeEnd('INSERT INTO');
console.time('DELETE INTO');
queryString = 'DELETE FROM files WHERE ';
arr = [];
for (const file of filesDeleted) {
if (arr.length >= 100) {
const arr1 = arr.map((i) => `path=${mysql.escape(i)}`).join(' OR ');
await connection.query(queryString + arr1);
arr = [];
}
arr.push(file);
}
if (arr.length) {
const arr1 = arr.map((i) => `path=${mysql.escape(i)}`).join(' OR ');
await connection.query(queryString + arr1);
}
console.timeEnd('DELETE INTO');
};
const rebuildTrayMenu = () => {
const menuItem = [
{
label: '显示/隐藏最后窗口',
click: (menuItem, browserWindow, event) => {
for (let i = 0; i < windowHistory.length;) {
const id = windowHistory[i];
if (id in windows) {
if (windows[id].isVisible()) {
windows[id].hide();
} else {
windows[id].show();
}
break;
} else {
windowHistory.splice(0, 1);
}
}
rebuildTrayMenu();
},
},
{
label: '显示所有窗口',
click: (menuItem, browserWindow, event) => {
for (const id of Object.keys(windows)) {
windows[id].show();
}
rebuildTrayMenu();
},
},
{
label: '隐藏所有窗口',
click: (menuItem, browserWindow, event) => {
for (const id of Object.keys(windows)) {
windows[id].hide();
}
rebuildTrayMenu();
},
},
{ type: 'separator' },
];
for (const id of Object.keys(windows)) {
if (windows[id].isVisible()) continue;
menuItem.push({
label: `${id}: ${windows[id].getTitle().substr(0, 40)}`,
click: (menuItem, browserWindow, event) => {
windows[id].show();
rebuildTrayMenu();
},
});
}
menuItem.push(
{ type: 'separator' },
{
label: '保存并退出',
click: (menuItem, browserWindow, event) => {
// isQuiting = true;
saveLastTabs();
for (const id of Object.keys(windows)) windows[id].close();
},
},
{
label: '退出',
click: (menuItem, browserWindow, event) => {
// isQuiting = true;
for (const id of Object.keys(windows)) windows[id].close();
},
},
);
const contextMenu = Menu.buildFromTemplate(menuItem);
tray.setContextMenu(contextMenu);
};
const saveLastTabs = () => {
const urls = [];
const separator = __dirname.replace(/\\/g, '/');
for (const id of Object.keys(windows)) {
let url = windows[id].webContents.getURL();
const arr = url.split(separator);
if (arr.length > 1) url = `.${arr.slice(1).join(separator)}`;
urls.push(url);
}
config.lastTabs = urls;
console.log('last tabs wrote');
};
ipcMain.on('open', async (event, urls) => {
for (const url of [].concat(urls)) {
await openWindow(url);
}
event.returnValue = true;
});
ipcMain.on('open-external', async (event, url, name) => {
if (name === 'path') {
const fullpath = path.resolve(config.libraryFolder, url);
await shell.openItem(fullpath);
} else if (name === 'item') {
const fullpath = path.resolve(config.libraryFolder, url);
await shell.showItemInFolder(fullpath);
} else if (['delete', 'empty'].includes(name)) {
const fullpath = path.resolve(config.libraryFolder, url);
if (fse.existsSync(fullpath)) {
if (name === 'delete') {
fse.unlinkSync(fullpath);
} else if (name === 'empty') {
const targetData = fse.readFileSync(fullpath);
const zipContent = await new JSZip().loadAsync(targetData);
const fileList = Object.keys(zipContent.files).filter((i) => !i.match(/(info.txt|\/)$/));
for (const i of fileList) zipContent.remove(i);
const content = await zipContent.generateAsync({
type: 'nodebuffer',
compression: 'DEFLATE',
compressionOptions: {
level: 9,
},
});
fse.writeFileSync(fullpath, content);
}
}
const cover = path.resolve(path.dirname(fullpath), `${path.parse(fullpath).name}.jpg`);
if (fse.existsSync(cover)) fse.unlinkSync(cover);
await connection.query(`DELETE FROM files WHERE path=${mysql.escape(url)}`);
store[name] = Array.from(new Set([].concat(store[name] || [], url)));
if (store.lastViewPosition && url in store.lastViewPosition) delete store.lastViewPosition[url];
if (store.lastViewTime && url in store.lastViewTime) delete store.lastViewTime[url];
if (store.history && store.history.includes(url)) store.history.splice(store.history.indexOf(url), 1);
} else if (name === 'everything') {
if (config.everything && fse.existsSync(config.everything)) cp.execFileSync(config.everything, ['-search', url]);
} else if (!name) {
await shell.openExternal(url);
}
});
ipcMain.on('config', (event, todo = 'get', name, value) => {
let configThis;
if (todo === 'set') {
const obj = name || {};
configThis = Object.assign(config, obj);
fse.writeJSONSync('./config.json', configThis, { spaces: 2 });
config = configThis;
} else if (todo === 'get') {
// config = fse.existsSync('./config.json') ? fse.readJSONSync('./config.json') : {};
configThis = config;
if (name) configThis = name in configThis ? configThis[name] : value;
}
event.returnValue = configThis;
});
ipcMain.on('store', (event, todo = 'get', name, value) => {
let storeThis;
if (todo === 'set') {
const obj = name || {};
storeThis = Object.assign(store, obj);
fse.writeJSONSync('./store.json', storeThis, { spaces: 2 });
store = storeThis;
} else if (todo === 'get') {
// store = fse.existsSync('./store.json') ? fse.readJSONSync('./store.json') : {};
storeThis = store;
if (name) storeThis = name in storeThis ? storeThis[name] : value;
}
event.returnValue = storeThis;
});
ipcMain.on('clear', (event) => {
delete store.history;
delete store.delete;
for (const i of ['lastViewPosition', 'lastViewTime']) {
for (const file of Object.keys(store[i])) {
const fullpath = path.resolve(config.libraryFolder, file);
if (!fse.existsSync(fullpath)) delete store[i][file];
}
}
for (const i of ['star']) {
store[i] = Array.from(new Set(store[i]));
for (let j = 0; j < store[i].length; j++) {
const file = store[i][j];
const fullpath = path.resolve(config.libraryFolder, file);
if (!fse.existsSync(fullpath)) {
store[i].splice(j, 1);
j = j - 1;
}
}
}
event.returnValue = true;
});
ipcMain.on('database-connect', async (event, obj, todo) => {
obj = obj || config;
// todo: test,delete,init,update
// code: -1,0,1
const [status, code] = await createConnection(obj);
lastConnection.result = [status, code];
// console.debug({ status, code, obj, todo, connection })
if (todo === 'test' || code === -1 || !todo) {
event.returnValue = [status, code];
} else if (todo === 'delete') {
if (code === 1) {
await connection.query(`DROP DATABASE ${obj.database}`);
event.returnValue = ['Delete Success', code];
} else {
event.returnValue = ['No Such Database', code];
}
} else if (todo === 'init') {
let queryString = `CREATE DATABASE IF NOT EXISTS ${obj.database} CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci`;
await connection.query(queryString);
queryString = `USE ${obj.database}`;
await connection.query(queryString);
queryString = `CREATE TABLE IF NOT EXISTS \`files\` (${[
'id int unsigned not null auto_increment',
...Object.keys(columns).map((i) => `${i} ${columns[i]}`),
'PRIMARY KEY (id)',
].join(', ')})`;
await connection.query(queryString);
event.returnValue = ['Init Success', code];
} else if (code === 0) {
event.returnValue = ['You need to init', code];
} else if (todo === 'update') {
await updateTableFiles(obj);
event.returnValue = ['Update Success', code];
}
});
ipcMain.on('log', (event, ...args) => {
console.debug(...args);
});
ipcMain.on('database-query', async (event, str) => {
if (!connection || new Date().getTime() - connectionLastTime >= connectionTimeout) await createConnection(config);
console.debug('database-query', '\n\x1b[32m', str, '\x1b[0m');
let result = [
[],
];
try {
result = await connection.query(str);
} catch (error) {
console.error('Error:', error.message);
}
console.debug('database-query-end', result[0].length);
event.returnValue = result;
});
ipcMain.on('query-by-condition', async (event, condition) => {
if (!connection || new Date().getTime() - connectionLastTime >= connectionTimeout) await createConnection(config);
// console.log('query-by-condition', condition)
let query = 'SELECT * FROM files WHERE ';
const querySegment = [];
let order = condition.some((i) => i[1] === 'order') ? [] : ['path', 'time_upload', 'time_download'];
for (const i of condition) {
let [not, column, comparison, value, value1] = i;
const type = columns[column];
let str;
if (column === 'command') {
continue;
} else if (column === 'order') {
order.push(`${value} ${comparison}`);
continue;
} else if (type === 'datetime') {
value = value ? mysql.escape(value) : 'CURDATE()';
if (['=', '!=', '>', '>=', '<', '<='].includes(comparison)) {
str = `DATE(${column}) ${comparison} ${value}`;
} else if (['today', 'yesteday', 'the day before yesterday'].includes(comparison)) {
const sep = ['today', 'yesteday', 'the day before yesterday'].indexOf(comparison);
str = `DATE(${column}) = DATE_SUB(${value}, INTERVAL ${sep} DAY)`;
} else if (['tomorrow', 'the day after tomorrow'].includes(comparison)) {
const sep = ['today', 'tomorrow', 'the day after tomorrow'].indexOf(comparison);
str = `DATE(${column}) = DATE_ADD(${value}, INTERVAL ${sep} DAY)`;
} else if (['this_week'].includes(comparison)) {
str = `YEARWEEK(${column}, 1) = YEARWEEK(${value}, 1)`;
} else if (['this_year'].includes(comparison)) {
str = `MONTH(${column}) = MONTH(${value}) AND YEAR(${column}) = YEAR(${value})`;
} else if (['BETWEEN AND', 'NOT BETWEEN AND'].includes(comparison)) {
value1 = value1 ? mysql.escape(value1) : 'CURDATE()';
str = `DATE(${column}) ${comparison === 'NOT BETWEEN AND' ? 'NOT ' : ''}BETWEEN ${value} AND ${value1}`;
}
} else if (type === 'json') {
// unused method:
// equal: JSON_SEARCH(tags, 'one', 'mind break', null, '$.female[*]')
const [column, path] = comparison.split(':');
if (value.match(/^[><=!]+\d+$/)) {
str = `JSON_LENGTH(JSON_EXTRACT(${column},'$.${path}[*]'))${value}`;
} else {
if (value.match(/^\/(.*)\/$/)) {
value = value.match(/^\/(.*)\/$/)[1];
comparison = 'REGEXP';
} else {
value = `%${value.replace(/[%_\\]/g, '\\$&')}%`;
comparison = 'LIKE';
}
if (path === '*') {
// WHERE tags like '%mind break%'
str = `${column} ${comparison} ${mysql.escape(value)}`;
} else {
// WHERE JSON_EXTRACT(tags, '$.female[*]') like '%mind break%'
str = `JSON_EXTRACT(${column}, '$.${path}[*]') ${comparison} ${mysql.escape(value)}`;
}
}
} else if (['=', '!=', '>', '>=', '<', '<='].includes(comparison)) {
if (type === 'text' || type.match('varchar')) value = mysql.escape(value);
str = `${column} ${comparison} ${value}`;
} else if (['LIKE', 'NOT LIKE'].includes(comparison)) {
// https://www.runoob.com/mysql/mysql-like-clause.html
// % 多个字符
// _ 单个字符
// [] 【^】
str = `${column} ${comparison} ${mysql.escape(`%${value.replace(/[%_\\]/g, '\\$&')}%`)}`;
// str=`INSTR(${column}, ${mysql.escape(`${value}`)})`
// str=`NOT(INSTR(${column}, ${mysql.escape(`${value}`)}))`
} else if (['START WITH'].includes(comparison)) {
str = `${column} LIKE ${mysql.escape(`${value.replace(/[%_\\]/g, '\\$&')}%`)}`;
} else if (['END WITH'].includes(comparison)) {
str = `${column} LIKE ${mysql.escape(`%${value.replace(/[%_\\]/g, '\\$&')}`)}`;
} else if (['REGEXP', 'NOT REGEXP'].includes(comparison)) {
str = `${column} ${comparison} ${mysql.escape(`${value}`)}`;
} else if (['Duplicate'].includes(comparison)) {
const str1 = `SELECT ${column} FROM files WHERE ${column} != "" GROUP BY ${column} HAVING COUNT(${column}) > 1`;
str = `${column} IN (${str1})`;
order = [column, 'artist'];
}
if (not) str = `NOT(${str})`;
querySegment.push(str);
}
query = query + querySegment.join(' AND ');
query = `${query} ORDER BY ${order.join(', ')}`;
if (condition.filter((i) => !i[0] && i[1] === 'command').length) query = condition.filter((i) => !i[0] && i[1] === 'command').map((i) => i[3]).join('\n');
console.debug('database-query', '\n\x1b[32m', query, '\x1b[0m');
let result = [[]];
try {
result = await connection.query(query);
} catch (error) {
console.error('Error:', error.message);
}
console.debug('database-query-end', result[0].length);
event.returnValue = result;
});
ipcMain.on('save-last-tabs', (event) => {
saveLastTabs();
});
ipcMain.on('hide-tab', (event, id) => {
windows[id].hide();
rebuildTrayMenu();
});
ipcMain.on('hide-all-tabs', (event) => {
for (const id of Object.keys(windows)) windows[id].hide();
rebuildTrayMenu();
});
ipcMain.on('close-all-tabs', (event, id) => {
for (const id of Object.keys(windows)) windows[id].close();
});
app.on('window-all-closed', () => {
fse.writeJSONSync('./config.json', config, { spaces: 2 });
fse.writeJSONSync('./store.json', store, { spaces: 2 });
if (process.platform !== 'darwin') app.quit();
});
// Main
const main = async () => {
config = fse.existsSync('./config.json') ? fse.readJSONSync('./config.json') : {};
app.on('ready', async () => {
const urls = ['./src/index.html'];
store = fse.existsSync('./store.json') ? fse.readJSONSync('./store.json') : {};
for (const url of urls) {
await openWindow(url);
}
tray = new Tray('./src/icon.png');
rebuildTrayMenu();
tray.on('click', () => {
for (let i = 0; i < windowHistory.length;) {
const id = windowHistory[i];
if (id in windows) {
if (windows[id].isVisible()) {
windows[id].hide();
} else {
windows[id].show();
}
break;
} else {
windowHistory.splice(0, 1);
}
}
rebuildTrayMenu();
});
});
};
main().then(async () => {
//
}, async (err) => {
console.error(err);
process.exit(1);
});