forked from waaverecords/PowerToys-Run-Spotify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.cs
481 lines (408 loc) · 16 KB
/
Main.cs
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
using Wox.Plugin;
using System.Windows.Controls;
using Microsoft.PowerToys.Settings.UI.Library;
using System.Windows.Media.Imaging;
using SpotifyAPI.Web;
using SpotifyAPI.Web.Auth;
using System.IO;
using Newtonsoft.Json;
using System.Windows.Input;
using System.Net;
using System.Diagnostics;
using ManagedCommon;
namespace PowerToys_Run_Spotify;
public class Main : IPlugin, IContextMenu, ISettingProvider
{
public static string PluginID => "BX1Z634F30489859A3671B4FQ7Y07193";
public string Name => "Spotify";
public string Description => "Searches and controls Spotify.";
internal string ClientId { get; private set; }
private string _appDataPath;
private string _credentialsPath;
private SpotifyClient _spotifyClient;
private string _imageDirectory { get; set; }
IEnumerable<PluginAdditionalOption> ISettingProvider.AdditionalOptions => new List<PluginAdditionalOption>()
{
new PluginAdditionalOption
{
Key = nameof(ClientId),
DisplayLabel = "Client ID",
DisplayDescription = "Your Spotify's app client id.",
PluginOptionType = PluginAdditionalOption.AdditionalOptionType.Textbox
}
};
public void Init(PluginInitContext context)
{
_appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PowerToys-Run-Spotify");
_credentialsPath = Path.Combine(_appDataPath, "credentials.json");
context.API.ThemeChanged += OnThemeChanged;
OnThemeChanged(Theme.Light, context.API.GetCurrentTheme());
}
public Control CreateSettingPanel()
{
throw new NotImplementedException();
}
public void UpdateSettings(PowerLauncherPluginSettings settings)
{
ClientId = (string)GetSettingOrDefault(settings, nameof(ClientId));
}
private object GetSettingOrDefault(
PowerLauncherPluginSettings settings,
string key
)
{
var defaultOptions = ((ISettingProvider)this).AdditionalOptions;
var defaultOption = defaultOptions.First(x => x.Key == key);
var option = settings?.AdditionalOptions?.FirstOrDefault(x => x.Key == key);
switch(defaultOption.PluginOptionType)
{
case PluginAdditionalOption.AdditionalOptionType.Textbox:
return option?.TextValue ?? defaultOption.TextValue;
}
throw new NotSupportedException();
}
private void OnThemeChanged(
Theme pre,
Theme now
) {
_imageDirectory = (now == Theme.Light || now == Theme.HighContrastWhite) ? "images/light" : "images/dark";
}
public List<Result> Query(Query query)
{
if (string.IsNullOrEmpty(ClientId))
return new List<Result>() {new Result
{
Title = "Spotify - Missing client ID",
SubTitle = "Set your client ID in the plugin's settings",
Action = context => true
}};
if (!File.Exists(_credentialsPath))
return new List<Result>() {new Result
{
Title = "Spotify - Login",
SubTitle = "Login to authorize the use of the Spotify API",
Action = context =>
{
_ = LoginToSpotify(ClientId);
return true;
}
}};
var results = new List<Result>();
if (_spotifyClient == null)
_spotifyClient = GetSpotifyClient(ClientId).GetAwaiter().GetResult();
if (string.IsNullOrEmpty(query.Search?.Trim()))
return GetBasicActions();
var searchRequest = new SearchRequest(SearchRequest.Types.All, query.Search)
{
Limit = 5
};
var searchResponse = _spotifyClient.Search.Item(searchRequest).GetAwaiter().GetResult();
// TODO: Result.TitleHighlightData
if (searchResponse.Tracks.Items != null)
results.AddRange(searchResponse.Tracks.Items.Select(track => new Result
{
Title = track.Name,
SubTitle = $"Song • By {string.Join(", ", track.Artists.Select(x => x.Name))}",
Icon = () => new BitmapImage(new Uri(track.Album.Images.OrderBy(x => x.Width * x.Height).First().Url)),
ContextData = new ContextData
{
ResultType = ResultType.Song,
Uri = track.Uri
},
Action = context =>
{
_ = EnsureActiveDevice(
async (player, request) => await player.ResumePlayback(request),
new PlayerResumePlaybackRequest { Uris = new List<string> { track.Uri } }
);
return true;
}
}));
if (searchResponse.Albums.Items != null)
results.AddRange(searchResponse.Albums.Items.Select(album => new Result
{
Title = album.Name,
SubTitle = "Album",
Icon = () => new BitmapImage(new Uri(album.Images.OrderBy(x => x.Width * x.Height).First().Url)),
ContextData = new ContextData
{
ResultType = ResultType.Album,
Uri = album.Uri
},
Action = context =>
{
_ = EnsureActiveDevice(
async (player, request) => await player.ResumePlayback(request),
new PlayerResumePlaybackRequest { ContextUri = album.Uri }
);
return true;
}
}));
if (searchResponse.Artists.Items != null)
results.AddRange(searchResponse.Artists.Items.Select(artist => new Result
{
Title = artist.Name,
SubTitle = "Artist",
Icon = () => new BitmapImage(new Uri(artist.Images.OrderBy(x => x.Width * x.Height).First().Url)),
ContextData = new ContextData
{
ResultType = ResultType.Artist,
Uri = artist.Uri
},
Action = context =>
{
_ = EnsureActiveDevice(
async (player, request) => await player.ResumePlayback(request),
new PlayerResumePlaybackRequest { ContextUri = artist.Uri }
);
return true;
}
}));
if (searchResponse.Playlists.Items != null)
results.AddRange(searchResponse.Playlists.Items.Select(playList => new Result
{
Title = playList.Name,
SubTitle = "Playlist",
Icon = () => new BitmapImage(new Uri(playList.Images.OrderBy(x => x.Width * x.Height).First().Url)),
ContextData = new ContextData
{
ResultType = ResultType.Playlist,
Uri = playList.Uri
},
Action = context =>
{
_ = EnsureActiveDevice(
async (player, request) => await player.ResumePlayback(request),
new PlayerResumePlaybackRequest { ContextUri = playList.Uri}
);
return true;
}
}));
foreach (var result in results)
result.Score = GetScore(result.Title, query.Search);
return results;
}
private List<Result> GetBasicActions()
{
List<Result> results = new List<Result>();
var previousTrack = new Result
{
Title = "Previous track",
IcoPath = Path.Combine(_imageDirectory, "previous.png"),
Action = context =>
{
_ = EnsureActiveDevice(
async (player, request) => await player.SkipPrevious(request),
new PlayerSkipPreviousRequest()
);
return true;
},
Score = 25
};
var nextTrack = new Result
{
Title = "Next track",
IcoPath = Path.Combine(_imageDirectory, "next.png"),
Action = context =>
{
_ = EnsureActiveDevice(
async (player, request) => await player.SkipNext(request),
new PlayerSkipNextRequest()
);
return true;
},
Score = 50
};
var pausePlayback = new Result
{
Title = "Pause playback",
IcoPath = Path.Combine(_imageDirectory, "pause.png"),
Action = context =>
{
_ = EnsureActiveDevice(
async (player, request) => await player.PausePlayback(request),
new PlayerPausePlaybackRequest()
);
return true;
},
Score = 75
};
var resumePlayback = new Result
{
Title = "Resume playback",
IcoPath = Path.Combine(_imageDirectory, "play.png"),
Action = context =>
{
_ = EnsureActiveDevice(
async (player, request) => await player.ResumePlayback(request),
new PlayerResumePlaybackRequest()
);
return true;
},
Score = 0
};
results.Add(previousTrack);
results.Add(nextTrack);
results.Add(pausePlayback);
results.Add(resumePlayback);
return results;
}
private int GetScore(
string str1,
string str2
)
{
// Levenshtein distance
str1 = str1.ToLower();
str2 = str2.ToLower();
var m = str1.Length;
var n = str2.Length;
var dp = new int[m + 1, n + 1];
for (int i = 0; i <= m; i++)
dp[i, 0] = i;
for (int j = 0; j <= n; j++)
dp[0, j] = j;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
{
var cost = (str1[i - 1] == str2[j - 1]) ? 0 : 1;
dp[i, j] = Math.Min(
Math.Min(
dp[i - 1, j] + 1, // deletion
dp[i, j - 1] + 1 // insertion
),
dp[i - 1, j - 1] + cost // substitution
);
}
var d = dp[m, n];
return 100 - d;
}
public List<ContextMenuResult> LoadContextMenus(Result result)
{
var results = new List<ContextMenuResult>();
var data = result.ContextData as ContextData;
switch (data?.ResultType)
{
case ResultType.Song:
results.Add(new ContextMenuResult
{
Title = $"Add to queue (Shift+Enter)",
Glyph = "\xF8AA",
FontFamily = "Segoe MDL2 Assets",
AcceleratorKey = Key.Enter,
AcceleratorModifiers = ModifierKeys.Shift,
Action = context =>
{
_ = EnsureActiveDevice(
async (player, request) => await player.AddToQueue(request),
new PlayerAddToQueueRequest(data.Uri)
);
return true;
},
});
break;
case ResultType.Album:
case ResultType.Artist:
case ResultType.Playlist:
default:
break;
}
return results;
}
private async Task LoginToSpotify(string clientId)
{
var (verifier, challenge) = PKCEUtil.GenerateCodes();
var tcs = new TaskCompletionSource();
var callbackUri = new Uri("http://localhost:5543/callback");
var authServer = new EmbedIOAuthServer(callbackUri, 5543);
authServer.AuthorizationCodeReceived += async (sender, response) =>
{
await authServer.Stop();
var tokenRequest = new PKCETokenRequest(clientId, response.Code, authServer.BaseUri, verifier);
var client = new OAuthClient();
var tokenResponse = await client.RequestToken(tokenRequest);
Directory.CreateDirectory(_appDataPath);
File.WriteAllText(_credentialsPath, JsonConvert.SerializeObject(tokenResponse));
tcs.SetResult();
};
await authServer.Start();
var loginRequest = new LoginRequest(authServer.BaseUri, clientId, LoginRequest.ResponseType.Code)
{
CodeChallenge = challenge,
CodeChallengeMethod = "S256",
Scope = new List<string>
{
Scopes.UserReadPlaybackState,
Scopes.UserModifyPlaybackState
}
};
try
{
BrowserUtil.Open(loginRequest.ToUri());
}
catch (Exception)
{
// TODO: notify user somehow?
return;
}
await tcs.Task;
}
private async Task<SpotifyClient> GetSpotifyClient(string clientId)
{
var json = await File.ReadAllTextAsync(_credentialsPath);
var token = JsonConvert.DeserializeObject<PKCETokenResponse>(json);
var authenticator = new PKCEAuthenticator(clientId!, token!);
authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(_credentialsPath, JsonConvert.SerializeObject(token));
var config = SpotifyClientConfig.CreateDefault()
.WithAuthenticator(authenticator);
return new SpotifyClient(config);
}
private async Task<TResult> EnsureActiveDevice<T, TResult>(
Func<IPlayerClient, T, Task<TResult>> callback,
T request
)
{
var requestType = request.GetType();
var deviceIdProperty = requestType.GetProperty("DeviceId");
if (deviceIdProperty == null)
throw new InvalidOperationException ($"Request of type {requestType.Name} does not need an active device.");
try
{
return await callback(_spotifyClient.Player, request);
}
catch (APIException exception)
{
if (exception.Response?.StatusCode != HttpStatusCode.NotFound)
throw;
var possiblePaths = new List<string>
{
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Spotify", "Spotify.exe"),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Spotify", "Spotify.exe"),
};
var windowsAppsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft", "WindowsApps");
if (Directory.Exists(windowsAppsPath))
{
var subDirectories = Directory.GetDirectories(windowsAppsPath, "SpotifyAB.SpotifyMusic_*");
foreach (string subDirectory in subDirectories)
{
var exePath = Path.Combine(subDirectory, "Spotify.exe");
if (File.Exists(exePath))
possiblePaths.Add(exePath);
}
}
foreach (var path in possiblePaths)
{
if (!File.Exists(path))
continue;
if (Process.Start(path) == null)
throw new ApplicationException($"Failed to start process {path}");
Thread.Sleep(1000 * 10); // wait for Spotify to open
var deviceResponse = await _spotifyClient.Player.GetAvailableDevices();
var device = deviceResponse.Devices.FirstOrDefault(x => x.Name == Environment.MachineName);
deviceIdProperty.SetValue(request, device?.Id);
return await callback(_spotifyClient.Player, request);;
}
throw new ApplicationException("Could not find the Spotify executable");
}
}
}