Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions packages/common/src/services/audius-backend/AudiusBackend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ import {
PushNotificationSetting,
PushNotifications
} from '../../store'
import type {
PlaybackDeviceType,
PlaybackSnapshot,
RemotePlaybackState
} from '../../store/playback/snapshot'
import { getErrorMessage, Maybe, Nullable } from '../../utils'
import type { LocalStorage } from '../auth/hedgehogLib'

Expand Down Expand Up @@ -408,6 +413,113 @@ export const audiusBackend = ({
}
}

// Playback state is published every few seconds while listening, so reuse
// one signature per user for a while instead of signing every request.
const PLAYBACK_STATE_SIGNATURE_TTL_MS = 60 * 60 * 1000
let playbackStateSignature: {
userId: number
signedAt: number
data: string
signature: string
} | null = null

async function signPlaybackStateRequest({
sdk,
userId
}: {
sdk: AudiusSdkWithServices
userId: number
}) {
const cached = playbackStateSignature
if (
cached &&
cached.userId === userId &&
Date.now() - cached.signedAt < PLAYBACK_STATE_SIGNATURE_TTL_MS
) {
return cached
}
const { data, signature } = await signAPIRequest({ sdk })
if (signature) {
playbackStateSignature = { userId, signedAt: Date.now(), data, signature }
}
return { data, signature }
}

/**
* Cross-device playback sync: reads the latest playback snapshot any of the
* user's devices published. Resolves null when there is none; throws on
* network / server errors so callers can tell "nothing saved" from "failed".
*/
async function getPlaybackState({
sdk,
userId
}: {
sdk: AudiusSdkWithServices
userId: number
}): Promise<RemotePlaybackState | null> {
const { data, signature } = await signPlaybackStateRequest({ sdk, userId })
const encodedUserId = encodeHashId(userId)
if (!signature || !encodedUserId) return null
const base = env.API_URL.replace(/\/$/, '')
const res = await fetch(
`${base}/v1/users/${encodedUserId}/playback-state?user_id=${encodedUserId}`,
{
headers: {
[AuthHeaders.Message]: data,
[AuthHeaders.Signature]: signature
}
}
)
if (!res.ok) throw new Error(`getPlaybackState failed: ${res.status}`)
const json = await res.json()
return (json?.data as RemotePlaybackState | null) ?? null
}

/**
* Cross-device playback sync: publishes this device's playback snapshot.
* Resolves with the server's envelope (new version) or throws.
*/
async function putPlaybackState({
sdk,
userId,
deviceId,
deviceName,
deviceType,
state
}: {
sdk: AudiusSdkWithServices
userId: number
deviceId: string
deviceName?: string
deviceType?: PlaybackDeviceType
state: PlaybackSnapshot
}): Promise<RemotePlaybackState | null> {
const { data, signature } = await signPlaybackStateRequest({ sdk, userId })
const encodedUserId = encodeHashId(userId)
if (!signature || !encodedUserId) return null
const base = env.API_URL.replace(/\/$/, '')
const res = await fetch(
`${base}/v1/users/${encodedUserId}/playback-state?user_id=${encodedUserId}`,
{
method: 'PUT',
headers: {
'Content-Type': 'application/json',
[AuthHeaders.Message]: data,
[AuthHeaders.Signature]: signature
},
body: JSON.stringify({
device_id: deviceId,
device_name: deviceName,
device_type: deviceType,
state
})
}
)
if (!res.ok) throw new Error(`putPlaybackState failed: ${res.status}`)
const json = await res.json()
return (json?.data as RemotePlaybackState | null) ?? null
}

