-
Notifications
You must be signed in to change notification settings - Fork 134
/
main.js
558 lines (529 loc) · 15.3 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
const { app, BrowserWindow, ipcMain, Menu } = require('electron');
const autoUpdater = require("electron-updater").autoUpdater;
const path = require('path');
const url = require('url');
const nedb = require('nedb-promise');
const util = require('util');
const os = require('os');
const ncp = require('ncp');
const request = require('request');
const alltomp3 = require('alltomp3');
const VERSION = app.getVersion();
let DEV = false;
if (process.env.ALLTOMP3_DEV == '1') {
DEV = true;
}
// autoUpdater
if (!DEV && os.platform() != 'linux') {
autoUpdater.checkForUpdates();
}
var db = {
config: nedb.datastore({ filename: path.join(app.getPath('userData'), 'config.db'), autoload: true })
};
var perrors = [];
process.on('uncaughtException', function (error) {
perrors.push(error);
console.log(error);
});
// Configure alltomp3 library binaries
function asarPath(p) {
return p.replace('app.asar', 'app.asar.unpacked');
}
alltomp3.tempFolder = app.getPath('temp') + path.sep;
if (os.platform() == 'win32') { // On Windows, we need to move eyeD3 in the tempFolder
let eyeD3Folder = alltomp3.tempFolder + 'eyeD3';
let eyeD3Exe = path.join(eyeD3Folder, 'main.exe');
ncp(asarPath(path.join(__dirname, 'bin/eyeD3')), eyeD3Folder, () => {});
alltomp3.setFfmpegPaths(asarPath(path.join(__dirname, 'bin/ffmpeg.exe')), asarPath(path.join(__dirname, 'bin/ffprobe.exe')));
alltomp3.setFpcalcPath(asarPath(path.join(__dirname, 'bin/fpcalc.exe')));
alltomp3.configEyeD3(eyeD3Exe, eyeD3Folder, (m) => {
function changep(p) {
return path.join('..', path.basename(p));
}
if (m.lyrics) {
m.lyrics = changep(m.lyrics);
}
if (m.image) {
m.image = changep(m.image);
}
return m;
});
} else if (os.platform() == 'darwin') {
alltomp3.setFfmpegPaths(asarPath(path.join(__dirname, 'bin/ffmpeg')), asarPath(path.join(__dirname, 'bin/ffprobe')));
alltomp3.setFpcalcPath(asarPath(path.join(__dirname, 'bin/fpcalc')));
alltomp3.configEyeD3(asarPath(path.join(__dirname, 'bin/eyeD3/bin/eyeD3')), asarPath(path.join(__dirname, 'bin/eyeD3/build/lib')));
} else if (os.platform() == 'linux') {
alltomp3.configEyeD3(asarPath(path.join(__dirname, 'bin/eyeD3/bin/eyeD3')), asarPath(path.join(__dirname, 'bin/eyeD3/build/lib')));
}
// Database
// Initialization
db.config.findOne({ name: 'saving-path' }).then(conf => {
console.log(conf);
if (!conf) {
return db.config.insert({ name: 'saving-path', value: app.getPath('music') });
}
return conf;
});
let firstLaunch = false;
db.config.findOne({ name: 'help-displayedn' }).then(helpDisplayed => {
if (!helpDisplayed) {
firstLaunch = true;
return db.config.insert({ name: 'help-displayedn', value: 0 });
}
});
// Messages so the renderer can query the database
ipcMain.on('db.findOne', (event, arg) => {
console.log('[DB] findOne', arg);
db[arg.db].findOne(arg.query).then(record => {
console.log(record);
event.returnValue = record;
});
});
ipcMain.on('db.update', (event, arg) => {
console.log('[DB] update', arg);
db[arg.db].update(arg.query, arg.update).then(num => {
console.log(num, 'records updated');
event.returnValue = num;
});
});
ipcMain.on('app.ready', (event, arg) => {
db.config.findOne({ name: 'previous-version' }).then(previousVersion => {
if ((!firstLaunch && !previousVersion) || (previousVersion && previousVersion.value !== VERSION)) {
let pv;
if (previousVersion) {
pv = previousVersion.value;
} else {
pv = '0.2.5';
}
request({
uri: 'https://app.alltomp3.org/release-notes/' + pv + '/' + VERSION,
json: true
}, (e, r, releaseNotes) => {
if (!e && releaseNotes && releaseNotes.length > 0) {
event.sender.send('releasenotes', releaseNotes);
}
});
}
if (!previousVersion) {
db.config.insert({ name: 'previous-version', value: VERSION });
} else if (previousVersion !== VERSION) {
db.config.update({ name: 'previous-version' }, { name: 'previous-version', value: VERSION });
}
});
db.config.findOne({ name: 'last-news' }).then(lastNews => {
if (lastNews) {
request({
uri: 'https://app.alltomp3.org/news/' + os.platform() + '/' + VERSION + '/' + lastNews.value,
json: true
}, (e, r, news) => {
if (!e && news && news.length > 0) {
event.sender.send('news', news);
}
});
}
if (!lastNews) {
db.config.insert({ name: 'last-news', value: (new Date()).toISOString() });
} else {
db.config.update({ name: 'last-news' }, { name: 'last-news', value: (new Date()).toISOString() });
}
});
});
// alltomp3 library
function forwardEvents(emitter, sender, id, allData) {
let events = ['download', 'download-end', 'convert', 'error', 'infos', 'convert-end', 'end', 'begin-url', 'end-url'];
events.forEach(e => {
emitter.on(e, forwardEvent(e, sender, id, allData));
});
ipcMain.once('at3.abort.' + id, () => {
emitter.emit('abort');
});
}
function forwardEvent(name, sender, id, allData) {
return function(d) {
console.log('[AT3] event', name, d);
if (d instanceof Error) {
d = { error: true, name: d.name, message: d.message, stack: d.stack };
}
sender.send('at3.event', {
id: id,
name: name,
data: d,
allData: allData
});
}
}
ipcMain.on('at3.suggestions', (event, id, q) => {
console.log('[AT3] suggestions', q);
let type = alltomp3.typeOfQuery(q);
if (type == 'text') {
Promise.all([
alltomp3.suggestedSongs(q, 5),
alltomp3.suggestedAlbums(q, 5),
]).then(suggestions => {
event.sender.send('at3.answer.' + id, {
type: type,
suggestions: {
songs: suggestions[0],
albums: suggestions[1]
}
});
});
} else {
event.sender.send('at3.answer.' + id, {
type: type,
urlType: alltomp3.guessURLType(q)
});
}
});
/**
* q = {
* url: 'url to download',
* folder: 'folder where downloading the song',
* id: 'identifier choosen by the renderer to identify this download'
* }
*/
ipcMain.on('at3.downloadSingleURL', (event, q) => {
console.log('[AT3] downloadSingleURL', q);
let e = alltomp3.downloadAndTagSingleURL(q.url, q.folder);
forwardEvents(e, event.sender, q.id);
});
/**
* q = {
* track: 'trackInfos',
* folder: 'folder where downloading the song',
* id: 'identifier choosen by the renderer to identify this download'
* }
*/
ipcMain.on('at3.downloadTrack', (event, q) => {
console.log('[AT3] downloadTrack', q);
let e = alltomp3.downloadTrack(q.track, q.folder);
forwardEvents(e, event.sender, q.id);
});
/**
* q = {
* url: 'track url',
* folder: 'folder where downloading the song',
* id: 'identifier choosen by the renderer to identify this download'
* }
*/
ipcMain.on('at3.downloadTrackURL', (event, q) => {
console.log('[AT3] downloadTrackURL', q);
let e = alltomp3.downloadTrackURL(q.url, q.folder);
forwardEvents(e, event.sender, q.id);
});
/**
* q = {
* url: 'playlist URL',
* folder: 'folder where downloading the playlist',
* id: 'identifier choosen by the renderer to identify this download'
* }
*/
ipcMain.on('at3.downloadPlaylist', (event, q) => {
console.log('[AT3] downloadPlaylist', q);
let e = alltomp3.downloadPlaylist(q.url, q.folder, () => {}, 4, path.join('{artist}', '{title}'));
e.on('playlist-infos', playlistInfos => {
forwardEvents(e, event.sender, q.id, playlistInfos.items);
event.sender.send('at3.event', {
id: q.id,
name: 'playlist-infos',
data: playlistInfos,
allData: playlistInfos
});
});
});
// Install update
ipcMain.on('update.install', (event) => {
autoUpdater.quitAndInstall();
});
autoUpdater.on('update-downloaded', () => {
win.webContents.send('update.downloaded');
});
autoUpdater.on('update-available', () => {
win.webContents.send('update.available');
});
// Feedback
let feedbackWin = null;
ipcMain.on('feedback.launch', (event, infos) => {
console.log('[Feedback] launch');
if (feedbackWin != null) {
return;
}
feedbackWin = new BrowserWindow({width: 800, height: 460})
feedbackWin.webContents.on('did-finish-load', () => {
win.capturePage(image => {
infos.os = {
platform: process.platform,
version: os.release()
};
infos.version = VERSION;
infos.perrors = util.inspect(perrors);
infos.errors = util.inspect(infos.errors);
infos.screenshot = image.toPNG().toString('base64');
infos.locale = app.getLocale();
let infosify = JSON.stringify(infos);
feedbackWin.webContents.send('feedback.infos', infosify);
});
});
feedbackWin.loadURL(url.format({
pathname: path.join(__dirname, 'feedback/index.html'),
protocol: 'file:',
slashes: true
}));
// Open the DevTools.
if (DEV) {
feedbackWin.webContents.openDevTools();
}
feedbackWin.on('closed', () => {
feedbackWin = null;
});
});
let menuTexts = {
ar: {
about: 'حول',
quit: 'ترك',
edit: 'تصحيح',
undo: 'فك',
redo: 'فعل ثانية',
cut: 'قص',
copy: 'مثال',
paste: 'معجون',
selectAll: 'اختر الكل',
},
fa: {
about: 'درباره',
quit: 'خروج',
edit: 'ویرایش',
undo: 'بازگردانی به قبل',
redo: 'بازگردانی به بعد',
cut: 'برش',
copy: 'کپی',
paste: 'چسباندن',
selectAll: 'انتخاب همه',
},
en: {
about: 'About',
quit: 'Quit',
edit: 'Edit',
undo: 'Undo',
redo: 'Redo',
cut: 'Cut',
copy: 'Copy',
paste: 'Paste',
selectAll: 'Select All',
},
es: {
about: 'Acerca de',
quit: 'Salir',
edit: 'Editar',
undo: 'Deshacer',
redo: 'Rehacer',
cut: 'Cortar',
copy: 'Copiar',
paste: 'Pegar',
selectAll: 'Seleccionar Todo',
},
fi: {
about: 'Tietoa',
quit: 'Sulje',
edit: 'Muokkaa',
undo: 'Kumoa',
redo: 'Tee uudestaan',
cut: 'Leikkaa',
copy: 'Kopioi',
paste: 'Liitä',
selectAll: 'Valitse kaikki',
},
fr: {
about: 'À propos',
quit: 'Quitter',
edit: 'Édition',
undo: 'Annuler',
redo: 'Répéter',
cut: 'Couper',
copy: 'Copier',
paste: 'Coller',
selectAll: 'Tout sélectionner',
},
it: {
about: 'Info',
quit: 'Esci',
edit: 'Modifica',
undo: 'Indietro',
redo: 'Avanti',
cut: 'Taglia',
copy: 'Copia',
paste: 'Incolla',
selectAll: 'Seleziona tutto',
},
ja: {
about: 'AllToMP3について',
quit: '終了',
edit: '編集',
undo: '元に戻す',
redo: 'やり直す',
cut: 'カット',
copy: 'コピー',
paste: '貼り付け',
selectAll: 'すべて選択',
},
pt: {
about: 'Sobre',
quit: 'Sair',
edit: 'Editar',
undo: 'Desfazer',
redo: 'Refazer',
cut: 'Recortar',
copy: 'Copiar',
paste: 'Colar',
selectAll: 'Selecionar Tudo',
},
ru: {
about: 'О программе',
quit: 'Выход',
edit: 'Изменить',
undo: 'Отменить',
redo: 'Вернуть',
cut: 'Вырезать',
copy: 'Копировать',
paste: 'Вставить',
selectAll: 'Выбрать все',
},
tr: {
about: 'Hakkında',
quit: 'Çık',
edit: 'Değiştir',
undo: 'Geri',
redo: 'Tekrar',
cut: 'Kes',
copy: 'Kopyala',
paste: 'Yapıştır',
selectAll: 'Hepsini seç',
},
hu: {
about: 'Névjegy',
quit: 'Kilépés',
edit: 'Szerkesztés',
undo: 'Visszavonás',
redo: 'Ismét',
cut: 'Kivágás',
copy: 'Másolás',
paste: 'Beillesztés',
selectAll: 'Összes kijelölése',
},
de: {
about: 'Über',
quit: 'Schließen',
edit: 'Bearbeiten',
undo: 'Widerrufen',
redo: 'Wiederholen',
cut: 'Ausschneiden',
copy: 'Kopieren',
paste: 'Einfügen',
selectAll: 'Alles auswählen'
},
he: {
about: 'אודות',
quit: 'צא',
edit: 'ערוך',
undo: 'בטל',
redo: 'החזר',
cut: 'גזור',
copy: 'העתק',
paste: 'הדבק',
selectAll: 'בחר הכול'
},
nl: {
about: 'Over',
quit: 'Sluiten',
edit: 'Bewerken',
undo: 'Ongedaan maken',
redo: 'Opnieuw toepassen',
cut: 'Knippen',
copy: 'Kopiëren',
paste: 'Plakken',
selectAll: 'Alles selecteren'
}
};
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;
function createWindow () {
let locales = app.getLocale().split('-');
let locale = locales[0];
if (locales.length == 2) {
alltomp3.regionCode = locales[1];
} else {
alltomp3.relevanceLanguage = locale;
}
let supportedLocales = ['en', 'fr', 'ar', 'tr', 'fi', 'ja', 'es', 'pt', 'de', 'it', 'hu', 'he', 'ru', 'ir', 'nl'];
let supportedLocale = 'en';
if (supportedLocales.indexOf(locale) > -1) {
supportedLocale = locale;
}
// Create the browser window.
win = new BrowserWindow({width: 400, height: 700})
// and load the index.html of the app.
if (DEV) {
win.loadURL('http://localhost:4200');
} else {
win.loadURL(url.format({
pathname: path.join(__dirname, 'app/dist/' + supportedLocale + '/index.html'),
protocol: 'file:',
slashes: true
}));
}
// Open the DevTools.
if (DEV) {
win.webContents.openDevTools();
}
// Emitted when the window is closed.
win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
});
let menuText = menuTexts[supportedLocale];
let template = [{
label: "AllToMP3",
submenu: [
{ label: menuText.about, selector: "orderFrontStandardAboutPanel:" },
{ type: "separator" },
{ label: menuText.quit, accelerator: "Command+Q", click: function() { app.quit(); }}
]}, {
label: menuText.edit,
submenu: [
{ label: menuText.undo, accelerator: "CmdOrCtrl+Z", selector: "undo:" },
{ label: menuText.redo, accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
{ type: "separator" },
{ label: menuText.cut, accelerator: "CmdOrCtrl+X", selector: "cut:" },
{ label: menuText.copy, accelerator: "CmdOrCtrl+C", selector: "copy:" },
{ label: menuText.paste, accelerator: "CmdOrCtrl+V", selector: "paste:" },
{ label: menuText.selectAll, accelerator: "CmdOrCtrl+A", selector: "selectAll:" }
]}
];
if (os.platform() == 'darwin') {
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.