playdoobs 0.1.0

Service and matching CLI application for controlling the currently active MPRIS2 player
Documentation
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
1001
1002
1003
1004
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt::Display;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Instant;

use color_eyre::eyre::{Context, Result, bail};
use doobs_mpris::binding::{Player as PlayerIface, PlayerProxy, PlayerSignals, Seeked};
use doobs_mpris::types::{Metadata, MprisDuration, PlaybackStatus, TrackId};
use doobs_mpris::{Enumerator, EnumeratorEvent};
use log::{debug, error, info, trace};
use parking_lot::RwLock;
use tokio::sync::{Mutex as AsyncMutex, mpsc, oneshot};
use tokio::task::JoinHandle;
use tokio::{select, task};
use tokio_stream::{Stream, StreamExt, StreamMap};
use zbus::Connection;
use zbus::names::OwnedBusName;
use zbus::object_server::InterfaceRef;
use zbus::proxy::PropertyChanged;
use zbus::zvariant::{OwnedValue, Str as ZStr};

use crate::provider::PlaydoobsdPlayerProvider;
use crate::{
    PLAYDOOBSD_BUS_NAME, PLAYER_DBUS_NAME_METADATA_KEY, PLAYERCTLD_BUS_NAME, no_track_metadata,
};

pub type ActivityLock = Arc<RwLock<ActivityMap>>;
type PlaydoobsIface = PlayerIface<PlaydoobsdPlayerProvider>;
type InterfaceRefLock = Arc<AsyncMutex<InterfaceRef<PlaydoobsIface>>>;

pub fn create_service_and_activity_map() -> (PlaydoobsIface, ActivityLock) {
    let activity: ActivityLock = Default::default();
    let player = PlaydoobsdPlayerProvider::new(activity.clone());
    let service = PlayerIface::new(player);
    (service, activity)
}

#[derive(Default)]
pub struct ActivityMap {
    /// Bus name to the handles for this player.
    handles: HashMap<String, PlayerHandle>,
    /// Bus name of the last active player.
    last_active: Option<String>,
}

impl ActivityMap {
    fn get_active(&self) -> Option<&PlayerHandle> {
        self.last_active.as_ref().and_then(|p| self.handles.get(p))
    }

    pub(crate) fn send_command_to_active(&self, cmd: PlayerCommand) -> Result<()> {
        if let Some(handle) = self.get_active() {
            debug!("Sending command to active player: {cmd}");
            handle
                .server_tx
                .try_send(PlayerProxyMessage::Command(cmd))
                .wrap_err("Could not send command to active player")?;
        } else {
            debug!("Sending command to active player: No player active");
        }
        Ok(())
    }

    /// Updates the cached playback status for the player with the given bus name.
    /// Returns `true` if the playback status changed.
    fn update_playback_status(
        &mut self,
        bus_name: &str,
        playback_status: Option<PlaybackStatus>,
    ) -> bool {
        if let Some(handle) = self.handles.get_mut(bus_name) {
            if handle.activity.status != playback_status {
                handle.activity = PlayerActivity {
                    status: playback_status,
                    since: Instant::now(),
                };
                return true;
            }
        } else {
            error!("No player found to update playback status for: {bus_name}");
        }
        false
    }
}

#[derive(Clone)]
pub struct SharedState {
    activity: ActivityLock,
    iface_ref: InterfaceRefLock,
}

impl SharedState {
    pub fn new(activity: ActivityLock, iface_ref: InterfaceRef<PlaydoobsIface>) -> Self {
        Self {
            activity,
            iface_ref: Arc::new(AsyncMutex::new(iface_ref)),
        }
    }

    /// Registers the player with the given name.
    /// If it is already known its task will be cancelled.
    async fn create_state_and_spawn_task(
        &mut self,
        bus_name: OwnedBusName,
        proxy: PlayerProxy<'static>,
    ) -> Result<()> {
        let bus_name = bus_name.to_string();

        // in practice it shouldn't happen that messages queue up
        let (server_tx, server_rx) = mpsc::channel::<PlayerProxyMessage>(5);

        let player_state = PlayerState {
            proxy,
            server_rx,
            shared_state: self.clone(),
        };

        let (start_tx, start_rx) = oneshot::channel::<()>();
        let join_handle = task::spawn(async {
            start_rx
                .await
                .expect("player task start sender should never be dropped");

            run_player_property_watcher(player_state).await
        });

        let handle = PlayerHandle {
            activity: PlayerActivity::new(),
            server_tx,
            join_handle,
        };

        // insert handle for this player
        // a player only becomes active if we receive a playback status property
        let prev_handle = self
            .activity
            .write_arc()
            .handles
            .insert(bus_name.clone(), handle);

        // cancel previous properties handler if we already had one for this player
        if let Some(prev_handle) = prev_handle {
            _ = prev_handle
                .server_tx
                .send(PlayerProxyMessage::Cancel)
                .await
                .inspect_err(|err| {
                    error!("Could not send cancel message to player \"{bus_name}\": {err}")
                });
        }

        // tell the task to start processing
        start_tx
            .send(())
            .expect("player task start receiver should never be dropped");

        Ok(())
    }

    fn is_last_active(&self, bus_name: &str) -> bool {
        self.activity
            .read_arc()
            .last_active
            .as_ref()
            .is_some_and(|a| a == bus_name)
    }

    /// Recalculates the active player and performs the necessary steps to activate it.
    async fn recalc_active_player(&mut self) {
        let new_active = {
            let lock = self.activity.read_arc();
            let mut handles = lock.handles.iter().collect::<Vec<_>>();
            handles.sort_by(|(_k1, v1), (_k2, v2)| v1.activity.cmp(&v2.activity));

            handles.last().map(|(k, _v)| k.to_string())
        };

        if let Some(new_active) = new_active {
            debug!("Promoting to active player after recalc: {new_active}");
            self.change_active_player(&new_active).await;
        } else {
            debug!("No players remaining");
            self.activity.write_arc().last_active = None;
            self.unpublish_all().await;
        }
    }

    /// Changes the active player to the one with the given bus name.
    /// The previous player's properties (if it exists) will be unsubscribed
    /// and the new player's properties will be subscribes instead.
    async fn change_active_player(&self, bus_name: &str) {
        if self
            .activity
            .read_arc()
            .last_active
            .as_ref()
            .is_some_and(|n| n == bus_name)
        {
            trace!("Active player remains unchanged: {bus_name}");
            return;
        }

        // TODO log playback status
        info!("Changing active player to: {bus_name}");

        let prev_bus_name = self
            .activity
            .write_arc()
            .last_active
            .replace(bus_name.to_string());

        // unsubscribe from previous proxy
        if let Some(prev_bus_name) = prev_bus_name {
            if let Some(prev_proxy_tx) = {
                self.activity
                    .read_arc()
                    .handles
                    .get(&prev_bus_name)
                    .map(|h| h.server_tx.clone())
            } {
                _ = prev_proxy_tx
                    .send(PlayerProxyMessage::Unsubscribe)
                    .await
                    .inspect_err(|err| error!("Could not send unsubscribe message to player \"{prev_bus_name}\": {err}"));
            } else {
                error!(
                    "Handle for previously active player does not exist in map: {prev_bus_name}"
                );
            }
        }

        // subscribe to new proxy
        if let Some(proxy_tx) = {
            self.activity
                .read_arc()
                .handles
                .get(bus_name)
                .map(|h| h.server_tx.clone())
        } {
            _ = proxy_tx
                .send(PlayerProxyMessage::Subscribe)
                .await
                .inspect_err(|err| {
                    error!("Could not send subscribe message to player \"{bus_name}\": {err}")
                });
        } else {
            // should never happen
            error!("Handle for new active player does not exist in map: {bus_name}");
            self.unpublish_all().await;
        }
    }

    async fn publish_all<'a>(&self, proxy: &PlayerProxy<'a>, bus_name: Option<&str>) {
        debug!("Publishing all properties");

        let iface_ref = self.iface_ref.lock().await;
        let mut iface = iface_ref.get_mut().await;
        let player = iface.inner_mut();

        player.playback_status = proxy
            .playback_status()
            .await
            .inspect_err(|err| error!("Could not get playback_status: {err}"))
            .unwrap_or(PlaybackStatus::Stopped);

        player.can_seek = proxy
            .can_seek()
            .await
            .inspect_err(|err| error!("Could not get can_seek: {err}"))
            .unwrap_or(false);

        let mut metadata = proxy
            .metadata()
            .await
            .inspect_err(|err| error!("Could not get metadata: {err}"))
            .unwrap_or_else(|_| no_track_metadata());
        // custom metadata value so a client can identify what the active player is
        metadata.insert(
            PLAYER_DBUS_NAME_METADATA_KEY.into(),
            OwnedValue::from(ZStr::from(
                bus_name.expect("if we have metadata we must also have the bus name"),
            )),
        );
        player.metadata = metadata;

        let signal = iface_ref.signal_emitter();
        if let Err(err) = iface.playback_status_changed(signal).await {
            error!("Could not emit playback_status_changed signal: {err}");
        }
        if let Err(err) = iface.can_seek_changed(signal).await {
            error!("Could not emit can_seek_changed signal: {err}");
        }
        if let Err(err) = iface.metadata_changed(signal).await {
            error!("Could not emit metadata_changed signal: {err}");
        }
        // there is no position_changed signal
    }

    async fn unpublish_all(&self) {
        debug!("Unpublishing all properties");

        let iface_ref = self.iface_ref.lock().await;
        let mut iface = iface_ref.get_mut().await;

        iface.inner_mut().reset_properties();

        // TODO it makes sense to have the reset logic in the struct
        // but that makes having the signal_emitters here a bit ugly
        let signal = iface_ref.signal_emitter();
        if let Err(err) = iface.playback_status_changed(signal).await {
            error!("Could not emit playback_status_changed signal: {err}");
        }
        if let Err(err) = iface.can_seek_changed(signal).await {
            error!("Could not emit can_seek_changed signal: {err}");
        }
        if let Err(err) = iface.metadata_changed(signal).await {
            error!("Could not emit metadata_changed signal: {err}");
        }
        // there is no position_changed signal
    }

    async fn publish_property(&mut self, bus_name: &str, value: PropertyStreamValue) {
        _ = match value {
            PropertyStreamValue::PlaybackStatus(prop) => {
                self.change_active_and_publish_playback_status(bus_name, prop)
                    .await
            }
            PropertyStreamValue::CanSeek(prop) => self.publish_can_seek(prop).await,
            PropertyStreamValue::Metadata(prop) => self.publish_metadata(prop, bus_name).await,
            PropertyStreamValue::Seeked(signal) => self.emit_seeked(signal).await,
        }
        .inspect_err(|err| error!("Error while publishing property: {err:#}"));
    }

    async fn change_active_and_publish_playback_status<'a>(
        &mut self,
        bus_name: &str,
        playback_status: PropertyChanged<'a, PlaybackStatus>,
    ) -> Result<()> {
        let playback_status = playback_status
            .get()
            .await
            .wrap_err_with(|| format!("{bus_name}: Could not get playback_status"))?;

        // TODO reevalute this, maybe we can just default new players to Stopped
        let publish_playback_status = self
            .update_playback_status_and_recalc_active(bus_name, Some(playback_status))
            .await;

        if publish_playback_status {
            debug!("Publishing playback_status: {playback_status:?}");
            let iface_ref = self.iface_ref.lock().await;
            let mut iface = iface_ref.get_mut().await;
            iface.inner_mut().playback_status = playback_status;
            iface
                .playback_status_changed(iface_ref.signal_emitter())
                .await
                .wrap_err("Could not emit playback_status_changed signal")?;
        }

        Ok(())
    }

    /// Updates the playback status and recalcs the active player.
    /// Returns `true` if `bus_name` was and still is the active player.
    /// This is done so the caller can publish the original `ZPlaybackStatus`.
    ///
    /// This function mostly exists to make testing easier and should not be called outside of
    /// `change_active_and_publish_playback_status`.
    async fn update_playback_status_and_recalc_active(
        &mut self,
        bus_name: &str,
        playback_status: Option<PlaybackStatus>,
    ) -> bool {
        debug!("{bus_name}: Updating playback status to {playback_status:?}");

        let status_changed = self
            .activity
            .write_arc()
            .update_playback_status(bus_name, playback_status);
        if !status_changed {
            debug!("{bus_name}: Playback status remains unchanged");
            return false;
        }

        let mut player_remains_active = false;

        if self.is_last_active(bus_name) {
            match playback_status {
                Some(PlaybackStatus::Playing) | Some(PlaybackStatus::Paused) => {
                    // we're already active and in a definitely acitve state (playing/paused)
                    // so we just need to publish the state change
                    player_remains_active = true;
                }
                Some(PlaybackStatus::Stopped) | None => {
                    // if the playback stopped it makes sense to promote a potential other player
                    // to active

                    // recalc publishes the properties for the new player accordingly
                    // since we'd have to subscribe to the bus_name if became active,
                    // the subscribe would already take care of publishing the playback status
                    self.recalc_active_player().await;

                    // if we remain active we still need to publish our playback status
                    // since no subscribe happened
                    if self.is_last_active(bus_name) {
                        player_remains_active = true;
                    }
                }
            }
        } else {
            // if we weren't active, this will either do nothing or we become active
            // which means the subscribe will take care of publishing the playback status
            self.recalc_active_player().await;
        }

        player_remains_active
    }

    async fn publish_can_seek<'a>(&self, can_seek: PropertyChanged<'a, bool>) -> Result<()> {
        let can_seek = can_seek.get().await.wrap_err("Could not get can_seek")?;

        debug!("Publishing can_seek: {can_seek:?}");
        let iface_ref = self.iface_ref.lock().await;
        let mut iface = iface_ref.get_mut().await;
        iface.inner_mut().can_seek = can_seek;
        iface
            .can_seek_changed(iface_ref.signal_emitter())
            .await
            .wrap_err("Could not emit can_seek_changed signal")?;
        Ok(())
    }

    async fn publish_metadata<'a>(
        &self,
        metadata: PropertyChanged<'a, Metadata>,
        bus_name: &str,
    ) -> Result<()> {
        let mut metadata = metadata.get().await.wrap_err("Could not get metadata")?;

        // custom metadata value so a client can identify what the active player is
        metadata.insert(
            PLAYER_DBUS_NAME_METADATA_KEY.into(),
            OwnedValue::from(ZStr::from(bus_name)),
        );

        debug!("Publishing metadata: {metadata:?}");
        let iface_ref = self.iface_ref.lock().await;
        let mut iface = iface_ref.get_mut().await;
        iface.inner_mut().metadata = metadata;
        iface
            .metadata_changed(iface_ref.signal_emitter())
            .await
            .wrap_err("Could not emit metadata_changed signal")?;
        Ok(())
    }

    async fn emit_seeked(&self, seeked: Seeked) -> Result<()> {
        let position = seeked
            .args()
            .wrap_err("Could not get seeked signal args")?
            .position;

        // the spec says the signal does not need to be emitted when playback starts etc.
        // firefox does it anyway (seeked on every play/pause), mpv doesn't (only on actual seeks)
        debug!("Publishing seeked position: {position:?}");
        let iface_ref = self.iface_ref.lock().await;
        iface_ref
            .seeked(position)
            .await
            .wrap_err("Could not emit seeked signal")?;
        Ok(())
    }
}

