-
Notifications
You must be signed in to change notification settings - Fork 0
/
spotify.rs
344 lines (295 loc) · 10.9 KB
/
spotify.rs
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
use std::{
sync::{Arc, OnceLock},
time::Duration,
};
use base64::{engine::general_purpose, Engine as _};
use loading::Loading;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::{sync::RwLock, time::sleep};
use crate::deezer::DeezerPlaylist;
use crate::logger::{log, LogCategory};
const TOKEN_URL: &str = "https://accounts.spotify.com/api/token";
const SCOPES: [&str; 4] = [
"user-read-email",
"user-read-private",
"playlist-modify-private",
"playlist-modify-public",
];
const REDIRECT_URI: &str = "http://localhost:8080/Spotify";
pub static CODE: OnceLock<Arc<RwLock<String>>> = OnceLock::new();
#[derive(Debug)]
pub struct Spotify<'app> {
pub email: String,
pub password: String,
client: &'app Client,
access_token: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct SpotifyTrack {
id: String,
title: String,
artist_name: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct SpotifyPlaylist {
pub title: String,
pub tracks: Vec<SpotifyTrack>,
}
#[async_trait::async_trait]
impl<'app> crate::App for Spotify<'app> {
type Error = String;
async fn init(&mut self) {
println!("{}", Spotify::get_auth_url());
let spot_load = Loading::default();
spot_load.text(String::from(
"Please sign in to Spotify with the link above",
));
let mut timeout = 0;
while CODE.get().is_none() {
if timeout == 150 {
spot_load.fail(String::from("[5min timeout] Failed to login to Spotify"));
std::process::exit(1);
}
timeout += 1;
sleep(Duration::from_secs(2)).await;
}
match self.fetch_token().await {
Ok(_) => spot_load.success(String::from("Logged in to Spotify!")),
Err(err) => {
spot_load.fail(format!("Failed to login to Spotify ({err})"));
std::process::exit(1);
}
}
spot_load.end();
}
// Keep in mind that, if you wanna use this, you need to handle the refresh token (every 60 minutes, the access token expires)
async fn fetch_token(&mut self) -> Result<(), Self::Error> {
let id = dotenv::var("SPOTIFY_CLIENT_ID")
.map_err(|err| format!("Failed to get Spotify client ID from env: {err}"))?;
let secret = dotenv::var("SPOTIFY_CLIENT_SECRET")
.map_err(|err| format!("Failed to get Spotify client SECRET from env: {err}"))?;
let res = self
.client
.post(format!(
"{}?grant_type=authorization_code&code={}&client_id={}&client_secret={}&redirect_uri={}",
TOKEN_URL,
CODE.get().unwrap().read().await,
id,
secret,
REDIRECT_URI
))
.header(
"Authorization",
format!(
"Basic {}",
general_purpose::STANDARD.encode(format!("{}:{}", id, secret))
),
)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Content-Length", "0")
.send()
.await
.map_err(|err| format!("Failed to send Spotify token request: {err}"))?;
if !res.status().is_success() {
return Err(format!(
"Failed to fetch Spotify token: ({}) {:?}",
res.status(),
res.text().await
));
}
let body: serde_json::Value = res
.json()
.await
.map_err(|err| format!("Failed to get Spotify token json result: {err}"))?;
self.access_token = body["access_token"]
.as_str()
.ok_or_else(|| format!("Failed to get Spotify access token from json result: {body}"))?
.to_owned();
Ok(())
}
fn get_auth_url() -> String {
let id = dotenv::var("SPOTIFY_CLIENT_ID")
.map_err(|err| format!("Failed to get Spotify client ID from env {err}"))
.unwrap();
let scopes = SCOPES.join("%20");
format!(
"https://accounts.spotify.com/authorize?client_id={}&response_type=code&show_dialog=true&redirect_uri={}&scope={}",
id, REDIRECT_URI, scopes
)
}
}
impl<'app> Spotify<'app> {
pub fn new(client: &'app Client) -> Self {
Self {
email: String::new(),
password: String::new(),
client,
access_token: String::new(),
}
}
pub async fn get_tracks_from_deezer(
&self,
playlist: Vec<DeezerPlaylist>,
) -> Result<Vec<SpotifyPlaylist>, <Spotify<'app> as crate::App>::Error> {
let mut p = Vec::new();
for playlist in playlist {
let mut curr_playlist = SpotifyPlaylist {
title: playlist.title.clone(),
tracks: Vec::new(),
};
log!(
"Spotify",
LogCategory::Info,
"Fetching playlist \"{}\" tracks",
playlist.title
);
for track in playlist.tracks {
let res = self
.client
.get(format!(
"https://api.spotify.com/v1/search?q={}%20artist:{}&type=track&limit=1",
track.title,
track.artist_name.replace(' ', "%20")
))
.header("Authorization", format!("Bearer {}", self.access_token))
.send()
.await
.map_err(|err| format!("Failed to send Spotify search request: {err}"))?;
if !res.status().is_success() {
return Err(format!(
"Failed to fetch Spotify search: ({}) {:?}",
res.status(),
res.text().await
));
}
let body: serde_json::Value = res
.json()
.await
.map_err(|err| format!("Failed to get Spotify search json result: {err}"))?;
let items_found = body["tracks"]["items"].as_array();
if items_found.is_none() {
log!(
"Spotify",
LogCategory::Info,
"Track not found on Spotify: {} by {}",
track.title,
track.artist_name
);
// println!("DEBUG: {:#?}", body);
continue;
}
for item in items_found.unwrap() {
if item["type"].as_str().is_some_and(|t| t == "track") {
let found_track = SpotifyTrack {
id: item["id"].as_str().unwrap().to_owned(),
title: item["name"].as_str().unwrap().to_owned(),
artist_name: item["artists"][0]["name"].as_str().unwrap().to_owned(),
};
log!(
"Spotify",
LogCategory::Info,
"| Found track \"{}\" by \"{}\" on Spotify",
found_track.title,
found_track.artist_name
);
curr_playlist.tracks.push(found_track);
}
}
}
p.push(curr_playlist);
}
Ok(p)
}
pub async fn get_my_id(&self) -> Result<String, <Spotify<'app> as crate::App>::Error> {
let res = self
.client
.get("https://api.spotify.com/v1/me")
.header("Authorization", format!("Bearer {}", self.access_token))
.send()
.await
.map_err(|err| format!("Failed to send Spotify user info request: {err}"))?;
if !res.status().is_success() {
return Err(format!(
"Failed to fetch Spotify user info: ({}) {:?}",
res.status(),
res.text().await
));
}
let body: serde_json::Value = res
.json()
.await
.map_err(|err| format!("Failed to get Spotify user info json result: {err}"))?;
Ok(body["id"].as_str().unwrap().to_owned())
}
pub async fn create_playlists(
&self,
playlists: Vec<SpotifyPlaylist>,
) -> Result<(), <Spotify<'app> as crate::App>::Error> {
let id = self.get_my_id().await?;
for playlist in playlists {
let res = self
.client
.post(format!("https://api.spotify.com/v1/users/{id}/playlists"))
.header("Authorization", format!("Bearer {}", self.access_token))
.json(&json!({
"name": playlist.title,
"description": "",
"public": false
}))
.send()
.await
.map_err(|err| {
format!("Couldn't send Spotify post resquest to create playlist {err}")
})?;
if !res.status().is_success() {
return Err(format!(
"Failed to create Spotify playlist: ({}) {:?}",
res.status(),
res.text().await
));
}
let body: serde_json::Value = res
.json()
.await
.map_err(|err| format!("Failed to get Spotify playlist json result: {err}"))?;
let playlist_id = body["id"].as_str().unwrap().to_owned();
let uris = playlist
.tracks
.iter()
.map(|t| format!("spotify:track:{}", t.id))
.collect::<Vec<String>>();
let res = self
.client
.post(format!(
"https://api.spotify.com/v1/playlists/{playlist_id}/tracks",
))
.header("Authorization", format!("Bearer {}", self.access_token))
.json(&json!({ "uris": uris }))
.send()
.await
.map_err(|err| {
format!(
"Couldn't send Spotify post resquest to add tracks to playlist id: {} {}",
playlist_id, err
)
})?;
if !res.status().is_success() {
return Err(format!(
"Failed to add tracks to Spotify playlist id: {} ({}) {:?}",
playlist_id,
res.status(),
res.text().await
));
}
log!(
"Spotify",
LogCategory::Success,
"Created playlist \"{}\"",
playlist.title
);
}
Ok(())
}
}