-
Notifications
You must be signed in to change notification settings - Fork 636
/
spirc.rs
1566 lines (1391 loc) · 56.5 KB
/
spirc.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
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 std::{
convert::TryFrom,
future::Future,
pin::Pin,
sync::atomic::{AtomicUsize, Ordering},
time::{SystemTime, UNIX_EPOCH},
};
use futures_util::{stream::FusedStream, FutureExt, StreamExt};
use protobuf::{self, Message};
use rand::prelude::SliceRandom;
use thiserror::Error;
use tokio::sync::mpsc;
use tokio_stream::wrappers::UnboundedReceiverStream;
use crate::{
config::ConnectConfig,
context::PageContext,
core::{
authentication::Credentials, mercury::MercurySender, session::UserAttributes,
util::SeqGenerator, version, Error, Session, SpotifyId,
},
playback::{
mixer::Mixer,
player::{Player, PlayerEvent, PlayerEventChannel},
},
protocol::{
self,
explicit_content_pubsub::UserAttributesUpdate,
spirc::{DeviceState, Frame, MessageType, PlayStatus, State, TrackRef},
user_attributes::UserAttributesMutation,
},
};
#[derive(Debug, Error)]
pub enum SpircError {
#[error("response payload empty")]
NoData,
#[error("playback of local files is not supported")]
UnsupportedLocalPlayBack,
#[error("message addressed at another ident: {0}")]
Ident(String),
#[error("message pushed for another URI")]
InvalidUri(String),
}
impl From<SpircError> for Error {
fn from(err: SpircError) -> Self {
use SpircError::*;
match err {
NoData | UnsupportedLocalPlayBack => Error::unavailable(err),
Ident(_) | InvalidUri(_) => Error::aborted(err),
}
}
}
#[derive(Debug)]
enum SpircPlayStatus {
Stopped,
LoadingPlay {
position_ms: u32,
},
LoadingPause {
position_ms: u32,
},
Playing {
nominal_start_time: i64,
preloading_of_next_track_triggered: bool,
},
Paused {
position_ms: u32,
preloading_of_next_track_triggered: bool,
},
}
type BoxedStream<T> = Pin<Box<dyn FusedStream<Item = T> + Send>>;
struct SpircTask {
player: Player,
mixer: Box<dyn Mixer>,
sequence: SeqGenerator<u32>,
ident: String,
device: DeviceState,
state: State,
play_request_id: Option<u64>,
play_status: SpircPlayStatus,
remote_update: BoxedStream<Result<(String, Frame), Error>>,
connection_id_update: BoxedStream<Result<String, Error>>,
user_attributes_update: BoxedStream<Result<UserAttributesUpdate, Error>>,
user_attributes_mutation: BoxedStream<Result<UserAttributesMutation, Error>>,
sender: MercurySender,
commands: Option<mpsc::UnboundedReceiver<SpircCommand>>,
player_events: Option<PlayerEventChannel>,
shutdown: bool,
session: Session,
resolve_context: Option<String>,
autoplay_context: bool,
context: Option<PageContext>,
spirc_id: usize,
}
static SPIRC_COUNTER: AtomicUsize = AtomicUsize::new(0);
#[derive(Debug)]
pub enum SpircCommand {
Play,
PlayPause,
Pause,
Prev,
Next,
VolumeUp,
VolumeDown,
Shutdown,
Shuffle(bool),
Repeat(bool),
Disconnect,
SetPosition(u32),
SetVolume(u16),
Activate,
Load(SpircLoadCommand),
}
#[derive(Debug)]
pub struct SpircLoadCommand {
pub context_uri: String,
/// Whether the given tracks should immediately start playing, or just be initially loaded.
pub start_playing: bool,
pub shuffle: bool,
pub repeat: bool,
pub playing_track_index: u32,
pub tracks: Vec<TrackRef>,
}
impl From<SpircLoadCommand> for State {
fn from(command: SpircLoadCommand) -> Self {
let mut state = State::new();
state.set_context_uri(command.context_uri);
state.set_status(if command.start_playing {
PlayStatus::kPlayStatusPlay
} else {
PlayStatus::kPlayStatusStop
});
state.set_shuffle(command.shuffle);
state.set_repeat(command.repeat);
state.set_playing_track_index(command.playing_track_index);
state.track = command.tracks;
state
}
}
const CONTEXT_TRACKS_HISTORY: usize = 10;
const CONTEXT_FETCH_THRESHOLD: u32 = 5;
const VOLUME_STEPS: i64 = 64;
const VOLUME_STEP_SIZE: u16 = 1024; // (u16::MAX + 1) / VOLUME_STEPS
pub struct Spirc {
commands: mpsc::UnboundedSender<SpircCommand>,
}
fn initial_state() -> State {
let mut frame = protocol::spirc::State::new();
frame.set_repeat(false);
frame.set_shuffle(false);
frame.set_status(PlayStatus::kPlayStatusStop);
frame.set_position_ms(0);
frame.set_position_measured_at(0);
frame
}
fn int_capability(typ: protocol::spirc::CapabilityType, val: i64) -> protocol::spirc::Capability {
let mut cap = protocol::spirc::Capability::new();
cap.set_typ(typ);
cap.intValue.push(val);
cap
}
fn initial_device_state(config: ConnectConfig) -> DeviceState {
let mut msg = DeviceState::new();
msg.set_sw_version(version::SEMVER.to_string());
msg.set_is_active(false);
msg.set_can_play(true);
msg.set_volume(0);
msg.set_name(config.name);
msg.capabilities.push(int_capability(
protocol::spirc::CapabilityType::kCanBePlayer,
1,
));
msg.capabilities.push(int_capability(
protocol::spirc::CapabilityType::kDeviceType,
config.device_type as i64,
));
msg.capabilities.push(int_capability(
protocol::spirc::CapabilityType::kGaiaEqConnectId,
1,
));
// TODO: implement logout
msg.capabilities.push(int_capability(
protocol::spirc::CapabilityType::kSupportsLogout,
0,
));
msg.capabilities.push(int_capability(
protocol::spirc::CapabilityType::kIsObservable,
1,
));
msg.capabilities.push(int_capability(
protocol::spirc::CapabilityType::kVolumeSteps,
if config.has_volume_ctrl {
VOLUME_STEPS
} else {
0
},
));
msg.capabilities.push(int_capability(
protocol::spirc::CapabilityType::kSupportsPlaylistV2,
1,
));
msg.capabilities.push(int_capability(
protocol::spirc::CapabilityType::kSupportsExternalEpisodes,
1,
));
// TODO: how would such a rename command be triggered? Handle it.
msg.capabilities.push(int_capability(
protocol::spirc::CapabilityType::kSupportsRename,
1,
));
msg.capabilities.push(int_capability(
protocol::spirc::CapabilityType::kCommandAcks,
0,
));
// TODO: does this mean local files or the local network?
// LAN may be an interesting privacy toggle.
msg.capabilities.push(int_capability(
protocol::spirc::CapabilityType::kRestrictToLocal,
0,
));
// TODO: what does this hide, or who do we hide from?
// May be an interesting privacy toggle.
msg.capabilities
.push(int_capability(protocol::spirc::CapabilityType::kHidden, 0));
let mut supported_types = protocol::spirc::Capability::new();
supported_types.set_typ(protocol::spirc::CapabilityType::kSupportedTypes);
supported_types
.stringValue
.push("audio/episode".to_string());
supported_types
.stringValue
.push("audio/episode+track".to_string());
supported_types.stringValue.push("audio/track".to_string());
// other known types:
// - "audio/ad"
// - "audio/interruption"
// - "audio/local"
// - "video/ad"
// - "video/episode"
msg.capabilities.push(supported_types);
msg
}
fn url_encode(bytes: impl AsRef<[u8]>) -> String {
form_urlencoded::byte_serialize(bytes.as_ref()).collect()
}
impl Spirc {
pub async fn new(
config: ConnectConfig,
session: Session,
credentials: Credentials,
player: Player,
mixer: Box<dyn Mixer>,
) -> Result<(Spirc, impl Future<Output = ()>), Error> {
let spirc_id = SPIRC_COUNTER.fetch_add(1, Ordering::AcqRel);
debug!("new Spirc[{}]", spirc_id);
let ident = session.device_id().to_owned();
let remote_update = Box::pin(
session
.mercury()
.listen_for("hm://remote/user/")
.map(UnboundedReceiverStream::new)
.flatten_stream()
.map(|response| -> Result<(String, Frame), Error> {
let uri_split: Vec<&str> = response.uri.split('/').collect();
let username = match uri_split.get(4) {
Some(s) => s.to_string(),
None => String::new(),
};
let data = response.payload.first().ok_or(SpircError::NoData)?;
Ok((username, Frame::parse_from_bytes(data)?))
}),
);
let connection_id_update = Box::pin(
session
.mercury()
.listen_for("hm://pusher/v1/connections/")
.map(UnboundedReceiverStream::new)
.flatten_stream()
.map(|response| -> Result<String, Error> {
let connection_id = response
.uri
.strip_prefix("hm://pusher/v1/connections/")
.ok_or_else(|| SpircError::InvalidUri(response.uri.clone()))?;
Ok(connection_id.to_owned())
}),
);
let user_attributes_update = Box::pin(
session
.mercury()
.listen_for("spotify:user:attributes:update")
.map(UnboundedReceiverStream::new)
.flatten_stream()
.map(|response| -> Result<UserAttributesUpdate, Error> {
let data = response.payload.first().ok_or(SpircError::NoData)?;
Ok(UserAttributesUpdate::parse_from_bytes(data)?)
}),
);
let user_attributes_mutation = Box::pin(
session
.mercury()
.listen_for("spotify:user:attributes:mutated")
.map(UnboundedReceiverStream::new)
.flatten_stream()
.map(|response| -> Result<UserAttributesMutation, Error> {
let data = response.payload.first().ok_or(SpircError::NoData)?;
Ok(UserAttributesMutation::parse_from_bytes(data)?)
}),
);
// Connect *after* all message listeners are registered
session.connect(credentials, true).await?;
let canonical_username = &session.username();
debug!("canonical_username: {}", canonical_username);
let sender_uri = format!("hm://remote/user/{}/", url_encode(canonical_username));
let sender = session.mercury().sender(sender_uri);
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let initial_volume = config.initial_volume;
let device = initial_device_state(config);
let player_events = player.get_player_event_channel();
let mut task = SpircTask {
player,
mixer,
sequence: SeqGenerator::new(1),
ident,
device,
state: initial_state(),
play_request_id: None,
play_status: SpircPlayStatus::Stopped,
remote_update,
connection_id_update,
user_attributes_update,
user_attributes_mutation,
sender,
commands: Some(cmd_rx),
player_events: Some(player_events),
shutdown: false,
session,
resolve_context: None,
autoplay_context: false,
context: None,
spirc_id,
};
if let Some(volume) = initial_volume {
task.set_volume(volume);
} else {
let current_volume = task.mixer.volume();
task.set_volume(current_volume);
}
let spirc = Spirc { commands: cmd_tx };
task.hello()?;
Ok((spirc, task.run()))
}
pub fn play(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Play)?)
}
pub fn play_pause(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::PlayPause)?)
}
pub fn pause(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Pause)?)
}
pub fn prev(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Prev)?)
}
pub fn next(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Next)?)
}
pub fn volume_up(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::VolumeUp)?)
}
pub fn volume_down(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::VolumeDown)?)
}
pub fn shutdown(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Shutdown)?)
}
pub fn shuffle(&self, shuffle: bool) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Shuffle(shuffle))?)
}
pub fn repeat(&self, repeat: bool) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Repeat(repeat))?)
}
pub fn set_volume(&self, volume: u16) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::SetVolume(volume))?)
}
pub fn set_position_ms(&self, position_ms: u32) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::SetPosition(position_ms))?)
}
pub fn disconnect(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Disconnect)?)
}
pub fn activate(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Activate)?)
}
pub fn load(&self, command: SpircLoadCommand) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Load(command))?)
}
}
impl SpircTask {
async fn run(mut self) {
while !self.session.is_invalid() && !self.shutdown {
let commands = self.commands.as_mut();
let player_events = self.player_events.as_mut();
tokio::select! {
remote_update = self.remote_update.next() => match remote_update {
Some(result) => match result {
Ok((username, frame)) => {
if username != self.session.username() {
warn!("could not dispatch remote update: frame was intended for {}", username);
} else if let Err(e) = self.handle_remote_update(frame) {
error!("could not dispatch remote update: {}", e);
}
},
Err(e) => error!("could not parse remote update: {}", e),
}
None => {
error!("remote update selected, but none received");
break;
}
},
user_attributes_update = self.user_attributes_update.next() => match user_attributes_update {
Some(result) => match result {
Ok(attributes) => self.handle_user_attributes_update(attributes),
Err(e) => error!("could not parse user attributes update: {}", e),
}
None => {
error!("user attributes update selected, but none received");
break;
}
},
user_attributes_mutation = self.user_attributes_mutation.next() => match user_attributes_mutation {
Some(result) => match result {
Ok(attributes) => self.handle_user_attributes_mutation(attributes),
Err(e) => error!("could not parse user attributes mutation: {}", e),
}
None => {
error!("user attributes mutation selected, but none received");
break;
}
},
connection_id_update = self.connection_id_update.next() => match connection_id_update {
Some(result) => match result {
Ok(connection_id) => self.handle_connection_id_update(connection_id),
Err(e) => error!("could not parse connection ID update: {}", e),
}
None => {
error!("connection ID update selected, but none received");
break;
}
},
cmd = async { commands?.recv().await }, if commands.is_some() => if let Some(cmd) = cmd {
if let Err(e) = self.handle_command(cmd) {
debug!("could not dispatch command: {}", e);
}
},
event = async { player_events?.recv().await }, if player_events.is_some() => if let Some(event) = event {
if let Err(e) = self.handle_player_event(event) {
error!("could not dispatch player event: {}", e);
}
},
result = self.sender.flush(), if !self.sender.is_flushed() => if result.is_err() {
error!("Cannot flush spirc event sender.");
break;
},
context_uri = async { self.resolve_context.take() }, if self.resolve_context.is_some() => {
let context_uri = context_uri.unwrap(); // guaranteed above
if context_uri.contains("spotify:show:") || context_uri.contains("spotify:episode:") {
continue; // not supported by apollo stations
}
let context = if context_uri.starts_with("hm://") {
self.session.spclient().get_next_page(&context_uri).await
} else {
// only send previous tracks that were before the current playback position
let current_position = self.state.playing_track_index() as usize;
let previous_tracks = self.state.track[..current_position].iter().filter_map(|t| SpotifyId::try_from(t).ok()).collect();
let scope = if self.autoplay_context {
"stations" // this returns a `StationContext` but we deserialize it into a `PageContext`
} else {
"tracks" // this returns a `PageContext`
};
self.session.spclient().get_apollo_station(scope, &context_uri, None, previous_tracks, self.autoplay_context).await
};
match context {
Ok(value) => {
self.context = match serde_json::from_slice::<PageContext>(&value) {
Ok(context) => {
info!(
"Resolved {:?} tracks from <{:?}>",
context.tracks.len(),
self.state.context_uri(),
);
Some(context)
}
Err(e) => {
error!("Unable to parse JSONContext {:?}", e);
None
}
};
},
Err(err) => {
error!("ContextError: {:?}", err)
}
}
},
else => break
}
}
if self.sender.flush().await.is_err() {
warn!("Cannot flush spirc event sender when done.");
}
}
fn now_ms(&mut self) -> i64 {
let dur = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(dur) => dur,
Err(err) => err.duration(),
};
dur.as_millis() as i64 + 1000 * self.session.time_delta()
}
fn update_state_position(&mut self, position_ms: u32) {
let now = self.now_ms();
self.state.set_position_measured_at(now as u64);
self.state.set_position_ms(position_ms);
}
fn handle_command(&mut self, cmd: SpircCommand) -> Result<(), Error> {
if matches!(cmd, SpircCommand::Shutdown) {
trace!("Received SpircCommand::Shutdown");
CommandSender::new(self, MessageType::kMessageTypeGoodbye).send()?;
self.handle_disconnect();
self.shutdown = true;
if let Some(rx) = self.commands.as_mut() {
rx.close()
}
Ok(())
} else if self.device.is_active() {
trace!("Received SpircCommand::{:?}", cmd);
match cmd {
SpircCommand::Play => {
self.handle_play();
self.notify(None)
}
SpircCommand::PlayPause => {
self.handle_play_pause();
self.notify(None)
}
SpircCommand::Pause => {
self.handle_pause();
self.notify(None)
}
SpircCommand::Prev => {
self.handle_prev();
self.notify(None)
}
SpircCommand::Next => {
self.handle_next();
self.notify(None)
}
SpircCommand::VolumeUp => {
self.handle_volume_up();
self.notify(None)
}
SpircCommand::VolumeDown => {
self.handle_volume_down();
self.notify(None)
}
SpircCommand::Disconnect => {
self.handle_disconnect();
self.notify(None)
}
SpircCommand::Shuffle(shuffle) => {
self.state.set_shuffle(shuffle);
self.notify(None)
}
SpircCommand::Repeat(repeat) => {
self.state.set_repeat(repeat);
self.notify(None)
}
SpircCommand::SetPosition(position) => {
self.handle_seek(position);
self.notify(None)
}
SpircCommand::SetVolume(volume) => {
self.set_volume(volume);
self.notify(None)
}
SpircCommand::Load(command) => {
self.handle_load(&command.into())?;
self.notify(None)
}
_ => Ok(()),
}
} else {
match cmd {
SpircCommand::Activate => {
trace!("Received SpircCommand::{:?}", cmd);
self.handle_activate();
self.notify(None)
}
_ => {
warn!("SpircCommand::{:?} will be ignored while Not Active", cmd);
Ok(())
}
}
}
}
fn handle_player_event(&mut self, event: PlayerEvent) -> Result<(), Error> {
// we only process events if the play_request_id matches. If it doesn't, it is
// an event that belongs to a previous track and only arrives now due to a race
// condition. In this case we have updated the state already and don't want to
// mess with it.
if let Some(play_request_id) = event.get_play_request_id() {
if Some(play_request_id) == self.play_request_id {
match event {
PlayerEvent::EndOfTrack { .. } => self.handle_end_of_track(),
PlayerEvent::Loading { .. } => {
match self.play_status {
SpircPlayStatus::LoadingPlay { position_ms } => {
self.update_state_position(position_ms);
self.state.set_status(PlayStatus::kPlayStatusPlay);
trace!("==> kPlayStatusPlay");
}
SpircPlayStatus::LoadingPause { position_ms } => {
self.update_state_position(position_ms);
self.state.set_status(PlayStatus::kPlayStatusPause);
trace!("==> kPlayStatusPause");
}
_ => {
self.state.set_status(PlayStatus::kPlayStatusLoading);
self.update_state_position(0);
trace!("==> kPlayStatusLoading");
}
}
self.notify(None)
}
PlayerEvent::Playing { position_ms, .. }
| PlayerEvent::PositionCorrection { position_ms, .. }
| PlayerEvent::Seeked { position_ms, .. } => {
trace!("==> kPlayStatusPlay");
let new_nominal_start_time = self.now_ms() - position_ms as i64;
match self.play_status {
SpircPlayStatus::Playing {
ref mut nominal_start_time,
..
} => {
if (*nominal_start_time - new_nominal_start_time).abs() > 100 {
*nominal_start_time = new_nominal_start_time;
self.update_state_position(position_ms);
self.notify(None)
} else {
Ok(())
}
}
SpircPlayStatus::LoadingPlay { .. }
| SpircPlayStatus::LoadingPause { .. } => {
self.state.set_status(PlayStatus::kPlayStatusPlay);
self.update_state_position(position_ms);
self.play_status = SpircPlayStatus::Playing {
nominal_start_time: new_nominal_start_time,
preloading_of_next_track_triggered: false,
};
self.notify(None)
}
_ => Ok(()),
}
}
PlayerEvent::Paused {
position_ms: new_position_ms,
..
} => {
trace!("==> kPlayStatusPause");
match self.play_status {
SpircPlayStatus::Paused { .. } | SpircPlayStatus::Playing { .. } => {
self.state.set_status(PlayStatus::kPlayStatusPause);
self.update_state_position(new_position_ms);
self.play_status = SpircPlayStatus::Paused {
position_ms: new_position_ms,
preloading_of_next_track_triggered: false,
};
self.notify(None)
}
SpircPlayStatus::LoadingPlay { .. }
| SpircPlayStatus::LoadingPause { .. } => {
self.state.set_status(PlayStatus::kPlayStatusPause);
self.update_state_position(new_position_ms);
self.play_status = SpircPlayStatus::Paused {
position_ms: new_position_ms,
preloading_of_next_track_triggered: false,
};
self.notify(None)
}
_ => Ok(()),
}
}
PlayerEvent::Stopped { .. } => {
trace!("==> kPlayStatusStop");
match self.play_status {
SpircPlayStatus::Stopped => Ok(()),
_ => {
self.state.set_status(PlayStatus::kPlayStatusStop);
self.play_status = SpircPlayStatus::Stopped;
self.notify(None)
}
}
}
PlayerEvent::TimeToPreloadNextTrack { .. } => {
self.handle_preload_next_track();
Ok(())
}
PlayerEvent::Unavailable { track_id, .. } => {
self.handle_unavailable(track_id);
Ok(())
}
_ => Ok(()),
}
} else {
Ok(())
}
} else {
Ok(())
}
}
fn handle_connection_id_update(&mut self, connection_id: String) {
trace!("Received connection ID update: {:?}", connection_id);
self.session.set_connection_id(&connection_id);
}
fn handle_user_attributes_update(&mut self, update: UserAttributesUpdate) {
trace!("Received attributes update: {:#?}", update);
let attributes: UserAttributes = update
.pairs
.iter()
.map(|pair| (pair.key().to_owned(), pair.value().to_owned()))
.collect();
self.session.set_user_attributes(attributes)
}
fn handle_user_attributes_mutation(&mut self, mutation: UserAttributesMutation) {
for attribute in mutation.fields.iter() {
let key = &attribute.name;
if key == "autoplay" && self.session.config().autoplay.is_some() {
trace!("Autoplay override active. Ignoring mutation.");
continue;
}
if let Some(old_value) = self.session.user_data().attributes.get(key) {
let new_value = match old_value.as_ref() {
"0" => "1",
"1" => "0",
_ => old_value,
};
self.session.set_user_attribute(key, new_value);
trace!(
"Received attribute mutation, {} was {} is now {}",
key,
old_value,
new_value
);
if key == "filter-explicit-content" && new_value == "1" {
self.player
.emit_filter_explicit_content_changed_event(matches!(new_value, "1"));
}
if key == "autoplay" && old_value != new_value {
self.player
.emit_auto_play_changed_event(matches!(new_value, "1"));
}
} else {
trace!(
"Received attribute mutation for {} but key was not found!",
key
);
}
}
}
fn handle_remote_update(&mut self, update: Frame) -> Result<(), Error> {
trace!("Received update frame: {:#?}", update);
// First see if this update was intended for us.
let device_id = &self.ident;
let ident = update.ident();
if ident == device_id
|| (!update.recipient.is_empty() && !update.recipient.contains(device_id))
{
return Err(SpircError::Ident(ident.to_string()).into());
}
let old_client_id = self.session.client_id();
for entry in update.device_state.metadata.iter() {
match entry.type_() {
"client_id" => self.session.set_client_id(entry.metadata()),
"brand_display_name" => self.session.set_client_brand_name(entry.metadata()),
"model_display_name" => self.session.set_client_model_name(entry.metadata()),
_ => (),
}
}
self.session.set_client_name(update.device_state.name());
let new_client_id = self.session.client_id();
if self.device.is_active() && new_client_id != old_client_id {
self.player.emit_session_client_changed_event(
new_client_id,
self.session.client_name(),
self.session.client_brand_name(),
self.session.client_model_name(),
);
}
match update.typ() {
MessageType::kMessageTypeHello => self.notify(Some(ident)),
MessageType::kMessageTypeLoad => {
self.handle_load(update.state.get_or_default())?;
self.notify(None)
}
MessageType::kMessageTypePlay => {
self.handle_play();
self.notify(None)
}
MessageType::kMessageTypePlayPause => {
self.handle_play_pause();
self.notify(None)
}
MessageType::kMessageTypePause => {
self.handle_pause();
self.notify(None)
}
MessageType::kMessageTypeNext => {
self.handle_next();
self.notify(None)
}
MessageType::kMessageTypePrev => {
self.handle_prev();
self.notify(None)
}
MessageType::kMessageTypeVolumeUp => {
self.handle_volume_up();
self.notify(None)
}
MessageType::kMessageTypeVolumeDown => {
self.handle_volume_down();
self.notify(None)
}
MessageType::kMessageTypeRepeat => {
let repeat = update.state.repeat();
self.state.set_repeat(repeat);
self.player.emit_repeat_changed_event(repeat);
self.notify(None)
}
MessageType::kMessageTypeShuffle => {
let shuffle = update.state.shuffle();
self.state.set_shuffle(shuffle);
if shuffle {
let current_index = self.state.playing_track_index();
let tracks = &mut self.state.track;
if !tracks.is_empty() {
tracks.swap(0, current_index as usize);
if let Some((_, rest)) = tracks.split_first_mut() {
let mut rng = rand::thread_rng();
rest.shuffle(&mut rng);
}
self.state.set_playing_track_index(0);
}
}
self.player.emit_shuffle_changed_event(shuffle);
self.notify(None)
}
MessageType::kMessageTypeSeek => {
self.handle_seek(update.position());
self.notify(None)
}
MessageType::kMessageTypeReplace => {
let context_uri = update.state.context_uri().to_owned();
// completely ignore local playback.
if context_uri.starts_with("spotify:local-files") {
self.notify(None)?;
return Err(SpircError::UnsupportedLocalPlayBack.into());
}
self.update_tracks(update.state.get_or_default());
if let SpircPlayStatus::Playing {
preloading_of_next_track_triggered,
..
}
| SpircPlayStatus::Paused {
preloading_of_next_track_triggered,
..
} = self.play_status
{
if preloading_of_next_track_triggered {
// Get the next track_id in the playlist
if let Some(track_id) = self.preview_next_track() {
self.player.preload(track_id);
}
}
}
self.notify(None)
}
MessageType::kMessageTypeVolume => {
self.set_volume(update.volume() as u16);
self.notify(None)
}
MessageType::kMessageTypeNotify => {
if self.device.is_active()
&& update.device_state.is_active()
&& self.device.became_active_at() <= update.device_state.became_active_at()
{
self.handle_disconnect();
}
self.notify(None)
}
_ => Ok(()),
}
}