-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
616 lines (522 loc) · 19.2 KB
/
main.js
File metadata and controls
616 lines (522 loc) · 19.2 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
const { app, BrowserWindow, ipcMain, dialog, globalShortcut, Tray, Menu, shell } = require('electron');
const { autoUpdater } = require('electron-updater');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const Storage = require('./src/storage');
const { parseFile } = require('./src/metadata');
const DiscordRPC = require('./src/discord');
// Initialize Storage
const storage = new Storage(app.getPath('userData'));
// Initialize Discord RPC (Replace with your actual Client ID)
const discordRpc = new DiscordRPC('1446922918654115920');
let mainWindow;
let tray;
function createWindow() {
const settings = storage.getSettingsSync();
const useCustomTitleBar = settings.customTitleBar !== false;
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 300,
minHeight: 120,
frame: !useCustomTitleBar, // false = custom (frameless), true = native
transparent: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true,
webSecurity: true,
backgroundThrottling: false,
webviewTag: true,
devTools: true
},
icon: path.join(__dirname, 'icon.ico')
});
mainWindow.loadFile('index.html');
// Load Settings
if (settings.alwaysOnTop) {
mainWindow.setAlwaysOnTop(true);
}
// mainWindow.webContents.openDevTools(); // For debugging
// Enable Ad Blocker for main session
enableAdBlocker(mainWindow.webContents.session);
// Download Handling
mainWindow.webContents.session.on('will-download', (event, item, webContents) => {
const settings = storage.getSettingsSync();
const musicFolder = settings.musicFolder || app.getPath('music');
// Rename logic: Remove _spotdown.org suffix
let filename = item.getFilename();
filename = filename.replace(/_spotdown\.org/g, '');
const savePath = path.join(musicFolder, filename);
// Force save path (no prompt)
item.setSavePath(savePath);
const downloadId = uuidv4();
// Notify renderer started
mainWindow.webContents.send('download-started', {
id: downloadId,
filename: filename,
totalBytes: item.getTotalBytes(),
cover: 'assets/placeholder.svg' // Placeholder until we can parse it
});
item.on('updated', (event, state) => {
if (state === 'interrupted') {
// handle interruption if needed
} else if (state === 'progressing') {
if (mainWindow) {
mainWindow.webContents.send('download-progress', {
id: downloadId,
progress: item.getReceivedBytes() / item.getTotalBytes(),
state: state
});
}
}
});
item.on('done', (event, state) => {
if (mainWindow) {
mainWindow.webContents.send('download-complete', {
id: downloadId,
filename: filename,
path: savePath,
state: state
});
}
});
});
mainWindow.on('close', (event) => {
if (!app.isQuitting) {
event.preventDefault();
mainWindow.hide();
}
return false;
});
}
function createTray() {
const iconPath = path.join(__dirname, 'icon.ico');
if (!fs.existsSync(iconPath)) {
console.log('Tray icon not found, skipping tray creation.');
return;
}
tray = new Tray(iconPath);
const contextMenu = Menu.buildFromTemplate([
{
label: 'Show Moadify',
click: () => {
if (mainWindow) {
mainWindow.show();
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
}
},
{ type: 'separator' },
{
label: 'Quit',
click: () => {
app.isQuitting = true;
app.quit();
}
}
]);
tray.setToolTip('Moadify Music Player');
tray.setContextMenu(contextMenu);
tray.on('click', () => {
if (mainWindow) {
if (mainWindow.isVisible()) {
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.focus();
} else {
mainWindow.show();
mainWindow.focus();
}
}
});
}
// File Sync Logic
let fileSyncInterval = null;
async function checkFileIntegrity() {
// console.log('Checking file integrity...');
const library = await storage.getLibrary();
let libraryChanged = false;
const newLibrary = [];
// Check Library
for (const song of library) {
try {
await fs.promises.access(song.path);
newLibrary.push(song);
} catch (e) {
// libraryChanged = true; // DISABLED SAFETY: Do not auto-delete files if missing.
// console.log(`Removing missing file: ${song.path}`);
}
}
if (libraryChanged) {
await storage.saveLibrary(newLibrary);
}
// Check History (Recently Played)
const history = await storage.getHistory();
let historyChanged = false;
const newHistory = [];
for (const song of history) {
try {
await fs.promises.access(song.path);
newHistory.push(song);
} catch (e) {
// historyChanged = true; // DISABLED SAFETY
}
}
if (historyChanged) {
await storage.saveHistory(newHistory);
}
if (libraryChanged || historyChanged) {
if (mainWindow) {
mainWindow.webContents.send('library-updated');
}
}
}
function startFileSync() {
if (fileSyncInterval) clearInterval(fileSyncInterval);
console.log('Starting File Sync Watcher');
checkFileIntegrity(); // Run immediately
fileSyncInterval = setInterval(checkFileIntegrity, 2000); // Check every 2 seconds
}
function stopFileSync() {
if (fileSyncInterval) {
clearInterval(fileSyncInterval);
fileSyncInterval = null;
console.log('Stopped File Sync Watcher');
}
}
// Secure Webview Navigation
app.on('web-contents-created', (event, contents) => {
if (contents.getType() === 'webview') {
// Block Navigation to external sites
contents.on('will-navigate', (event, navigationUrl) => {
const parsedUrl = new URL(navigationUrl);
if (!parsedUrl.hostname.includes('spotdown.org')) {
event.preventDefault();
}
});
// Block New Windows
contents.setWindowOpenHandler(({ url }) => {
const parsedUrl = new URL(url);
if (!parsedUrl.hostname.includes('spotdown.org')) {
return { action: 'deny' };
}
return { action: 'allow' };
});
// Apply Network Ad Blocker to Webview Session
enableAdBlocker(contents.session);
}
});
function enableAdBlocker(session) {
const filter = {
urls: ["*://*/*"]
};
const adDomains = [
"doubleclick.net", "googlesyndication.com", "googleadservices.com", "google-analytics.com",
"adnxs.com", "adsrvr.org", "openx.net", "popads.net", "popcash.net",
"propellerads.com", "adroll.com", "criteo.com", "outbrain.com", "taboola.com",
"rubiconproject.com", "pubmatic.com", "media.net", "adtech.de", "adtech.com",
"chartbeat.net", "scorecardresearch.com", "quantserve.com", "moatads.com",
"amazon-adsystem.com", "advertising.com", "bidswitch.net", "contextweb.com",
"criteo.net", "casalemedia.com", "facebook.com/tr/", "ads.twitter.com",
"adservice.google.com", "pagead2.googlesyndication.com", "tpc.googlesyndication.com",
"www.googletagservices.com"
];
session.webRequest.onBeforeRequest(filter, (details, callback) => {
const url = details.url.toLowerCase();
// Block by domain
const shouldBlock = adDomains.some(domain => url.includes(domain));
// Block by simple patterns
const isAdPattern = [
"/ads/", "/ad/", "/banner/", "/banners/", "/sponsors/",
"googlesyndication", "g.doubleclick"
].some(pattern => url.includes(pattern));
if (shouldBlock || isAdPattern) {
callback({ cancel: true });
} else {
callback({ cancel: false });
}
});
}
app.whenReady().then(() => {
createWindow();
createTray();
// Global shortcuts for media keys are removed to allow the native Media Session API
// (navigator.mediaSession) in the renderer to handle media controls and the system overlay (SMTC).
// This ensures the "Now Playing" overlay appears and works correctly on Windows.
// Check for File Sync Setting
const settings = storage.getSettingsSync();
if (settings.fileSync) {
startFileSync();
}
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
// Auto-Update Check on Launch
// Auto-Update Check on Launch
const autoUpdate = settings.autoUpdate !== false; // Default true
autoUpdater.autoDownload = autoUpdate;
// Check for updates on startup if enabled
if (settings.autoCheckUpdate !== false) {
// Silent check
try {
autoUpdater.checkForUpdates().catch(e => console.log('Auto-update check failed', e));
} catch (e) { console.log('Auto-update error', e); }
}
});
app.on('before-quit', () => {
app.isQuitting = true;
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
// IPC Handlers
// Window Controls
ipcMain.on('minimize-window', () => mainWindow.minimize());
ipcMain.on('maximize-window', () => {
if (mainWindow.isMaximized()) mainWindow.unmaximize();
else mainWindow.maximize();
});
ipcMain.on('close-window', () => mainWindow.close()); // This triggers the close event which hides to tray
ipcMain.on('set-window-size', (event, { width, height, x, y }) => {
if (mainWindow) {
mainWindow.setSize(width, height);
if (x !== undefined && y !== undefined) {
mainWindow.setPosition(Math.round(x), Math.round(y));
}
}
});
ipcMain.on('set-always-on-top', (event, enable) => {
if (mainWindow) {
mainWindow.setAlwaysOnTop(enable);
}
});
// Library & Storage
// Library & Storage
ipcMain.handle('get-library', async () => await storage.getLibrary());
ipcMain.handle('save-library', async (event, data) => await storage.saveLibrary(data));
ipcMain.handle('get-playlists', async () => await storage.getPlaylists());
ipcMain.handle('save-playlists', async (event, data) => await storage.savePlaylists(data));
ipcMain.handle('get-history', async () => await storage.getHistory());
ipcMain.handle('save-history', async (event, data) => await storage.saveHistory(data));
ipcMain.handle('get-version', () => app.getVersion());
// File Import
ipcMain.handle('select-files', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile', 'multiSelections'],
filters: [{ name: 'Audio', extensions: ['mp3', 'wav', 'ogg', 'flac', 'aac', 'm4a'] }]
});
if (result.canceled) return [];
return result.filePaths;
});
ipcMain.handle('select-folder', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory']
});
if (result.canceled) return null;
return result.filePaths[0];
});
ipcMain.handle('parse-metadata', async (event, filePath) => {
const metadata = await parseFile(filePath);
if (metadata) {
return {
id: uuidv4(),
path: filePath,
...metadata,
dateAdded: Date.now()
};
}
return null;
});
// Discord RPC
ipcMain.on('discord-set-activity', (event, activity) => {
discordRpc.setActivity(activity.details, activity.state, activity.largeImageKey, activity.largeImageText);
});
ipcMain.on('discord-clear-activity', () => {
discordRpc.clearActivity();
});
ipcMain.handle('fetch-online-cover', async (event, query) => {
// Check Cache first
const coverCache = await storage.getCoverCache();
if (coverCache[query]) {
// console.log('Found in cache:', query);
return coverCache[query];
}
try {
const response = await fetch(`https://itunes.apple.com/search?term=${encodeURIComponent(query)}&media=music&entity=song&limit=1`);
const data = await response.json();
if (data.results && data.results.length > 0) {
const url = data.results[0].artworkUrl100.replace('100x100bb', '512x512bb');
// Save to Cache
coverCache[query] = url;
await storage.saveCoverCache(coverCache);
return url;
}
} catch (e) {
// console.error('Fetch error:', e);
}
return null;
});
ipcMain.handle('fetch-online-metadata', async (event, query) => {
try {
const response = await fetch(`https://itunes.apple.com/search?term=${encodeURIComponent(query)}&media=music&entity=song&limit=1`);
const data = await response.json();
if (data.results && data.results.length > 0) {
const result = data.results[0];
return {
title: result.trackName,
artist: result.artistName,
album: result.collectionName,
cover: result.artworkUrl100.replace('100x100bb', '512x512bb'),
year: result.releaseDate ? new Date(result.releaseDate).getFullYear() : undefined
};
}
} catch (e) {
// console.error('Fetch error:', e);
}
return null;
});
// Cover Art Upload
ipcMain.handle('select-cover', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile'],
filters: [{ name: 'Images', extensions: ['jpg', 'png', 'jpeg', 'webp'] }]
});
if (result.canceled || result.filePaths.length === 0) return null;
const filePath = result.filePaths[0];
const bitmap = fs.readFileSync(filePath);
return `data:image/${path.extname(filePath).slice(1)};base64,${bitmap.toString('base64')}`;
});
// Auto-Start
ipcMain.handle('toggle-autostart', (event, enable) => {
app.setLoginItemSettings({
openAtLogin: enable,
path: app.getPath('exe')
});
return enable;
});
ipcMain.handle('get-autostart-status', () => {
const settings = app.getLoginItemSettings();
return settings.openAtLogin;
});
// Advanced Settings Handlers
ipcMain.handle('open-config-folder', () => {
shell.openPath(app.getPath('userData'));
});
ipcMain.handle('reset-app', async () => {
const userDataPath = app.getPath('userData');
const files = ['library.json', 'playlists.json', 'settings.json', 'history.json'];
try {
for (const file of files) {
const filePath = path.join(userDataPath, file);
if (fs.existsSync(filePath)) {
await fs.promises.unlink(filePath);
}
}
return true;
} catch (e) {
console.error('Reset failed:', e);
return false;
}
});
ipcMain.on('set-debug-mode', (event, enable) => {
if (mainWindow) {
if (enable) {
mainWindow.webContents.openDevTools({ mode: 'detach', activate: true });
} else {
mainWindow.webContents.closeDevTools();
}
}
});
// File Sync Handlers
ipcMain.handle('toggle-file-sync', async (event, enable) => {
const settings = await storage.getSettings();
settings.fileSync = enable;
await storage.saveSettings(settings);
if (enable) {
startFileSync();
} else {
stopFileSync();
}
return enable;
});
ipcMain.handle('get-file-sync-status', async () => {
const settings = await storage.getSettings();
return !!settings.fileSync;
});
// Auto-Updater Logic
autoUpdater.autoInstallOnAppQuit = true;
autoUpdater.allowPrerelease = true;
function sendUpdateStatus(status, text, info = null) {
if (mainWindow) {
mainWindow.webContents.send('update-status', { status, text, info });
}
}
autoUpdater.on('checking-for-update', () => {
sendUpdateStatus('checking', 'Checking for updates...');
});
autoUpdater.on('update-available', (info) => {
// If autoDownload is true, it starts downloading automatically
// We notify the UI regardless
sendUpdateStatus('available', `Update available: v${info.version}`, info);
});
autoUpdater.on('update-not-available', (info) => {
sendUpdateStatus('not-available', 'You are up to date.', info);
});
autoUpdater.on('error', (err) => {
sendUpdateStatus('error', 'Error: ' + (err.message || err));
});
autoUpdater.on('download-progress', (progressObj) => {
if (mainWindow) {
mainWindow.webContents.send('update-progress', progressObj);
}
});
autoUpdater.on('update-downloaded', (info) => {
sendUpdateStatus('downloaded', 'Update downloaded. Restart to install.', info);
});
ipcMain.on('check-for-updates', async () => {
const settings = await storage.getSettings();
autoUpdater.autoDownload = settings.autoUpdate !== false;
autoUpdater.checkForUpdates();
});
ipcMain.on('download-update', () => {
autoUpdater.downloadUpdate();
});
ipcMain.on('quit-and-install', () => {
autoUpdater.quitAndInstall();
});
ipcMain.handle('get-auto-update-setting', async () => {
const settings = await storage.getSettings();
return settings.autoUpdate !== false;
});
ipcMain.on('set-auto-update-setting', async (event, enable) => {
const settings = await storage.getSettings();
settings.autoUpdate = enable;
await storage.saveSettings(settings);
autoUpdater.autoDownload = enable;
});
ipcMain.handle('get-auto-check-update-setting', async () => {
const settings = await storage.getSettings();
return settings.autoCheckUpdate !== false;
});
ipcMain.on('set-auto-check-update-setting', async (event, enable) => {
const settings = await storage.getSettings();
settings.autoCheckUpdate = enable;
await storage.saveSettings(settings);
});
ipcMain.handle('set-always-on-top-setting', async (event, enable) => {
const settings = await storage.getSettings();
settings.alwaysOnTop = enable;
await storage.saveSettings(settings);
if (mainWindow) {
mainWindow.setAlwaysOnTop(enable);
}
return enable;
});
ipcMain.handle('get-always-on-top-setting', async () => {
const settings = await storage.getSettings();
return !!settings.alwaysOnTop;
});