Skip to content
Merged
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
2 changes: 1 addition & 1 deletion app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ plugins {
}

// The release workflow reads this line: "x.y.z-beta.n" is published from the beta branch, "x.y.z" from main.
val appVersion = "0.9.0-beta.2"
val appVersion = "0.9.0-beta.3"

// The version code follows from the name, so each release installs over the one before, and a beta sits under the
// stable release that ends it: 0.3.0-beta.2 is 30002 and 0.3.0 is 30099.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import androidx.compose.ui.test.pressKey
import androidx.compose.ui.test.requestFocus
import org.junit.Rule
import org.junit.Test
import video.typetype.tv.ui.auth.TvTextField
import video.typetype.tv.ui.components.TvTextField

class TvTextFieldFocusTest {
@get:Rule
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import org.junit.Rule
import org.junit.Test
import video.typetype.tv.ui.auth.TvTextField
import video.typetype.tv.ui.components.TvTextField

class TvTextFieldLabelTest {
@get:Rule
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/java/video/typetype/tv/AppContainer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class AppContainer(context: Context) {
return SignedInServices(
repository(backend, profile, userSettings, access),
playback(backend, access),
RemoteControlLink(backend.api.remote),
RemoteControlLink(backend.api.remote, remoteIdentity.status),
)
}

Expand Down
1 change: 0 additions & 1 deletion app/src/main/java/video/typetype/tv/ui/ScreensaverHost.kt
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ fun ScreensaverHost(
LaunchedEffect(startRequests) {
if (startRequests > 0) showing = true
}
// The phone remote's wake button: like a key, it only wakes the screen.
LaunchedEffect(wakeRequests) {
if (wakeRequests > 0 && showing) {
showing = false
Expand Down
19 changes: 14 additions & 5 deletions app/src/main/java/video/typetype/tv/ui/remote/RemoteControlHost.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package video.typetype.tv.ui.remote

import android.app.Activity
import android.media.AudioManager
import android.view.KeyEvent
import androidx.activity.compose.LocalActivity
import androidx.compose.runtime.Composable
Expand All @@ -21,8 +22,6 @@ private const val STATE_REFRESH_MILLIS = 5_000L
private const val PLAYING_REFRESH_MILLIS = 2_000L
private const val JUMP_MILLIS = 1_500L

// Keeps this TV reachable from the phones of the account: it applies their commands and tells them what shows. Keys
// are replayed into the activity as if they came from the remote in the hand, so focus and Back behave as usual.
@Composable
fun RemoteControlHost(
link: RemoteControlLink,
Expand All @@ -44,7 +43,13 @@ fun RemoteControlHost(
is RemoteCommand.Seek -> playback.current?.seekTo(command.positionMs)
is RemoteCommand.Skip -> playback.current?.skip(command.deltaMs)
is RemoteCommand.Open -> routes.open(command.url)
is RemoteCommand.Press -> if (command.key == RemoteKey.Home) routes.home() else activity?.press(command.key)
is RemoteCommand.Press -> when (command.key) {
RemoteKey.Home -> routes.home()
RemoteKey.VolumeUp -> activity?.adjustVolume(AudioManager.ADJUST_RAISE)
RemoteKey.VolumeDown -> activity?.adjustVolume(AudioManager.ADJUST_LOWER)
RemoteKey.Mute -> activity?.adjustVolume(AudioManager.ADJUST_TOGGLE_MUTE)
else -> activity?.press(command.key)
}
is RemoteCommand.Type -> routes.search(command.text)
is RemoteCommand.Rename -> identity.rename(command.name)
}
Expand All @@ -64,7 +69,6 @@ fun RemoteControlHost(
durationMs = player?.durationMs ?: 0L,
playing = player?.playing ?: false,
)
// A seek or a skip is a change too: the position is not where the last state let the phone expect it.
val expected = last?.let { it.positionMs + if (it.playing) now - sentAt else 0L } ?: 0L
val jumped = abs(state.positionMs - expected) > JUMP_MILLIS
val changed = jumped || state.copy(positionMs = 0) != last?.copy(positionMs = 0)
Expand All @@ -87,8 +91,13 @@ private fun Activity.press(key: RemoteKey) {
RemoteKey.Right -> KeyEvent.KEYCODE_DPAD_RIGHT
RemoteKey.Ok -> KeyEvent.KEYCODE_DPAD_CENTER
RemoteKey.Back -> KeyEvent.KEYCODE_BACK
RemoteKey.Home -> return
RemoteKey.Home, RemoteKey.VolumeUp, RemoteKey.VolumeDown, RemoteKey.Mute -> return
}
dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, code))
dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, code))
}

private fun Activity.adjustVolume(direction: Int) {
val audio = getSystemService(AudioManager::class.java) ?: return
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, direction, AudioManager.FLAG_SHOW_UI)
}
2 changes: 0 additions & 2 deletions app/src/main/java/video/typetype/tv/ui/remote/RemoteRoutes.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ import video.typetype.tv.navigation.MockNavigator
import video.typetype.tv.navigation.Route
import video.typetype.tv.ui.search.SearchSession

