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
|
use lazy_static::lazy_static;
use rocket::http::Status;
use rocket::response::{status, Redirect};
use rspotify::spotify::client::{ApiError, Spotify};
use rspotify::spotify::oauth2::{SpotifyClientCredentials, SpotifyOAuth};
use rspotify::spotify::util::process_token;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
lazy_static! {
static ref CACHE: Arc<Mutex<HashMap<String, SpotifyOAuth>>> =
Arc::new(Mutex::new(HashMap::new()));
}
#[get("/callback/<name>/<url>")]
pub fn get_tracks(name: String, url: String) -> Result<(), status::Custom<String>> {
let mut guard = CACHE.lock().or(Err(status::Custom(
Status::InternalServerError,
String::from("failed to lock cache mutex"),
)))?;
let mut oauth = guard.remove(&name).ok_or(status::Custom(
Status::NotFound,
String::from("uuid not found in cache"),
))?;
println!("auth: {:?} url: {}", oauth, url);
let token_info = process_token(&mut oauth, &mut ("?code=".to_owned() + url.as_ref()));
let client_credential = SpotifyClientCredentials::default()
.token_info(token_info.unwrap())
.build();
let spotify = Spotify::default()
.client_credentials_manager(client_credential)
.build();
let user_id = spotify.current_user().unwrap().id;
let mut client = crate::CLIENT.lock().or(Err(status::Custom(
Status::InternalServerError,
String::from("failed to lock cache mutex"),
)))?;
client
.execute(
"INSERT INTO suser (user_name) VALUES ($1) ON CONFLICT (user_name) DO NOTHING;",
&[&user_id],
)
.unwrap();
let uid = get_uid(user_id.as_ref(), &mut client).ok_or(status::Custom(
Status::NotFound,
format!("username {} not found", user_id),
))?;
client
.execute("DELETE FROM user_track WHERE user_id = $1;", &[&uid])
.unwrap();
drop(client);
let chunk_size = 50;
let mut playlist_index = 0;
loop {
match spotify.user_playlists(user_id.as_ref(), Some(chunk_size), Some(playlist_index)) {
Ok(playlists) => {
playlist_index += chunk_size;
if playlists.items.is_empty() {
break;
}
for playlist in playlists.items {
println!("playlist: {:?}", playlist.name);
let mut track_index = 0;
loop {
match spotify.user_playlist_tracks(
user_id.as_ref(),
&playlist.id,
None,
Some(chunk_size),
Some(track_index),
None,
) {
Ok(tracks) => {
track_index += chunk_size;
if tracks.items.is_empty() {
break;
}
for track in tracks.items {
//println!("{:?}", track.track.name);
let mut client = crate::CLIENT.lock().or(Err(
status::Custom(Status::InternalServerError, String::new()),
))?;
if track.track.id.is_none() {
println!("{:#?}", track);
continue;
}
print!(" {} ", track.track.id.clone().unwrap());
client
.execute(
"INSERT INTO track (track_code, name, artist, popularity)
VALUES ($1, $2, $3, $4)
ON CONFLICT DO NOTHING
",
&[&(track.track.id.clone().unwrap()), &track.track.name, &track.track.artists[0].name, &(track.track.popularity as i32)],
)
.unwrap();
let tid: i32 = client
.query(
"SELECT track_id FROM track where track_code = $1;",
&[&(track.track.id.clone().unwrap())],
)
.unwrap()[0]
.get(0);
println!("uid: {} tid: {}", uid, tid);
client
.execute(
"INSERT INTO user_track (track_id, user_id, count)
VALUES ($1, $2, $3)
ON CONFLICT
ON CONSTRAINT track_user_pkey
DO NOTHING;",
&[&tid, &uid, &0],
)
.unwrap();
client
.execute(
"UPDATE user_track SET count = count + 1 WHERE track_id = $1 AND user_id = $2;",
&[&tid, &uid],
)
.unwrap();
}
}
Err(e) => match e.downcast::<ApiError>() {
Ok(ApiError::RateLimited(x)) => std::thread::sleep(
std::time::Duration::from_secs(x.unwrap_or(5) as u64),
),
cause => {
println!("Error: {:?}", cause);
break;
}
},
}
}
}
}
Err(e) => match e.downcast::<ApiError>() {
Ok(ApiError::RateLimited(x)) => {
std::thread::sleep(std::time::Duration::from_secs(x.unwrap_or(5) as u64))
}
cause => {
println!("Error: {:?}", cause);
break;
}
},
}
}
Ok(())
}
#[get("/token/<name>")]
pub fn token(name: String) -> Result<Redirect, status::Custom<String>> {
let state = rspotify::spotify::util::generate_random_string(16);
let oauth = SpotifyOAuth::default();
//let callback = oauth.redirect_uri.clone();
let oauth = oauth
.scope("playlist-read-private, playlist-read-collaborative, user-read-private, user-follow-read, user-library-read")
//.redirect_uri(format!("{}/{}", callback, &state).as_ref())
.build();
let auth_url = oauth.get_authorize_url(Some(&state), None);
match CACHE.lock() {
Ok(mut guard) => {
guard.insert(name, oauth);
Ok(Redirect::to(auth_url))
}
Err(_) => Err(status::Custom(
Status::ImATeapot,
"Internal Server Error".to_owned(),
)),
}
}
fn get_uid(name: &str, client: &mut postgres::Client) -> Option<i32> {
match client.query("SELECT user_id FROM suser where user_name = $1;", &[&name]) {
Ok(rows) => match rows.len() {
0 => None,
x => {
let x: i32 = rows[0].get(0);
Some(x)
}
},
_ => None,
}
}
#[get("/match/<name1>/<name2>")]
pub fn match_users(name1: String, name2: String) -> Result<String, status::NotFound<String>> {
let mut client = crate::CLIENT.lock().unwrap();
let uid1 = get_uid(name1.as_ref(), &mut client)
.ok_or(status::NotFound(format!("username {} not found", name1)))?;
let uid2 = get_uid(name2.as_ref(), &mut client)
.ok_or(status::NotFound(format!("username {} not found", name2)))?;
let mut songs = String::new();
for row in client
.query(
"
SELECT track_id FROM user_track where user_id = $1
INTERSECT
SELECT track_id FROM user_track where user_id = $2
",
&[&uid1, &uid2],
)
.unwrap()
{
let tid: i32 = row.get(0);
let song = &client
.query(
"SELECT name, artist FROM track where track_id = $1",
&[&tid],
)
.unwrap()[0];
println!("{:?}", song.columns());
let name: String = song.get(0);
let artist: String = song.get(1);
songs = format!("{}{} by {}\n", songs, name, artist);
}
Ok(songs)
}
#[get("/user")]
pub fn get_users() -> Result<String, status::NotFound<String>> {
let mut client = crate::CLIENT.lock().unwrap();
let mut users = String::new();
for row in client.query("SELECT user_name FROM suser", &[]).unwrap() {
let user: String = row.get(0);
users = format!("{}{}\n", users, user);
}
Ok(users)
}
|