|
| 1 | +package gent.zeus.guitar.ext.playerstate |
| 2 | + |
| 3 | +import gent.zeus.guitar.DataResult |
| 4 | +import gent.zeus.guitar.EmptyPlayerStateError |
| 5 | +import gent.zeus.guitar.PlayerState |
| 6 | +import gent.zeus.guitar.ServerError |
| 7 | +import gent.zeus.guitar.UserError |
| 8 | +import gent.zeus.guitar.data.Track |
| 9 | +import gent.zeus.guitar.ext.ModelFiller |
| 10 | +import gent.zeus.guitar.ext.OrderingError |
| 11 | +import kotlinx.coroutines.runBlocking |
| 12 | +import kotlinx.coroutines.sync.withLock |
| 13 | +import org.apache.catalina.Server |
| 14 | + |
| 15 | +class PlayerStateFetcher : ModelFiller<Track> { |
| 16 | + override fun fetchInto(musicModel: Track): DataResult<Track> = runBlocking { |
| 17 | + musicModel.durationInMs |
| 18 | + ?: return@runBlocking DataResult.Error(OrderingError("durationInMs")) |
| 19 | + |
| 20 | + val id = PlayerState.mutex.withLock { PlayerState.currentTrackId } |
| 21 | + ?: return@runBlocking DataResult.Error(EmptyPlayerStateError()) |
| 22 | + |
| 23 | + if (id != musicModel.spotifyId) DataResult.Error(NotCurrentTrackError()) |
| 24 | + |
| 25 | + val startedAt = PlayerState.mutex.withLock { PlayerState.currentStartTime } |
| 26 | + ?: return@runBlocking DataResult.Error(EmptyPlayerStateError()) |
| 27 | + |
| 28 | + DataResult.Ok( |
| 29 | + musicModel.copy( |
| 30 | + startedAtMs = startedAt, |
| 31 | + endsAtMs = startedAt + musicModel.durationInMs |
| 32 | + ) |
| 33 | + ) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +class NotCurrentTrackError : ServerError( |
| 38 | + "this is not the current track", |
| 39 | + null, |
| 40 | +) |
0 commit comments