/// Message send to a specific player proxy.
#[derive(PartialEq, Debug)]
enum PlayerProxyMessage {
    /// Subscribe to the properties for this player.
    Subscribe,
    /// Unsubscribe from the properties for this player.
    Unsubscribe,
    /// Cancel the task for this player.
    Cancel,
    /// Command to send to the player.
    Command(PlayerCommand),
}

/// Methods to call on the specific player proxy.
#[derive(Debug)]
pub(crate) enum PlayerCommand {
    /// Toggles play/pause.
    PlayPause,
    /// Starts or resumes playback.
    Play,
    /// Pauses playback.
    Pause,
    /// Stops playback.
    Stop,
    /// Skip to the next track.
    Next,
    /// Skip to the previous track.
    Previous,
    /// Seeks forward/back in the current track by the specified number of microseconds.
    Seek {
        offset: MprisDuration,
    },
    /// Sets the current track position in microseconds.
    SetPosition {
        track_id: TrackId,
        position: MprisDuration,
    },
    FetchPosition(oneshot::Sender<MprisDuration>),
}

impl PartialEq for PlayerCommand {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Seek { offset: l_offset }, Self::Seek { offset: r_offset }) => {
                l_offset == r_offset
            }
            (
                Self::SetPosition {
                    track_id: l_track_id,
                    position: l_position,
                },
                Self::SetPosition {
                    track_id: r_track_id,
                    position: r_position,
                },
            ) => l_track_id == r_track_id && **l_position == **r_position,
            // also compare the discriminant for FetchPosition, because of the Sender
            _ => core::mem::discriminant(self) == core::mem::discriminant(other),
        }
    }
}

