-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
301 lines (255 loc) · 10.2 KB
/
Copy pathProgram.cs
File metadata and controls
301 lines (255 loc) · 10.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
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using SpotifyAPI.Web;
using SpotifyAPI.Web.Auth;
using Windows.Media;
using Windows.Media.Playback;
using Windows.Storage.Streams;
AttachConsole(-1);
string? configDir = null;
string? clientIdArg = null;
var doOauth = false;
for (var i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "-c" or "--config" when i + 1 < args.Length: configDir = args[++i]; break;
case "-i" or "--client-id" when i + 1 < args.Length: clientIdArg = args[++i]; break;
case "-j" or "--oauth": doOauth = true; break;
case "-h" or "--help": Usage(); return;
default:
Console.Error.WriteLine($"bad argument: {args[i]}");
Usage();
Environment.ExitCode = 1;
return;
}
}
configDir = configDir is null ? null : Environment.ExpandEnvironmentVariables(configDir);
// Catch this now rather than after the browser dance, when Save would throw.
if (configDir is not null && File.Exists(configDir))
{
Console.Error.WriteLine($"--config wants a directory, but {configDir} is a file.");
Environment.ExitCode = 1;
return;
}
var config = Load(configDir);
// A client id on the command line wins over one already in the config.
var clientId = clientIdArg ?? config.ClientId;
if (string.IsNullOrEmpty(clientId))
{
Console.Error.WriteLine("No client id. Pass --client-id, or use a --config that has one.");
Environment.ExitCode = 1;
return;
}
var spotify = await Connect(clientId, config.RefreshToken, doOauth, configDir);
var player = new MediaPlayer();
var smtc = player.SystemMediaTransportControls;
smtc.IsEnabled = true;
smtc.IsPlayEnabled = true;
smtc.IsPauseEnabled = true;
smtc.IsNextEnabled = true;
smtc.IsPreviousEnabled = true;
smtc.ButtonPressed += async (_, e) =>
{
try
{
switch (e.Button)
{
case SystemMediaTransportControlsButton.Play: await spotify.Player.ResumePlayback(); break;
case SystemMediaTransportControlsButton.Pause: await spotify.Player.PausePlayback(); break;
case SystemMediaTransportControlsButton.Next: await spotify.Player.SkipNext(); break;
case SystemMediaTransportControlsButton.Previous: await spotify.Player.SkipPrevious(); break;
}
}
catch (APIException ex)
{
Console.WriteLine($"{e.Button} failed: {ex.Message}");
}
};
// Spotify has no way to notify us of changes, so asking on a timer is the only option.
// ponytail: a fixed 1s poll. If you start seeing 429s, back off while nothing is playing.
Console.WriteLine("Watching Spotify. Ctrl+C to stop.");
string? lastTrackId = null;
while (true)
{
try
{
var playback = await spotify.Player.GetCurrentPlayback();
if (playback?.Item is FullTrack track)
{
// Only redraw when the song actually changes; Update() on every tick makes it flicker.
if (track.Id != lastTrackId)
{
lastTrackId = track.Id;
var artists = string.Join(", ", track.Artists.Select(a => a.Name));
var display = smtc.DisplayUpdater;
display.Type = MediaPlaybackType.Music;
display.MusicProperties.Title = track.Name;
display.MusicProperties.Artist = artists;
display.MusicProperties.AlbumTitle = track.Album.Name;
if (track.Album.Images.Count > 0)
display.Thumbnail = RandomAccessStreamReference.CreateFromUri(
new Uri(track.Album.Images[0].Url));
display.Update();
Console.WriteLine($"{track.Name} - {artists}");
}
smtc.PlaybackStatus = playback.IsPlaying
? MediaPlaybackStatus.Playing
: MediaPlaybackStatus.Paused;
// Drives the scrub bar in the overlay.
smtc.UpdateTimelineProperties(new SystemMediaTransportControlsTimelineProperties
{
StartTime = TimeSpan.Zero,
MinSeekTime = TimeSpan.Zero,
Position = TimeSpan.FromMilliseconds(playback.ProgressMs),
MaxSeekTime = TimeSpan.FromMilliseconds(track.DurationMs),
EndTime = TimeSpan.FromMilliseconds(track.DurationMs),
});
}
else
{
// Nothing playing, or it's a podcast episode rather than a track.
smtc.PlaybackStatus = MediaPlaybackStatus.Stopped;
lastTrackId = null;
}
}
catch (APIException ex)
{
Console.WriteLine($"spotify: {ex.Message}");
}
// player is unreferenced after line 62; without this the GC collects it and the session vanishes.
GC.KeepAlive(player);
await Task.Delay(1000);
}
// CLI Flags
static void Usage() => Console.WriteLine("""
-c, --config <dir> directory to keep the client id and login in.
Created if it does not exist. Omit it and
nothing is written to disk.
-i, --client-id <id> client id from your Spotify developer app
-j, --oauth force a fresh browser login, to switch account.
Logging in happens on its own when there is
no saved login.
-h, --help this message
first run: SpotSMTC -i <client id> -c %APPDATA%\SpotSMTC
after that: SpotSMTC -c %APPDATA%\SpotSMTC
""");
// Config
static Config Load(string? dir)
{
if (dir is null) return new Config(null, null);
var file = ConfigFile(dir);
if (!File.Exists(file)) return new Config(null, null);
try
{
var stored = JsonSerializer.Deserialize<Config>(File.ReadAllText(file)) ?? new Config(null, null);
return stored with { RefreshToken = Unprotect(stored.RefreshToken) };
}
catch (JsonException ex)
{
Console.Error.WriteLine($"ignoring unreadable config {file}: {ex.Message}");
return new Config(null, null);
}
}
static void Save(string? dir, string clientId, string? refreshToken)
{
// No --config means the login is never written down; it lasts as long as the process.
if (dir is null || string.IsNullOrEmpty(refreshToken)) return;
Directory.CreateDirectory(dir);
File.WriteAllText(ConfigFile(dir), JsonSerializer.Serialize(
new Config(clientId, Protect(refreshToken)),
new JsonSerializerOptions { WriteIndented = true }));
}
// DPAPI, so the file is inert for any other Windows account that can read it.
static string Protect(string token) => Convert.ToBase64String(
ProtectedData.Protect(Encoding.UTF8.GetBytes(token), null, DataProtectionScope.CurrentUser));
static string? Unprotect(string? stored)
{
if (string.IsNullOrEmpty(stored)) return null;
try
{
return Encoding.UTF8.GetString(
ProtectedData.Unprotect(Convert.FromBase64String(stored), null, DataProtectionScope.CurrentUser));
}
catch (Exception ex) when (ex is CryptographicException or FormatException)
{
// Another account's file, or one written before this was encrypted. Log in again.
return null;
}
}
static string ConfigFile(string dir) => Path.Combine(dir, "config.json");
// Auth
static async Task<SpotifyClient> Connect(string clientId, string? refreshToken, bool forceLogin, string? configDir)
{
PKCETokenResponse token;
if (!forceLogin && !string.IsNullOrEmpty(refreshToken))
{
try
{
token = await new OAuthClient().RequestToken(
new PKCETokenRefreshRequest(clientId, refreshToken));
}
catch (APIException)
{
// Saved login was revoked or is no longer valid; start over.
token = await LogIn(clientId);
}
}
else
{
token = await LogIn(clientId);
}
Save(configDir, clientId, token.RefreshToken);
// Renews the access token by itself every hour, and hands us the new refresh token to store.
var authenticator = new PKCEAuthenticator(clientId, token);
authenticator.TokenRefreshed += (_, t) => Save(configDir, clientId, t.RefreshToken);
return new SpotifyClient(SpotifyClientConfig.CreateDefault().WithAuthenticator(authenticator));
}
static async Task<PKCETokenResponse> LogIn(string clientId)
{
var redirect = new Uri("http://127.0.0.1:5000/callback");
var (verifier, challenge) = PKCEUtil.GenerateCodes();
var state = Convert.ToHexString(RandomNumberGenerator.GetBytes(16));
// Our own listener rather than EmbedIOAuthServer, which binds every interface.
using var listener = new HttpListener();
listener.Prefixes.Add("http://127.0.0.1:5000/");
listener.Start();
var login = new LoginRequest(redirect, clientId, LoginRequest.ResponseType.Code)
{
CodeChallengeMethod = "S256",
CodeChallenge = challenge,
State = state,
Scope = new List<string> { Scopes.UserReadPlaybackState, Scopes.UserModifyPlaybackState },
};
Console.WriteLine("Opening your browser to log in to Spotify...");
BrowserUtil.Open(login.ToUri());
// Anything without our state is someone else knocking; answer it and keep waiting.
string? code = null, error = null;
while (code is null && error is null)
{
var ctx = await listener.GetContextAsync();
var query = ctx.Request.QueryString;
if (query["state"] == state)
{
code = query["code"];
error = query["error"];
}
var body = Encoding.UTF8.GetBytes(
code is not null ? "Logged in. You can close this tab."
: error is not null ? $"Login failed: {error}"
: "Waiting for the Spotify callback.");
ctx.Response.ContentType = "text/plain; charset=utf-8";
ctx.Response.ContentLength64 = body.Length;
await ctx.Response.OutputStream.WriteAsync(body);
ctx.Response.Close();
}
if (code is null) throw new InvalidOperationException($"Spotify refused the login: {error}");
return await new OAuthClient().RequestToken(
new PKCETokenRequest(clientId, code, redirect, verifier));
}
[DllImport("kernel32.dll")]
static extern bool AttachConsole(int processId);
record Config(string? ClientId, string? RefreshToken);