Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

feat(study): implement listen together feature with chat and member management

Tonho0e71788a36eb
diff --git a/src/lib/study-music/listen-together-store.svelte.ts b/src/lib/study-music/listen-together-store.svelte.ts
new file mode 100644
index 00000000..276cf397
--- /dev/null
+++ b/src/lib/study-music/listen-together-store.svelte.ts
@@ -0,0 +1,425 @@
+import { musicPlayer, type MusicTrack } from "./player-store.svelte";
+
+export type ListenMember = {
+ id: string;
+ name: string;
+ role: "host" | "guest";
+};
+
+type WireMessage =
+ | { type: "welcome"; id: string; role: "host" | "guest"; members: ListenMember[] }
+ | { type: "user_joined"; id: string; name: string; role: "host" | "guest" }
+ | { type: "user_left"; id: string }
+ | { type: "host_changed"; id: string }
+ | { type: "promoted_to_host" }
+ | { type: "sync_request"; from: string }
+ | { type: "state_sync"; track: MusicTrack; time: number; paused: boolean; from?: string; at?: number }
+ | { type: "track_change"; track: MusicTrack; from?: string; at?: number }
+ | { type: "play"; from?: string; at?: number }
+ | { type: "pause"; time?: number; from?: string; at?: number }
+ | { type: "seek"; time: number; from?: string; at?: number }
+ | { type: "chat"; from: string; name: string; text: string; at: number }
+ | { type: "pong"; at: number }
+ | { type: "error"; code: string; message: string };
+
+export type ChatLine = {
+ id: string;
+ name: string;
+ text: string;
+ at: number;
+};
+
+const STORAGE_KEY = "study-music-listen-relay";
+
+class ListenTogetherStore {
+ private ws: WebSocket | null = null;
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
+ private pingTimer: ReturnType<typeof setInterval> | null = null;
+ private intentionalDisconnect = false;
+ private suppressBroadcast = false;
+ private connectionUrl: string | null = null;
+ private playerUnsub: (() => void) | null = null;
+
+ status = $state<"idle" | "connecting" | "connected" | "error">("idle");
+ errorMessage = $state<string | null>(null);
+ selfId = $state<string | null>(null);
+ selfRole = $state<"host" | "guest" | null>(null);
+ roomCode = $state<string | null>(null);
+ displayName = $state("");
+ relayUrl = $state("");
+ members = $state<ListenMember[]>([]);
+ chat = $state<ChatLine[]>([]);
+
+ constructor() {
+ if (typeof window !== "undefined") {
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY);
+ if (raw) {
+ const data = JSON.parse(raw) as { relayUrl?: string; displayName?: string };
+ if (typeof data.relayUrl === "string") this.relayUrl = data.relayUrl;
+ if (typeof data.displayName === "string") this.displayName = data.displayName;
+ }
+ } catch {
+ /* ignore */
+ }
+ }
+ }
+
+ get isHost(): boolean {
+ return this.selfRole === "host";
+ }
+
+ get connected(): boolean {
+ return this.status === "connected";
+ }
+
+ private persist() {
+ try {
+ localStorage.setItem(
+ STORAGE_KEY,
+ JSON.stringify({ relayUrl: this.relayUrl, displayName: this.displayName }),
+ );
+ } catch {
+ /* ignore */
+ }
+ }
+
+ setRelayUrl(url: string) {
+ this.relayUrl = url.trim();
+ this.persist();
+ }
+
+ setDisplayName(name: string) {
+ this.displayName = name.trim().slice(0, 40);
+ this.persist();
+ }
+
+ static randomRoomCode(): string {
+ const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
+ let out = "";
+ const buf = new Uint8Array(6);
+ crypto.getRandomValues(buf);
+ for (let i = 0; i < 6; i++) out += alphabet[buf[i] % alphabet.length];
+ return out;
+ }
+
+ createRoom(code?: string) {
+ const room = (code ?? ListenTogetherStore.randomRoomCode()).toUpperCase();
+ return this.connect(room, "host");
+ }
+
+ joinRoom(code: string) {
+ return this.connect(code.trim().toUpperCase(), "guest");
+ }
+
+ private connect(room: string, role: "host" | "guest") {
+ this.disconnect(true);
+ this.intentionalDisconnect = false;
+ if (!this.relayUrl) {
+ this.status = "error";
+ this.errorMessage = "Relay URL not set";
+ return;
+ }
+ if (!this.displayName) {
+ this.status = "error";
+ this.errorMessage = "Display name required";
+ return;
+ }
+ this.status = "connecting";
+ this.errorMessage = null;
+ const base = this.relayUrl.replace(/\/+$/, "");
+ const sep = base.includes("?") ? "&" : "?";
+ const url = `${base}${sep}room=${encodeURIComponent(room)}&name=${encodeURIComponent(this.displayName)}&role=${role}`;
+ this.connectionUrl = url;
+ this.openSocket(url, room);
+ }
+
+ private openSocket(url: string, room: string) {
+ try {
+ const ws = new WebSocket(url);
+ this.ws = ws;
+ this.roomCode = room;
+ ws.onopen = () => {
+ this.startPing();
+ this.attachPlayerListener();
+ };
+ ws.onmessage = (event) => {
+ try {
+ const msg = JSON.parse(event.data) as WireMessage;
+ this.handleMessage(msg);
+ } catch {
+ /* ignore malformed */
+ }
+ };
+ ws.onerror = () => {
+ if (this.status !== "connected") {
+ this.status = "error";
+ this.errorMessage = "Failed to reach relay";
+ }
+ };
+ ws.onclose = () => {
+ this.stopPing();
+ if (this.intentionalDisconnect) {
+ this.resetSessionState();
+ this.status = "idle";
+ return;
+ }
+ this.status = "connecting";
+ this.scheduleReconnect();
+ };
+ } catch (e) {
+ this.status = "error";
+ this.errorMessage = e instanceof Error ? e.message : String(e);
+ }
+ }
+
+ private scheduleReconnect() {
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
+ if (!this.connectionUrl || !this.roomCode) return;
+ this.reconnectTimer = setTimeout(() => {
+ this.openSocket(this.connectionUrl!, this.roomCode!);
+ }, 3000);
+ }
+
+ private startPing() {
+ this.stopPing();
+ this.pingTimer = setInterval(() => {
+ if (this.ws?.readyState === 1) {
+ try {
+ this.ws.send(JSON.stringify({ type: "ping" }));
+ } catch {
+ /* ignore */
+ }
+ }
+ }, 25_000);
+ }
+
+ private stopPing() {
+ if (this.pingTimer !== null) {
+ clearInterval(this.pingTimer);
+ this.pingTimer = null;
+ }
+ }
+
+ private resetSessionState() {
+ this.selfId = null;
+ this.selfRole = null;
+ this.roomCode = null;
+ this.members = [];
+ this.chat = [];
+ this.detachPlayerListener();
+ }
+
+ private attachPlayerListener() {
+ if (this.playerUnsub) return;
+ this.playerUnsub = musicPlayer.addBroadcastListener((ev) => {
+ if (this.suppressBroadcast || !this.isHost) return;
+ switch (ev.type) {
+ case "play":
+ this.send({ type: "play" });
+ break;
+ case "pause":
+ this.send({ type: "pause", time: ev.time });
+ break;
+ case "seek":
+ this.send({ type: "seek", time: ev.time });
+ break;
+ case "track-change":
+ this.send({ type: "track_change", track: ev.track });
+ break;
+ }
+ });
+ }
+
+ private detachPlayerListener() {
+ if (this.playerUnsub) {
+ this.playerUnsub();
+ this.playerUnsub = null;
+ }
+ }
+
+ disconnect(keepStatus = false) {
+ this.intentionalDisconnect = true;
+ if (this.reconnectTimer) {
+ clearTimeout(this.reconnectTimer);
+ this.reconnectTimer = null;
+ }
+ this.stopPing();
+ if (this.ws) {
+ try {
+ this.ws.close();
+ } catch {
+ /* ignore */
+ }
+ this.ws = null;
+ }
+ this.connectionUrl = null;
+ if (!keepStatus) {
+ this.resetSessionState();
+ this.status = "idle";
+ }
+ }
+
+ private handleMessage(msg: WireMessage) {
+ switch (msg.type) {
+ case "welcome": {
+ this.selfId = msg.id;
+ this.selfRole = msg.role;
+ this.members = msg.members;
+ this.status = "connected";
+ this.errorMessage = null;
+ break;
+ }
+ case "user_joined": {
+ this.members = [...this.members, { id: msg.id, name: msg.name, role: msg.role }];
+ break;
+ }
+ case "user_left": {
+ this.members = this.members.filter((m) => m.id !== msg.id);
+ break;
+ }
+ case "host_changed": {
+ this.members = this.members.map((m) => ({
+ ...m,
+ role: m.id === msg.id ? "host" : "guest",
+ }));
+ if (this.selfId === msg.id) this.selfRole = "host";
+ break;
+ }
+ case "promoted_to_host": {
+ this.selfRole = "host";
+ break;
+ }
+ case "sync_request": {
+ if (this.isHost) this.broadcastFullState();
+ break;
+ }
+ case "state_sync": {
+ if (!this.isHost) this.applyState(msg);
+ break;
+ }
+ case "track_change": {
+ if (!this.isHost && msg.track) this.applyTrack(msg.track);
+ break;
+ }
+ case "play": {
+ if (!this.isHost) {
+ this.suppressBroadcast = true;
+ try {
+ if (musicPlayer.currentTrack) {
+ musicPlayer.resume();
+ }
+ } finally {
+ queueMicrotask(() => {
+ this.suppressBroadcast = false;
+ });
+ }
+ }
+ break;
+ }
+ case "pause": {
+ if (!this.isHost) {
+ this.suppressBroadcast = true;
+ try {
+ musicPlayer.pause();
+ if (typeof msg.time === "number") {
+ musicPlayer.seek(msg.time);
+ }
+ } finally {
+ queueMicrotask(() => {
+ this.suppressBroadcast = false;
+ });
+ }
+ }
+ break;
+ }
+ case "seek": {
+ if (!this.isHost && typeof msg.time === "number") {
+ this.suppressBroadcast = true;
+ try {
+ musicPlayer.seek(msg.time);
+ } finally {
+ queueMicrotask(() => {
+ this.suppressBroadcast = false;
+ });
+ }
+ }
+ break;
+ }
+ case "chat": {
+ this.chat = [
+ ...this.chat,
+ { id: msg.from, name: msg.name, text: msg.text, at: msg.at },
+ ].slice(-50);
+ break;
+ }
+ case "error": {
+ this.status = "error";
+ this.errorMessage = `${msg.code}: ${msg.message}`;
+ this.intentionalDisconnect = true;
+ break;
+ }
+ case "pong":
+ break;
+ }
+ }
+
+ private applyState(msg: { track: MusicTrack; time: number; paused: boolean; at?: number }) {
+ const drift = msg.at ? (Date.now() - msg.at) / 1000 : 0;
+ const targetTime = msg.time + (msg.paused ? 0 : drift);
+ this.suppressBroadcast = true;
+ try {
+ if (
+ !musicPlayer.currentTrack ||
+ musicPlayer.currentTrack.id !== msg.track.id
+ ) {
+ void musicPlayer.play(msg.track);
+ }
+ musicPlayer.seek(Math.max(0, targetTime));
+ if (msg.paused) musicPlayer.pause();
+ else musicPlayer.resume();
+ } finally {
+ queueMicrotask(() => {
+ this.suppressBroadcast = false;
+ });
+ }
+ }
+
+ private applyTrack(track: MusicTrack) {
+ this.suppressBroadcast = true;
+ try {
+ void musicPlayer.play(track);
+ } finally {
+ queueMicrotask(() => {
+ this.suppressBroadcast = false;
+ });
+ }
+ }
+
+ private send(msg: Record<string, unknown>) {
+ if (!this.ws || this.ws.readyState !== 1) return;
+ try {
+ this.ws.send(JSON.stringify(msg));
+ } catch {
+ /* ignore */
+ }
+ }
+
+ broadcastFullState() {
+ if (!this.isHost || !musicPlayer.currentTrack) return;
+ this.send({
+ type: "state_sync",
+ track: musicPlayer.currentTrack,
+ time: musicPlayer.currentTime,
+ paused: musicPlayer.paused,
+ });
+ }
+
+ sendChat(text: string) {
+ const trimmed = text.trim();
+ if (!trimmed) return;
+ this.send({ type: "chat", text: trimmed.slice(0, 500) });
+ }
+}
+
+export const listenTogether = new ListenTogetherStore();
diff --git a/src/lib/study-music/player-store.svelte.ts b/src/lib/study-music/player-store.svelte.ts
index d523adbd..97de6a69 100644
--- a/src/lib/study-music/player-store.svelte.ts
+++ b/src/lib/study-music/player-store.svelte.ts
@@ -6,6 +6,12 @@ import { attachHls, type HlsHandle } from "./hls-loader.svelte";
export type TrackSource = "local" | "spotify" | "youtube" | "soundcloud";
+export type PlayerBroadcastEvent =
+ | { type: "track-change"; track: MusicTrack }
+ | { type: "play" }
+ | { type: "pause"; time: number }
+ | { type: "seek"; time: number };
+
export type MusicTrack = {
id: number;
path: string;
@@ -308,6 +314,39 @@ class MusicPlayerStore {
youtubeSponsorBlockSegments = $state<import("$lib/study-bridge").SponsorBlockSegment[]>([]);
private mediaSessionInstalled = false;
+ private broadcastListeners = new Set<(ev: PlayerBroadcastEvent) => void>();
+
+ addBroadcastListener(cb: (ev: PlayerBroadcastEvent) => void): () => void {
+ this.broadcastListeners.add(cb);
+ return () => {
+ this.broadcastListeners.delete(cb);
+ };
+ }
+
+ private fireBroadcast(ev: PlayerBroadcastEvent) {
+ for (const cb of this.broadcastListeners) {
+ try {
+ cb(ev);
+ } catch {
+ /* listener errors must not break playback */
+ }
+ }
+ }
+
+ sleepTimerEndsAt = $state<number | null>(null);
+ sleepTimerEndOfTrack = $state(false);
+ private sleepFadeStarted = false;
+ private sleepBaseVolume = 1;
+ crossfadeSec = $state(0);
+ private crossfadeStarted = false;
+ private crossfadeBaseVolume = 1;
+ normalizationEnabled = $state(false);
+ private normalizationGain: GainNode | null = null;
+ skipSilenceEnabled = $state(false);
+ private silenceAnalyser: AnalyserNode | null = null;
+ private silenceCheckHandle: ReturnType<typeof setInterval> | null = null;
+ private silenceStartedAt: number | null = null;
+
init() {
if (this.audio || typeof window === "undefined") return;
const audio = new Audio();
@@ -340,12 +379,15 @@ class MusicPlayerStore {
this.currentTime = audio.currentTime;
this.scheduleQueueSave();
this.updateMediaSessionPosition();
+ this.tickSleepTimer();
+ this.tickCrossfade();
});
audio.addEventListener("loadedmetadata", () => {
this.duration = audio.duration || 0;
this.ready = true;
this.loading = false;
this.updateMediaSessionPosition();
+ this.applyNormalizationGain();
});
audio.addEventListener("loadstart", () => {
this.loading = true;
@@ -402,6 +444,10 @@ class MusicPlayerStore {
eqEnabled?: boolean;
eqGains?: number[];
eqPreset?: EqPreset;
+ crossfadeSec?: number;
+ sleepEndOfTrack?: boolean;
+ normalizationEnabled?: boolean;
+ skipSilenceEnabled?: boolean;
};
if (typeof data.volume === "number") {
audio.volume = Math.min(1, Math.max(0, data.volume));
@@ -420,6 +466,18 @@ class MusicPlayerStore {
if (data.eqPreset && data.eqPreset in EQ_PRESETS) {
this.eqPreset = data.eqPreset;
}
+ if (typeof data.crossfadeSec === "number") {
+ this.crossfadeSec = Math.max(0, Math.min(12, data.crossfadeSec));
+ }
+ if (typeof data.sleepEndOfTrack === "boolean") {
+ this.sleepTimerEndOfTrack = data.sleepEndOfTrack;
+ }
+ if (typeof data.normalizationEnabled === "boolean") {
+ this.normalizationEnabled = data.normalizationEnabled;
+ }
+ if (typeof data.skipSilenceEnabled === "boolean") {
+ this.skipSilenceEnabled = data.skipSilenceEnabled;
+ }
}
} catch {
/* ignore */
@@ -1167,23 +1225,116 @@ class MusicPlayerStore {
});
const out = ctx.createGain();
out.gain.value = 1;
+ const norm = ctx.createGain();
+ norm.gain.value = 1;
+ const analyser = ctx.createAnalyser();
+ analyser.fftSize = 2048;
+ analyser.smoothingTimeConstant = 0.85;
let node: AudioNode = source;
for (const f of filters) {
node.connect(f);
node = f;
}
node.connect(out);
- out.connect(ctx.destination);
+ out.connect(norm);
+ norm.connect(analyser);
+ analyser.connect(ctx.destination);
this.eqContext = ctx;
this.eqSource = source;
this.eqFilters = filters;
this.eqGainNode = out;
+ this.normalizationGain = norm;
+ this.silenceAnalyser = analyser;
this.applyEq();
+ this.applyNormalizationGain();
+ this.maybeStartSilenceWatcher();
} catch {
/* ignore — EQ optional */
}
}
+ private applyNormalizationGain() {
+ if (!this.normalizationGain) return;
+ if (!this.normalizationEnabled) {
+ this.normalizationGain.gain.value = 1;
+ return;
+ }
+ const ld = (this.currentTrack as unknown as { loudness_db?: number } | null)
+ ?.loudness_db;
+ if (typeof ld === "number" && Number.isFinite(ld)) {
+ const target = -14;
+ const factor = Math.pow(10, (target - ld) / 20);
+ this.normalizationGain.gain.value = Math.max(0.3, Math.min(3, factor));
+ } else {
+ this.normalizationGain.gain.value = 1;
+ }
+ }
+
+ setNormalization(enabled: boolean) {
+ this.normalizationEnabled = enabled;
+ this.ensureEqGraph();
+ this.applyNormalizationGain();
+ this.persistPlayerSettings();
+ }
+
+ setSkipSilence(enabled: boolean) {
+ this.skipSilenceEnabled = enabled;
+ this.ensureEqGraph();
+ this.maybeStartSilenceWatcher();
+ this.persistPlayerSettings();
+ }
+
+ private maybeStartSilenceWatcher() {
+ if (!this.skipSilenceEnabled || !this.silenceAnalyser) {
+ if (this.silenceCheckHandle !== null) {
+ clearInterval(this.silenceCheckHandle);
+ this.silenceCheckHandle = null;
+ this.silenceStartedAt = null;
+ }
+ return;
+ }
+ if (this.silenceCheckHandle !== null) return;
+ const analyser = this.silenceAnalyser;
+ const buf = new Float32Array(analyser.fftSize);
+ const SILENCE_RMS_THRESHOLD = 0.01;
+ const SILENCE_HOLD_MS = 1500;
+ let lastSkipAt = 0;
+ this.silenceCheckHandle = setInterval(() => {
+ if (!this.audio || this.audio.paused) {
+ this.silenceStartedAt = null;
+ return;
+ }
+ analyser.getFloatTimeDomainData(buf);
+ let sumSq = 0;
+ for (let i = 0; i < buf.length; i++) sumSq += buf[i] * buf[i];
+ const rms = Math.sqrt(sumSq / buf.length);
+ const now = Date.now();
+ if (rms < SILENCE_RMS_THRESHOLD) {
+ if (this.silenceStartedAt === null) {
+ this.silenceStartedAt = now;
+ } else if (
+ now - this.silenceStartedAt >= SILENCE_HOLD_MS &&
+ now - lastSkipAt >= 10_000 &&
+ this.audio.duration > 0 &&
+ this.audio.currentTime + 3 < this.audio.duration
+ ) {
+ try {
+ this.audio.currentTime = Math.min(
+ this.audio.currentTime + 3,
+ this.audio.duration - 1,
+ );
+ lastSkipAt = now;
+ this.silenceStartedAt = null;
+ } catch {
+ /* ignore */
+ }
+ }
+ } else {
+ this.silenceStartedAt = null;
+ }
+ }, 300);
+ }
+
private applyEq() {
if (this.eqFilters.length !== 5) return;
const gains = this.eqEnabled ? this.eqGains : [0, 0, 0, 0, 0];
@@ -1251,6 +1402,7 @@ class MusicPlayerStore {
this.lastError = null;
this.status = "resolving";
this.loading = true;
+ this.fireBroadcast({ type: "track-change", track });
this.ready = false;
this.currentTime = 0;
this.duration = (track.duration_ms ?? 0) / 1000;
@@ -1655,21 +1807,26 @@ class MusicPlayerStore {
}
pause() {
+ const time = this.currentTime;
if (this.isSpotify()) {
void spotifySdk.pause();
+ this.fireBroadcast({ type: "pause", time });
return;
}
if (this.audio && !this.paused) this.audio.pause();
+ this.fireBroadcast({ type: "pause", time });
}
resume() {
if (this.isSpotify()) {
void spotifySdk.resume();
+ this.fireBroadcast({ type: "play" });
return;
}
if (this.audio && this.paused && this.currentTrack) {
this.audio.play().catch(() => {});
this.ensureEqGraph();
+ this.fireBroadcast({ type: "play" });
}
}
@@ -1731,13 +1888,16 @@ class MusicPlayerStore {
this.updateMediaSessionPosition();
void spotifySdk.seek(ms);
void this.fireRpcUpdate();
+ this.fireBroadcast({ type: "seek", time: target });
return;
}
if (!this.audio) return;
const dur = this.audio.duration || this.duration;
if (!Number.isFinite(dur) || dur <= 0) return;
- this.audio.currentTime = Math.max(0, Math.min(dur, seconds));
+ const target = Math.max(0, Math.min(dur, seconds));
+ this.audio.currentTime = target;
void this.fireRpcUpdate();
+ this.fireBroadcast({ type: "seek", time: target });
}
seekRatio(ratio: number) {
@@ -1809,6 +1969,12 @@ class MusicPlayerStore {
private handleEnded() {
void this.flushPlayReport();
+ if (this.sleepTimerEndOfTrack) {
+ this.sleepTimerEndOfTrack = false;
+ this.audio?.pause();
+ this.persistPlayerSettings();
+ return;
+ }
if (this.repeat === "one" && this.audio) {
this.audio.currentTime = 0;
this.audio.play().catch(() => {});
@@ -1817,6 +1983,104 @@ class MusicPlayerStore {
this.next();
}
+ setSleepTimerMinutes(minutes: number | null) {
+ if (minutes === null || minutes <= 0) {
+ this.sleepTimerEndsAt = null;
+ this.sleepFadeStarted = false;
+ if (this.audio && this.sleepBaseVolume > 0) {
+ this.audio.volume = this.sleepBaseVolume;
+ }
+ } else {
+ this.sleepTimerEndsAt = Date.now() + minutes * 60_000;
+ this.sleepBaseVolume = this.audio?.volume ?? 1;
+ this.sleepFadeStarted = false;
+ }
+ this.persistPlayerSettings();
+ }
+
+ setSleepEndOfTrack(enabled: boolean) {
+ this.sleepTimerEndOfTrack = enabled;
+ if (enabled) {
+ this.sleepTimerEndsAt = null;
+ }
+ this.persistPlayerSettings();
+ }
+
+ cancelSleepTimer() {
+ this.sleepTimerEndsAt = null;
+ this.sleepTimerEndOfTrack = false;
+ this.sleepFadeStarted = false;
+ if (this.audio && this.sleepBaseVolume > 0) {
+ this.audio.volume = this.sleepBaseVolume;
+ }
+ this.persistPlayerSettings();
+ }
+
+ setCrossfade(seconds: number) {
+ this.crossfadeSec = Math.max(0, Math.min(12, seconds));
+ this.persistPlayerSettings();
+ }
+
+ private tickSleepTimer() {
+ if (!this.audio) return;
+ if (this.sleepTimerEndsAt === null) return;
+ const remaining = this.sleepTimerEndsAt - Date.now();
+ const FADE_MS = 10_000;
+ if (remaining <= 0) {
+ this.audio.pause();
+ this.audio.volume = this.sleepBaseVolume;
+ this.sleepTimerEndsAt = null;
+ this.sleepFadeStarted = false;
+ this.persistPlayerSettings();
+ return;
+ }
+ if (remaining <= FADE_MS) {
+ if (!this.sleepFadeStarted) {
+ this.sleepFadeStarted = true;
+ this.sleepBaseVolume = this.audio.volume || 1;
+ }
+ const factor = Math.max(0, remaining / FADE_MS);
+ this.audio.volume = this.sleepBaseVolume * factor;
+ }
+ }
+
+ private tickCrossfade() {
+ if (!this.audio) return;
+ if (this.crossfadeSec <= 0 || this.duration <= 0) {
+ if (this.crossfadeStarted && this.crossfadeBaseVolume > 0) {
+ this.audio.volume = this.crossfadeBaseVolume;
+ this.crossfadeStarted = false;
+ }
+ return;
+ }
+ const remaining = this.duration - this.currentTime;
+ if (remaining <= this.crossfadeSec && remaining > 0) {
+ if (!this.crossfadeStarted) {
+ this.crossfadeStarted = true;
+ this.crossfadeBaseVolume = this.audio.volume || 1;
+ }
+ const factor = Math.max(0, remaining / this.crossfadeSec);
+ this.audio.volume = this.crossfadeBaseVolume * factor;
+ } else if (this.crossfadeStarted) {
+ this.audio.volume = this.crossfadeBaseVolume;
+ this.crossfadeStarted = false;
+ }
+ }
+
+ private persistPlayerSettings() {
+ try {
+ const raw = localStorage.getItem(PERSIST_KEY);
+ const data = raw ? JSON.parse(raw) : {};
+ data.crossfadeSec = this.crossfadeSec;
+ data.sleepEndOfTrack = this.sleepTimerEndOfTrack;
+ data.normalizationEnabled = this.normalizationEnabled;
+ data.skipSilenceEnabled = this.skipSilenceEnabled;
+ localStorage.setItem(PERSIST_KEY, JSON.stringify(data));
+ } catch {
+ /* ignore */
+ }
+ }
+
private async flushPlayReport() {
const track_id = this.lastReportTrackId;
if (!track_id) return;
diff --git a/src/lib/study-music/soundcloud-store.svelte.ts b/src/lib/study-music/soundcloud-store.svelte.ts
index 3cf84181..c7cda506 100644
--- a/src/lib/study-music/soundcloud-store.svelte.ts
+++ b/src/lib/study-music/soundcloud-store.svelte.ts
@@ -165,8 +165,15 @@ class SoundCloudStore {
async refreshStatus() {
try {
- const s = await pluginInvoke<AuthStatus>("study", "study:soundcloud:auth:refresh");
+ let s = await pluginInvoke<AuthStatus>("study", "study:soundcloud:auth:refresh");
this.status = s;
+ if (!s.has_oauth) {
+ const hydrated = await this.tryHydrateFromCookieManager();
+ if (hydrated) {
+ s = await pluginInvoke<AuthStatus>("study", "study:soundcloud:auth:refresh");
+ this.status = s;
+ }
+ }
if (s.has_oauth && s.user_id == null) {
try {
const me = await pluginInvoke<any>("study", "study:soundcloud:me");
@@ -188,6 +195,29 @@ class SoundCloudStore {
}
}
+ async tryHydrateFromCookieManager(): Promise<boolean> {
+ try {
+ const { invoke } = await import("@tauri-apps/api/core");
+ const accounts = await invoke<{ domain: string; accounts: { slug: string }[] }>(
+ "cookies_accounts_for_url",
+ { url: "https://soundcloud.com/" }
+ );
+ if (!accounts.accounts.length) return false;
+ const slug = accounts.accounts[0].slug;
+ const cookies = await invoke<
+ { name: string; value: string; domain: string; path: string }[]
+ >("cookies_read_as_json", { request: { domain: accounts.domain, slug } });
+ if (!cookies.length) return false;
+ await pluginInvoke("study", "study:soundcloud:auth:set_cookies", {
+ cookies_json: JSON.stringify(cookies),
+ });
+ return true;
+ } catch (e) {
+ console.warn("[soundcloud] hydrate from cookie manager failed:", e);
+ return false;
+ }
+ }
+
async logout() {
try {
await pluginInvoke("study", "study:soundcloud:auth:logout");
diff --git a/src/lib/study-music/ui-store.svelte.ts b/src/lib/study-music/ui-store.svelte.ts
index 6c709e49..4877b261 100644
--- a/src/lib/study-music/ui-store.svelte.ts
+++ b/src/lib/study-music/ui-store.svelte.ts
@@ -74,6 +74,20 @@ class MusicUI {
closeEqualizer() {
this.equalizerOpen = false;
}
+ sleepTimerOpen = $state(false);
+ toggleSleepTimer() {
+ this.sleepTimerOpen = !this.sleepTimerOpen;
+ }
+ closeSleepTimer() {
+ this.sleepTimerOpen = false;
+ }
+ listenTogetherOpen = $state(false);
+ toggleListenTogether() {
+ this.listenTogetherOpen = !this.listenTogetherOpen;
+ }
+ closeListenTogether() {
+ this.listenTogetherOpen = false;
+ }
openLastFm() {
this.lastfmOpen = true;
}