Repository: aome510/spotify-player (language: rust)

Issue:
ResumePause doesn't always register. Play/Pause Icon is confused.
**Describe the bug**
The Icon may show play icon while it is actually paused (and vice versa) pressing space will correct the icon but not play.

**To Reproduce**
Run program -> pause shown
Press space -> music plays, icon flips from paused to play to pause again.
Press space -> icon flips to play
press space -> music pauses, icon flips from play to pause and the play again.
Press space -> icon flips to pause.

If we navigate to another song after loading the program and play that it will play initially but the icons still get confused when resuming.

**Expected behaviour**
Run program -> pause shown
Press space -> music plays, icon flips from paused to play
press space -> music pauses, icon flips from play to pause

**Log and backtrace**
The following log snippet looks related.
```
2024-03-04T05:50:11.958455Z  INFO client_request{request=Player(ResumePause)}: spotify_player::client: successfully handled the client request, took: 226ms
2024-03-04T05:50:13.989474Z  INFO client_request{request=Player(ResumePause)}: spotify_player::client: successfully handled the client request, took: 235ms
2024-03-04T05:50:14.357216Z  INFO spotify_player::streaming: Got a new player event: Paused { track_id: TrackId("6BUWdfmuPehKO5E7pznn1L"), position_ms: 55474, duration_ms: 375272 }
2024-03-04T05:50:14.591747Z  INFO client_request{request=GetCurrentPlayback}: spotify_player::client: successfully handled the client request, took: 234ms
2024-03-04T05:50:18.160894Z  INFO client_request{request=Player(ResumePause)}: spotify_player::client: successfully handled the client request, took: 287ms
2024-03-04T05:50:18.162149Z  INFO spotify_player::streaming: Got a new player event: Playing { track_id: TrackId("6BUWdfmuPehKO5E7pznn1L"), position_ms: 55474, duration_ms: 375272 }
2024-03-04T05:50:18.162361Z  INFO spotify_player::streaming: Got a new player event: Playing { track_id: TrackId("6BUWdfmuPehKO5E7pznn1L"), position_ms: 55474, duration_ms: 375272 }
2024-03-04T05:50:18.404869Z  INFO client_request{request=GetCurrentPlayback}: spotify_player::client: successfully handled the client request, took: 242ms
2024-03-04T05:50:18.457483Z  INFO client_request{request=GetCurrentPlayback}: spotify_player::client: successfully handled the client request, took: 295ms
```

**Screenshots**
If applicable, add screenshots to help explain your problem.
Can add on request.

**Environment**

- Application version: 0.17.0
- Application features: Default.

```
             .',;::::;,'.                Gibus@Gibus
         .';:cccccccccccc:;,.            -----------
      .;cccccccccccccccccccccc;.         OS: Fedora Linux 39 (Thirty Nine) x86_64
    .:cccccccccccccccccccccccccc:.       Host: B550 AORUS PRO AX
  .;ccccccccccccc;.:dddl:.;ccccccc;.     Kernel: 6.6.13-200.fc39.x86_64
 .:ccccccccccccc;OWMKOOXMWd;ccccccc:.    Uptime: 4 hours, 9 mins
.:ccccccccccccc;KMMc;cc;xMMc:ccccccc:.   Packages: 2282 (rpm)
,cccccccccccccc;MMM.;cc;;WW::cccccccc,   Shell: bash 5.2.26
:cccccccccccccc;MMM.;cccccccccccccccc:   Resolution: 1920x1080, 2560x1440, 1920x1080
:ccccccc;oxOOOo;MMM0OOk.;cccccccccccc:   WM: i3
cccccc:0MMKxdd:;MMMkddc.;cccccccccccc;   Theme: oomox-Pandora-Arc [GTK2/3]
ccccc:XM0';cccc;MMM.;cccccccccccccccc'   Icons: Vortex-Dark-Icons [GTK2/3]
ccccc;MMo;ccccc;MMW.;ccccccccccccccc;    Terminal: WezTerm
ccccc;0MNc.ccc.xMMd:ccccccccccccccc;     CPU: AMD Ryzen 5 5600X (12) @ 3.700GHz
cccccc;dNMWXXXWM0::cccccccccccccc:,      GPU: NVIDIA GeForce RTX 3060 Ti
cccccccc;.:odl:.;cccccccccccccc:,.       Memory: 3036MiB / 32032MiB
:cccccccccccccccccccccccccccc:'.
.:cccccccccccccccccccccc:;,..
  '::cccccccccccccc::;,.
```

**Additional context**
Following may be relevant:
- Running Pipewire (assume default backend?)
- own Client ID, No other changes to app.toml
- Tried with Default keymap and same issue
- Had spotify-tui installed prior to install


Discussion / hints:

Fix patch:
diff --git a/spotify_player/src/cli/handlers.rs b/spotify_player/src/cli/handlers.rs
index eb32ce5d..f9636cc2 100644
--- a/spotify_player/src/cli/handlers.rs
+++ b/spotify_player/src/cli/handlers.rs
@@ -1,6 +1,6 @@
 use crate::{
     auth::{new_session, new_session_with_new_creds, AuthConfig},
-    client, event, state,
+    client, state,
 };
 
 use super::*;
@@ -152,19 +152,13 @@ fn try_connect_to_client(socket: &UdpSocket, configs: &state::Configs) -> Result
             // no running `spotify_player` instance found,
             // initialize a new client to handle the current CLI command
 
-            let (client_pub, _) = flume::unbounded::<event::ClientRequest>();
-
             let auth_config = AuthConfig::new(configs)?;
             let rt = tokio::runtime::Runtime::new()?;
             let session = rt.block_on(new_session(&auth_config, false))?;
 
             // create a Spotify API client
-            let client = client::Client::new(
-                session,
-                auth_config,
-                configs.app_config.client_id.clone(),
-                client_pub,
-            );
+            let client =
+                client::Client::new(session, auth_config, configs.app_config.client_id.clone());
             rt.block_on(client.init_token())?;
 
             // create a client socket for handling CLI commands
diff --git a/spotify_player/src/client/mod.rs b/spotify_player/src/client/mod.rs
index a2d8bde8..aaebfd69 100644
--- a/spotify_player/src/client/mod.rs
+++ b/spotify_player/src/client/mod.rs
@@ -30,7 +30,6 @@ use serde::Deserialize;
 pub struct Client {
     http: reqwest::Client,
     pub spotify: Arc<spotify::Spotify>,
-    pub client_pub: flume::Sender<ClientRequest>,
     #[cfg(feature = "streaming")]
     stream_conn: Arc<Mutex<Option<Spirc>>>,
 }
@@ -55,18 +54,12 @@ fn market_query() -> Query<'static> {
 
 impl Client {
     /// creates a new client
-    pub fn new(
-        session: Session,
-        auth_config: AuthConfig,
-        client_id: String,
-        client_pub: flume::Sender<ClientRequest>,
-    ) -> Self {
+    pub fn new(session: Session, auth_config: AuthConfig, client_id: String) -> Self {
         Self {
             spotify: Arc::new(spotify::Spotify::new(session, auth_config, client_id)),
             http: reqwest::Client::new(),
             #[cfg(feature = "streaming")]
             stream_conn: Arc::new(Mutex::new(None)),
-            client_pub,
         }
     }
 
@@ -82,8 +75,14 @@ impl Client {
         #[cfg(feature = "streaming")]
         if state.is_streaming_enabled() {
             self.new_streaming_connection(state).await;
-            // handle `ConnectDevice` separately as we don't want to block here
-            self.client_pub.send(ClientRequest::ConnectDevice(None))?;
+            // handle `connect_device` task separately as we don't want to block here
+            tokio::task::spawn({
+                let client = self.clone();
+                let state = state.clone();
+                async move {
+                    client.connect_device(&state, None).await;
+                }
+            });
         }
 
         Ok(())
@@ -97,7 +96,6 @@ impl Client {
         let new_conn = streaming::new_connection(
             session,
             state.configs.app_config.device.clone(),
-            self.client_pub.clone(),
             state.configs.app_config.player_event_hook_command.clone(),
         );
 
diff --git a/spotify_player/src/main.rs b/spotify_player/src/main.rs
index 4e2ba1f0..d78eadee 100644
--- a/spotify_player/src/main.rs
+++ b/spotify_player/src/main.rs
@@ -130,7 +130,6 @@ async fn start_app(state: &state::SharedState) -> Result<()> {
         session,
         auth_config,
         state.configs.app_config.client_id.clone(),
-        client_pub.clone(),
     );
     client.init_token().await?;
 
diff --git a/spotify_player/src/streaming.rs b/spotify_player/src/streaming.rs
index 19a00072..0f97365c 100644
--- a/spotify_player/src/streaming.rs
+++ b/spotify_player/src/streaming.rs
@@ -1,4 +1,4 @@
-use crate::{config, event::ClientRequest};
+use crate::config;
 use librespot_connect::spirc::Spirc;
 use librespot_core::{
     config::{ConnectConfig, DeviceType},
@@ -164,7 +164,6 @@ fn execute_player_event_hook_command(
 pub fn new_connection(
     session: Session,
     device: config::DeviceConfig,
-    client_pub: flume::Sender<ClientRequest>,
     player_event_hook_command: Option<config::Command>,
 ) -> Spirc {
     // `librespot` volume is a u16 number ranging from 0 to 65535,
@@ -230,12 +229,6 @@ pub fn new_connection(
                                 );
                             }
                         }
-
-                        // notify the application about the new player event by making playback update request
-                        client_pub
-                            .send_async(ClientRequest::GetCurrentPlayback)
-                            .await
-                            .unwrap_or_default();
                     }
                     Ok(None) => {}
                 }


Test patch: