-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathextension.js
More file actions
480 lines (417 loc) · 15.8 KB
/
extension.js
File metadata and controls
480 lines (417 loc) · 15.8 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
const vscode = require('vscode');
const https = require('https');
let spotifyPanel = null;
let updateInterval = null;
let accessToken = null;
let refreshToken = null;
let tokenExpiresAt = null;
let lastTrackId = null;
function getClientId() {
const config = vscode.workspace.getConfiguration('spotifyWidget');
if(config.get('clientId')) {
return config.get('clientId');
} else {
return 'ac8d0a8761004cfbb0b582950be8314c';
}
}
const REDIRECT_URI = 'https://itsnotalexy.github.io/vscode-spotify-widget-auth/callback';
const SCOPES = 'user-read-playback-state user-modify-playback-state user-read-currently-playing';
let pendingCodeVerifier = null;
function activate(context) {
console.log('Spotify Widget extension is now active');
accessToken = context.globalState.get('spotifyAccessToken');
refreshToken = context.globalState.get('spotifyRefreshToken');
tokenExpiresAt = context.globalState.get('spotifyTokenExpiresAt');
let authCommand = vscode.commands.registerCommand('spotify-widget.authenticate', async function () {
await authenticateSpotify(context);
});
let handleUriCommand = vscode.commands.registerCommand('spotify-widget.handleUri', async function (uri) {
await handleAuthCallback(uri, context);
});
let showCommand = vscode.commands.registerCommand('spotify-widget.show', function () {
createOrShowSpotifyWidget(context);
});
let hideCommand = vscode.commands.registerCommand('spotify-widget.hide', function () {
if (spotifyPanel) {
spotifyPanel.dispose();
}
});
context.subscriptions.push(authCommand);
context.subscriptions.push(handleUriCommand);
context.subscriptions.push(showCommand);
context.subscriptions.push(hideCommand);
const uriHandler = {
handleUri: async (uri) => {
if (uri.path === '/auth') {
await handleAuthCallback(uri, context);
}
}
};
context.subscriptions.push(vscode.window.registerUriHandler(uriHandler));
const config = vscode.workspace.getConfiguration('spotifyWidget');
const showOnStartup = config.get('showOnStartup', true);
if (showOnStartup) {
setTimeout(() => {
createOrShowSpotifyWidget(context);
}, 1000);
}
}
async function handleAuthCallback(uri, context) {
try {
const query = new URLSearchParams(uri.query);
const code = query.get('code');
if (!code) {
vscode.window.showErrorMessage('No authorization code found in callback');
return;
}
const codeVerifier = pendingCodeVerifier || context.globalState.get('pendingCodeVerifier');
if (!codeVerifier) {
vscode.window.showErrorMessage('Authentication session expired. Please try again.');
return;
}
const clientId = getClientId();
await completeAuthentication(code, codeVerifier, clientId, context);
pendingCodeVerifier = null;
await context.globalState.update('pendingCodeVerifier', undefined);
} catch (error) {
vscode.window.showErrorMessage('Failed to handle authentication callback: ' + error.message);
}
}
async function completeAuthentication(code, codeVerifier, clientId, context) {
try {
const tokens = await exchangeCodeForToken(code, codeVerifier, clientId);
accessToken = tokens.access_token;
refreshToken = tokens.refresh_token;
tokenExpiresAt = Date.now() + (tokens.expires_in * 1000);
await context.globalState.update('spotifyAccessToken', accessToken);
await context.globalState.update('spotifyRefreshToken', refreshToken);
await context.globalState.update('spotifyTokenExpiresAt', tokenExpiresAt);
vscode.window.showInformationMessage('Successfully authenticated with Spotify!');
} catch (error) {
vscode.window.showErrorMessage('Authentication failed: ' + error.message);
throw error;
}
}
async function authenticateSpotify(context) {
const clientId = getClientId();
const codeVerifier = generateRandomString(128);
const codeChallenge = await generateCodeChallenge(codeVerifier);
pendingCodeVerifier = codeVerifier;
await context.globalState.update('pendingCodeVerifier', codeVerifier);
const authUrl = `https://accounts.spotify.com/authorize?` +
`client_id=${clientId}&` +
`response_type=code&` +
`redirect_uri=${encodeURIComponent(REDIRECT_URI)}&` +
`scope=${encodeURIComponent(SCOPES)}&` +
`code_challenge_method=S256&` +
`code_challenge=${codeChallenge}&` +
`show_dialog=true`;
const result = await vscode.window.showInformationMessage(
'You will be redirected to Spotify to authenticate. After authorizing, you can either click "Open in VS Code" on the page or paste the code manually.',
'Open Spotify Login', 'Cancel'
);
if (result === 'Open Spotify Login') {
vscode.env.openExternal(vscode.Uri.parse(authUrl));
await new Promise(resolve => setTimeout(resolve, 2000));
const manualInput = await vscode.window.showInputBox({
prompt: 'If auto-login didn\'t work, paste the authorization code from the page (or press Esc if already authenticated)',
placeHolder: 'AQD... (optional if you used "Open in VS Code" button)',
ignoreFocusOut: true,
password: false
});
if (manualInput) {
await completeAuthentication(manualInput.trim(), codeVerifier, clientId, context);
}
}
}
function generateRandomString(length) {
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const values = crypto.getRandomValues(new Uint8Array(length));
return values.reduce((acc, x) => acc + possible[x % possible.length], '');
}
async function generateCodeChallenge(codeVerifier) {
const crypto = require('crypto');
const hash = crypto.createHash('sha256').update(codeVerifier).digest();
return base64URLEncode(hash);
}
function base64URLEncode(buffer) {
return buffer.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
function exchangeCodeForToken(code, codeVerifier, clientId) {
return new Promise((resolve, reject) => {
const postData = new URLSearchParams({
client_id: clientId,
grant_type: 'authorization_code',
code: code,
redirect_uri: REDIRECT_URI,
code_verifier: codeVerifier
}).toString();
const options = {
hostname: 'accounts.spotify.com',
path: '/api/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => {
if (res.statusCode === 200) {
resolve(JSON.parse(data));
} else {
reject(new Error(`Token exchange failed: ${data}`));
}
});
});
req.on('error', reject);
req.write(postData);
req.end();
});
}
function refreshAccessToken(clientId, context) {
return new Promise((resolve, reject) => {
if (!refreshToken) {
reject(new Error('No refresh token available'));
return;
}
const postData = new URLSearchParams({
client_id: clientId,
grant_type: 'refresh_token',
refresh_token: refreshToken
}).toString();
const options = {
hostname: 'accounts.spotify.com',
path: '/api/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', async () => {
if (res.statusCode === 200) {
const tokens = JSON.parse(data);
accessToken = tokens.access_token;
tokenExpiresAt = Date.now() + (tokens.expires_in * 1000);
// Update refresh token if a new one is provided
if (tokens.refresh_token) {
refreshToken = tokens.refresh_token;
await context.globalState.update('spotifyRefreshToken', refreshToken);
}
await context.globalState.update('spotifyAccessToken', accessToken);
await context.globalState.update('spotifyTokenExpiresAt', tokenExpiresAt);
console.log('Access token refreshed successfully');
resolve(tokens);
} else {
reject(new Error(`Token refresh failed: ${data}`));
}
});
});
req.on('error', reject);
req.write(postData);
req.end();
});
}
function createOrShowSpotifyWidget(context) {
// Store context for token refresh
getCurrentTrack.context = context;
if (spotifyPanel) {
spotifyPanel.reveal(vscode.ViewColumn.Two);
return;
}
spotifyPanel = vscode.window.createWebviewPanel(
'spotifyWidget',
'Spotify Player',
vscode.ViewColumn.Two,
{
enableScripts: true,
retainContextWhenHidden: true,
localResourceRoots: []
}
);
spotifyPanel.webview.html = getWebviewContent();
spotifyPanel.webview.onDidReceiveMessage(
async message => {
switch (message.command) {
case 'playPause':
await sendSpotifyCommand('PlayPause');
break;
case 'next':
await sendSpotifyCommand('Next');
break;
case 'previous':
await sendSpotifyCommand('Previous');
break;
case 'getCurrentTrack':
const trackInfo = await getCurrentTrack();
spotifyPanel.webview.postMessage({
command: 'updateTrack',
data: trackInfo
});
break;
}
},
undefined,
context.subscriptions
);
const config = vscode.workspace.getConfiguration('spotifyWidget');
const refreshInterval = config.get('refreshInterval', 1000);
updateInterval = setInterval(async () => {
if (spotifyPanel) {
const trackInfo = await getCurrentTrack();
spotifyPanel.webview.postMessage({
command: 'updateTrack',
data: trackInfo
});
}
}, refreshInterval);
spotifyPanel.onDidDispose(
() => {
spotifyPanel = null;
if (updateInterval) {
clearInterval(updateInterval);
updateInterval = null;
}
},
null,
context.subscriptions
);
}
async function getCurrentTrack() {
// Check if token is expired or about to expire (within 5 minutes)
if (tokenExpiresAt && Date.now() >= (tokenExpiresAt - 5 * 60 * 1000)) {
if (refreshToken) {
try {
const clientId = getClientId();
// Pass the context from the activate function
await refreshAccessToken(clientId, getCurrentTrack.context);
} catch (error) {
console.error('Failed to refresh token:', error);
return createEmptyTrackInfo('Token expired', 'Please re-authenticate with Spotify');
}
} else {
return createEmptyTrackInfo('Token expired', 'Please re-authenticate with Spotify');
}
}
if (!accessToken) {
return createEmptyTrackInfo('Not authenticated', 'Run "Authenticate with Spotify" command');
}
try {
const data = await spotifyApiRequest('/v1/me/player/currently-playing');
if (!data || !data.item) {
return createEmptyTrackInfo('No track playing', 'Start playing music on Spotify');
}
const currentTrackId = data.item.id;
if (lastTrackId !== currentTrackId) {
lastTrackId = currentTrackId;
}
return {
isPlaying: data.is_playing,
track: data.item.name,
artist: data.item.artists.map(a => a.name).join(', '),
album: data.item.album.name,
albumArt: data.item.album.images[0]?.url || '',
progress: data.progress_ms || 0,
duration: data.item.duration_ms || 0
};
} catch (error) {
vscode.window.showErrorMessage('Spotify API error: ' + error.message);
if (error.message.includes('401')) {
return createEmptyTrackInfo('Authentication expired', 'Please re-authenticate');
}
return createEmptyTrackInfo('Connecting...', 'Loading track info');
}
}
function spotifyApiRequest(path) {
return new Promise((resolve, reject) => {
const options = {
hostname: 'api.spotify.com',
path: path,
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
timeout: 5000
};
const req = https.request(options, (res) => {
if (res.statusCode === 204) {
resolve(null);
return;
}
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => {
if (res.statusCode === 200) {
try {
resolve(JSON.parse(data));
} catch {
reject(new Error('Failed to parse response'));
}
} else {
reject(new Error(`${res.statusCode}: ${data}`));
}
});
});
req.on('error', reject);
req.on('timeout', () => {
req.destroy();
reject(new Error('Request timeout'));
});
req.end();
});
}
function createEmptyTrackInfo(artist, album) {
return {
isPlaying: false,
track: null,
artist: artist,
album: album,
albumArt: '',
progress: 0,
duration: 0,
error: true
};
}
async function sendSpotifyCommand(command) {
try {
const { exec } = require('child_process');
const psCommands = {
'PlayPause': `(New-Object -ComObject WScript.Shell).SendKeys([char]179)`,
'Next': `(New-Object -ComObject WScript.Shell).SendKeys([char]176)`,
'Previous': `(New-Object -ComObject WScript.Shell).SendKeys([char]177)`
};
exec(`powershell -command "${psCommands[command]}"`, (error) => {
if (error) {
console.error(`Error sending command: ${error}`);
}
});
} catch (error) {
console.error('Error sending Spotify command:', error);
vscode.window.showErrorMessage('Failed to control Spotify. Make sure Spotify is running.');
}
}
function getWebviewContent() {
const fs = require('fs');
const path = require('path');
const htmlPath = path.join(__dirname, 'webview.html');
return fs.readFileSync(htmlPath, 'utf8');
}
function deactivate() {
if (updateInterval) {
clearInterval(updateInterval);
}
}
module.exports = {
activate,
deactivate
};