-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
329 lines (288 loc) · 9.36 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
const fs = require("fs");
const path = require("path");
const { app, BrowserWindow, Menu, Tray } = require("electron");
const rpc = require("discord-rpc");
const si = require("systeminformation");
let mainWindow;
let tray = null;
let minimizeToTray = true;
let appIsQuitting = false; // Initialize app quitting state
// Read config.json with error handling
let config;
try {
config = JSON.parse(fs.readFileSync(path.join(__dirname, "config.json")));
} catch (error) {
console.error("Error reading config.json:", error);
process.exit(1); // Exit the app if config is not available
}
const clientId = config.clientId;
// Discord Rich Presence setup
rpc.register(clientId);
let client = new rpc.Client({ transport: "ipc" });
let isConnected = false;
let presenceUpdateInterval; // Interval for updating Discord Rich Presence
// Function to set Discord Rich Presence activity
function setDiscordActivity(songTitle = "Loading Song", artist = "Loading Artist", songUrl = "", albumArtUrl = "") {
if (!client) return;
client
.setActivity({
details: `${songTitle}`,
state: `by ${artist}`,
largeImageKey: albumArtUrl || "icon",
largeImageText: "YouTube Music",
instance: false,
buttons: [
{
label: "Listen on YouTube Music",
url: songUrl || "https://music.youtube.com",
},
{
label: "Get App",
url: "https://github.com/nubsuki/YouTube-Music-Player",
},
],
})
.catch((error) => {
console.error("Error setting Discord activity:", error);
});
}
// Fetch song info from YouTube Music
async function getCurrentSongInfo() {
try {
// Fetch song title and artist
const songTitle = await mainWindow.webContents.executeJavaScript(
`document.querySelector('.title.ytmusic-player-bar')?.textContent.trim() || 'Loading Song'`
);
const artist = await mainWindow.webContents.executeJavaScript(
`document.querySelector('.byline.ytmusic-player-bar')?.textContent.trim() || 'Loading Artist'`
);
const qartist = await mainWindow.webContents.executeJavaScript(`
(() => {
const byline = document.querySelector('.byline.ytmusic-player-bar')?.textContent.trim();
if (!byline) return 'Loading Artist';
// Split the text by '•' and take the first part
return byline.split('•')[0].trim() || 'Loading Artist';
})();
`);
// Construct the search query URL
const query = encodeURIComponent(`${songTitle} by ${qartist}`);
const songUrl = `https://music.youtube.com/search?q=${query}`;
// Fetch the album art URL
const albumArtUrl = await mainWindow.webContents.executeJavaScript(`
(() => {
const imgElement = document.querySelector('.image.style-scope.ytmusic-player-bar');
return imgElement ? imgElement.src : '';
})();
`);
return { songTitle, artist, songUrl, albumArtUrl};
} catch (error) {
console.error("Error fetching song info:", error);
return { songTitle: "Loading Song", artist: "Loading Artist", albumArtUrl: "" };
}
}
// Connect to Discord
async function connectToDiscord() {
try {
// Properly destroy old client if it exists and is connected
if (client) {
try {
await client.destroy();
console.log("Destroyed old Discord client session.");
} catch (error) {
console.warn("Error destroying old client (might already be destroyed):", error.message);
}
}
// Create a new client instance
client = new rpc.Client({ transport: "ipc" });
client.on("ready", () => {
console.log("Successfully connected to Discord!");
isConnected = true;
// Set initial activity
setDiscordActivity();
// Periodically update Rich Presence
presenceUpdateInterval = setInterval(async () => {
const { songTitle, artist, songUrl, albumArtUrl } = await getCurrentSongInfo();
setDiscordActivity(songTitle, artist, songUrl, albumArtUrl);
}, 12000);
});
client.on("error", (error) => {
console.error("Discord RPC Error:", error.message);
handleDiscordDisconnect();
});
client.on("disconnected", () => {
console.warn("Disconnected from Discord. Attempting to reconnect...");
handleDiscordDisconnect();
});
// Attempt to login
await client.login({ clientId });
} catch (error) {
console.error("Failed to connect to Discord:", error.message);
// Retry connection after 10 seconds
if (!isConnected) {
setTimeout(connectToDiscord, 10000);
}
}
}
// Handle disconnections and clean up properly
function handleDiscordDisconnect() {
isConnected = false;
if (client) {
client.clearActivity().catch((error) => console.error("Error clearing activity:", error.message));
client.destroy().catch((error) => console.error("Error destroying client:", error.message));
}
client = null; // Reset client to ensure a fresh connection next time
setTimeout(waitForDiscord, 5000);
}
// Check if Discord is running
async function isDiscordRunning() {
try {
const processes = await si.processes();
return processes.list.some((process) => process.name.toLowerCase().includes("discord"));
} catch (error) {
console.error("Error checking processes:", error);
return false;
}
}
// Wait for Discord to start
async function waitForDiscord() {
// Wait for Discord to start
while (!(await isDiscordRunning())) {
console.log("Waiting for Discord to start...");
await new Promise((resolve) => setTimeout(resolve, 5000)); // Check every 5 seconds
}
// Wait for 30 seconds before attempting to connect
console.log("Discord detected! Waiting 30 seconds before connecting...");
await new Promise((resolve) => setTimeout(resolve, 30000));
console.log("Attempting to connect to Discord...");
connectToDiscord(); // Attempt to connect after the delay
}
// Request a single instance lock
const gotLock = app.requestSingleInstanceLock();
if (!gotLock) {
app.quit();
} else {
app.on("second-instance", () => {
if (mainWindow) {
if (!mainWindow.isVisible()) {
mainWindow.show();
} else if (mainWindow.isMinimized()) {
mainWindow.restore();
} else {
mainWindow.focus();
}
}
});
app.on("ready", () => {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: false, // Disable nodeIntegration for security
contextIsolation: true, // Enable context isolation
partition: "persist:youtube-music-data",
},
title: "YouTube Music",
backgroundColor: "#000000",
icon: path.join(
__dirname,
"assets",
process.platform === "win32" ? "icon.ico" : "icon.icns"
),
});
mainWindow.loadURL("https://music.youtube.com");
// Minimize to tray on close
mainWindow.on("close", (event) => {
if (minimizeToTray && !appIsQuitting) {
event.preventDefault();
mainWindow.hide();
if (!tray) {
const iconPath = path.join(__dirname, "assets", "icon.png");
if (fs.existsSync(iconPath)) {
tray = new Tray(iconPath);
tray.setToolTip("YouTube Music");
const contextMenu = Menu.buildFromTemplate([
{
label: "Show",
click: () => {
mainWindow.show();
},
},
{
label: "Exit",
click: () => {
appIsQuitting = true;
app.quit();
},
},
]);
tray.on("click", () => {
mainWindow.show();
});
tray.setContextMenu(contextMenu);
} else {
console.error("Tray icon not found at path:", iconPath);
}
}
}else {
// If minimizeToTray is false, allow the app to quit
appIsQuitting = true;
app.quit();
}return false;
});
// Custom menu
const menu = Menu.buildFromTemplate([
{
label: "File",
submenu: [
{ role: "reload" },
{
label: "Quit",
accelerator: process.platform === "darwin" ? "Command+Q" : "Alt+F4",
click: () => {
appIsQuitting = true;
app.exit();
},
},
],
},
{
label: "Window",
submenu: [
{ role: "togglefullscreen" },
{
label: "Minimize to Tray on Close",
type: "checkbox",
checked: minimizeToTray,
checked: true,
enabled: false,
},
],
},
{
label: "About",
click: () => {
const { shell } = require("electron");
shell.openExternal("https://github.com/nubsuki/YouTube-Music-Player");
},
},
]);
Menu.setApplicationMenu(menu);
// Start monitoring for Discord
waitForDiscord();
});
app.on("before-quit", async () => {
appIsQuitting = true;
clearInterval(presenceUpdateInterval); // Clear the interval
if (tray) {
tray.destroy(); // Destroy the tray icon
}
// Pause music before quitting
try {
await mainWindow.webContents.executeJavaScript(
`document.querySelector('video').pause()`
);
} catch (error) {
console.error("Error pausing music:", error);
}
});
}