vionya / discord-rich-presence

A cross-platform Discord Rich Presence library written in Rust
MIT License
89 stars 16 forks source link

Is it possible to check if the client is connected? #14

Closed Toldoven closed 1 year ago

Toldoven commented 1 year ago

Trying to implement automatic reconnection.

First I check if user enabled rich presence, and if it's disabled, I want to check if the client is open, and then close it. Then if it is enabled, I want to start the client, otherwise continue the loop.

I noticed that there is the connected field on the DiscordIpcClient struct, but it was private. Then I tried to make it public, but it just seams that the functionality is just not implemented yet.

Is there a way to check if the client is connected, or maybe a better way to do what I'm trying to do?

#[tauri::command(async)]
async fn discord_start_interval(client: State<'_, DiscordRP>, prefs: State<'_, PrefsStore>) -> Result<(), ()> {

  let mut interval = interval(Duration::from_secs(1));

  loop {

    interval.tick().await;

    let prefs = prefs.0.lock().unwrap();
    let mut client = client.0.lock().unwrap();

    if !prefs.discord_rich_presence_enabled {
      if !client.connected { if client.close().is_err() { continue } };
      break;
    }

    if client.connected { continue };

    match client.connect() {
      Ok(_) => println!("Opened Discord IPC client"),
      Err(_) => println!("Failed to open Discord IPC client"),
    }

    if client.set_activity(Activity::new()
      .state("foo")
      .details("bar") 
    ).is_err() {
      println!("Failed to set activity")
    }

  }

  Ok(())

}
vionya commented 1 year ago

So for your question, in my own projects, I've handled automatic reconnection by calling something like ipc.reconnect().is_ok() and continuing if false. Could be helpful here.

However you raise a good point regarding the connected attribute, I can't remember why I left it there without implementing it. I'll look into giving it a purpose/replacing it with something to the same effect.