// The phone remote's view of the screens: which one shows (the phone adapts its buttons to it) and the moves it can
// ask for besides keys. Bound by the app root, which owns the navigation.
class RemoteRoutes {
private var navigator by mutableStateOf<MockNavigator?>(null)
private var search: SearchSession? = null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package video.typetype.tv.data
import kotlinx.coroutines.flow.Flow

interface ContentRepository : VideoActivityRepository, PresenceSink, SubscriptionsRepository {
// `refresh` skips the copy kept a short while and asks the server again (the home's Refresh button).
suspend fun home(services: Set<ContentSource> = ContentSource.extractors.toSet(), refresh: Boolean = false): HomeContent

// One of the rows HomeContent.later names, or null when it has nothing for these services.
Expand Down
14 changes: 14 additions & 0 deletions core/data/src/main/java/video/typetype/tv/data/Models.kt
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,20 @@ sealed interface SettingItem {
@StringRes val titleRes: Int,
@StringRes val summaryRes: Int,
) : SettingItem

data class Guide(
override val id: String,
@StringRes val titleRes: Int,
@StringRes val summaryRes: Int,
val text: String,
) : SettingItem

data class Text(
override val id: String,
@StringRes val titleRes: Int,
val value: String,
val maxLength: Int,
) : SettingItem
}

data class BlockedChannel(
Expand Down
17 changes: 14 additions & 3 deletions core/data/src/main/java/video/typetype/tv/data/RemoteControl.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package video.typetype.tv.data

// What a phone of the same account can ask the TV through the instance (the phone remote).
sealed interface RemoteCommand {
data object Play : RemoteCommand
data object Pause : RemoteCommand
Expand All @@ -13,9 +12,21 @@ sealed interface RemoteCommand {
data class Rename(val name: String) : RemoteCommand
}

enum class RemoteKey(val wire: String) { Up("up"), Down("down"), Left("left"), Right("right"), Ok("ok"), Back("back"), Home("home") }
enum class RemoteKey(val wire: String) {
Up("up"),
Down("down"),
Left("left"),
Right("right"),
Ok("ok"),
Back("back"),
Home("home"),
VolumeUp("volume_up"),
VolumeDown("volume_down"),
Mute("mute"),
}

enum class RemoteLinkStatus { Off, Connecting, Connected, Unsupported, Refused }

// The screen the phone adapts its buttons to.
enum class RemoteScreen(val wire: String) {
Home("home"),
Browse("browse"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import java.io.IOException
class RemoteControlRefused(val status: Int) : IOException("Remote control refused with $status")

class RemoteControlApi(private val client: ApiClient) {
// The stream the TV keeps open: the instance lists it to the phones of the account while it lives.
fun commands(deviceId: String, name: String): Flow<SseEvent> = flow {
val request = Request.Builder()
.url(client.url("remote/tv/commands", mapOf("deviceId" to deviceId, "name" to name)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@ package video.typetype.tv.data.device
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import video.typetype.tv.data.RemoteLinkStatus
import video.typetype.tv.data.SettingItem
import video.typetype.tv.data.SettingsGroup
import video.typetype.tv.data.remote.TextProvider
import video.typetype.tv.resources.R
import java.util.UUID

// How the phones of the account know this TV: an id made once for the box, and a name that starts as the box's own
// name and is changed from the phone.
class RemoteIdentity(private val store: DeviceStore, private val defaultName: () -> String) : DeviceSection {
class RemoteIdentity(
private val store: DeviceStore,
val status: MutableStateFlow<RemoteLinkStatus> = MutableStateFlow(RemoteLinkStatus.Off),
private val defaultName: () -> String,
) : DeviceSection {
val deviceId: String = store.text(DEVICE_ID, "").ifEmpty {
"tv-${UUID.randomUUID()}".also { store.putText(DEVICE_ID, it) }
}
Expand All @@ -32,20 +35,39 @@ class RemoteIdentity(private val store: DeviceStore, private val defaultName: ()
id = GROUP,
titleRes = R.string.settings_group_remote,
items = listOf(
SettingItem.Info(NAME, R.string.settings_remote_name, state.value),
SettingItem.Info(HOW, R.string.settings_remote_how, texts.text(R.string.settings_remote_how_value)),
SettingItem.Text(NAME, R.string.settings_remote_name, state.value, MAX_NAME),
SettingItem.Info(STATUS, R.string.settings_remote_status, texts.text(status.value.label())),
SettingItem.Guide(
HOW,
R.string.settings_remote_how,
R.string.settings_remote_how_summary,
texts.text(R.string.settings_remote_how_steps, state.value),
),
),
),
)

override fun update(id: String, value: String): Boolean = false
override fun update(id: String, value: String): Boolean {
if (id != NAME) return false
rename(value)
return true
}

private companion object {
const val GROUP = "remote"
const val BEFORE_GROUP = "account"
const val HOW = "remote-how"
const val STATUS = "remote-status"
const val DEVICE_ID = "remote-device-id"
const val NAME = "remote-name"
const val MAX_NAME = 40
}
}

private fun RemoteLinkStatus.label(): Int = when (this) {
RemoteLinkStatus.Off -> R.string.settings_remote_status_off
RemoteLinkStatus.Connecting -> R.string.settings_remote_status_connecting
RemoteLinkStatus.Connected -> R.string.settings_remote_status_connected
RemoteLinkStatus.Unsupported -> R.string.settings_remote_status_unsupported
RemoteLinkStatus.Refused -> R.string.settings_remote_status_refused
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@ package video.typetype.tv.data.remote

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.serialization.SerializationException
import video.typetype.tv.data.RemoteCommand
import video.typetype.tv.data.RemoteKey
import video.typetype.tv.data.RemoteLinkStatus
import video.typetype.tv.data.RemoteTvState
import video.typetype.tv.data.api.RemoteControlApi
import video.typetype.tv.data.api.RemoteControlRefused
Expand All @@ -16,42 +21,48 @@ import video.typetype.tv.data.net.ApiException
import video.typetype.tv.data.net.ApiJson
import java.io.IOException

// The TV's side of the phone remote: the command stream stays open while it is collected and comes back after a drop
// with backoff; a refusal (another account's limit of TVs, an old server without the remote) waits the longest step.
class RemoteControlLink(
private val api: RemoteControlApi,
private val linkStatus: MutableStateFlow<RemoteLinkStatus> = MutableStateFlow(RemoteLinkStatus.Off),
private val pause: suspend (Long) -> Unit = { delay(it) },
) {
val status: StateFlow<RemoteLinkStatus> = linkStatus.asStateFlow()

fun commands(deviceId: String, name: () -> String): Flow<RemoteCommand> = flow {
var failures = 0
while (true) {
if (linkStatus.value == RemoteLinkStatus.Off) linkStatus.value = RemoteLinkStatus.Connecting
try {
api.commands(deviceId, name()).collect { event ->
when (event.name) {
HELLO -> failures = 0
HELLO -> {
failures = 0
linkStatus.value = RemoteLinkStatus.Connected
}
COMMAND -> decode(event.data)?.let { emit(it) }
}
}
} catch (_: RemoteControlRefused) {
} catch (refused: RemoteControlRefused) {
failures = BACKOFF_MILLIS.lastIndex
linkStatus.value = if (refused.status == NOT_FOUND) RemoteLinkStatus.Unsupported else RemoteLinkStatus.Refused
} catch (_: IOException) {
// A dropped stream: reconnect below.
linkStatus.value = RemoteLinkStatus.Connecting
}
pause(BACKOFF_MILLIS[failures.coerceAtMost(BACKOFF_MILLIS.lastIndex)])
failures++
}
}
}.onCompletion { linkStatus.value = RemoteLinkStatus.Off }

suspend fun publish(deviceId: String, state: RemoteTvState) {
try {
api.publish(state.toDto(deviceId))
} catch (_: ApiException) {
// The stream is not open yet or the server dropped it: the next state goes out after the reconnection.
}
}

companion object {
private const val HELLO = "hello"
private const val NOT_FOUND = 404
private const val COMMAND = "command"
private val BACKOFF_MILLIS = longArrayOf(1_000L, 2_000L, 5_000L, 10_000L, 30_000L, 60_000L)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package video.typetype.tv.data.device

import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import video.typetype.tv.data.SettingItem
import video.typetype.tv.data.remote.TextProvider
import video.typetype.tv.resources.R

class RemoteIdentityTest {
private class MemoryStore : DeviceStore {
Expand All @@ -22,6 +26,9 @@ class RemoteIdentityTest {
}

private val store = MemoryStore()
private val texts = object : TextProvider {
override fun text(id: Int) = ""
}

@Test
fun theIdIsMadeOnceAndKept() {
Expand All @@ -47,4 +54,14 @@ class RemoteIdentityTest {
identity.rename("x".repeat(60))
assertEquals(40, identity.name.value.length)
}

@Test
fun theNameIsASettingTheTvCanChange() {
val identity = RemoteIdentity(store) { "Shield" }
val item = identity.addTo(emptyList(), texts).single().items.first()
assertEquals(SettingItem.Text("remote-name", R.string.settings_remote_name, "Shield", 40), item)
assertTrue(identity.update("remote-name", " Salon "))
assertEquals("Salon", identity.name.value)
assertFalse(identity.update("screensaver-after", "5"))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import org.junit.Before
import org.junit.Test
import video.typetype.tv.data.RemoteCommand
import video.typetype.tv.data.RemoteKey
import video.typetype.tv.data.RemoteLinkStatus
import video.typetype.tv.data.RemoteScreen
import video.typetype.tv.data.RemoteTvState
import video.typetype.tv.data.RemoteVideo
Expand Down Expand Up @@ -62,13 +63,30 @@ class RemoteControlLinkTest {
assertEquals(listOf(60_000L), pauses)
}

@Test
fun theStatusSaysWhetherTheServerHasTheRemote() = runBlocking {
assertEquals(RemoteLinkStatus.Off, link.status.value)
server.enqueue(MockResponse().setResponseCode(404))
server.enqueue(MockResponse().setResponseCode(409))
server.enqueue(stream("event: hello\ndata: {}\n\n" + command("""{"kind":"play"}""")))
val seen = mutableListOf<RemoteLinkStatus>()
link = RemoteControlLink(RemoteControlApi(ApiClient(server.url("/api/"), OkHttpClient(), retry = RetryPolicy.NONE))) {
seen += link.status.value
}
link.commands("tv-1234567890") { "Salon" }.take(1).collect { seen += link.status.value }
assertEquals(listOf(RemoteLinkStatus.Unsupported, RemoteLinkStatus.Refused, RemoteLinkStatus.Connected), seen)
assertEquals(RemoteLinkStatus.Off, link.status.value)
}

@Test
fun onlyKnownCommandsAreKept() {
assertEquals(RemoteCommand.Seek(42_000), RemoteControlLink.decode("""{"kind":"seek","positionMs":42000}"""))
assertEquals(RemoteCommand.Open("https://www.youtube.com/watch?v=x"), RemoteControlLink.decode("""{"kind":"open","url":"https://www.youtube.com/watch?v=x"}"""))
assertEquals(RemoteCommand.Type("lofi"), RemoteControlLink.decode("""{"kind":"text","text":"lofi"}"""))
assertEquals(RemoteCommand.Rename("Chambre"), RemoteControlLink.decode("""{"kind":"rename","name":" Chambre "}"""))
assertEquals(RemoteCommand.Wake, RemoteControlLink.decode("""{"kind":"wake"}"""))
assertEquals(RemoteCommand.Press(RemoteKey.VolumeUp), RemoteControlLink.decode("""{"kind":"key","key":"volume_up"}"""))
assertEquals(RemoteCommand.Press(RemoteKey.Mute), RemoteControlLink.decode("""{"kind":"key","key":"mute"}"""))
assertNull(RemoteControlLink.decode("""{"kind":"key","key":"power"}"""))
assertNull(RemoteControlLink.decode("""{"kind":"open","url":"javascript:alert(1)"}"""))
assertNull(RemoteControlLink.decode("""{"kind":"seek"}"""))
Expand Down
Loading