Dough Git

commit

discord fix

commit
1e7bc349fc7e13787c8452cb8ca6ec7beba8d733
author
Clove Twilight <[email protected]>
date
2026-08-01 16:42

diff --git a/apps/desktop/src-tauri/src/discord.rs b/apps/desktop/src-tauri/src/discord.rs
index ad14911..63dfa64 100644
--- a/apps/desktop/src-tauri/src/discord.rs
+++ b/apps/desktop/src-tauri/src/discord.rs
@@ -29,6 +29,12 @@ pub enum PresenceUpdate {
         // reachable without auth (see the public /cover route). Empty/None
         // just falls back to the app's default icon.
         cover_url: Option<String>,
+        // Current playback position in seconds, so a resumed track's elapsed
+        // bar starts from the right place instead of from zero.
+        position_s: Option<f64>,
+        // When false (paused) we omit the timestamps entirely, which stops
+        // Discord from animating the elapsed/remaining bar past where it is.
+        playing: bool,
     },
     Clear,
 }
@@ -42,7 +48,7 @@ pub fn spawn(application_id: u64, rx: Receiver<PresenceUpdate>) {
             discord_social_sdk::run_callbacks();
 
             match rx.try_recv() {
-                Ok(PresenceUpdate::NowPlaying { title, artist, album, duration_s, cover_url }) => {
+                Ok(PresenceUpdate::NowPlaying { title, artist, album, duration_s, cover_url, position_s, playing }) => {
                     let mut activity = Activity::new();
                     activity.set_activity_type(ActivityType::Listening);
                     activity.set_details(Some(&title));
@@ -55,17 +61,27 @@ pub fn spawn(application_id: u64, rx: Receiver<PresenceUpdate>) {
                     };
                     activity.set_state(Some(&state));
 
-                    if let Some(duration_s) = duration_s {
-                        let now_ms = std::time::SystemTime::now()
-                            .duration_since(std::time::UNIX_EPOCH)
-                            .unwrap_or_default()
-                            .as_millis() as u64;
-                        let end_ms = now_ms + (duration_s * 1000.0) as u64;
+                    // Only show the elapsed/remaining bar while actually
+                    // playing. When paused we omit timestamps so Discord stops
+                    // advancing the bar (it would otherwise keep ticking toward
+                    // `end` even though playback is stopped).
+                    if playing {
+                        if let Some(duration_s) = duration_s {
+                            let now_ms = std::time::SystemTime::now()
+                                .duration_since(std::time::UNIX_EPOCH)
+                                .unwrap_or_default()
+                                .as_millis() as u64;
+                            // Anchor `start` back by the current position so the
+                            // bar reflects real elapsed time on a resumed track.
+                            let position_ms = (position_s.unwrap_or(0.0).max(0.0) * 1000.0) as u64;
+                            let start_ms = now_ms.saturating_sub(position_ms);
+                            let end_ms = start_ms + (duration_s * 1000.0) as u64;
 
-                        let mut timestamps = ActivityTimestamps::new();
-                        timestamps.set_start(now_ms);
-                        timestamps.set_end(end_ms);
-                        activity.set_timestamps(Some(&timestamps));
+                            let mut timestamps = ActivityTimestamps::new();
+                            timestamps.set_start(start_ms);
+                            timestamps.set_end(end_ms);
+                            activity.set_timestamps(Some(&timestamps));
+                        }
                     }
 
                     // Album art as the large presence image. large_image takes
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 838c031..65e0335 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -43,6 +43,8 @@ fn set_now_playing(
     album: Option<String>,
     #[allow(non_snake_case)] durationS: Option<f64>,
     #[allow(non_snake_case)] coverUrl: Option<String>,
+    #[allow(non_snake_case)] positionS: Option<f64>,
+    playing: bool,
     handle: State<DiscordHandle>,
 ) -> Result<(), String> {
     handle
@@ -55,6 +57,8 @@ fn set_now_playing(
             album,
             duration_s: durationS,
             cover_url: coverUrl,
+            position_s: positionS,
+            playing,
         })
         .map_err(|e| e.to_string())
 }
@@ -83,6 +87,8 @@ fn set_now_playing(
     album: Option<String>,
     #[allow(non_snake_case)] durationS: Option<f64>,
     #[allow(non_snake_case)] coverUrl: Option<String>,
+    #[allow(non_snake_case)] positionS: Option<f64>,
+    playing: bool,
 ) -> Result<(), String> {
     Ok(())
 }
diff --git a/apps/web/src/app.ts b/apps/web/src/app.ts
index cd936a9..bed9ac2 100644
--- a/apps/web/src/app.ts
+++ b/apps/web/src/app.ts
@@ -54,11 +54,34 @@ const state = {
   adminCounts: { duplicates: 0, linkRequests: 0 },
 };
 
+// Discord presence is refreshed whenever the *song* or the *play/pause* state
+// changes — not on every timeupdate — so pausing freezes/removes the elapsed
+// bar and resuming a already-loaded track re-activates presence. Deduped by
+// (songId, playing) so the constant "change" stream doesn't spam Discord.
+let presSongId: string | null = null;
+let presPlaying = false;
+let presInit = false;
+function maybeUpdatePresence(): void {
+  const song = player.current;
+  const songId = song?.id ?? null;
+  const playing = player.playing;
+  if (presInit && songId === presSongId && playing === presPlaying) return;
+  presInit = true;
+  presSongId = songId;
+  presPlaying = playing;
+  if (!song) {
+    void syncDiscordPresence(null);
+    return;
+  }
+  void syncDiscordPresence(song, { playing, positionS: player.progress.current });
+}
+
 let lastSave = 0;
 player.events.on("change", () => {
   renderPlayerBar();
   syncLyrics();
   checkScrobbleThreshold();
+  maybeUpdatePresence();
   // Cheap: just keep the active row's play/pause (animation) state in sync.
   // Which row is active is handled on trackchange, so no full sweep here.
   document
@@ -95,7 +118,9 @@ function onTrackStarted(song: Song): void {
 }
 player.events.on("trackchange", (song) => {
   onTrackStarted(song);
-  void syncDiscordPresence(song);
+  // Push presence immediately for the new track (with its current position),
+  // rather than waiting for the next "change" tick. Deduped downstream.
+  maybeUpdatePresence();
   highlightPlayingRow(); // move the now-playing bars to the new track's row
 });
 
diff --git a/apps/web/src/desktop.ts b/apps/web/src/desktop.ts
index e7be538..3a76532 100644
--- a/apps/web/src/desktop.ts
+++ b/apps/web/src/desktop.ts
@@ -175,7 +175,14 @@ export function clearDesktopToken(): void {
 // Forwards the currently playing track to the Rust side, which owns the
 // actual Discord Social SDK client. Fire-and-forget: presence is cosmetic
 // and should never block or break playback.
-export async function syncDiscordPresence(song: Song | null): Promise<void> {
+//
+// `playback` carries the live play/pause state and current position so Rust
+// can build (or omit) the elapsed-time bar: paused → no bar, and resuming
+// mid-track → the bar starts from the right place instead of from zero.
+export async function syncDiscordPresence(
+  song: Song | null,
+  playback?: { playing: boolean; positionS: number },
+): Promise<void> {
   if (!isDesktop) return;
   try {
     const { invoke } = await import("@tauri-apps/api/core");
@@ -191,6 +198,8 @@ export async function syncDiscordPresence(song: Song | null): Promise<void> {
       album: song.album,
       durationS: song.durationS,
       coverUrl,
+      positionS: playback?.positionS ?? 0,
+      playing: playback?.playing ?? true,
     });
   } catch {
     /* best-effort — never blocks playback */