impl Display for PlayerCommand {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            PlayerCommand::PlayPause => "PlayPause",
            PlayerCommand::Play => "Play",
            PlayerCommand::Pause => "Pause",
            PlayerCommand::Stop => "Stop",
            PlayerCommand::Next => "Next",
            PlayerCommand::Previous => "Previous",
            PlayerCommand::Seek { .. } => "Seek",
            PlayerCommand::SetPosition { .. } => "SetPosition",
            PlayerCommand::FetchPosition(_) => "FetchPosition",
        };
        write!(f, "{name}")
    }
}

#[derive(PartialEq, Eq, Debug)]
struct PlayerActivity {
    status: Option<PlaybackStatus>,
    since: Instant,
}

impl PlayerActivity {
    fn new() -> Self {
        Self {
            status: None,
            since: Instant::now(),
        }
    }
}

impl Ord for PlayerActivity {
    fn cmp(&self, other: &Self) -> Ordering {
        let playback_status_to_int = |s: Option<PlaybackStatus>| {
            s.map_or(0, |s| match s {
                PlaybackStatus::Stopped => 1,
                // anything that is not stopped (or None) counts as more active
                // this is so after pausing a player it still counts as active for unpausing
                // otherwise activity would switch to potential other players that are playing
                // which is undesirable
                PlaybackStatus::Paused | PlaybackStatus::Playing => 2,
            })
        };

        playback_status_to_int(self.status)
            .cmp(&playback_status_to_int(other.status))
            .then(self.since.cmp(&other.since))
    }
}

impl PartialOrd for PlayerActivity {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

#[derive(Debug)]
struct PlayerHandle {
    /// When the player last got its playback status set.
    activity: PlayerActivity,
    /// Send update messages from the server task.
    server_tx: mpsc::Sender<PlayerProxyMessage>,
    /// Join handle for the player task.
    join_handle: JoinHandle<()>,
}

struct PlayerState<'a> {
    /// D-Bus proxy for this player.
    proxy: PlayerProxy<'a>,
    /// Receive update messages from the server task.
    server_rx: mpsc::Receiver<PlayerProxyMessage>,
    /// TODO
    shared_state: SharedState,
}

pub async fn run(mut state: SharedState) -> Result<()> {
    info!("Starting discovery of players");

    let conn = Connection::session().await?;

    init_players(&mut state, &conn).await?;

    let mut event_stream = Enumerator::new(&conn).await?.receive_changes().await?;

    while let Some(event) = event_stream.next().await {
        let event = match event {
            Ok(event) => event,
            Err(err) => {
                error!("Error in MPRIS event: {err}");
                continue;
            }
        };
        match event {
            EnumeratorEvent::Add(bus_name) => {
                if let Err(err) = init_player(&mut state, &conn, bus_name.clone()).await {
                    bail!("{bus_name}: Could not init as new player: {err}");
                }
            }
            EnumeratorEvent::Remove(bus_name) => {
                if let Err(err) = deinit_player(&mut state, bus_name.clone()).await {
                    bail!("{bus_name}: Could not remove player: {err}");
                }
            }
        }
    }

    bail!("MPRIS stream closed")
}

async fn init_players(state: &mut SharedState, conn: &Connection) -> Result<()> {
    for bus_name in Enumerator::new(conn).await?.players().await? {
        if let Err(err) = init_player(state, conn, bus_name.clone()).await {
            error!("{bus_name}: Could not init as new player: {err}");
        }
    }

    Ok(())
}

