forked from Rigellute/spotify-tui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.rs
More file actions
1172 lines (1075 loc) Β· 38.7 KB
/
app.rs
File metadata and controls
1172 lines (1075 loc) Β· 38.7 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
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::{config::ClientConfig, user_config::UserConfig};
use failure::{err_msg, format_err};
use rspotify::spotify::{
client::Spotify,
model::{
album::{FullAlbum, SavedAlbum, SimplifiedAlbum},
artist::FullArtist,
context::FullPlayingContext,
device::DevicePayload,
offset::{for_position, Offset},
page::{CursorBasedPage, Page},
playing::PlayHistory,
playlist::{PlaylistTrack, SimplifiedPlaylist},
recommend::Recommendations,
search::{SearchAlbums, SearchArtists, SearchPlaylists, SearchTracks},
track::{FullTrack, SavedTrack, SimplifiedTrack},
user::PrivateUser,
},
senum::{Country, RepeatState},
};
use serde_json::{map::Map, Value};
use std::{
cmp::{max, min},
collections::HashSet,
time::Instant,
};
use tui::layout::Rect;
use clipboard::{ClipboardContext, ClipboardProvider};
pub const LIBRARY_OPTIONS: [&str; 6] = [
"Made For You",
"Recently Played",
"Liked Songs",
"Albums",
"Artists",
"Podcasts",
];
const DEFAULT_ROUTE: Route = Route {
id: RouteId::Home,
active_block: ActiveBlock::Empty,
hovered_block: ActiveBlock::Library,
};
#[derive(Clone)]
pub struct ScrollableResultPages<T> {
index: usize,
pages: Vec<T>,
}
impl<T> ScrollableResultPages<T> {
pub fn new() -> ScrollableResultPages<T> {
ScrollableResultPages {
index: 0,
pages: vec![],
}
}
pub fn get_results(&self, at_index: Option<usize>) -> Option<&T> {
match at_index {
Some(index) => self.pages.get(index),
None => self.pages.get(self.index),
}
}
pub fn add_pages(&mut self, new_pages: T) {
self.pages.push(new_pages);
// Whenever a new page is added, set the active index to the end of the vector
self.index = self.pages.len() - 1;
}
}
#[derive(Default)]
pub struct SpotifyResultAndSelectedIndex<T> {
pub index: usize,
pub result: T,
}
#[derive(Clone)]
pub struct Library {
pub selected_index: usize,
pub saved_tracks: ScrollableResultPages<Page<SavedTrack>>,
pub saved_albums: ScrollableResultPages<Page<SavedAlbum>>,
pub saved_artists: ScrollableResultPages<CursorBasedPage<FullArtist>>,
}
#[derive(Clone)]
pub struct PlaybackParams {
context_uri: Option<String>,
uris: Option<Vec<String>>,
offset: Option<Offset>,
}
#[derive(PartialEq, Debug)]
pub enum SearchResultBlock {
AlbumSearch,
SongSearch,
ArtistSearch,
PlaylistSearch,
Empty,
}
#[derive(PartialEq, Debug, Clone)]
pub enum ArtistBlock {
TopTracks,
Albums,
RelatedArtists,
Empty,
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum ActiveBlock {
PlayBar,
AlbumTracks,
AlbumList,
ArtistBlock,
Empty,
Error,
HelpMenu,
Home,
Input,
Library,
MyPlaylists,
Podcasts,
RecentlyPlayed,
SearchResultBlock,
SelectDevice,
TrackTable,
MadeForYou,
Artists,
}
#[derive(Clone, PartialEq, Debug)]
pub enum RouteId {
AlbumTracks,
AlbumList,
Artist,
Error,
Home,
RecentlyPlayed,
Search,
SelectedDevice,
TrackTable,
MadeForYou,
Artists,
Podcasts,
Recommendations,
}
pub struct Route {
pub id: RouteId,
pub active_block: ActiveBlock,
pub hovered_block: ActiveBlock,
}
// Is it possible to compose enums?
#[derive(PartialEq, Debug)]
pub enum TrackTableContext {
MyPlaylists,
AlbumSearch,
PlaylistSearch,
SavedTracks,
RecommendedTracks,
}
#[derive(Clone, PartialEq, Debug)]
pub enum AlbumTableContext {
Simplified,
Full,
}
#[derive(Clone, PartialEq, Debug)]
pub enum RecommendationsContext {
Artist,
Song,
}
pub struct SearchResult {
pub albums: Option<SearchAlbums>,
pub artists: Option<SearchArtists>,
pub playlists: Option<SearchPlaylists>,
pub selected_album_index: Option<usize>,
pub selected_artists_index: Option<usize>,
pub selected_playlists_index: Option<usize>,
pub selected_tracks_index: Option<usize>,
pub tracks: Option<SearchTracks>,
pub hovered_block: SearchResultBlock,
pub selected_block: SearchResultBlock,
}
#[derive(Default)]
pub struct TrackTable {
pub tracks: Vec<FullTrack>,
pub selected_index: usize,
pub context: Option<TrackTableContext>,
}
#[derive(Clone)]
pub struct SelectedAlbum {
pub album: SimplifiedAlbum,
pub tracks: Page<SimplifiedTrack>,
pub selected_index: usize,
}
#[derive(Clone)]
pub struct SelectedFullAlbum {
pub album: FullAlbum,
pub selected_index: usize,
}
#[derive(Clone)]
pub struct Artist {
pub artist_name: String,
pub albums: Page<SimplifiedAlbum>,
pub related_artists: Vec<FullArtist>,
pub top_tracks: Vec<FullTrack>,
pub selected_album_index: usize,
pub selected_related_artist_index: usize,
pub selected_top_track_index: usize,
pub artist_hovered_block: ArtistBlock,
pub artist_selected_block: ArtistBlock,
}
pub struct App {
instant_since_last_current_playback_poll: Instant,
navigation_stack: Vec<Route>,
pub home_scroll: u16,
pub client_config: ClientConfig,
pub user_config: UserConfig,
pub artists: Vec<FullArtist>,
pub artist: Option<Artist>,
pub album_table_context: AlbumTableContext,
pub saved_album_tracks_index: usize,
pub api_error: String,
pub current_playback_context: Option<FullPlayingContext>,
pub devices: Option<DevicePayload>,
// Inputs:
// input is the string for input;
// input_idx is the index of the cursor in terms of character;
// input_cursor_position is the sum of the width of charaters preceding the cursor.
// Reason for this complication is due to non-ASCII characters, they may
// take more than 1 bytes to store and more than 1 character width to display.
pub input: Vec<char>,
pub input_idx: usize,
pub input_cursor_position: u16,
pub liked_song_ids_set: HashSet<String>,
pub large_search_limit: u32,
pub library: Library,
pub playlist_offset: u32,
pub playback_params: PlaybackParams,
pub playlist_tracks: Vec<PlaylistTrack>,
pub playlists: Option<Page<SimplifiedPlaylist>>,
pub recently_played: SpotifyResultAndSelectedIndex<Option<CursorBasedPage<PlayHistory>>>,
pub recommended_tracks: Vec<FullTrack>,
pub recommendations_seed: String,
pub recommendations_context: Option<RecommendationsContext>,
pub search_results: SearchResult,
pub selected_album: Option<SelectedAlbum>,
pub selected_album_full: Option<SelectedFullAlbum>,
pub selected_device_index: Option<usize>,
pub selected_playlist_index: Option<usize>,
pub size: Rect,
pub small_search_limit: u32,
pub song_progress_ms: u128,
pub spotify: Option<Spotify>,
pub track_table: TrackTable,
pub user: Option<PrivateUser>,
pub album_list_index: usize,
pub artists_list_index: usize,
pub clipboard_context: Option<ClipboardContext>,
}
impl App {
pub fn new() -> App {
App {
album_table_context: AlbumTableContext::Full,
album_list_index: 0,
artists_list_index: 0,
artists: vec![],
artist: None,
user_config: UserConfig::new(),
client_config: Default::default(),
saved_album_tracks_index: 0,
recently_played: Default::default(),
size: Rect::default(),
selected_album: None,
selected_album_full: None,
home_scroll: 0,
library: Library {
saved_tracks: ScrollableResultPages::new(),
saved_albums: ScrollableResultPages::new(),
saved_artists: ScrollableResultPages::new(),
selected_index: 0,
},
liked_song_ids_set: HashSet::new(),
navigation_stack: vec![DEFAULT_ROUTE],
large_search_limit: 20,
small_search_limit: 4,
api_error: String::new(),
current_playback_context: None,
devices: None,
input: vec![],
input_idx: 0,
input_cursor_position: 0,
playlist_offset: 0,
playlist_tracks: vec![],
playlists: None,
recommended_tracks: vec![],
recommendations_context: None,
recommendations_seed: "".to_string(),
search_results: SearchResult {
hovered_block: SearchResultBlock::SongSearch,
selected_block: SearchResultBlock::Empty,
albums: None,
artists: None,
playlists: None,
selected_album_index: None,
selected_artists_index: None,
selected_playlists_index: None,
selected_tracks_index: None,
tracks: None,
},
song_progress_ms: 0,
selected_device_index: None,
selected_playlist_index: None,
spotify: None,
track_table: Default::default(),
playback_params: PlaybackParams {
context_uri: None,
uris: None,
offset: None,
},
user: None,
instant_since_last_current_playback_poll: Instant::now(),
clipboard_context: None,
}
}
pub fn get_user(&mut self) {
if let Some(spotify) = &self.spotify {
match spotify.current_user() {
Ok(user) => {
self.user = Some(user);
}
Err(e) => {
self.handle_error(e);
}
}
}
}
pub fn handle_get_devices(&mut self) {
if let Some(spotify) = &self.spotify {
if let Ok(result) = spotify.device() {
self.push_navigation_stack(RouteId::SelectedDevice, ActiveBlock::SelectDevice);
if !result.devices.is_empty() {
self.devices = Some(result);
// Select the first device in the list
self.selected_device_index = Some(0);
}
}
}
}
pub fn get_current_playback(&mut self) {
if let Some(spotify) = &self.spotify {
let context = spotify.current_playback(None);
if let Ok(ctx) = context {
if let Some(c) = ctx {
self.current_playback_context = Some(c.clone());
self.instant_since_last_current_playback_poll = Instant::now();
if let Some(track) = c.item {
if let Some(track_id) = track.id {
self.current_user_saved_tracks_contains(vec![track_id]);
}
}
}
};
}
}
pub fn current_user_saved_tracks_contains(&mut self, ids: Vec<String>) {
if let Some(spotify) = &self.spotify {
match spotify.current_user_saved_tracks_contains(&ids) {
Ok(is_saved_vec) => {
for (i, id) in ids.iter().enumerate() {
if let Some(is_liked) = is_saved_vec.get(i) {
if *is_liked {
self.liked_song_ids_set.insert(id.to_string());
} else {
// The song is not liked, so check if it should be removed
if self.liked_song_ids_set.contains(id) {
self.liked_song_ids_set.remove(id);
}
}
};
}
}
Err(e) => {
self.handle_error(e);
}
}
}
}
fn poll_current_playback(&mut self) {
// Poll every 5 seconds
let poll_interval_ms = 5_000;
let elapsed = self
.instant_since_last_current_playback_poll
.elapsed()
.as_millis();
if elapsed >= poll_interval_ms {
self.get_current_playback();
}
}
pub fn update_on_tick(&mut self) {
self.poll_current_playback();
if let Some(current_playback_context) = &self.current_playback_context {
if let (Some(track), Some(progress_ms)) = (
¤t_playback_context.item,
current_playback_context.progress_ms,
) {
if current_playback_context.is_playing {
let elapsed = self
.instant_since_last_current_playback_poll
.elapsed()
.as_millis()
+ u128::from(progress_ms);
if elapsed < u128::from(track.duration_ms) {
self.song_progress_ms = elapsed;
} else {
self.song_progress_ms = track.duration_ms.into();
}
}
}
}
}
fn seek(&mut self, position_ms: u32) {
if let (Some(spotify), Some(device_id)) = (&self.spotify, &self.client_config.device_id) {
match spotify.seek_track(position_ms, Some(device_id.to_string())) {
Ok(()) => {
self.get_current_playback();
}
Err(e) => {
self.handle_error(e);
}
};
}
}
pub fn seek_forwards(&mut self) {
if let Some(current_playback_context) = &self.current_playback_context {
if let Some(track) = ¤t_playback_context.item {
if track.duration_ms - self.song_progress_ms as u32
> self.user_config.behavior.seek_milliseconds
{
self.seek(
self.song_progress_ms as u32 + self.user_config.behavior.seek_milliseconds,
);
} else {
self.next_track();
}
}
}
}
pub fn seek_backwards(&mut self) {
let new_progress =
if self.song_progress_ms as u32 > self.user_config.behavior.seek_milliseconds {
self.song_progress_ms as u32 - self.user_config.behavior.seek_milliseconds
} else {
0u32
};
self.seek(new_progress);
}
pub fn pause_playback(&mut self) {
if let (Some(spotify), Some(device_id)) = (&self.spotify, &self.client_config.device_id) {
match spotify.pause_playback(Some(device_id.to_string())) {
Ok(()) => {
self.get_current_playback();
}
Err(e) => {
self.handle_error(e);
}
};
}
}
pub fn get_recommendations_for_seed(
&mut self,
seed_artists: Option<Vec<String>>,
seed_tracks: Option<Vec<String>>,
first_track: Option<&FullTrack>,
) {
if let (Some(spotify), Some(user)) = (&self.spotify, &self.user.to_owned()) {
let user_country =
Country::from_str(&user.country.to_owned().unwrap_or_else(|| "".to_string()));
let empty_payload: Map<String, Value> = Map::new();
match spotify.recommendations(
seed_artists, // artists
None, // genres
seed_tracks, // tracks
self.large_search_limit, // adjust playlist to screen size
user_country, // country
&empty_payload, // payload
) {
Ok(result) => {
if let Some(mut recommended_tracks) = self.extract_recommended_tracks(&result) {
//custom first track
if let Some(track) = first_track {
recommended_tracks.insert(0, track.clone());
}
self.recommended_tracks = recommended_tracks.clone();
self.set_tracks_to_table(recommended_tracks);
self.track_table.context = Some(TrackTableContext::RecommendedTracks);
if self.get_current_route().id != RouteId::Recommendations {
self.push_navigation_stack(
RouteId::Recommendations,
ActiveBlock::TrackTable,
);
};
}
self.start_recommendations_playback(Some(0));
}
Err(e) => println!("error: {:?}", e),
}
}
}
pub fn get_recommendations_for_trackid(&mut self, id: &str) {
if let Some(track) = self.get_fulltrack_from_id(id) {
let track_id_list: Option<Vec<String>> = match &track.id {
Some(id) => Some(vec![id.to_string()]),
None => None,
};
self.get_recommendations_for_seed(None, track_id_list, Some(&track));
}
}
fn change_volume(&mut self, volume_percent: u8) {
if let (Some(spotify), Some(device_id), Some(context)) = (
&self.spotify,
&self.client_config.device_id,
&mut self.current_playback_context,
) {
match spotify.volume(volume_percent, Some(device_id.to_string())) {
Ok(()) => {
context.device.volume_percent = volume_percent.into();
}
Err(e) => {
self.handle_error(e);
}
};
}
}
pub fn increase_volume(&mut self) {
if let Some(context) = self.current_playback_context.clone() {
let current_volume = context.device.volume_percent as u8;
let next_volume = min(current_volume + 10, 100);
if next_volume != current_volume {
self.change_volume(next_volume);
}
}
}
pub fn decrease_volume(&mut self) {
if let Some(context) = self.current_playback_context.clone() {
let current_volume = context.device.volume_percent as i8;
let next_volume = max(current_volume - 10, 0);
if next_volume != current_volume {
self.change_volume(next_volume as u8);
}
}
}
pub fn handle_error(&mut self, e: failure::Error) {
self.push_navigation_stack(RouteId::Error, ActiveBlock::Error);
self.api_error = e.to_string();
}
pub fn toggle_playback(&mut self) {
if let Some(current_playback_context) = &self.current_playback_context {
if current_playback_context.is_playing {
self.pause_playback();
} else {
// When no offset or uris are passed, spotify will resume current playback
self.start_playback(None, None, None);
}
}
}
pub fn next_track(&mut self) {
if let (Some(spotify), Some(device_id)) = (&self.spotify, &self.client_config.device_id) {
match spotify.next_track(Some(device_id.to_string())) {
Ok(()) => {
self.get_current_playback();
}
Err(e) => {
self.handle_error(e);
}
};
}
}
pub fn previous_track(&mut self) {
if let (Some(spotify), Some(device_id)) = (&self.spotify, &self.client_config.device_id) {
match spotify.previous_track(Some(device_id.to_string())) {
Ok(()) => {
self.get_current_playback();
}
Err(e) => {
self.handle_error(e);
}
};
}
}
pub fn start_recommendations_playback(&mut self, offset: Option<usize>) {
self.start_playback(
None,
Some(
self.recommended_tracks
.iter()
.map(|x| x.uri.clone())
.collect::<Vec<String>>(),
),
offset,
);
}
pub fn start_playback(
&mut self,
context_uri: Option<String>,
uris: Option<Vec<String>>,
offset: Option<usize>,
) {
let (uris, context_uri) = if context_uri.is_some() {
(None, context_uri)
} else if uris.is_some() {
(uris, None)
} else {
(None, None)
};
let offset = offset.and_then(|o| for_position(o as u32));
let result = match &self.client_config.device_id {
Some(device_id) => match &self.spotify {
Some(spotify) => spotify.start_playback(
Some(device_id.to_string()),
context_uri.clone(),
uris.clone(),
offset.clone(),
None,
),
None => Err(err_msg("Spotify is not ready to be used".to_string())),
},
None => Err(err_msg("No device_id selected")),
};
match result {
Ok(()) => {
self.get_current_playback();
self.song_progress_ms = 0;
self.playback_params = PlaybackParams {
context_uri,
uris,
offset,
}
}
Err(e) => {
self.handle_error(e);
}
}
}
pub fn get_playlist_tracks(&mut self, playlist_id: String) {
match &self.spotify {
Some(spotify) => {
if let Ok(playlist_tracks) = spotify.user_playlist_tracks(
"spotify",
&playlist_id,
None,
Some(self.large_search_limit),
Some(self.playlist_offset),
None,
) {
self.set_playlist_tracks_to_table(&playlist_tracks);
self.playlist_tracks = playlist_tracks.items;
if self.get_current_route().id != RouteId::TrackTable {
self.push_navigation_stack(RouteId::TrackTable, ActiveBlock::TrackTable);
};
};
}
None => {}
}
}
// The navigation_stack actually only controls the large block to the right of `library` and
// `playlists`
pub fn push_navigation_stack(
&mut self,
next_route_id: RouteId,
next_active_block: ActiveBlock,
) {
self.navigation_stack.push(Route {
id: next_route_id,
active_block: next_active_block,
hovered_block: next_active_block,
});
}
pub fn pop_navigation_stack(&mut self) -> Option<Route> {
if self.navigation_stack.len() == 1 {
None
} else {
self.navigation_stack.pop()
}
}
pub fn get_current_route(&self) -> &Route {
match self.navigation_stack.last() {
Some(route) => route,
None => &DEFAULT_ROUTE, // if for some reason there is no route return the default
}
}
fn get_current_route_mut(&mut self) -> &mut Route {
self.navigation_stack.last_mut().unwrap()
}
pub fn set_current_route_state(
&mut self,
active_block: Option<ActiveBlock>,
hovered_block: Option<ActiveBlock>,
) {
let mut current_route = self.get_current_route_mut();
if let Some(active_block) = active_block {
current_route.active_block = active_block;
}
if let Some(hovered_block) = hovered_block {
current_route.hovered_block = hovered_block;
}
}
pub fn copy_song_url(&mut self) {
let clipboard = match &mut self.clipboard_context {
Some(ctx) => ctx,
None => return,
};
if let Some(FullPlayingContext {
item: Some(FullTrack { id: Some(id), .. }),
..
}) = &self.current_playback_context
{
if let Err(e) = clipboard.set_contents(format!("https://open.spotify.com/track/{}", id))
{
self.handle_error(format_err!("failed to set clipboard content: {}", e));
}
}
}
fn set_saved_tracks_to_table(&mut self, saved_track_page: &Page<SavedTrack>) {
self.set_tracks_to_table(
saved_track_page
.items
.clone()
.into_iter()
.map(|item| item.track)
.collect::<Vec<FullTrack>>(),
);
}
fn set_playlist_tracks_to_table(&mut self, playlist_track_page: &Page<PlaylistTrack>) {
self.set_tracks_to_table(
playlist_track_page
.items
.clone()
.into_iter()
.map(|item| item.track)
.collect::<Vec<FullTrack>>(),
);
}
fn extract_recommended_tracks(
&self,
recommendations: &Recommendations,
) -> Option<Vec<FullTrack>> {
if let Some(spotify) = &self.spotify {
let tracks = recommendations
.clone()
.tracks
.into_iter()
.map(|item| item.uri)
.collect::<Vec<String>>();
if let Ok(result) =
spotify.tracks(tracks.iter().map(|x| &x[..]).collect::<Vec<&str>>(), None)
{
return Some(result.tracks);
}
}
None
}
fn get_fulltrack_from_id(&self, id: &str) -> Option<FullTrack> {
if let Some(spotify) = &self.spotify {
match spotify.track(id) {
Ok(track) => {
return Some(track);
}
Err(_e) => {
return None;
}
};
}
None
}
pub fn set_tracks_to_table(&mut self, tracks: Vec<FullTrack>) {
self.track_table.tracks = tracks.clone();
self.current_user_saved_tracks_contains(
tracks
.into_iter()
.filter_map(|item| item.id)
.collect::<Vec<String>>(),
);
}
pub fn get_current_user_saved_tracks(&mut self, offset: Option<u32>) {
if let Some(spotify) = &self.spotify {
match spotify.current_user_saved_tracks(self.large_search_limit, offset) {
Ok(saved_tracks) => {
self.set_saved_tracks_to_table(&saved_tracks);
self.library.saved_tracks.add_pages(saved_tracks);
self.track_table.context = Some(TrackTableContext::SavedTracks);
}
Err(e) => {
self.handle_error(e);
}
}
}
}
pub fn get_current_user_saved_tracks_next(&mut self) {
// Before fetching the next tracks, check if we have already fetched them
match self
.library
.saved_tracks
.get_results(Some(self.library.saved_tracks.index + 1))
.cloned()
{
Some(saved_tracks) => {
self.set_saved_tracks_to_table(&saved_tracks);
self.library.saved_tracks.index += 1
}
None => {
if let Some(saved_tracks) = &self.library.saved_tracks.get_results(None) {
let offset = Some(saved_tracks.offset + saved_tracks.limit);
self.get_current_user_saved_tracks(offset);
}
}
}
}
pub fn get_current_user_saved_tracks_previous(&mut self) {
if self.library.saved_tracks.index > 0 {
self.library.saved_tracks.index -= 1;
}
if let Some(saved_tracks) = &self.library.saved_tracks.get_results(None).cloned() {
self.set_saved_tracks_to_table(&saved_tracks);
}
}
pub fn get_album_tracks(&mut self, album: SimplifiedAlbum) {
if let Some(album_id) = &album.id {
if let Some(spotify) = &self.spotify {
match spotify.album_track(&album_id.clone(), self.large_search_limit, 0) {
Ok(tracks) => {
self.selected_album = Some(SelectedAlbum {
album,
tracks: tracks.clone(),
selected_index: 0,
});
self.current_user_saved_tracks_contains(
tracks
.items
.into_iter()
.filter_map(|item| item.id)
.collect::<Vec<String>>(),
);
self.album_table_context = AlbumTableContext::Simplified;
self.push_navigation_stack(RouteId::AlbumTracks, ActiveBlock::AlbumTracks);
}
Err(e) => {
self.handle_error(e);
}
}
}
}
}
pub fn toggle_save_track(&mut self, track_id: String) {
if let Some(spotify) = &self.spotify {
match spotify.current_user_saved_tracks_contains(&[track_id.clone()]) {
Ok(saved) => {
if saved.first() == Some(&true) {
match spotify.current_user_saved_tracks_delete(&[track_id.clone()]) {
Ok(()) => {
self.liked_song_ids_set.remove(&track_id);
}
Err(e) => {
self.handle_error(e);
}
}
} else {
match spotify.current_user_saved_tracks_add(&[track_id.clone()]) {
Ok(()) => {
// TODO: This should ideally use the same logic as `self.current_user_saved_tracks_contains`
self.liked_song_ids_set.insert(track_id);
}
Err(e) => {
self.handle_error(e);
}
}
}
}
Err(e) => {
self.handle_error(e);
}
}
};
}
pub fn shuffle(&mut self) {
if let (Some(spotify), Some(context)) = (&self.spotify, &mut self.current_playback_context)
{
match spotify.shuffle(!context.shuffle_state, self.client_config.device_id.clone()) {
Ok(()) => {
// Update the UI eagerly (otherwise the UI will wait until the next 5 second interval
// due to polling playback context)
context.shuffle_state = !context.shuffle_state;
}
Err(e) => {
self.handle_error(e);
}
}
};
}
pub fn repeat(&mut self) {
if let (Some(spotify), Some(context)) = (&self.spotify, &mut self.current_playback_context)
{
let next_repeat_state = match context.repeat_state {
RepeatState::Off => RepeatState::Context,
RepeatState::Context => RepeatState::Track,
RepeatState::Track => RepeatState::Off,
};
match spotify.repeat(next_repeat_state, self.client_config.device_id.clone()) {
Ok(()) => {
// Update the UI eagerly (otherwise the UI will wait until the next 5 second interval
// due to polling playback context)
context.repeat_state = next_repeat_state;
}
Err(e) => {
self.handle_error(e);
}
}
}
}
pub fn get_artist(&mut self, artist_id: &str, artist_name: &str) {
if let (Some(spotify), Some(user)) = (&self.spotify, &self.user.to_owned()) {
let user_country =
Country::from_str(&user.country.to_owned().unwrap_or_else(|| "".to_string()));
let albums = spotify.artist_albums(
artist_id,
None,