-
Notifications
You must be signed in to change notification settings - Fork 823
Expand file tree
/
Copy pathspirc.rs
More file actions
1859 lines (1623 loc) · 69 KB
/
spirc.rs
File metadata and controls
1859 lines (1623 loc) · 69 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 crate::{
LoadContextOptions, LoadRequestOptions, PlayContext,
context_resolver::{ContextAction, ContextResolver, ResolveContext},
core::{
Error, Session, SpotifyUri,
authentication::Credentials,
dealer::{
manager::{BoxedStream, BoxedStreamResult, Reply, RequestReply},
protocol::{Command, FallbackWrapper, Message, Request},
},
session::UserAttributes,
spclient::TransferRequest,
},
model::{LoadRequest, PlayingTrack, SpircPlayStatus},
playback::{
mixer::Mixer,
player::{Player, PlayerEvent, PlayerEventChannel},
},
protocol::{
connect::{Cluster, ClusterUpdate, LogoutCommand, SetVolumeCommand},
context::Context,
explicit_content_pubsub::UserAttributesUpdate,
playlist4_external::PlaylistModificationInfo,
social_connect_v2::SessionUpdate,
transfer_state::TransferState,
user_attributes::UserAttributesMutation,
},
state::{
context::{ContextType, ResetContext},
provider::IsProvider,
{ConnectConfig, ConnectState},
},
};
use futures_util::StreamExt;
use librespot_protocol::context_page::ContextPage;
use protobuf::MessageField;
use std::{
future::Future,
sync::Arc,
sync::atomic::{AtomicUsize, Ordering},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use thiserror::Error;
use tokio::{sync::mpsc, time::sleep};
#[derive(Debug, Error)]
enum SpircError {
#[error("response payload empty")]
NoData,
#[error("{0} had no uri")]
NoUri(&'static str),
#[error("message pushed for another URI")]
InvalidUri(String),
#[error("failed to put connect state for new device")]
FailedDealerSetup,
#[error("unknown endpoint: {0:#?}")]
UnknownEndpoint(serde_json::Value),
}
impl From<SpircError> for Error {
fn from(err: SpircError) -> Self {
use SpircError::*;
match err {
NoData | NoUri(_) => Error::unavailable(err),
InvalidUri(_) | FailedDealerSetup => Error::aborted(err),
UnknownEndpoint(_) => Error::unimplemented(err),
}
}
}
struct SpircTask {
player: Arc<Player>,
mixer: Arc<dyn Mixer>,
/// the state management object
connect_state: ConnectState,
connect_established: bool,
play_request_id: Option<u64>,
play_status: SpircPlayStatus,
connection_id_update: BoxedStreamResult<String>,
connect_state_update: BoxedStreamResult<ClusterUpdate>,
connect_state_volume_update: BoxedStreamResult<SetVolumeCommand>,
connect_state_logout_request: BoxedStreamResult<LogoutCommand>,
playlist_update: BoxedStreamResult<PlaylistModificationInfo>,
session_update: BoxedStreamResult<FallbackWrapper<SessionUpdate>>,
connect_state_command: BoxedStream<RequestReply>,
user_attributes_update: BoxedStreamResult<UserAttributesUpdate>,
user_attributes_mutation: BoxedStreamResult<UserAttributesMutation>,
commands: Option<mpsc::UnboundedReceiver<SpircCommand>>,
player_events: Option<PlayerEventChannel>,
context_resolver: ContextResolver,
shutdown: bool,
session: Session,
/// is set when transferring, and used after resolving the contexts to finish the transfer
pub transfer_state: Option<TransferState>,
/// when set to true, it will update the volume after [VOLUME_UPDATE_DELAY],
/// when no other future resolves, otherwise resets the delay
update_volume: bool,
/// when set to true, it will update the volume after [UPDATE_STATE_DELAY],
/// when no other future resolves, otherwise resets the delay
update_state: bool,
spirc_id: usize,
}
static SPIRC_COUNTER: AtomicUsize = AtomicUsize::new(0);
#[derive(Debug)]
enum SpircCommand {
Play,
PlayPause,
Pause,
Prev,
Next,
VolumeUp,
VolumeDown,
Shutdown,
Shuffle(bool),
Repeat(bool),
RepeatTrack(bool),
Disconnect { pause: bool },
SetPosition(u32),
SeekOffset(i32),
SetVolume(u16),
Activate,
Transfer(Option<TransferRequest>),
Load(LoadRequest),
}
const CONTEXT_FETCH_THRESHOLD: usize = 2;
// delay to update volume after a certain amount of time, instead on each update request
const VOLUME_UPDATE_DELAY: Duration = Duration::from_millis(500);
// to reduce updates to remote, we group some request by waiting for a set amount of time
const UPDATE_STATE_DELAY: Duration = Duration::from_millis(200);
/// The spotify connect handle
#[derive(Clone)]
pub struct Spirc {
commands: mpsc::UnboundedSender<SpircCommand>,
}
impl Spirc {
/// Initializes a new spotify connect device
///
/// The returned tuple consists out of a handle to the [`Spirc`] that
/// can control the local connect device when active. And a [`Future`]
/// which represents the [`Spirc`] event loop that processes the whole
/// connect device logic.
pub async fn new(
config: ConnectConfig,
session: Session,
credentials: Credentials,
player: Arc<Player>,
mixer: Arc<dyn Mixer>,
) -> Result<(Spirc, impl Future<Output = ()>), Error> {
fn extract_connection_id(msg: Message) -> Result<String, Error> {
let connection_id = msg
.headers
.get("Spotify-Connection-Id")
.ok_or_else(|| SpircError::InvalidUri(msg.uri.clone()))?;
Ok(connection_id.to_owned())
}
let spirc_id = SPIRC_COUNTER.fetch_add(1, Ordering::AcqRel);
debug!("new Spirc[{spirc_id}]");
let connect_state = ConnectState::new(config, &session);
let connection_id_update = session
.dealer()
.listen_for("hm://pusher/v1/connections/", extract_connection_id)?;
let connect_state_update = session
.dealer()
.listen_for("hm://connect-state/v1/cluster", Message::from_raw)?;
let connect_state_volume_update = session
.dealer()
.listen_for("hm://connect-state/v1/connect/volume", Message::from_raw)?;
let connect_state_logout_request = session
.dealer()
.listen_for("hm://connect-state/v1/connect/logout", Message::from_raw)?;
let playlist_update = session
.dealer()
.listen_for("hm://playlist/v2/playlist/", Message::from_raw)?;
let session_update = session
.dealer()
.listen_for("social-connect/v2/session_update", Message::try_from_json)?;
let user_attributes_update = session
.dealer()
.listen_for("spotify:user:attributes:update", Message::from_raw)?;
// can be trigger by toggling autoplay in a desktop client
let user_attributes_mutation = session
.dealer()
.listen_for("spotify:user:attributes:mutated", Message::from_raw)?;
let connect_state_command = session
.dealer()
.handle_for("hm://connect-state/v1/player/command")?;
// pre-acquire client_token, preventing multiple request while running
let _ = session.spclient().client_token().await?;
// Connect *after* all message listeners are registered
session.connect(credentials, true).await?;
// pre-acquire access_token (we need to be authenticated to retrieve a token)
let _ = session.login5().auth_token().await?;
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let player_events = player.get_player_event_channel();
let mut task = SpircTask {
player,
mixer,
connect_state,
connect_established: false,
play_request_id: None,
play_status: SpircPlayStatus::Stopped,
connection_id_update,
connect_state_update,
connect_state_volume_update,
connect_state_logout_request,
playlist_update,
session_update,
connect_state_command,
user_attributes_update,
user_attributes_mutation,
commands: Some(cmd_rx),
player_events: Some(player_events),
context_resolver: ContextResolver::new(session.clone()),
shutdown: false,
session,
transfer_state: None,
update_volume: false,
update_state: false,
spirc_id,
};
let spirc = Spirc { commands: cmd_tx };
let initial_volume = task.connect_state.device_info().volume;
task.connect_state.set_volume(0);
match initial_volume.try_into() {
Ok(volume) => {
task.set_volume(volume);
// we don't want to update the volume initially,
// we just want to set the mixer to the correct volume
task.update_volume = false;
}
Err(why) => error!("failed to update initial volume: {why}"),
};
Ok((spirc, task.run()))
}
/// Safely shutdowns the spirc.
///
/// This pauses the playback, disconnects the connect device and
/// bring the future initially returned to an end.
pub fn shutdown(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Shutdown)?)
}
/// Resumes the playback
///
/// Does nothing if we are not the active device, or it isn't paused.
pub fn play(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Play)?)
}
/// Resumes or pauses the playback
///
/// Does nothing if we are not the active device.
pub fn play_pause(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::PlayPause)?)
}
/// Pauses the playback
///
/// Does nothing if we are not the active device, or if it isn't playing.
pub fn pause(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Pause)?)
}
/// Seeks to the beginning or skips to the previous track.
///
/// Seeks to the beginning when the current track position
/// is greater than 3 seconds.
///
/// Does nothing if we are not the active device.
pub fn prev(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Prev)?)
}
/// Skips to the next track.
///
/// Does nothing if we are not the active device.
pub fn next(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Next)?)
}
/// Increases the volume by configured steps of [ConnectConfig].
///
/// Does nothing if we are not the active device.
pub fn volume_up(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::VolumeUp)?)
}
/// Decreases the volume by configured steps of [ConnectConfig].
///
/// Does nothing if we are not the active device.
pub fn volume_down(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::VolumeDown)?)
}
/// Shuffles the playback according to the value.
///
/// If true shuffles/reshuffles the playback. Otherwise, does
/// nothing (if not shuffled) or unshuffles the playback while
/// resuming at the position of the current track.
///
/// Does nothing if we are not the active device.
pub fn shuffle(&self, shuffle: bool) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Shuffle(shuffle))?)
}
/// Repeats the playback context according to the value.
///
/// Does nothing if we are not the active device.
pub fn repeat(&self, repeat: bool) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Repeat(repeat))?)
}
/// Repeats the current track if true.
///
/// Does nothing if we are not the active device.
///
/// Skipping to the next track disables the repeating.
pub fn repeat_track(&self, repeat: bool) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::RepeatTrack(repeat))?)
}
/// Update the volume to the given value.
///
/// Does nothing if we are not the active device.
pub fn set_volume(&self, volume: u16) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::SetVolume(volume))?)
}
/// Updates the position to the given value.
///
/// Does nothing if we are not the active device.
///
/// If value is greater than the track duration,
/// the update is ignored.
pub fn set_position_ms(&self, position_ms: u32) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::SetPosition(position_ms))?)
}
/// Load a new context and replace the current.
///
/// Does nothing if we are not the active device.
///
/// Does not overwrite the queue.
pub fn load(&self, command: LoadRequest) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Load(command))?)
}
/// Seek to given offset.
///
/// Does nothing if we are not the active device.
pub fn seek_offset(&self, offset_ms: i32) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::SeekOffset(offset_ms))?)
}
/// Disconnects the current device and pauses the playback according the value.
///
/// Does nothing if we are not the active device.
pub fn disconnect(&self, pause: bool) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Disconnect { pause })?)
}
/// Acquires the control as active connect device.
///
/// Does not [Spirc::transfer] the playback. Does nothing if we are not the active device.
pub fn activate(&self) -> Result<(), Error> {
Ok(self.commands.send(SpircCommand::Activate)?)
}
/// Acquires the control as active connect device over the transfer flow.
///
/// Does nothing if we are not the active device.
pub fn transfer(&self, transfer_request: Option<TransferRequest>) -> Result<(), Error> {
Ok(self
.commands
.send(SpircCommand::Transfer(transfer_request))?)
}
}
impl SpircTask {
async fn run(mut self) {
// simplify unwrapping of received item or parsed result
macro_rules! unwrap {
( $next:expr, |$some:ident| $use_some:expr ) => {
match $next {
Some($some) => $use_some,
None => {
error!("{} selected, but none received", stringify!($next));
break;
}
}
};
( $next:expr, match |$ok:ident| $use_ok:expr ) => {
unwrap!($next, |$ok| match $ok {
Ok($ok) => $use_ok,
Err(why) => error!("could not parse {}: {}", stringify!($ok), why),
})
};
}
if let Err(why) = self.session.dealer().start().await {
error!("starting dealer failed: {why}");
return;
}
while !self.session.is_invalid() && !self.shutdown {
let commands = self.commands.as_mut();
let player_events = self.player_events.as_mut();
// when state and volume update have a higher priority than context resolving
// because of that the context resolving has to wait, so that the other tasks can finish
let allow_context_resolving = !self.update_state && !self.update_volume;
tokio::select! {
// startup of the dealer requires a connection_id, which is retrieved at the very beginning
connection_id_update = self.connection_id_update.next() => unwrap! {
connection_id_update,
match |connection_id| if let Err(why) = self.handle_connection_id_update(connection_id).await {
error!("failed handling connection id update: {why}");
break;
}
},
// main dealer update of any remote device updates
cluster_update = self.connect_state_update.next() => unwrap! {
cluster_update,
match |cluster_update| if let Err(e) = self.handle_cluster_update(cluster_update).await {
error!("could not dispatch connect state update: {e}");
}
},
// main dealer request handling (dealer expects an answer)
request = self.connect_state_command.next() => unwrap! {
request,
|request| if let Err(e) = self.handle_connect_state_request(request).await {
error!("couldn't handle connect state command: {e}");
}
},
// volume request handling is send separately (it's more like a fire forget)
volume_update = self.connect_state_volume_update.next() => unwrap! {
volume_update,
match |volume_update| match volume_update.volume.try_into() {
Ok(volume) => self.set_volume(volume),
Err(why) => error!("can't update volume, failed to parse i32 to u16: {why}")
}
},
logout_request = self.connect_state_logout_request.next() => unwrap! {
logout_request,
|logout_request| {
error!("received logout request, currently not supported: {logout_request:#?}");
// todo: call logout handling
}
},
playlist_update = self.playlist_update.next() => unwrap! {
playlist_update,
match |playlist_update| if let Err(why) = self.handle_playlist_modification(playlist_update) {
error!("failed to handle playlist modification: {why}")
}
},
user_attributes_update = self.user_attributes_update.next() => unwrap! {
user_attributes_update,
match |attributes| self.handle_user_attributes_update(attributes)
},
user_attributes_mutation = self.user_attributes_mutation.next() => unwrap! {
user_attributes_mutation,
match |attributes| self.handle_user_attributes_mutation(attributes)
},
session_update = self.session_update.next() => unwrap! {
session_update,
match |session_update| self.handle_session_update(session_update)
},
cmd = async { commands?.recv().await }, if commands.is_some() && self.connect_established => if let Some(cmd) = cmd {
if let Err(e) = self.handle_command(cmd).await {
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}");
}
},
_ = async { sleep(UPDATE_STATE_DELAY).await }, if self.update_state => {
self.update_state = false;
if let Err(why) = self.notify().await {
error!("state update: {why}")
}
},
_ = async { sleep(VOLUME_UPDATE_DELAY).await }, if self.update_volume => {
self.update_volume = false;
info!("delayed volume update for all devices: volume is now {}", self.connect_state.device_info().volume);
if let Err(why) = self.connect_state.notify_volume_changed(&self.session).await {
error!("error updating connect state for volume update: {why}")
}
// for some reason the web-player does need two separate updates, so that the
// position of the current track is retained, other clients also send a state
// update before they send the volume update
if let Err(why) = self.notify().await {
error!("error updating connect state for volume update: {why}")
}
},
// context resolver handling, the idea/reason behind it the following:
//
// when we request a context that has multiple pages (for example an artist)
// resolving all pages at once can take around ~1-30sec, when we resolve
// everything at once that would block our main loop for that time
//
// to circumvent this behavior, we request each context separately here and
// finish after we received our last item of a type
next_context = async {
self.context_resolver.get_next_context(|| {
// Sending local file URIs to this endpoint results in a Bad Request status.
// It's likely appropriate to filter them out anyway; Spotify's backend
// has no knowledge about these tracks and so can't do anything with them.
self.connect_state.recent_track_uris()
.into_iter()
.filter(|t| !t.starts_with("spotify:local"))
.collect::<Vec<_>>()
}).await
}, if allow_context_resolving && self.context_resolver.has_next() => {
let update_state = self.handle_next_context(next_context);
if update_state {
if let Err(why) = self.notify().await {
error!("update after context resolving failed: {why}")
}
}
},
else => break
}
}
if !self.shutdown && self.connect_state.is_active() {
warn!("unexpected shutdown");
if let Err(why) = self.handle_disconnect().await {
error!("error during disconnecting: {why}")
}
}
// this should clear the active session id, leaving an empty state
if let Err(why) = self.session.spclient().delete_connect_state_request().await {
error!("error during connect state deletion: {why}")
};
self.session.dealer().close().await;
}
fn handle_next_context(&mut self, next_context: Result<Context, Error>) -> bool {
let next_context = match next_context {
Err(why) => {
self.context_resolver.mark_next_unavailable();
self.context_resolver.remove_used_and_invalid();
error!("{why}");
return false;
}
Ok(ctx) => ctx,
};
debug!("handling next context {:?}", next_context.uri);
match self
.context_resolver
.apply_next_context(&mut self.connect_state, next_context)
{
Ok(remaining) => {
if let Some(remaining) = remaining {
self.context_resolver.add_list(remaining)
}
}
Err(why) => {
error!("{why}")
}
}
let update_state = if self
.context_resolver
.try_finish(&mut self.connect_state, &mut self.transfer_state)
{
self.add_autoplay_resolving_when_required();
true
} else {
false
};
self.context_resolver.remove_used_and_invalid();
update_state
}
// todo: is the time_delta still necessary?
fn now_ms(&self) -> i64 {
let dur = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_else(|err| err.duration());
dur.as_millis() as i64 + 1000 * self.session.time_delta()
}
async fn handle_command(&mut self, cmd: SpircCommand) -> Result<(), Error> {
trace!("Received SpircCommand::{cmd:?}");
match cmd {
SpircCommand::Shutdown => {
trace!("Received SpircCommand::Shutdown");
self.handle_pause();
self.handle_disconnect().await?;
self.shutdown = true;
if let Some(rx) = self.commands.as_mut() {
rx.close()
}
}
SpircCommand::Transfer(request) if !self.connect_state.is_active() => {
let device_id = self.session.device_id();
self.session
.spclient()
.transfer(device_id, device_id, request.as_ref())
.await?;
return Ok(());
}
SpircCommand::Activate if !self.connect_state.is_active() => {
trace!("Received SpircCommand::{cmd:?}");
self.handle_activate();
return self.notify().await;
}
SpircCommand::Transfer(..) | SpircCommand::Activate => {
warn!("SpircCommand::{cmd:?} will be ignored while already active")
}
_ if !self.connect_state.is_active() => {
warn!("SpircCommand::{cmd:?} will be ignored while Not Active")
}
SpircCommand::Disconnect { pause } => {
if pause {
self.handle_pause()
}
return self.handle_disconnect().await;
}
SpircCommand::Play => self.handle_play(),
SpircCommand::PlayPause => self.handle_play_pause(),
SpircCommand::Pause => self.handle_pause(),
SpircCommand::Prev => self.handle_prev()?,
SpircCommand::Next => self.handle_next(None)?,
SpircCommand::VolumeUp => self.handle_volume_up(),
SpircCommand::VolumeDown => self.handle_volume_down(),
SpircCommand::Shuffle(shuffle) => self.handle_shuffle(shuffle)?,
SpircCommand::Repeat(repeat) => self.handle_repeat_context(repeat)?,
SpircCommand::RepeatTrack(repeat) => self.handle_repeat_track(repeat),
SpircCommand::SetPosition(position) => self.handle_seek(position),
SpircCommand::SeekOffset(offset) => self.handle_seek_offset(offset),
SpircCommand::SetVolume(volume) => self.set_volume(volume),
SpircCommand::Load(command) => self.handle_load(command, None, None).await?,
};
self.notify().await
}
fn handle_player_event(&mut self, event: PlayerEvent) -> Result<(), Error> {
if let PlayerEvent::TrackChanged { audio_item } = event {
self.connect_state.update_duration(audio_item.duration_ms);
self.update_state = true;
return Ok(());
}
// update play_request_id
if let PlayerEvent::PlayRequestIdChanged { play_request_id } = event {
self.play_request_id = Some(play_request_id);
return Ok(());
}
let is_current_track = matches! {
(event.get_play_request_id(), self.play_request_id),
(Some(event_id), Some(current_id)) if event_id == current_id
};
// 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 !is_current_track {
return Ok(());
}
match event {
PlayerEvent::EndOfTrack { .. } => {
let next_track = self
.connect_state
.repeat_track()
.then(|| self.connect_state.current_track(|t| t.uri.clone()));
self.handle_next(next_track)?
}
PlayerEvent::Loading { .. } => match self.play_status {
SpircPlayStatus::LoadingPlay { position_ms } => {
self.connect_state
.update_position(position_ms, self.now_ms());
trace!("==> LoadingPlay");
}
SpircPlayStatus::LoadingPause { position_ms } => {
self.connect_state
.update_position(position_ms, self.now_ms());
trace!("==> LoadingPause");
}
_ => {
self.connect_state.update_position(0, self.now_ms());
trace!("==> Loading");
}
},
PlayerEvent::Seeked { position_ms, .. } => {
trace!("==> Seeked");
self.connect_state
.update_position(position_ms, self.now_ms())
}
PlayerEvent::Playing { position_ms, .. }
| PlayerEvent::PositionCorrection { position_ms, .. } => {
trace!("==> Playing");
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.connect_state
.update_position(position_ms, self.now_ms());
} else {
return Ok(());
}
}
SpircPlayStatus::LoadingPlay { .. } | SpircPlayStatus::LoadingPause { .. } => {
self.connect_state
.update_position(position_ms, self.now_ms());
self.play_status = SpircPlayStatus::Playing {
nominal_start_time: new_nominal_start_time,
preloading_of_next_track_triggered: false,
};
}
_ => return Ok(()),
}
}
PlayerEvent::Paused {
position_ms: new_position_ms,
..
} => {
trace!("==> Paused");
match self.play_status {
SpircPlayStatus::Paused { .. } | SpircPlayStatus::Playing { .. } => {
self.connect_state
.update_position(new_position_ms, self.now_ms());
self.play_status = SpircPlayStatus::Paused {
position_ms: new_position_ms,
preloading_of_next_track_triggered: false,
};
}
SpircPlayStatus::LoadingPlay { .. } | SpircPlayStatus::LoadingPause { .. } => {
self.connect_state
.update_position(new_position_ms, self.now_ms());
self.play_status = SpircPlayStatus::Paused {
position_ms: new_position_ms,
preloading_of_next_track_triggered: false,
};
}
_ => return Ok(()),
}
}
PlayerEvent::Stopped { .. } => {
trace!("==> Stopped");
match self.play_status {
SpircPlayStatus::Stopped => return Ok(()),
_ => self.play_status = SpircPlayStatus::Stopped,
}
}
PlayerEvent::TimeToPreloadNextTrack { .. } => {
self.handle_preload_next_track();
return Ok(());
}
PlayerEvent::Unavailable { track_id, .. } => {
self.handle_unavailable(&track_id)?;
if self.connect_state.current_track(|t| &t.uri) == &track_id.to_uri()? {
self.handle_next(None)?
}
}
_ => return Ok(()),
}
self.update_state = true;
Ok(())
}
async fn handle_connection_id_update(&mut self, connection_id: String) -> Result<(), Error> {
trace!("Received connection ID update: {connection_id:?}");
self.session.set_connection_id(&connection_id);
let cluster = match self
.connect_state
.notify_new_device_appeared(&self.session)
.await
{
Ok(res) => Cluster::parse_from_bytes(&res).ok(),
Err(why) => {
error!("{why:?}");
None
}
}
.ok_or(SpircError::FailedDealerSetup)?;
debug!(
"successfully put connect state for {} with connection-id {connection_id}",
self.session.device_id()
);
self.connect_established = true;
let same_session = cluster.player_state.session_id == self.session.session_id()
|| cluster.player_state.session_id.is_empty();
if !cluster.active_device_id.is_empty() || !same_session {
info!(
"active device is <{}> with session <{}>",
cluster.active_device_id, cluster.player_state.session_id
);
return Ok(());
} else if cluster.transfer_data.is_empty() {
debug!("got empty transfer state, do nothing");
return Ok(());
} else {
info!(
"trying to take over control automatically, session_id: {}",
cluster.player_state.session_id
)
}
use protobuf::Message;
match TransferState::parse_from_bytes(&cluster.transfer_data) {
Ok(transfer_state) => self.handle_transfer(transfer_state)?,
Err(why) => error!("failed to take over control: {why}"),
}
Ok(())
}
fn handle_user_attributes_update(&mut self, update: UserAttributesUpdate) {
trace!("Received attributes update: {update:#?}");
let attributes: UserAttributes = update
.pairs
.iter()
.map(|(key, value)| (key.to_owned(), 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, {key} was {old_value} is now {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"));
self.add_autoplay_resolving_when_required()
}
} else {
trace!("Received attribute mutation for {key} but key was not found!");
}
}
}
async fn handle_cluster_update(
&mut self,
mut cluster_update: ClusterUpdate,
) -> Result<(), Error> {
let reason = cluster_update.update_reason.enum_value();
let device_ids = cluster_update.devices_that_changed.join(", ");
debug!(
"cluster update: {reason:?} from {device_ids}, active device: {}",
cluster_update.cluster.active_device_id
);
if let Some(cluster) = cluster_update.cluster.take() {
let became_inactive = self.connect_state.is_active()
&& cluster.active_device_id != self.session.device_id();
if became_inactive {
info!("device became inactive");
self.handle_disconnect().await?;
self.handle_stop();
} else if self.connect_state.is_active() {
// fixme: workaround fix, because of missing information why it behaves like it does
// background: when another device sends a connect-state update, some player's position de-syncs
// tried: providing session_id, playback_id, track-metadata "track_player"
self.update_state = true;
}
} else if self.connect_state.is_active() {
self.connect_state.became_inactive(&self.session).await?;
}
Ok(())
}
async fn handle_connect_state_request(
&mut self,
(request, sender): RequestReply,
) -> Result<(), Error> {
self.connect_state.set_last_command(request.clone());
debug!(
"handling: '{}' from {}",
request.command, request.sent_by_device_id
);
let response = match self.handle_request(request).await {
Ok(_) => Reply::Success,
Err(why) => {
error!("failed to handle request: {why}");
Reply::Failure
}
};
sender.send(response).map_err(Into::into)
}
async fn handle_request(&mut self, request: Request) -> Result<(), Error> {
use Command::*;
match request.command {
// errors and unknown commands
Transfer(transfer) if transfer.data.is_none() => {
warn!("transfer endpoint didn't contain any data to transfer");
Err(SpircError::NoData)?
}
Unknown(unknown) => Err(SpircError::UnknownEndpoint(unknown))?,
// implicit update of the connect_state
UpdateContext(update_context) => {
if matches!(update_context.context.uri, Some(ref uri) if uri != self.connect_state.context_uri())
{
debug!(
"ignoring context update for <{:?}>, because it isn't the current context <{}>",
update_context.context.uri,
self.connect_state.context_uri()
)