async fn init_player(
    state: &mut SharedState,
    conn: &Connection,
    bus_name: OwnedBusName,
) -> Result<()> {
    match bus_name.as_str() {
        PLAYDOOBSD_BUS_NAME => {
            trace!("Skipping initializing self ({bus_name})");
            return Ok(());
        }
        PLAYERCTLD_BUS_NAME => {
            debug!("Skipping initializing playerctld ({bus_name})");
            return Ok(());
        }
        _ => {}
    }

    info!("Initializing player: {bus_name}");

    // it looks like PropertyStreams require caching to be enabled for those properties
    // we can't cache Position because it doesn't have a signal emitter
    match PlayerProxy::builder(conn)
        .destination(bus_name.clone())?
        .uncached_properties(&["Position"])
        .build()
        .await
    {
        Ok(proxy) => state.create_state_and_spawn_task(bus_name, proxy).await?,
        Err(err) => error!("Could not connect to player \"{bus_name}\": {err}"),
    }

    Ok(())
}

async fn deinit_player(state: &mut SharedState, bus_name: OwnedBusName) -> Result<()> {
    match bus_name.as_str() {
        // these won't get initialized, so we don't have to deinit them either
        PLAYDOOBSD_BUS_NAME | PLAYERCTLD_BUS_NAME => return Ok(()),
        _ => {}
    }

    info!("Removing player: {bus_name}");

    if let Some(handle) = {
        state
            .activity
            .write_arc()
            .handles
            .remove(&bus_name.to_string())
    } {
        _ = handle
            .server_tx
            .send(PlayerProxyMessage::Cancel)
            .await
            .inspect_err(|err| {
                error!("Could not send cancel message to player \"{bus_name}\": {err}")
            });

        // wait for the task, otherwise it might still promote itself back to the active player if
        // there are still property events queued
        _ = handle.join_handle.await.inspect_err(|err| {
            error!("Error waiting for task for player \"{bus_name}\" to finish: {err}")
        });
    } else {
        error!("Tried to remove player that was never added: {bus_name}");
    }

    state.recalc_active_player().await;

    Ok(())
}