async function signAPIRequest({
sdk,
input
Expand Down Expand Up @@ -827,6 +939,8 @@ export const audiusBackend = ({
getWAudioBalance,
identityServiceUrl,
pingActivity,
getPlaybackState,
putPlaybackState,
registerDeviceToken,
reportNotificationCampaignPushOpen,
sendTokens,
Expand Down
9 changes: 6 additions & 3 deletions packages/common/src/services/remote-config/feature-flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ export enum FeatureFlags {
TRACK_FEEDBACK_REQUESTS = 'track_feedback_requests',
GROUP_MESSAGES = 'group_messages',
DASHBOARD_TOP_CITIES = 'dashboard_top_cities',
TRENDING_GENRE_NOTIFICATION = 'trending_genre_notification'
TRENDING_GENRE_NOTIFICATION = 'trending_genre_notification',
PLAYBACK_STATE_SYNC = 'playback_state_sync'
}

type FlagDefaults = Record<FeatureFlags, boolean>
Expand All @@ -35,7 +36,8 @@ export const environmentFlagDefaults: Record<
[FeatureFlags.TRACK_FEEDBACK_REQUESTS]: true,
[FeatureFlags.GROUP_MESSAGES]: true,
[FeatureFlags.DASHBOARD_TOP_CITIES]: true,
[FeatureFlags.TRENDING_GENRE_NOTIFICATION]: true
[FeatureFlags.TRENDING_GENRE_NOTIFICATION]: true,
[FeatureFlags.PLAYBACK_STATE_SYNC]: true
},
production: {}
}
Expand All @@ -57,5 +59,6 @@ export const flagDefaults: FlagDefaults = {
[FeatureFlags.TRACK_FEEDBACK_REQUESTS]: false,
[FeatureFlags.GROUP_MESSAGES]: false,
[FeatureFlags.DASHBOARD_TOP_CITIES]: false,
[FeatureFlags.TRENDING_GENRE_NOTIFICATION]: false
[FeatureFlags.TRENDING_GENRE_NOTIFICATION]: false,
[FeatureFlags.PLAYBACK_STATE_SYNC]: false
}
1 change: 1 addition & 0 deletions packages/common/src/store/playback/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ export {
export * as playbackSelectors from './selectors'
export * from './types'
export { calculatePlayerBehavior } from './utils'
export * from './snapshot'
1 change: 1 addition & 0 deletions packages/common/src/store/playback/selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export const getRetries = getPlaybackRetryCount

export const getRepeat = (state: CommonState) => state.playback.repeat
export const getShuffle = (state: CommonState) => state.playback.shuffle
export const getResume = (state: CommonState) => state.playback.resume
export const getOvershot = (state: CommonState) => state.playback.overshot
export const getUndershot = (state: CommonState) => state.playback.undershot

Expand Down
82 changes: 80 additions & 2 deletions packages/common/src/store/playback/slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ export const initialState: PlaybackState = {
querySource: null,
retries: 0,
overshot: false,
undershot: false
undershot: false,
resume: null
}

const buildShufflePermutation = (length: number, currentIndex: number) => {
Expand Down Expand Up @@ -144,6 +145,18 @@ type ErrorPayload = {

type SetRetriesPayload = { retries: number }

export type HydratePayload = {
queue: PlaybackTrack[]
index: number
repeat: RepeatMode
shuffle: boolean
shuffleOriginalQueue: PlaybackTrack[]
shuffleOriginalIndices: number[]
playbackRate?: PlaybackRate
/** Where in the current track to pick up, in seconds */
seconds: number
}

type QueueAutoplayPayload = {
genre: string
exclusionList: number[]
Expand Down Expand Up @@ -386,6 +399,7 @@ const slice = createSlice({
seekTo: (state, action: PayloadAction<SeekPayload>) => {
state.seek = action.payload.seconds
state.seekCounter += 1
if (state.resume) state.resume.seconds = action.payload.seconds
},

setPlaybackRate: (state, action: PayloadAction<SetPlaybackRatePayload>) => {
Expand Down Expand Up @@ -440,6 +454,7 @@ const slice = createSlice({

playSucceeded: (state, action: PayloadAction<PlaySucceededPayload>) => {
state.playing = true
state.resume = null
const payload = action.payload ?? {}
if (typeof payload.index === 'number') state.playingIndex = payload.index
if (payload.trackId) state.playingTrackId = payload.trackId
Expand Down Expand Up @@ -469,6 +484,48 @@ const slice = createSlice({
state.previewing = false
},

/**
* Restores a queue published by another session, cued up but paused.
* Deliberately does not bump `counter` or touch `playing`: nothing is
* loaded into the audio engine until the user presses play, at which
* point the play saga consumes `resume`.
*/
hydrate: (state, action: PayloadAction<HydratePayload>) => {
const {
queue,
index,
repeat,
shuffle,
shuffleOriginalQueue,
shuffleOriginalIndices,
playbackRate,
seconds
} = action.payload
const current = queue[index]
if (!current) return
state.queue = queue
state.index = index
state.playingIndex = index
state.playingTrackId = current.trackId
state.playing = false
state.buffering = false
state.previewing = false
state.repeat = repeat
state.shuffle = shuffle
state.shuffleOriginalQueue = shuffleOriginalQueue
state.shuffleOriginalIndices = shuffleOriginalIndices
if (playbackRate) state.playbackRate = playbackRate
state.querySource = null
state.seek = null
state.retries = 0
state.overshot = false
state.undershot = false
state.resume = { trackId: current.trackId, seconds: Math.max(0, seconds) }
},

/** Ask the sync saga to re-check the server (app foreground / tab focus). */
requestSync: (_state) => {},

setRetries: (state, action: PayloadAction<SetRetriesPayload>) => {
state.retries = action.payload.retries
},
Expand Down Expand Up @@ -510,11 +567,32 @@ export const {
setIndex,
reset,
resetSucceeded,
hydrate,
requestSync,
setRetries,
incrementCounter,
error,
queueAutoplay
} = slice.actions

export default slice.reducer
/**
* A pending `resume` only makes sense while the hydrated track is still the
* one cued up. Anything that starts a new play cycle (bumps `counter`), moves
* the queue index, or changes which track is "playing" invalidates it.
*/
const reducer: typeof slice.reducer = (state, action) => {
const next = slice.reducer(state, action)
if (
state?.resume &&
next.resume === state.resume &&
(next.counter !== state.counter ||
next.index !== state.index ||
next.playingTrackId !== state.playingTrackId)
) {
return { ...next, resume: null }
}
return next
}

export default reducer
export const actions = slice.actions
Loading
Loading