-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
224 lines (190 loc) · 7.87 KB
/
Program.cs
File metadata and controls
224 lines (190 loc) · 7.87 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
using SpotifyAPI.Web;
using SpotifyAPI.Web.Auth;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Threading.Tasks;
namespace SpotifyControl
{
internal class Program
{
private static EmbedIOAuthServer _server;
private static SpotifyClient spotify;
private const int CALLBACK_PORT = 5543;
private static TaskCompletionSource<bool> refresh_token_received;
private const int VOLUME_BY = 10; // percent
private static readonly string CLIENT_ID = ConfigurationManager.AppSettings["CLIENT_ID"];
private static readonly string CLIENT_SECRET = ConfigurationManager.AppSettings["CLIENT_SECRET"];
private static string REFRESH_TOKEN = ConfigurationManager.AppSettings["REFRESH_TOKEN"];
/*
* Only one argument allowed: [r / + / - / 0 / 100]
* r : update the refresh token
* + : increase volume
* - : decrease volume
* 0 : zero volume
* 100 : full volume
*/
public static async Task Main(string[] args)
{
if ((args.Length != 1) || ((args[0] != "-") && (args[0] != "+") && (args[0] != "0") && (args[0] != "100") && (args[0] != "r")))
{
Console.WriteLine("[ERROR] Bad arguments\n" +
"* Only one argument allowed: [r / + / - / 0 / 100]\n" +
"* 'SpotifyControl r' : update the refresh token\n" +
"* 'SpotifyControl +' : increase volume\n" +
"* 'SpotifyControl -' : decrease volume\n" +
"* 'SpotifyControl 0' : zero volume\n" +
"* 'SpotifyControl 100' : full volume");
return;
}
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (args[0] == "r") // r
{
await RefreshToken(config);
}
else // - / + / 0 / 100
{
await ControlVolume(args[0]);
}
}
private static async Task RefreshToken(Configuration config)
{
try
{
await UpdateRefreshToken();
await refresh_token_received.Task; // wait until refresh token received
}
catch
{
Console.WriteLine("[ERROR] Can't get the refresh token (maybe any client id/secret issue?)");
return;
}
config.AppSettings.Settings["REFRESH_TOKEN"].Value = REFRESH_TOKEN;
config.Save();
Console.WriteLine("[SUCCESS] Received the refresh token successfully");
return;
}
private static async Task ControlVolume(string arg)
{
string accessToken;
try
{
accessToken = await GetAccessToken(REFRESH_TOKEN);
}
catch // can't get the access token
{
Console.WriteLine("[ERROR] Can't get the access token (issue with refresh token, refresh it via 'r' argument)");
return;
}
spotify = new SpotifyClient(accessToken);
int currentVolume = await GetVolume();
if (currentVolume == -1)
{
Console.WriteLine("[ERROR] No device is active currently (does any song play?)");
return;
}
try
{
await ModifyVolume(currentVolume, arg);
}
catch
{
Console.WriteLine("[ERROR] Can't change volume to this device (maybe it's a phone?)");
return;
}
}
private static async Task ModifyVolume(int currentVolume, string arg)
{
switch (arg)
{
case "+":
{
int newVolume = currentVolume + VOLUME_BY;
if (newVolume > 100)
newVolume = 100;
PlayerVolumeRequest volumeInfo = new(newVolume);
await spotify.Player.SetVolume(volumeInfo);
Console.WriteLine("[SUCCESS] + Volume");
}
break;
case "-":
{
int newVolume = currentVolume - VOLUME_BY;
if (newVolume < 0)
newVolume = 0;
PlayerVolumeRequest volumeInfo = new(newVolume);
await spotify.Player.SetVolume(volumeInfo);
Console.WriteLine("[SUCCESS] - Volume");
}
break;
case "0":
{
int newVolume = 0;
PlayerVolumeRequest volumeInfo = new(newVolume);
await spotify.Player.SetVolume(volumeInfo);
Console.WriteLine("[SUCCESS] 0 Volume");
}
break;
case "100":
{
int newVolume = 100;
PlayerVolumeRequest volumeInfo = new(newVolume);
await spotify.Player.SetVolume(volumeInfo);
Console.WriteLine("[SUCCESS] 100 Volume");
}
break;
}
}
private static async Task<string> GetAccessToken(string refreshToken)
{
AuthorizationCodeRefreshResponse newResponse = await new OAuthClient().RequestToken(new AuthorizationCodeRefreshRequest(CLIENT_ID, CLIENT_SECRET, refreshToken));
return newResponse.AccessToken;
}
// Updates REFRESH_TOKEN field
private static async Task UpdateRefreshToken()
{
await LoginSpotify();
refresh_token_received = new TaskCompletionSource<bool>(); // automatically task set to false (not already done) in order to make main thread to wait until refresh token will be received
}
private static async Task LoginSpotify()
{
_server = new EmbedIOAuthServer(new Uri($"http://localhost:{CALLBACK_PORT}/callback"), CALLBACK_PORT);
await _server.Start();
_server.AuthorizationCodeReceived += OnAuthorizationCodeReceived;
_server.ErrorReceived += OnErrorReceived;
LoginRequest request = new(_server.BaseUri, CLIENT_ID, LoginRequest.ResponseType.Code)
{
Scope = new List<string> { Scopes.UserReadPlaybackState, Scopes.UserModifyPlaybackState }
};
BrowserUtil.Open(request.ToUri());
}
private static async Task<int> GetVolume()
{
DeviceResponse devices = await spotify.Player.GetAvailableDevices();
foreach (Device device in devices.Devices)
{
if (device.IsActive)
{
return (int)device.VolumePercent;
}
}
return -1;
}
private static async Task OnAuthorizationCodeReceived(object sender, AuthorizationCodeResponse response)
{
await _server.Stop();
SpotifyClientConfig config = SpotifyClientConfig.CreateDefault();
AuthorizationCodeTokenResponse tokenResponse = await new OAuthClient(config).RequestToken(
new AuthorizationCodeTokenRequest(
CLIENT_ID, CLIENT_SECRET, response.Code, new Uri($"http://localhost:{CALLBACK_PORT}/callback")
)
);
REFRESH_TOKEN = tokenResponse.RefreshToken;
refresh_token_received.SetResult(true);
}
private static async Task OnErrorReceived(object sender, string error, string state)
{
await _server.Stop();
}
}
}