enum PropertyStreamValue {
    PlaybackStatus(PropertyChanged<'static, PlaybackStatus>),
    CanSeek(PropertyChanged<'static, bool>),
    Metadata(PropertyChanged<'static, Metadata>),
    Seeked(Seeked),
}

// Box so we can put different types in the same map, Pin because .next() requires it
type PinnedPropertyStream = Pin<Box<dyn Stream<Item = PropertyStreamValue> + Send>>;

async fn run_player_property_watcher(mut state: PlayerState<'static>) {
    let proxy = state.proxy;
    let bus_name = proxy.inner().destination();

    let mut property_streams = StreamMap::new();

    debug!("{bus_name}: Subscribing to playback_status");
    let playback_status_stream: PinnedPropertyStream = Box::pin(
        proxy
            .receive_playback_status_changed()
            .await
            .map(PropertyStreamValue::PlaybackStatus),
    );
    property_streams.insert("playback_status", playback_status_stream);

    loop {
        select! {
            server_msg = state.server_rx.recv() => match server_msg {
                Some(msg) => match msg {
                    PlayerProxyMessage::Subscribe => {
                        debug!("{bus_name}: Subscribing to properties");
                        // publish all properties of the new player
                        state.shared_state.publish_all(&proxy, Some(bus_name)).await;

                        debug!("{bus_name}: Subscribing to can_seek");
                        let can_seek_stream: PinnedPropertyStream = Box::pin(
                            proxy
                                .receive_can_seek_changed()
                                .await
                                .map(PropertyStreamValue::CanSeek)
                        );
                        property_streams.insert("can_seek", can_seek_stream);

                        debug!("{bus_name}: Subscribing to metadata");
                        let metadata_stream: PinnedPropertyStream = Box::pin(
                            proxy
                                .receive_metadata_changed()
                                .await
                                .map(PropertyStreamValue::Metadata)
                        );
                        property_streams.insert("metadata", metadata_stream);

                        // seeked is the only signal
                        debug!("{bus_name}: Subscribing to seeked");
                        if let Ok(seeked_stream) = proxy.receive_seeked().await {
                            let seeked_stream: PinnedPropertyStream = Box::pin(
                                seeked_stream.map(PropertyStreamValue::Seeked)
                            );
                            property_streams.insert("seeked", seeked_stream);
                        }
                    }
                    PlayerProxyMessage::Unsubscribe => {
                        debug!("{bus_name}: Unsubscribing from all propertie except playback_status");
                        let ps_key = "playback_status";
                        let pss = property_streams.remove(&ps_key);
                        property_streams.clear();
                        if let Some(pss) = pss {
                            property_streams.insert(ps_key, pss);
                        } else {
                            error!("{bus_name}: Missing playback_status stream during unsubscribe");
                            break;
                        }
                    }
                    PlayerProxyMessage::Cancel => {
                        debug!("{bus_name}: Player task got cancelled");
                        break;
                    }
                    PlayerProxyMessage::Command(cmd) => run_command(&proxy, cmd).await
                },
                None => {
                    debug!("{bus_name}: Server message channel got closed");
                    break;
                }
            },
            prop_res = property_streams.next() => match prop_res {
                Some((key, value)) => {
                    debug!("{bus_name}: received signal from stream: {key}");
                    state.shared_state.publish_property(bus_name, value).await
                }
                None => {
                    // this shouldn't happen, since the stream map always has at least
                    // the playback_status stream in it
                    error!("{bus_name}: All property streams got closed");
                    break;
                }
            },
        };
    }
}

/// Call the method for the given command on the player proxy.
async fn run_command<'a>(proxy: &PlayerProxy<'a>, cmd: PlayerCommand) {
    let bus_name = proxy.inner().destination();
    let cmd_name = cmd.to_string();
    debug!("{bus_name}: Calling {cmd:?}");
    _ = match cmd {
        PlayerCommand::PlayPause => proxy.play_pause().await,
        PlayerCommand::Play => proxy.play().await,
        PlayerCommand::Pause => proxy.pause().await,
        PlayerCommand::Stop => proxy.stop().await,
        PlayerCommand::Next => proxy.next().await,
        PlayerCommand::Previous => proxy.previous().await,
        PlayerCommand::Seek { offset } => proxy.seek(offset).await,
        PlayerCommand::SetPosition { track_id, position } => {
            proxy.set_position(track_id, position).await
        }
        PlayerCommand::FetchPosition(tx) => {
            let position = proxy
                .position()
                .await
                .inspect_err(|err| error!("{bus_name}: Could not fetch position: {err}"))
                .ok();
            tx.send(position.unwrap_or_default())
                .map_err(|_| zbus::fdo::Error::Failed("send failed".to_string()))
        }
    }
    .inspect_err(|err| error!("{bus_name}: Error calling {cmd_name}: {err}"));
}

#[cfg(test)]
mod test {
    use std::time::Instant;

    use doobs_mpris::binding::MPRIS_OBJECT_PATH;
    use doobs_mpris::types::PlaybackStatus;
    use tokio::sync::mpsc;
    use tokio::task;

    use crate::PLAYDOOBSD_BUS_NAME;
    use crate::daemon::{
        PlaydoobsIface, PlayerActivity, PlayerHandle, PlayerProxyMessage, SharedState,
        create_service_and_activity_map,
    };

    #[tokio::test]
    async fn test_active_player_change() {
        let state = &mut create_empty_state().await.unwrap();
        let (tx, mut rx) = mpsc::channel(2); // one for sub, one for unsub
        let tx = &tx;

        // by default, no player is active
        assert_eq!(None, state.activity.read_arc().last_active);

        // inserting one makes it active
        let player_1 = "1";
        add_player(state, player_1, PlaybackStatus::Stopped, tx).await;
        assert_eq!(PlayerProxyMessage::Subscribe, rx.recv().await.unwrap());
        assert!(rx.is_empty(), "expected no more messages");
        assert!(state.is_last_active(player_1));

        // inserting another one makes it active
        let player_2 = "2";
        add_player(state, player_2, PlaybackStatus::Stopped, tx).await;
        assert_eq!(PlayerProxyMessage::Unsubscribe, rx.recv().await.unwrap());
        assert_eq!(PlayerProxyMessage::Subscribe, rx.recv().await.unwrap());
        assert!(rx.is_empty(), "expected no more messages");
        assert!(state.is_last_active(player_2));

        // going from stopped to playing makes it active
        state
            .update_playback_status_and_recalc_active(&player_1, Some(PlaybackStatus::Playing))
            .await;
        assert_eq!(PlayerProxyMessage::Unsubscribe, rx.recv().await.unwrap());
        assert_eq!(PlayerProxyMessage::Subscribe, rx.recv().await.unwrap());
        assert!(rx.is_empty(), "expected no more messages");
        assert!(state.is_last_active(player_1));

        // adding a new one that's stopped doesn't make it active when another is playing
        let player_3 = "3";
        add_player(state, player_3, PlaybackStatus::Stopped, tx).await;
        assert!(rx.is_empty(), "expected no more messages");
        assert!(state.is_last_active(player_1));

        // setting it to from stopped to paused does make it active though, even if another is playing
        state
            .update_playback_status_and_recalc_active(&player_3, Some(PlaybackStatus::Paused))
            .await;
        assert_eq!(PlayerProxyMessage::Unsubscribe, rx.recv().await.unwrap());
        assert_eq!(PlayerProxyMessage::Subscribe, rx.recv().await.unwrap());
        assert!(rx.is_empty(), "expected no more messages");
        assert!(state.is_last_active(player_3));

        // setting it to playing makes it stay active
        state
            .update_playback_status_and_recalc_active(&player_3, Some(PlaybackStatus::Playing))
            .await;
        assert!(rx.is_empty(), "expected no more messages");
        assert!(state.is_last_active(player_3));

        // setting it back to paused makes it stay active, even though player_1 is also playing
        state
            .update_playback_status_and_recalc_active(&player_3, Some(PlaybackStatus::Paused))
            .await;
        assert!(rx.is_empty(), "expected no more messages");
        assert!(state.is_last_active(player_3));

        // setting it to stopped makes the next paused/playing player active
        state
            .update_playback_status_and_recalc_active(&player_3, Some(PlaybackStatus::Stopped))
            .await;
        assert_eq!(PlayerProxyMessage::Unsubscribe, rx.recv().await.unwrap());
        assert_eq!(PlayerProxyMessage::Subscribe, rx.recv().await.unwrap());
        assert!(rx.is_empty(), "expected no more messages");
        assert!(state.is_last_active(player_1));

        // removing the active player makes the next one active
        remove_player(state, player_1).await;
        // no unsub, since the player task is dead
        assert_eq!(PlayerProxyMessage::Subscribe, rx.recv().await.unwrap());
        assert!(rx.is_empty(), "expected no more messages");
        // player_3 has a newer stopped status than player_2 and is thus active
        assert!(state.is_last_active(player_3));

        // removing a not active player doesn't change anything
        remove_player(state, player_2).await;
        assert!(rx.is_empty(), "expected no more messages");
        assert!(state.is_last_active(player_3));
    }

    async fn create_empty_state() -> color_eyre::Result<SharedState> {
        let (service, activity) = create_service_and_activity_map();
        let conn = zbus::connection::Builder::session()?
            .name(format!("{PLAYDOOBSD_BUS_NAME}.test"))?
            .serve_at(MPRIS_OBJECT_PATH, service)?
            .build()
            .await?;
        let iface_ref = conn
            .object_server()
            .interface::<_, PlaydoobsIface>(MPRIS_OBJECT_PATH)
            .await?;

        Ok(SharedState::new(activity, iface_ref))
    }

    async fn add_player(
        state: &mut SharedState,
        bus_name: &str,
        status: PlaybackStatus,
        tx: &mpsc::Sender<PlayerProxyMessage>,
    ) {
        state
            .activity
            .write_arc()
            .handles
            .insert(bus_name.to_string(), {
                let tx = tx.clone();
                PlayerHandle {
                    activity: PlayerActivity {
                        status: Some(status),
                        since: Instant::now(),
                    },
                    server_tx: tx.clone(),
                    join_handle: task::spawn(async {}),
                }
            });
        state.recalc_active_player().await;
    }

    async fn remove_player(state: &mut SharedState, bus_name: &str) {
        state.activity.write_arc().handles.remove(bus_name);
        state.recalc_active_player().await;
    }
}