Orbit TV at 0.16.0-tuning-screen
First commit, imported from the working folder: Android TV app, loopback guide server, design sources and per-release verification notes. Includes the 0.16 tuning screen, built and tested but not yet confirmed on the box. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import java.net.URLEncoder
|
||||
|
||||
internal val AfterDarkGenres = listOf("Horror", "Thriller", "Science Fiction")
|
||||
internal data class AfterDarkMovie(val item: SampleItem, val year: Int?, val rating: String, val genres: List<String>)
|
||||
|
||||
/** One explicit genre query, at most twenty films. Genre evidence must be returned. */
|
||||
internal fun discoverAfterDarkMovies(transport: EmbyTransport, userId: String, token: () -> String,
|
||||
genre: String): List<AfterDarkMovie> {
|
||||
require(EmbyClient.validId(userId) && genre in AfterDarkGenres)
|
||||
val filter = URLEncoder.encode(genre, "UTF-8")
|
||||
val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&Recursive=true&IncludeItemTypes=Movie&Genres=$filter&StartIndex=0&Limit=20&SortBy=SortName&SortOrder=Ascending&Fields=Genres,MediaStreams&EnableImages=false&EnableUserData=false", token = token()))
|
||||
EmbyClient.expectSuccess(reply.status, false)
|
||||
val rows = EmbyClient.parse(reply.body).optJSONArray("Items") ?: throw EmbyCheckException("The provider did not return a film sample.")
|
||||
return (0 until minOf(rows.length(), 20)).mapNotNull { index ->
|
||||
val row = rows.optJSONObject(index) ?: return@mapNotNull null
|
||||
val id = row.optString("Id")
|
||||
if (!EmbyClient.validId(id) || row.optString("Type") != "Movie") return@mapNotNull null
|
||||
val tags = row.optJSONArray("Genres")
|
||||
val genres = (0 until minOf(tags?.length() ?: 0, 8)).mapNotNull { i ->
|
||||
(tags?.opt(i) as? String)?.let { EmbyClient.clean(it, 40) }?.takeIf { it.isNotBlank() }
|
||||
}.distinct()
|
||||
if (genres.none { it.equals(genre, ignoreCase = true) }) return@mapNotNull null
|
||||
val title = EmbyClient.clean(row.optString("Name"), 160).takeIf { it.isNotBlank() } ?: return@mapNotNull null
|
||||
val duration = (row.optLong("RunTimeTicks", 0) / 10_000).takeIf { it in 1_000..SampleChannel.MAX_DURATION_MS }
|
||||
AfterDarkMovie(SampleItem(title, "Movie", duration?.div(60_000), episodeMediaLabel(row).take(160), id, duration),
|
||||
row.optInt("ProductionYear").takeIf { it in 1800..2200 }, EmbyClient.clean(row.optString("OfficialRating"), 40), genres)
|
||||
}.distinctBy { it.item.id }
|
||||
}
|
||||
|
||||
internal fun mergeAfterDarkMovies(current: List<AfterDarkMovie>, incoming: List<AfterDarkMovie>): List<AfterDarkMovie> =
|
||||
(current + incoming).distinctBy { it.item.id }.take(60)
|
||||
|
||||
internal fun approvedAfterDarkItems(candidates: List<AfterDarkMovie>, ids: Set<String>): List<SampleItem> {
|
||||
if (ids.size !in 2..3 || !candidates.map { it.item.id }.containsAll(ids))
|
||||
throw EmbyCheckException("Approve two or three films from the checked After Dark sample first.")
|
||||
return candidates.filter { it.item.id in ids }.distinctBy { it.item.id }.map { it.item }
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.tv.material3.Text
|
||||
|
||||
@Composable
|
||||
internal fun AfterDarkReviewScreen(movies: List<AfterDarkMovie>, approved: Set<String>, busy: Boolean,
|
||||
message: String?, modifier: Modifier, onGenre: (String) -> Unit, onToggle: (String) -> Unit,
|
||||
onBuild: () -> Unit, onBack: () -> Unit) {
|
||||
BackHandler(onBack = onBack)
|
||||
Box(modifier.fillMaxWidth().background(Navy)) {
|
||||
Image(painterResource(R.drawable.orbit_after_dark_background), null, Modifier.matchParentSize(), contentScale = ContentScale.Crop, alpha = .45f)
|
||||
Column(Modifier.fillMaxSize().padding(18.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Image(painterResource(R.drawable.orbit_after_dark_epg), "102 Orbit After Dark", Modifier.width(230.dp).height(65.dp))
|
||||
Text("Late-night and cult cinema. Check a category, then choose two or three films.", color = Color.White, fontSize = 17.sp)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
AfterDarkGenres.forEach { genre -> OrbitButton("Check $genre", enabled = !busy, onClick = { onGenre(genre) }) }
|
||||
}
|
||||
if (busy) Text("Checking your film sample…", color = Yellow, fontSize = 15.sp)
|
||||
message?.let { Text(it, color = Yellow, fontSize = 15.sp, maxLines = 3) }
|
||||
if (movies.isEmpty() && !busy) Text("No checked films yet. Each category checks up to 20 records; this is a small sample of your library.", color = Muted, fontSize = 16.sp)
|
||||
LazyColumn(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(movies, key = { it.item.id }) { movie ->
|
||||
Column(Modifier.fillMaxWidth().background(Panel.copy(alpha = .94f)).padding(10.dp)) {
|
||||
Text(movie.item.title + (movie.year?.let { " ($it)" } ?: ""), color = Color.White, fontSize = 20.sp, maxLines = 2)
|
||||
val details = listOfNotNull(movie.rating.takeIf { it.isNotBlank() }, movie.item.minutes?.let { "$it min" }, movie.item.format.takeIf { it.isNotBlank() })
|
||||
if (details.isNotEmpty()) Text(details.joinToString(" • "), color = Muted, fontSize = 14.sp)
|
||||
Text("Categories: ${movie.genres.joinToString(", ")}", color = Muted, fontSize = 14.sp, maxLines = 2)
|
||||
OrbitButton(if (movie.item.id in approved) "✓ Remove from selection" else "+ Add to channel",
|
||||
selected = movie.item.id in approved, enabled = !busy && (movie.item.id in approved || approved.size < 3),
|
||||
onClick = { onToggle(movie.item.id) })
|
||||
}
|
||||
}
|
||||
}
|
||||
Text("${approved.size}/3 selected • Existing schedules change only when you create or rebuild this channel.", color = Muted, fontSize = 13.sp)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OrbitButton("Create / rebuild 102", enabled = !busy && approved.size in 2..3, onClick = onBuild)
|
||||
OrbitButton("Back", onClick = onBack)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
internal data class ChannelBranding(val presetId: String, val logo: Int, val background: Int)
|
||||
|
||||
internal object ChannelBrands {
|
||||
private val brands = mapOf(102 to ChannelBranding("orbit-after-dark", R.drawable.orbit_after_dark_epg, R.drawable.orbit_after_dark_background))
|
||||
fun forNumber(number: Int): ChannelBranding? = brands[number]
|
||||
}
|
||||
|
||||
internal fun availableSampleChannels(vararg channels: SampleChannel?): List<SampleChannel> =
|
||||
channels.filterNotNull().distinctBy { it.number }.sortedBy { it.number }
|
||||
@@ -0,0 +1,31 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.tv.material3.Text
|
||||
|
||||
/** Presentation only: no timers, media requests or schedule changes. */
|
||||
@Composable
|
||||
internal fun ChannelTuningBackdrop(number: Int, modifier: Modifier = Modifier) {
|
||||
val branding = ChannelBrands.forNumber(number)
|
||||
Box(modifier.fillMaxSize().background(Navy)) {
|
||||
if (branding != null) {
|
||||
Image(painterResource(branding.background), null, Modifier.matchParentSize(), contentScale = ContentScale.Crop)
|
||||
Image(painterResource(branding.logo), null,
|
||||
Modifier.align(Alignment.TopStart).padding(start = 40.dp, top = 32.dp).width(200.dp).height(62.dp))
|
||||
}
|
||||
ClassicTuningNumber(number, Modifier.align(Alignment.TopEnd).padding(top = 32.dp, end = 44.dp))
|
||||
Column(Modifier.align(Alignment.BottomStart).padding(start = 40.dp, bottom = 36.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Text("Tuning…", color = Muted, fontSize = 17.sp)
|
||||
Text("Back for TV guide", color = Muted, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.tv.material3.Text
|
||||
import kotlinx.coroutines.delay
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/** First visual pass: the icon row previews the future scheduled-channel controls. */
|
||||
@Composable
|
||||
internal fun ClassicProgrammeStrip(item: SampleItem, playing: Boolean, modifier: Modifier = Modifier, scheduled: ScheduledPlayback? = null) {
|
||||
var now by remember { mutableLongStateOf(System.currentTimeMillis()) }
|
||||
LaunchedEffect(Unit) { while (true) { delay(1000); now = System.currentTimeMillis() } }
|
||||
val paper = Color(0xFFE8EDF5)
|
||||
Column(modifier.border(1.dp, paper)) {
|
||||
Row(Modifier.fillMaxWidth().background(paper).padding(horizontal = 12.dp, vertical = 3.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(scheduled?.let { "${it.channel.number} ${it.channel.name}${if (it.clockOffsetMs != 0L) " / Transition check" else ""}" } ?: "Orbit Preview", color = Navy, fontWeight = FontWeight.Bold, fontSize = 14.sp)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(SimpleDateFormat("HH:mm EEE d MMM", Locale.UK).format(Date(now)), color = Navy, fontSize = 13.sp)
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().background(Blue).padding(horizontal = 14.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(if (playing || scheduled != null) "NOW" else "PAUSED", Modifier.width(70.dp), color = Yellow, fontWeight = FontWeight.Bold, fontSize = 14.sp)
|
||||
Text(item.title, color = Color.White, fontWeight = FontWeight.Bold, fontSize = 20.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(if (scheduled == null) "INFO" else "NEXT", Modifier.width(70.dp), color = Muted, fontWeight = FontWeight.Bold, fontSize = 13.sp)
|
||||
Text(scheduled?.let { "${clock(it.next.startMs)} ${it.next.media.item.title}" } ?: listOf(item.type, item.minutes?.let { "$it min" }.orEmpty()).filter { it.isNotBlank() }.joinToString(" • "),
|
||||
color = Color.White, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().background(paper).padding(horizontal = 14.dp, vertical = 5.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(30.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Legend("▲ ▼", "Channel")
|
||||
Legend("↶", "TV guide")
|
||||
Legend("CC", "Subtitles")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Legend(icon: String, label: String) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(icon, color = Navy, fontSize = 16.sp, fontWeight = FontWeight.Bold)
|
||||
Text(label, color = Navy, fontSize = 14.sp, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
internal const val DirectVideoContainers = "mp4,mkv,mov,m4v,webm,ts,mpegts,3gp"
|
||||
|
||||
internal fun supportedDirectContainer(value: String): String? = value.trim().lowercase(java.util.Locale.ROOT)
|
||||
.takeIf { it in DirectVideoContainers.split(",") }
|
||||
|
||||
/** Only a short format label may reach diagnostics; never a raw URL/path from metadata. */
|
||||
internal fun safeContainerLabel(value: String): String = value.trim().lowercase(java.util.Locale.ROOT)
|
||||
.takeIf { it.length in 1..16 && it.all { ch -> ch in 'a'..'z' || ch in '0'..'9' || ch == '-' || ch == '_' } }
|
||||
?: "unknown"
|
||||
@@ -0,0 +1,137 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.InputStream
|
||||
import java.net.URL
|
||||
import java.util.UUID
|
||||
import javax.net.ssl.HttpsURLConnection
|
||||
|
||||
internal class EmbyCheckException(message: String, val httpStatus: Int? = null) : Exception(message)
|
||||
internal data class SampleItem(val title: String, val type: String, val minutes: Long?, val format: String, val id: String = "", val durationMs: Long? = minutes?.takeIf { it in 1..(Long.MAX_VALUE / 60_000) }?.times(60_000))
|
||||
internal data class EmbySample(val items: List<SampleItem>, val total: Long?)
|
||||
internal class EmbyRequest(val method: String, val path: String, val body: String? = null, val token: String? = null)
|
||||
internal class EmbyReply(val status: Int, val body: String)
|
||||
internal fun interface EmbyTransport { fun execute(request: EmbyRequest): EmbyReply }
|
||||
|
||||
/** Network boundary: fixed HTTPS origin, standard TLS checks, no redirects or response logging. */
|
||||
internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUID().toString()) : EmbyTransport {
|
||||
companion object {
|
||||
const val SERVER = "https://bk2.appboxmanager.xyz"
|
||||
const val MAX_RESPONSE_BYTES = 2 * 1024 * 1024
|
||||
internal fun readBounded(stream: InputStream): String {
|
||||
val output = ByteArrayOutputStream()
|
||||
val buffer = ByteArray(8192)
|
||||
while (true) {
|
||||
val count = stream.read(buffer)
|
||||
if (count == -1) break
|
||||
if (output.size() + count > MAX_RESPONSE_BYTES) throw EmbyCheckException("The provider response was too large for this sample check.")
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
return output.toString(Charsets.UTF_8.name())
|
||||
}
|
||||
}
|
||||
override fun execute(request: EmbyRequest): EmbyReply {
|
||||
// Paths come from the protocol below, never from a provider response or a text field.
|
||||
require(request.path.startsWith("/") && !request.path.startsWith("//"))
|
||||
val connection = URL("$SERVER/emby${request.path}").openConnection() as HttpsURLConnection
|
||||
try {
|
||||
connection.requestMethod = request.method
|
||||
connection.instanceFollowRedirects = false
|
||||
connection.connectTimeout = 10_000
|
||||
connection.readTimeout = if (request.path == "/Sessions/Logout") 5_000 else 15_000
|
||||
connection.setRequestProperty("Accept", "application/json")
|
||||
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.16.0\"")
|
||||
request.token?.let { connection.setRequestProperty("X-Emby-Token", it) }
|
||||
if (request.method == "POST") {
|
||||
val bytes = request.body.orEmpty().toByteArray(Charsets.UTF_8)
|
||||
connection.doOutput = true
|
||||
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8")
|
||||
connection.setFixedLengthStreamingMode(bytes.size)
|
||||
connection.outputStream.use { it.write(bytes) }
|
||||
}
|
||||
val status = connection.responseCode
|
||||
if (status !in 200..299 || request.path == "/Sessions/Logout") return EmbyReply(status, "")
|
||||
if (connection.contentLengthLong > MAX_RESPONSE_BYTES) throw EmbyCheckException("The provider response was too large for this sample check.")
|
||||
val body = connection.inputStream.use { readBounded(it) }
|
||||
return EmbyReply(status, body)
|
||||
} catch (e: EmbyCheckException) { throw e }
|
||||
catch (_: javax.net.ssl.SSLException) { throw EmbyCheckException("The secure connection could not be verified. No insecure fallback was used.") }
|
||||
catch (_: java.io.IOException) { throw EmbyCheckException("The provider could not be reached. Check your connection and try again.") }
|
||||
finally { connection.disconnect() }
|
||||
}
|
||||
}
|
||||
|
||||
/** One explicit sign-in and one bounded metadata page; ownership passes to the sample screen. */
|
||||
internal class EmbyClient(private val transport: EmbyTransport = HttpsEmbyTransport()) {
|
||||
fun connect(username: String, password: String): EmbySampleSession {
|
||||
if (username.isBlank() || username.length > 256 || password.isEmpty() || password.length > 1024)
|
||||
throw EmbyCheckException("Enter your username and password to check the connection.")
|
||||
val login = transport.execute(EmbyRequest("POST", "/Users/AuthenticateByName",
|
||||
JSONObject().put("Username", username).put("Pw", password).toString()))
|
||||
expectSuccess(login.status, true)
|
||||
val authentication = parse(login.body)
|
||||
val token = authentication.opt("AccessToken") as? String
|
||||
?: throw EmbyCheckException("The provider returned an unusable login response.")
|
||||
if (token.isBlank() || token.length > 4096 || token.any { it.code !in 33..126 })
|
||||
throw EmbyCheckException("The provider returned an unusable login response.")
|
||||
var success = false
|
||||
try {
|
||||
val userId = authentication.optJSONObject("User")?.optString("Id").orEmpty()
|
||||
if (!validId(userId)) throw EmbyCheckException("The provider returned an unusable user identity.")
|
||||
val reply = transport.execute(EmbyRequest("GET", "/Users/$userId/Items?Recursive=true&IncludeItemTypes=Movie,Episode&StartIndex=0&Limit=20&SortBy=SortName&SortOrder=Ascending&Fields=MediaStreams&EnableImages=false&EnableUserData=false", token = token))
|
||||
expectSuccess(reply.status, false)
|
||||
val page = parse(reply.body)
|
||||
val records = page.optJSONArray("Items") ?: throw EmbyCheckException("The provider did not return a library sample.")
|
||||
val items = (0 until minOf(records.length(), 20)).mapNotNull { index ->
|
||||
val item = records.optJSONObject(index) ?: return@mapNotNull null
|
||||
val id = item.optString("Id")
|
||||
if (!validId(id)) return@mapNotNull null
|
||||
val type = item.optString("Type")
|
||||
if (type !in listOf("Movie", "Episode")) return@mapNotNull null
|
||||
val title = clean(item.optString("Name"), 160).ifBlank { "Untitled programme" }
|
||||
val ticks = item.optLong("RunTimeTicks", 0)
|
||||
val streams = item.optJSONArray("MediaStreams")
|
||||
val codecs = (0 until minOf(streams?.length() ?: 0, 32)).mapNotNull { streamIndex ->
|
||||
val stream = streams?.optJSONObject(streamIndex) ?: return@mapNotNull null
|
||||
if (stream.optString("Type") in listOf("Video", "Audio")) clean(stream.optString("Codec"), 24).ifBlank { null } else null
|
||||
}.distinct().take(3)
|
||||
SampleItem(title, type, if (ticks > 0) ticks / 600_000_000 else null,
|
||||
(listOf(clean(item.optString("Container"), 24)) + codecs).filter { it.isNotBlank() }.joinToString(" / "), id, (ticks / 10_000).takeIf { it > 0 })
|
||||
}
|
||||
val total = if (page.has("TotalRecordCount")) page.optLong("TotalRecordCount", -1).takeIf { it >= 0 } else null
|
||||
val session = EmbySampleSession(transport, token, userId, EmbySample(items, total))
|
||||
success = true
|
||||
return session
|
||||
} finally {
|
||||
if (!success) try { transport.execute(EmbyRequest("POST", "/Sessions/Logout", token = token)) }
|
||||
catch (_: Exception) { }
|
||||
}
|
||||
}
|
||||
fun resume(saved: RememberedState): EmbySampleSession {
|
||||
val identity = saved.identity
|
||||
val token = identity.token ?: throw EmbyCheckException("Sign in to restore your saved channel choices.")
|
||||
require(validId(identity.userId) && validId(identity.deviceId))
|
||||
val reply = transport.execute(EmbyRequest("GET", "/Users/${identity.userId}", token = token))
|
||||
expectSuccess(reply.status, false)
|
||||
if (parse(reply.body).optString("Id") != identity.userId)
|
||||
throw EmbyCheckException("The saved connection could not be verified. Sign in again.")
|
||||
return EmbySampleSession(transport, token, identity.userId, saved.sample).also { it.restoreRemembered(saved) }
|
||||
}
|
||||
companion object {
|
||||
internal fun validId(value: String) = Regex("[A-Za-z0-9_-]{1,128}").matches(value)
|
||||
internal fun parse(body: String): JSONObject = try { JSONObject(body) }
|
||||
catch (_: Exception) { throw EmbyCheckException("The provider returned a response this version cannot read.") }
|
||||
internal fun clean(value: String, limit: Int) = value.filter { !it.isISOControl() }.take(limit)
|
||||
internal fun expectSuccess(status: Int, login: Boolean) {
|
||||
when (status) {
|
||||
in 200..299 -> return
|
||||
401 -> throw EmbyCheckException(if (login) "Sign-in failed. Check your username and password." else "The temporary login expired. Try the connection check again.", status)
|
||||
403 -> throw EmbyCheckException("The provider did not permit this connection or library request.", status)
|
||||
429 -> throw EmbyCheckException("The provider asked us to slow down. Wait before trying again.", status)
|
||||
in 300..399 -> throw EmbyCheckException("The provider redirected the request. The login was not forwarded to another address.")
|
||||
else -> throw EmbyCheckException("The provider could not complete this check (HTTP $status).")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import android.view.KeyEvent
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.compose.LocalActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.BasicSecureTextField
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.text.input.InputTransformation
|
||||
import androidx.compose.foundation.text.input.TextFieldState
|
||||
import androidx.compose.foundation.text.input.TextObfuscationMode
|
||||
import androidx.compose.foundation.text.input.maxLength
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.tv.material3.Text
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@Composable
|
||||
internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolean,
|
||||
mainGuide: Boolean, onChannelAvailable: (Boolean) -> Unit, onGuide: () -> Unit,
|
||||
onBack: () -> Unit) {
|
||||
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
||||
val savedStore = remember { RememberedConnectionStore.get(appContext) }
|
||||
var setupSaved by remember { mutableStateOf(false) }
|
||||
var pendingSaved by remember { mutableStateOf<RememberedState?>(null) }
|
||||
var restoring by remember { mutableStateOf(true) }
|
||||
var restoreAttempt by remember { mutableIntStateOf(0) }
|
||||
var saveTicket by remember { mutableLongStateOf(savedStore.ticket()) }
|
||||
var username by remember { mutableStateOf("") }
|
||||
// Deliberately not rememberSaveable: credentials never enter saved instance state.
|
||||
val password = remember { TextFieldState() }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var seriesMatches by remember { mutableStateOf<List<SeriesMatches>?>(null) }
|
||||
var episodeSamples by remember { mutableStateOf<List<SeriesEpisodes>?>(null) }
|
||||
var reviewingSeries by remember { mutableStateOf(false) }
|
||||
var approvedSeries by remember { mutableStateOf<Set<String>>(emptySet()) }
|
||||
var sample by remember { mutableStateOf<EmbySample?>(null) }
|
||||
var session by remember { mutableStateOf<EmbySampleSession?>(null) }
|
||||
var playback by remember { mutableStateOf<EmbyPlaybackPlan?>(null) }
|
||||
var darkMovies by remember { mutableStateOf<List<AfterDarkMovie>>(emptyList()) }
|
||||
var approvedDark by remember { mutableStateOf<Set<String>>(emptySet()) }
|
||||
var reviewingDark by remember { mutableStateOf(false) }
|
||||
var afterDarkChannel by remember { mutableStateOf<SampleChannel?>(null) }
|
||||
var toonamiChannel by remember { mutableStateOf<SampleChannel?>(null) }
|
||||
var selectedNumber by remember { mutableIntStateOf(101) }
|
||||
var channel by remember { mutableStateOf<SampleChannel?>(null) }
|
||||
var watchingChannel by remember { mutableStateOf(false) }
|
||||
var channelClockOffset by remember { mutableLongStateOf(0) }
|
||||
var busyLabel by remember { mutableStateOf("Connecting…") }
|
||||
val sessionSlot = remember { EmbySessionSlot() }
|
||||
var message by remember { mutableStateOf<String?>(null) }
|
||||
var nextAttemptAt by remember { mutableLongStateOf(0) }
|
||||
var now by remember { mutableLongStateOf(System.currentTimeMillis()) }
|
||||
var job by remember { mutableStateOf<Job?>(null) }
|
||||
val scope = rememberCoroutineScope()
|
||||
val keyboard = LocalSoftwareKeyboardController.current
|
||||
val focus = LocalFocusManager.current
|
||||
val passwordFocus = remember { FocusRequester() }
|
||||
val submitFocus = remember { FocusRequester() }
|
||||
val activity = LocalActivity.current
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
val imeVisible = WindowInsets.ime.getBottom(LocalDensity.current) > 0
|
||||
fun clearPassword() { password.edit { replace(0, length, "") } }
|
||||
fun applyChoices(saved: RememberedState) {
|
||||
seriesMatches = saved.matches.takeIf { it.isNotEmpty() }; approvedSeries = saved.approved
|
||||
episodeSamples = saved.episodes; channel = saved.orbitOne; toonamiChannel = saved.toonami
|
||||
darkMovies = saved.darkMovies; approvedDark = saved.approvedDark; afterDarkChannel = saved.afterDark
|
||||
val available = availableSampleChannels(channel, afterDarkChannel, toonamiChannel)
|
||||
selectedNumber = available.firstOrNull { it.number == saved.selectedNumber }?.number ?: available.firstOrNull()?.number ?: 101
|
||||
onChannelAvailable(available.isNotEmpty())
|
||||
}
|
||||
fun closeSession(forget: Boolean = false) {
|
||||
setupSaved = false
|
||||
savedStore.invalidate()
|
||||
if (forget) {
|
||||
pendingSaved = null
|
||||
try { savedStore.clear() }
|
||||
catch (_: Exception) { message = "The saved connection could not be removed. Clear Orbit TV app data in Android Settings before leaving this device." }
|
||||
}
|
||||
seriesMatches = null; episodeSamples = null; reviewingSeries = false; approvedSeries = emptySet()
|
||||
darkMovies = emptyList(); approvedDark = emptySet(); reviewingDark = false; afterDarkChannel = null
|
||||
playback = null; session = null; sample = null; channel = null; toonamiChannel = null; selectedNumber = 101; watchingChannel = false
|
||||
onChannelAvailable(false)
|
||||
sessionSlot.clear()?.let { active -> EmbyCleanup.run { active.close() } }
|
||||
}
|
||||
BackHandler(imeVisible) { keyboard?.hide(); focus.clearFocus() }
|
||||
val protectScreen = visible || session != null || busy
|
||||
DisposableEffect(activity, protectScreen) {
|
||||
val alreadySecure = (activity?.window?.attributes?.flags ?: 0) and WindowManager.LayoutParams.FLAG_SECURE != 0
|
||||
if (protectScreen) activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
|
||||
onDispose {
|
||||
if (protectScreen && !alreadySecure) activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
|
||||
}
|
||||
}
|
||||
DisposableEffect(lifecycle) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_STOP) {
|
||||
clearPassword(); job?.cancel(); playback = null; watchingChannel = false; busy = false
|
||||
if (session == null && !restoring) sessionSlot.clear()?.let { active -> EmbyCleanup.run { active.close() } }
|
||||
}
|
||||
}
|
||||
lifecycle.addObserver(observer)
|
||||
onDispose {
|
||||
clearPassword(); job?.cancel(); lifecycle.removeObserver(observer)
|
||||
sessionSlot.clear()?.let { active -> EmbyCleanup.run { active.detach() } }
|
||||
}
|
||||
}
|
||||
LaunchedEffect(restoreAttempt) {
|
||||
restoring = true
|
||||
try {
|
||||
val saved = withContext(Dispatchers.IO) { savedStore.load() }
|
||||
pendingSaved = saved
|
||||
if (saved?.identity?.token != null && session == null) {
|
||||
val slotTicket = sessionSlot.ticket()
|
||||
val resumed = withContext(Dispatchers.IO) {
|
||||
val active = EmbyClient(HttpsEmbyTransport(saved.identity.deviceId)).resume(saved)
|
||||
if (!sessionSlot.attach(active, slotTicket)) { active.detach(); throw CancellationException() }
|
||||
active
|
||||
}
|
||||
session = resumed; sample = resumed.sample; applyChoices(saved)
|
||||
saveTicket = savedStore.ticket()
|
||||
message = "Saved connection restored."
|
||||
} else if (saved != null && session == null) message = "Sign in again to restore your saved channel choices."
|
||||
} catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: EmbyCheckException) {
|
||||
if (failure.httpStatus == 401 || failure.httpStatus == 403) {
|
||||
pendingSaved = pendingSaved?.withoutToken()
|
||||
try { pendingSaved?.let { value -> withContext(Dispatchers.IO) { savedStore.save(value, savedStore.ticket()) } } }
|
||||
catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (_: Exception) { /* Keep the expired token out of active use even if secure storage is unavailable. */ }
|
||||
message = "Your saved login expired. Sign in again; choices restore for the same account."
|
||||
} else message = "The saved connection could not be reached. Retry saved connection or sign in again."
|
||||
} catch (_: Exception) {
|
||||
// A corrupt file or unavailable key is never read as plaintext.
|
||||
try { withContext(Dispatchers.IO) { savedStore.clear() } } catch (_: Exception) { }
|
||||
pendingSaved = null
|
||||
message = "The saved connection could not be opened. Sign in again."
|
||||
} finally { restoring = false }
|
||||
}
|
||||
LaunchedEffect(session, seriesMatches, approvedSeries, episodeSamples, channel, toonamiChannel, selectedNumber, restoring, afterDarkChannel, darkMovies, approvedDark) {
|
||||
val active = session
|
||||
if (active != null && !restoring) {
|
||||
setupSaved = false
|
||||
delay(100)
|
||||
try {
|
||||
val saved = RememberedState(active.rememberedIdentity(), active.sample, seriesMatches.orEmpty(),
|
||||
approvedSeries, episodeSamples, channel, toonamiChannel, selectedNumber, afterDarkChannel, darkMovies, approvedDark)
|
||||
val ticket = saveTicket
|
||||
if (withContext(Dispatchers.IO) { savedStore.save(saved, ticket) }) {
|
||||
pendingSaved = saved; setupSaved = true
|
||||
}
|
||||
} catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (_: Exception) { message = "Connected, but this setup could not be saved securely. It will need sign-in after restart." }
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) { while (true) { now = System.currentTimeMillis(); delay(1000) } }
|
||||
LaunchedEffect(visible) {
|
||||
if (!visible) {
|
||||
clearPassword(); username = ""; keyboard?.hide()
|
||||
if (busy && !restoring) {
|
||||
job?.cancel()
|
||||
if (session == null) closeSession()
|
||||
busy = false
|
||||
}
|
||||
playback = null
|
||||
}
|
||||
}
|
||||
LaunchedEffect(mainGuide) {
|
||||
if (!mainGuide) { watchingChannel = false; channelClockOffset = 0 }
|
||||
}
|
||||
val ready = !busy && !restoring && now >= nextAttemptAt && username.isNotBlank() && password.text.isNotEmpty()
|
||||
playback?.let { plan -> session?.let { active -> EmbyPlaybackDialog(active, plan, onClose = { playback = null }) } }
|
||||
val liveSession = session
|
||||
val availableChannels = availableSampleChannels(channel, afterDarkChannel, toonamiChannel)
|
||||
val liveChannel = availableChannels.firstOrNull { it.number == selectedNumber }
|
||||
if (mainGuide && liveSession != null && liveChannel != null) {
|
||||
if (watchingChannel) ScheduledChannelPlayer(liveSession, liveChannel, channelClockOffset,
|
||||
onClose = { watchingChannel = false; channelClockOffset = 0 })
|
||||
SampleChannelGuide(liveChannel, modifier, onTune = { offset ->
|
||||
channelClockOffset = offset; watchingChannel = true
|
||||
}, onBack = onBack, otherChannels = availableChannels.filter { it.number != selectedNumber },
|
||||
onSwitch = { selectedNumber = it; watchingChannel = false; channelClockOffset = 0 })
|
||||
return
|
||||
}
|
||||
if (!visible) return
|
||||
if (reviewingDark) {
|
||||
AfterDarkReviewScreen(darkMovies, approvedDark, busy, message, modifier,
|
||||
onGenre = { genre ->
|
||||
val active = session
|
||||
if (!busy && active != null) {
|
||||
busy = true; message = null
|
||||
job = scope.launch {
|
||||
try {
|
||||
darkMovies = withContext(Dispatchers.IO) { active.checkAfterDarkMovies(genre) }
|
||||
message = "${darkMovies.size} checked films in this sample. If a category has no matches, it may have no results or incomplete genre metadata in its first page."
|
||||
} catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: EmbyCheckException) { message = failure.message }
|
||||
catch (_: Exception) { message = "The film check could not finish. Try again later." }
|
||||
finally { busy = false }
|
||||
}
|
||||
}
|
||||
}, onToggle = { id ->
|
||||
if (!busy) approvedDark = if (id in approvedDark) approvedDark - id else if (approvedDark.size < 3) approvedDark + id else approvedDark
|
||||
}, onBuild = {
|
||||
val active = session
|
||||
if (!busy && active != null && approvedDark.size in 2..3) {
|
||||
busy = true; message = null
|
||||
job = scope.launch {
|
||||
try {
|
||||
val built = withContext(Dispatchers.IO) {
|
||||
val context = coroutineContext
|
||||
active.buildAfterDarkChannel(approvedDark) { context.ensureActive() }
|
||||
}
|
||||
afterDarkChannel = built; selectedNumber = 102; reviewingDark = false
|
||||
onChannelAvailable(true); onGuide()
|
||||
} catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: EmbyCheckException) { message = failure.message }
|
||||
catch (_: Exception) { message = "Channel 102 could not be prepared. Try again later." }
|
||||
finally { busy = false }
|
||||
}
|
||||
}
|
||||
}, onBack = { job?.cancel(); busy = false; reviewingDark = false })
|
||||
return
|
||||
}
|
||||
fun checkMoreSeries() {
|
||||
val active = session ?: return
|
||||
if (busy) return
|
||||
val start = seriesMatches?.size ?: 0
|
||||
if (start >= ToonamiSearches.size) return
|
||||
busy = true; busyLabel = "Checking next five series…"; message = null
|
||||
job = scope.launch {
|
||||
try {
|
||||
val batch = withContext(Dispatchers.IO) {
|
||||
val context = coroutineContext
|
||||
active.checkToonamiSeries(start) { context.ensureActive() }
|
||||
}
|
||||
seriesMatches = seriesMatches.orEmpty() + batch
|
||||
reviewingSeries = true
|
||||
} catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: EmbyCheckException) { message = failure.message }
|
||||
catch (_: Exception) { message = "The series check could not finish. Try again later." }
|
||||
finally { busy = false }
|
||||
}
|
||||
}
|
||||
if (reviewingSeries) {
|
||||
SeriesReviewScreen(seriesMatches.orEmpty(), approvedSeries, episodeSamples, busy, message, modifier,
|
||||
onToggle = { id ->
|
||||
if (!busy) {
|
||||
approvedSeries = if (id in approvedSeries) approvedSeries - id else if (approvedSeries.size < 3) approvedSeries + id else approvedSeries
|
||||
episodeSamples = null
|
||||
}
|
||||
}, onMore = { checkMoreSeries() }, onEpisodes = {
|
||||
val active = session
|
||||
val selected = seriesMatches.orEmpty().flatMap { it.candidates }.distinctBy { it.id }.filter { it.id in approvedSeries }
|
||||
if (!busy && active != null && selected.size in 1..3) {
|
||||
busy = true; message = null; episodeSamples = null
|
||||
job = scope.launch {
|
||||
try {
|
||||
episodeSamples = withContext(Dispatchers.IO) {
|
||||
val context = coroutineContext
|
||||
active.checkSeriesEpisodes(selected) { context.ensureActive() }
|
||||
}
|
||||
} catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: EmbyCheckException) { message = failure.message }
|
||||
catch (_: Exception) { message = "The episode check could not finish. Try again later." }
|
||||
finally { busy = false }
|
||||
}
|
||||
}
|
||||
}, onBuild = {
|
||||
val active = session
|
||||
if (!busy && active != null && episodeSamples != null) {
|
||||
busy = true; message = null
|
||||
job = scope.launch {
|
||||
try {
|
||||
val built = withContext(Dispatchers.IO) {
|
||||
val context = coroutineContext
|
||||
active.buildToonamiChannel { context.ensureActive() }
|
||||
}
|
||||
toonamiChannel = built; selectedNumber = 103
|
||||
reviewingSeries = false; onChannelAvailable(true); onGuide()
|
||||
} catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: EmbyCheckException) { message = failure.message }
|
||||
catch (_: Exception) { message = "Channel 103 could not be prepared. Try again later." }
|
||||
finally { busy = false }
|
||||
}
|
||||
}
|
||||
}, onBack = { job?.cancel(); busy = false; reviewingSeries = false })
|
||||
return
|
||||
}
|
||||
Row(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(24.dp)) {
|
||||
Column(Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("Connect Emby", color = Yellow, fontSize = 27.sp)
|
||||
Text(HttpsEmbyTransport.SERVER, color = Muted, fontSize = 15.sp)
|
||||
Text("Sign in for a 20-item playback sample, then create your TV channel.", color = Color.White, fontSize = 16.sp)
|
||||
Text("Username", color = Muted, fontSize = 14.sp)
|
||||
var userFocused by remember { mutableStateOf(false) }
|
||||
BasicTextField(value = username, onValueChange = { if (it.length <= 256) username = it.replace("\n", "") },
|
||||
enabled = !busy && !restoring, singleLine = true, textStyle = TextStyle(color = Color.White, fontSize = 18.sp),
|
||||
cursorBrush = SolidColor(Yellow),
|
||||
keyboardOptions = KeyboardOptions(autoCorrectEnabled = false, imeAction = ImeAction.Next),
|
||||
keyboardActions = KeyboardActions(onNext = { passwordFocus.requestFocus(); keyboard?.show() }),
|
||||
modifier = Modifier.fillMaxWidth().onFocusChanged { userFocused = it.isFocused }
|
||||
.background(Panel).border(2.dp, if (userFocused) Yellow else Blue)
|
||||
.onPreviewKeyEvent { event ->
|
||||
if (event.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
|
||||
if (event.nativeKeyEvent.action == KeyEvent.ACTION_UP) keyboard?.show()
|
||||
true
|
||||
} else false
|
||||
}.padding(12.dp))
|
||||
Text("Password", color = Muted, fontSize = 14.sp)
|
||||
var passwordFocused by remember { mutableStateOf(false) }
|
||||
BasicSecureTextField(state = password, enabled = !busy && !restoring,
|
||||
textObfuscationMode = TextObfuscationMode.Hidden,
|
||||
inputTransformation = InputTransformation.maxLength(1024),
|
||||
textStyle = TextStyle(color = Color.White, fontSize = 18.sp), cursorBrush = SolidColor(Yellow),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done),
|
||||
onKeyboardAction = { keyboard?.hide(); if (ready) submitFocus.requestFocus() else focus.clearFocus() },
|
||||
modifier = Modifier.fillMaxWidth().focusRequester(passwordFocus)
|
||||
.onFocusChanged { passwordFocused = it.isFocused }
|
||||
.background(Panel).border(2.dp, if (passwordFocused) Yellow else Blue)
|
||||
.onPreviewKeyEvent { event ->
|
||||
if (event.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
|
||||
if (event.nativeKeyEvent.action == KeyEvent.ACTION_UP) keyboard?.show()
|
||||
true
|
||||
} else false
|
||||
}.padding(12.dp))
|
||||
OrbitButton(if (busy) "Checking connection…" else if (now < nextAttemptAt) "Wait before trying again" else "Check 20 items",
|
||||
Modifier.fillMaxWidth().focusRequester(submitFocus), enabled = ready, onClick = {
|
||||
if (!ready) return@OrbitButton
|
||||
val loginName = username.trim()
|
||||
val secret = password.text.toString()
|
||||
clearPassword(); keyboard?.hide(); focus.clearFocus()
|
||||
closeSession()
|
||||
val ticket = sessionSlot.ticket()
|
||||
busyLabel = "Connecting…"
|
||||
busy = true; message = null; sample = null
|
||||
nextAttemptAt = System.currentTimeMillis() + 15_000
|
||||
job = scope.launch {
|
||||
try {
|
||||
val connected = withContext(Dispatchers.IO) {
|
||||
val opened = EmbyClient().connect(loginName, secret)
|
||||
if (!sessionSlot.attach(opened, ticket)) { opened.close(); throw CancellationException() }
|
||||
opened
|
||||
}
|
||||
val saved = pendingSaved
|
||||
if (saved != null && connected.matchesAccount(saved.identity)) {
|
||||
connected.restoreRemembered(saved); applyChoices(saved)
|
||||
}
|
||||
session = connected; sample = connected.sample
|
||||
saveTicket = savedStore.ticket()
|
||||
}
|
||||
catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: EmbyCheckException) { message = failure.message }
|
||||
catch (_: Exception) { message = "The connection check could not finish. Try again later." }
|
||||
finally { busy = false }
|
||||
}
|
||||
})
|
||||
Text("This device remembers the session token and channel choices using encrypted storage. Your password is never saved.", color = Muted, fontSize = 13.sp)
|
||||
if (setupSaved && session != null) Text("Setup saved on this device", color = Yellow, fontSize = 14.sp)
|
||||
if (session != null) OrbitButton("Disconnect", Modifier.fillMaxWidth(), onClick = { job?.cancel(); closeSession(forget = true) })
|
||||
if (session == null && pendingSaved?.identity?.token != null)
|
||||
OrbitButton("Retry saved connection", Modifier.fillMaxWidth(), enabled = !restoring && !busy,
|
||||
onClick = { restoreAttempt++ })
|
||||
if (session == null && pendingSaved != null)
|
||||
OrbitButton("Forget saved connection", Modifier.fillMaxWidth(), enabled = !restoring && !busy,
|
||||
onClick = { closeSession(forget = true) })
|
||||
if (restoring) Text("Restoring saved connection…", color = Yellow, fontSize = 14.sp)
|
||||
OrbitButton("Return to Menu", Modifier.fillMaxWidth(), onClick = onBack)
|
||||
}
|
||||
Column(Modifier.weight(1.15f).fillMaxHeight().background(Panel).padding(16.dp)) {
|
||||
Text(if (sample != null) "Sample received" else "Connection check", color = Yellow, fontSize = 24.sp)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
val result = sample
|
||||
when {
|
||||
busy && result == null -> Text(busyLabel, color = Color.White, fontSize = 18.sp)
|
||||
message != null && result == null -> Text(message.orEmpty(), color = Color.White, fontSize = 18.sp)
|
||||
result != null -> {
|
||||
if (busy) Text(busyLabel, color = Yellow, fontSize = 14.sp)
|
||||
message?.let { Text(it, color = Yellow, fontSize = 14.sp) }
|
||||
Text("${result.items.size} records received${result.total?.let { " • $it available to this account" }.orEmpty()}", color = Color.White, fontSize = 16.sp)
|
||||
Text("Select a title, or create one channel from up to three playable titles.", color = Muted, fontSize = 13.sp)
|
||||
OrbitButton(if (channel == null) "Create sample channel" else "Open TV Guide",
|
||||
Modifier.fillMaxWidth(), enabled = !busy && session != null, onClick = {
|
||||
if (channel != null) { selectedNumber = 101; onGuide() } else {
|
||||
val active = session ?: return@OrbitButton
|
||||
busyLabel = "Preparing your channel…"; busy = true; message = null
|
||||
job = scope.launch {
|
||||
try {
|
||||
channel = withContext(Dispatchers.IO) { active.buildSampleChannel() }
|
||||
selectedNumber = 101
|
||||
onChannelAvailable(true)
|
||||
onGuide()
|
||||
} catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: EmbyCheckException) { message = failure.message }
|
||||
catch (_: Exception) { message = "The sample channel could not be created. Try again later." }
|
||||
finally { busy = false }
|
||||
}
|
||||
}
|
||||
})
|
||||
OrbitButton("102 Orbit After Dark — choose films", Modifier.fillMaxWidth(),
|
||||
enabled = !busy && session != null, onClick = { message = null; reviewingDark = true })
|
||||
OrbitButton(if (seriesMatches == null) "103 Toonami — check shortlist" else "103 Toonami — review matches",
|
||||
Modifier.fillMaxWidth(), enabled = !busy && session != null, onClick = {
|
||||
if (seriesMatches != null) reviewingSeries = true else checkMoreSeries()
|
||||
})
|
||||
Spacer(Modifier.height(8.dp))
|
||||
if (result.items.isEmpty()) Text("No movies or episodes were returned for this account.", color = Color.White, fontSize = 17.sp)
|
||||
LazyColumn(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
itemsIndexed(result.items) { index, item ->
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
Column(Modifier.fillMaxWidth().onFocusChanged { focused = it.isFocused }
|
||||
.border(1.dp, if (focused) Yellow else Blue).clickable(enabled = session != null) {
|
||||
if (busy) return@clickable
|
||||
val active = session ?: return@clickable
|
||||
busyLabel = "Preparing selected title…"; busy = true; message = null
|
||||
job = scope.launch {
|
||||
try { playback = withContext(Dispatchers.IO) { active.prepare(item) } }
|
||||
catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: EmbyCheckException) { message = failure.message }
|
||||
catch (_: Exception) { message = "This sample could not be opened. Try another title." }
|
||||
finally { busy = false }
|
||||
}
|
||||
}.padding(10.dp)) {
|
||||
Text("${index + 1}. ${item.title}", color = Color.White, fontSize = 17.sp, maxLines = 2)
|
||||
Text(listOf(item.type, item.minutes?.let { "$it min" }.orEmpty(), item.format)
|
||||
.filter { it.isNotBlank() }.joinToString(" • "), color = Muted, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else -> Text("Enter your provider login on the TV. Read a small sample, then create Orbit One in the main TV Guide.", color = Muted, fontSize = 18.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import android.view.KeyEvent
|
||||
import android.os.SystemClock
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.compose.ui.window.SecureFlagPolicy
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.PlaybackException
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.datasource.DataSource
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
|
||||
import androidx.media3.ui.PlayerView
|
||||
import androidx.tv.material3.Text
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
|
||||
@Composable
|
||||
internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPlan, onClose: () -> Unit, scheduled: ScheduledPlayback? = null) {
|
||||
val context = LocalContext.current
|
||||
var failure by remember { mutableStateOf<String?>(null) }
|
||||
var tuningNumberVisible by remember { mutableStateOf(true) }
|
||||
var ready by remember { mutableStateOf(false) }
|
||||
var playing by remember { mutableStateOf(false) }
|
||||
var infoVisible by remember { mutableStateOf(true) }
|
||||
var lastInteraction by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) }
|
||||
fun showInfo() { infoVisible = true; lastInteraction = SystemClock.elapsedRealtime() }
|
||||
val player = remember(session, plan) {
|
||||
val factory = DataSource.Factory { SecureMediaDataSource(session) }
|
||||
ExoPlayer.Builder(context).setMediaSourceFactory(DefaultMediaSourceFactory(factory))
|
||||
.setSeekBackIncrementMs(10_000).setSeekForwardIncrementMs(10_000).build().apply {
|
||||
setMediaItem(MediaItem.Builder().setUri(plan.url).setSubtitleConfigurations(plan.subtitles.map { subtitle ->
|
||||
MediaItem.SubtitleConfiguration.Builder(android.net.Uri.parse(subtitle.url)).setMimeType(subtitle.mime)
|
||||
.setLanguage(subtitle.language).setLabel(subtitle.label).build()
|
||||
}).build())
|
||||
if (scheduled != null) seekTo(scheduled.programme.offsetAt(scheduled.nowMs()))
|
||||
prepare(); playWhenReady = true
|
||||
}
|
||||
}
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
var foreground by remember { mutableStateOf(lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) }
|
||||
DisposableEffect(player, lifecycle) {
|
||||
var stopReported = false
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_START) foreground = true
|
||||
if (event == Lifecycle.Event.ON_STOP) {
|
||||
foreground = false
|
||||
val position = player.currentPosition
|
||||
player.stop(); ready = false
|
||||
stopReported = true
|
||||
EmbyCleanup.run { session.report(plan, "Playing/Stopped", position, true) }
|
||||
}
|
||||
}
|
||||
lifecycle.addObserver(observer)
|
||||
var joinedSchedule = false
|
||||
val listener = object : Player.Listener {
|
||||
override fun onPlayerError(error: PlaybackException) {
|
||||
val safeReason = generateSequence(error.cause) { it.cause }.filterIsInstance<MediaDeliveryException>().firstOrNull()?.message
|
||||
failure = safeReason ?: "Playback could not continue (${error.errorCodeName}). Try another sample title, or return and report this code."
|
||||
ready = false
|
||||
}
|
||||
override fun onIsPlayingChanged(isPlaying: Boolean) { playing = isPlaying }
|
||||
override fun onPlaybackStateChanged(state: Int) {
|
||||
if (state == Player.STATE_READY) {
|
||||
if (scheduled != null && !joinedSchedule) {
|
||||
joinedSchedule = true
|
||||
val target = scheduled.programme.offsetAt(scheduled.nowMs())
|
||||
if (kotlin.math.abs(player.currentPosition - target) > 2_000) player.seekTo(target)
|
||||
}
|
||||
ready = true
|
||||
}
|
||||
}
|
||||
}
|
||||
player.addListener(listener)
|
||||
onDispose {
|
||||
val position = player.currentPosition
|
||||
lifecycle.removeObserver(observer)
|
||||
player.removeListener(listener); player.release()
|
||||
if (!stopReported) EmbyCleanup.run { session.report(plan, "Playing/Stopped", position, true) }
|
||||
}
|
||||
}
|
||||
LaunchedEffect(player, ready) {
|
||||
if (ready) { delay(2_000); tuningNumberVisible = false }
|
||||
}
|
||||
LaunchedEffect(player, ready) {
|
||||
if (ready && foreground) {
|
||||
val startPosition = player.currentPosition; val startPaused = !player.isPlaying
|
||||
withContext(Dispatchers.IO) { if (foreground) session.report(plan, "Playing", startPosition, startPaused) }
|
||||
while (foreground) {
|
||||
delay(10_000)
|
||||
if (!foreground) break
|
||||
val position = player.currentPosition; val paused = !player.isPlaying
|
||||
withContext(Dispatchers.IO) { if (foreground) session.report(plan, "Playing/Progress", position, paused) }
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(infoVisible, lastInteraction, playing, ready) {
|
||||
if (infoVisible && playing && ready) { delay(5_000); infoVisible = false }
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false,
|
||||
decorFitsSystemWindows = false, securePolicy = SecureFlagPolicy.SecureOn)) {
|
||||
Box(Modifier.fillMaxSize().background(Color.Black)) {
|
||||
AndroidView(modifier = Modifier.fillMaxSize(), factory = { nativeContext ->
|
||||
PlayerView(nativeContext).apply {
|
||||
useController = false
|
||||
setOnKeyListener { _, code, event ->
|
||||
val supported = code in listOf(KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER,
|
||||
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN,
|
||||
KeyEvent.KEYCODE_CHANNEL_UP, KeyEvent.KEYCODE_CHANNEL_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,
|
||||
KeyEvent.KEYCODE_MEDIA_PLAY, KeyEvent.KEYCODE_MEDIA_PAUSE, KeyEvent.KEYCODE_MEDIA_REWIND, KeyEvent.KEYCODE_MEDIA_FAST_FORWARD)
|
||||
if (!supported) false else {
|
||||
if (event.action == KeyEvent.ACTION_UP) {
|
||||
when (code) {
|
||||
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> {
|
||||
if (scheduled == null && infoVisible) { if (player.isPlaying) player.pause() else player.play() }
|
||||
}
|
||||
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_MEDIA_REWIND -> if (scheduled == null) player.seekBack()
|
||||
KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> if (scheduled == null) player.seekForward()
|
||||
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> if (scheduled == null) { if (player.isPlaying) player.pause() else player.play() }
|
||||
KeyEvent.KEYCODE_MEDIA_PLAY -> player.play()
|
||||
KeyEvent.KEYCODE_MEDIA_PAUSE -> if (scheduled == null) player.pause()
|
||||
}
|
||||
showInfo()
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
setShowBuffering(PlayerView.SHOW_BUFFERING_WHEN_PLAYING)
|
||||
this.player = player
|
||||
isFocusable = true; isFocusableInTouchMode = true
|
||||
post { requestFocus() }
|
||||
}
|
||||
}, update = { it.player = player }, onRelease = { it.player = null })
|
||||
if (scheduled != null && !ready && failure == null && foreground)
|
||||
ChannelTuningBackdrop(scheduled.channel.number)
|
||||
if (scheduled != null && ready && tuningNumberVisible && failure == null)
|
||||
ClassicTuningNumber(scheduled.channel.number,
|
||||
Modifier.align(Alignment.TopEnd).padding(top = 32.dp, end = 44.dp))
|
||||
if (infoVisible && failure == null && ready) ClassicProgrammeStrip(plan.item, playing,
|
||||
Modifier.align(Alignment.BottomCenter).fillMaxWidth(.86f).padding(bottom = 26.dp), scheduled = scheduled)
|
||||
if (failure != null) Column(Modifier.align(Alignment.Center).widthIn(max = 620.dp).background(Navy).padding(24.dp)) {
|
||||
Text(failure.orEmpty(), color = Color.White, fontSize = 20.sp)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
OrbitButton("Return to sample", onClick = onClose)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.URI
|
||||
import java.net.URLDecoder
|
||||
import java.net.URLEncoder
|
||||
|
||||
internal class PlaybackSubtitle(val url: String, val mime: String, val language: String?, val label: String)
|
||||
internal class EmbyPlaybackPlan(val item: SampleItem, val url: String, val sourceId: String,
|
||||
val playSessionId: String, val subtitles: List<PlaybackSubtitle>, val durationMs: Long? = item.durationMs)
|
||||
|
||||
internal object PlaybackUrls {
|
||||
private val origin = URI(HttpsEmbyTransport.SERVER)
|
||||
fun isProvider(uri: URI) = uri.scheme.equals("https", true) && uri.host.equals(origin.host, true) && (uri.port == -1 || uri.port == 443)
|
||||
fun resolve(value: String, base: String = HttpsEmbyTransport.SERVER + "/emby/", token: String = ""): String {
|
||||
try {
|
||||
val uri = URI(base).resolve(value)
|
||||
if (!uri.scheme.equals("https", true) || uri.host.isNullOrBlank() || uri.userInfo != null || uri.fragment != null)
|
||||
throw EmbyCheckException("This stream does not provide a supported secure media address.")
|
||||
if (!isProvider(uri) && token.isNotEmpty() && (URLDecoder.decode(uri.rawPath, "UTF-8").contains(token) || uri.rawAuthority.contains(token)))
|
||||
throw EmbyCheckException("The provider login cannot be sent to another media host.")
|
||||
val query = uri.rawQuery?.split("&")?.filter { pair ->
|
||||
val key = URLDecoder.decode(pair.substringBefore('='), "UTF-8")
|
||||
val item = URLDecoder.decode(pair.substringAfter('=', ""), "UTF-8")
|
||||
if (!isProvider(uri) && token.isNotEmpty() && (item.contains(token) || uri.rawPath.contains(token)))
|
||||
throw EmbyCheckException("The provider login cannot be sent to another media host.")
|
||||
!(isProvider(uri) && (key.equals("api_key", true) || key.equals("X-Emby-Token", true)))
|
||||
}?.joinToString("&")
|
||||
val suffix = if (query.isNullOrEmpty()) "" else "?$query"
|
||||
return "${uri.scheme}://${uri.rawAuthority}${uri.rawPath}$suffix"
|
||||
} catch (e: EmbyCheckException) { throw e }
|
||||
catch (_: Exception) { throw EmbyCheckException("This stream does not provide a supported secure media address.") }
|
||||
}
|
||||
}
|
||||
|
||||
/** A temporary session is owned by the sample screen, never by persistent storage. */
|
||||
internal class EmbySampleSession(private val transport: EmbyTransport, private var token: String?,
|
||||
private val userId: String, sample: EmbySample) {
|
||||
var sample: EmbySample = sample
|
||||
private set
|
||||
private val reportLock = Any()
|
||||
@Volatile private var checkedEpisodes: List<SeriesEpisodes> = emptyList()
|
||||
@Volatile private var channelEpisodes: Map<String, SampleItem> = emptyMap()
|
||||
@Volatile private var candidateEpisodes: Map<String, SampleItem> = emptyMap()
|
||||
@Volatile private var darkCandidates: List<AfterDarkMovie> = emptyList()
|
||||
@Volatile private var darkLineup: Map<String, SampleItem> = emptyMap()
|
||||
@Volatile private var active: EmbyPlaybackPlan? = null
|
||||
@Volatile private var lastPositionMs = 0L
|
||||
fun rememberedIdentity() = RememberedIdentity(userId, currentToken(),
|
||||
(transport as? HttpsEmbyTransport)?.deviceId ?: "fixture-device")
|
||||
fun matchesAccount(identity: RememberedIdentity) = userId == identity.userId
|
||||
fun restoreRemembered(saved: RememberedState) {
|
||||
require(matchesAccount(saved.identity))
|
||||
sample = saved.sample
|
||||
checkedEpisodes = saved.episodes.orEmpty()
|
||||
candidateEpisodes = checkedEpisodes.flatMap { group -> group.episodes.map { episodeSampleItem(group.series, it) } }.associateBy { it.id }
|
||||
channelEpisodes = saved.toonami?.lineup.orEmpty().associate { it.item.id to it.item }
|
||||
darkCandidates = saved.darkMovies
|
||||
darkLineup = saved.afterDark?.lineup.orEmpty().associate { it.item.id to it.item }
|
||||
}
|
||||
/** End local use without invalidating the token saved for the next launch. */
|
||||
fun detach() = synchronized(reportLock) {
|
||||
active?.let { report(it, "Playing/Stopped", lastPositionMs, true) }
|
||||
synchronized(this) { token = null }
|
||||
checkedEpisodes = emptyList(); candidateEpisodes = emptyMap(); channelEpisodes = emptyMap(); darkCandidates = emptyList(); darkLineup = emptyMap()
|
||||
}
|
||||
private fun currentToken() = synchronized(this) { token ?: throw EmbyCheckException("This sample session has ended. Sign in again.") }
|
||||
fun mediaUrl(value: String, base: String = HttpsEmbyTransport.SERVER + "/emby/") = PlaybackUrls.resolve(value, base, currentToken())
|
||||
fun mediaHeaders(url: String): Map<String, String> {
|
||||
val auth = currentToken()
|
||||
return if (PlaybackUrls.isProvider(URI(url))) mapOf("X-Emby-Token" to auth) else emptyMap()
|
||||
}
|
||||
fun prepare(item: SampleItem, isPlayback: Boolean = true, preferredSourceId: String? = null): EmbyPlaybackPlan {
|
||||
if (preferredSourceId != null && !EmbyClient.validId(preferredSourceId)) throw EmbyCheckException("The channel source is no longer usable.")
|
||||
if (item.id.isBlank() || sample.items.none { it.id == item.id } && candidateEpisodes[item.id] != item && channelEpisodes[item.id] != item && darkCandidates.none { it.item == item } && darkLineup[item.id] != item) throw EmbyCheckException("Choose a title from the current sample.")
|
||||
val request = JSONObject().put("UserId", userId).put("IsPlayback", isPlayback)
|
||||
.put("EnableDirectPlay", true).put("EnableDirectStream", true).put("EnableTranscoding", false)
|
||||
.put("AutoOpenLiveStream", false)
|
||||
.put("DeviceProfile", JSONObject().put("Name", "Orbit TV playback test")
|
||||
.put("DirectPlayProfiles", JSONArray().put(JSONObject().put("Type", "Video").put("Container", DirectVideoContainers)))
|
||||
.put("TranscodingProfiles", JSONArray())
|
||||
.put("SubtitleProfiles", JSONArray().put(JSONObject().put("Format", "srt").put("Method", "External"))
|
||||
.put(JSONObject().put("Format", "vtt").put("Method", "External"))))
|
||||
if (preferredSourceId != null) request.put("MediaSourceId", preferredSourceId)
|
||||
val response = transport.execute(EmbyRequest("POST", "/Items/${item.id}/PlaybackInfo", request.toString(), currentToken()))
|
||||
EmbyClient.expectSuccess(response.status, false)
|
||||
val info = EmbyClient.parse(response.body)
|
||||
if (!info.isNull("ErrorCode") && !info.optString("ErrorCode").let { it.isBlank() || it == "0" || it == "None" }) throw EmbyCheckException("The provider did not offer a playable source for this account.")
|
||||
val sources = info.optJSONArray("MediaSources") ?: throw EmbyCheckException("The provider did not return a media source.")
|
||||
val directSources = (0 until minOf(sources.length(), 20)).mapNotNull { sources.optJSONObject(it) }.filter {
|
||||
(preferredSourceId == null || it.optString("Id") == preferredSourceId) &&
|
||||
(it.optBoolean("SupportsDirectStream") || it.optBoolean("SupportsDirectPlay")) && !it.optBoolean("RequiresOpening") && !it.optBoolean("RequiresClosing")
|
||||
}
|
||||
if (directSources.isEmpty()) throw EmbyCheckException("This title needs a playback method outside the current direct-stream test. Try another sample title.")
|
||||
val source = directSources.firstOrNull { supportedDirectContainer(it.optString("Container")) != null }
|
||||
?: throw EmbyCheckException("Unsupported direct container: ${directSources.map { safeContainerLabel(it.optString("Container")) }.distinct().take(3).joinToString(", ")}. Choose another series version for this sample.")
|
||||
val sourceId = source.optString("Id")
|
||||
if (!EmbyClient.validId(sourceId)) throw EmbyCheckException("The provider returned an unusable media source.")
|
||||
val playId = (if (info.isNull("PlaySessionId")) "" else info.optString("PlaySessionId")).ifBlank { java.util.UUID.randomUUID().toString() }
|
||||
if (!EmbyClient.validId(playId)) throw EmbyCheckException("The provider returned an unusable playback identity.")
|
||||
val container = requireNotNull(supportedDirectContainer(source.optString("Container")))
|
||||
val url = "${HttpsEmbyTransport.SERVER}/emby/Videos/${item.id}/stream.$container?Static=true&MediaSourceId=${encode(sourceId)}&PlaySessionId=${encode(playId)}"
|
||||
val streams = source.optJSONArray("MediaStreams")
|
||||
val subtitles = (0 until minOf(streams?.length() ?: 0, 32)).mapNotNull { index ->
|
||||
val stream = streams?.optJSONObject(index) ?: return@mapNotNull null
|
||||
if (stream.optString("Type") != "Subtitle" || !stream.optBoolean("IsExternal")) return@mapNotNull null
|
||||
val mime = when (stream.optString("DeliveryFormat").ifBlank { stream.optString("Codec") }.lowercase()) {
|
||||
"srt", "subrip" -> "application/x-subrip"
|
||||
"vtt", "webvtt" -> "text/vtt"
|
||||
else -> return@mapNotNull null
|
||||
}
|
||||
val delivery = stream.optString("DeliveryUrl").takeIf { it.isNotBlank() } ?: return@mapNotNull null
|
||||
val safe = try { mediaUrl(delivery) } catch (_: EmbyCheckException) { return@mapNotNull null }
|
||||
PlaybackSubtitle(safe, mime, stream.optString("Language").take(16).ifBlank { null },
|
||||
EmbyClient.clean(stream.optString("DisplayTitle").ifBlank { "Subtitles ${index + 1}" }, 80))
|
||||
}
|
||||
val runtime = (source.optLong("RunTimeTicks", 0) / 10_000).takeIf { it > 0 } ?: item.durationMs
|
||||
return EmbyPlaybackPlan(item, url, sourceId, playId, subtitles, runtime)
|
||||
}
|
||||
fun checkToonamiSeries(startIndex: Int = 0, checkActive: () -> Unit = {}): List<SeriesMatches> =
|
||||
discoverToonamiSeries(transport, userId, ::currentToken, startIndex, checkActive)
|
||||
fun checkSeriesEpisodes(series: List<SeriesCandidate>, checkActive: () -> Unit = {}): List<SeriesEpisodes> {
|
||||
val checked = discoverSeriesEpisodes(transport, userId, ::currentToken, series, checkActive)
|
||||
checkActive()
|
||||
currentToken()
|
||||
checkedEpisodes = checked
|
||||
candidateEpisodes = checked.flatMap { group -> group.episodes.map { episode -> episodeSampleItem(group.series, episode) } }.associateBy { it.id }
|
||||
return checked
|
||||
}
|
||||
fun buildToonamiChannel(checkActive: () -> Unit = {}): SampleChannel {
|
||||
val checked = checkedEpisodes
|
||||
val ordered = toonamiEpisodeOrder(checked)
|
||||
val media = ordered.map { item ->
|
||||
checkActive()
|
||||
val plan = try { prepare(item, isPlayback = false) }
|
||||
catch (failure: EmbyCheckException) {
|
||||
throw EmbyCheckException("${item.title}: ${failure.message}", failure.httpStatus)
|
||||
}
|
||||
val duration = plan.durationMs?.takeIf { it in 1_000..SampleChannel.MAX_DURATION_MS }
|
||||
?: throw EmbyCheckException("An episode has no usable runtime. Check the sample again.")
|
||||
ScheduledMedia(item, plan.sourceId, duration)
|
||||
}
|
||||
checkActive(); currentToken()
|
||||
val channel = SampleChannel(media, "Toonami", 103)
|
||||
channelEpisodes = ordered.associateBy { it.id }
|
||||
return channel
|
||||
}
|
||||
|
||||
fun checkAfterDarkMovies(genre: String): List<AfterDarkMovie> {
|
||||
val found = discoverAfterDarkMovies(transport, userId, ::currentToken, genre)
|
||||
currentToken()
|
||||
darkCandidates = mergeAfterDarkMovies(darkCandidates, found)
|
||||
return darkCandidates
|
||||
}
|
||||
fun buildAfterDarkChannel(approved: Set<String>, checkActive: () -> Unit = {}): SampleChannel {
|
||||
val items = approvedAfterDarkItems(darkCandidates, approved)
|
||||
val entries = items.map { item ->
|
||||
checkActive()
|
||||
val plan = try { prepare(item, isPlayback = false) }
|
||||
catch (failure: EmbyCheckException) { throw EmbyCheckException("${item.title}: ${failure.message}", failure.httpStatus) }
|
||||
val duration = plan.durationMs?.takeIf { it in 1_000..SampleChannel.MAX_DURATION_MS }
|
||||
?: throw EmbyCheckException("${item.title}: no usable source runtime.")
|
||||
ScheduledMedia(item, plan.sourceId, duration)
|
||||
}
|
||||
checkActive(); currentToken()
|
||||
return SampleChannel(entries, "Orbit After Dark", 102).also { darkLineup = items.associateBy { it.id } }
|
||||
}
|
||||
|
||||
fun buildSampleChannel(): SampleChannel {
|
||||
val entries = mutableListOf<ScheduledMedia>()
|
||||
for (item in sample.items.take(5)) {
|
||||
if (entries.any { it.item.id == item.id }) continue
|
||||
try {
|
||||
val source = prepare(item, isPlayback = false)
|
||||
val duration = source.durationMs ?: continue
|
||||
if (duration !in 1_000..SampleChannel.MAX_DURATION_MS) continue
|
||||
entries += ScheduledMedia(item.copy(minutes = duration / 60_000, durationMs = duration), source.sourceId, duration)
|
||||
if (entries.size == 3) break
|
||||
} catch (failure: EmbyCheckException) {
|
||||
if (failure.httpStatus == 401 || failure.httpStatus == 429) throw failure
|
||||
}
|
||||
}
|
||||
if (entries.size < 2) throw EmbyCheckException("This sample needs at least two direct-stream titles with usable runtimes to create a channel.")
|
||||
return SampleChannel(entries.toList())
|
||||
}
|
||||
fun report(plan: EmbyPlaybackPlan, event: String, positionMs: Long, paused: Boolean) = synchronized(reportLock) {
|
||||
require(event in listOf("Playing", "Playing/Progress", "Playing/Stopped"))
|
||||
if (synchronized(this) { token } == null) return@synchronized
|
||||
if (event == "Playing") active = plan
|
||||
val position = positionMs.coerceAtLeast(0)
|
||||
if (active === plan) lastPositionMs = position
|
||||
val payload = JSONObject().put("ItemId", plan.item.id).put("MediaSourceId", plan.sourceId)
|
||||
.put("PlaySessionId", plan.playSessionId).put("PositionTicks", position.coerceAtMost(Long.MAX_VALUE / 10_000) * 10_000)
|
||||
.put("IsPaused", paused).put("CanSeek", true).put("PlayMethod", "DirectStream")
|
||||
try { transport.execute(EmbyRequest("POST", "/Sessions/$event", payload.toString(), currentToken())) }
|
||||
catch (_: Exception) { /* Playback reports are best effort; never log response bodies or URLs. */ }
|
||||
if (event == "Playing/Stopped" && active === plan) active = null
|
||||
}
|
||||
fun close(): Boolean = synchronized(reportLock) {
|
||||
val auth = synchronized(this) { token } ?: return@synchronized true
|
||||
active?.let { report(it, "Playing/Stopped", lastPositionMs, true) }
|
||||
synchronized(this) { token = null }
|
||||
checkedEpisodes = emptyList(); candidateEpisodes = emptyMap(); channelEpisodes = emptyMap(); darkCandidates = emptyList(); darkLineup = emptyMap()
|
||||
try { transport.execute(EmbyRequest("POST", "/Sessions/Logout", token = auth)).status in 200..299 }
|
||||
catch (_: Exception) { false }
|
||||
}
|
||||
private fun encode(value: String) = URLEncoder.encode(value, "UTF-8")
|
||||
}
|
||||
|
||||
/** Invalidates an in-flight sign-in when its screen leaves or is backgrounded. */
|
||||
internal class EmbySessionSlot {
|
||||
private var generation = 0
|
||||
private var session: EmbySampleSession? = null
|
||||
@Synchronized fun ticket(): Int = generation
|
||||
@Synchronized fun attach(value: EmbySampleSession, ticket: Int): Boolean {
|
||||
if (ticket != generation || session != null) return false
|
||||
session = value; return true
|
||||
}
|
||||
@Synchronized fun clear(): EmbySampleSession? { generation++; return session.also { session = null } }
|
||||
}
|
||||
internal object EmbyCleanup {
|
||||
private val executor = java.util.concurrent.Executors.newSingleThreadExecutor { task -> Thread(task, "Orbit-session-cleanup").apply { isDaemon = true } }
|
||||
fun run(task: () -> Unit) { executor.execute { try { task() } catch (_: Exception) { } } }
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
internal data class EpisodeCandidate(val id: String, val title: String, val season: Int?, val episode: Int?, val durationMs: Long?, val mediaLabel: String = "")
|
||||
internal data class SeriesEpisodes(val series: SeriesCandidate, val episodes: List<EpisodeCandidate>, val moreAvailable: Boolean)
|
||||
|
||||
/** Metadata only: three approved series, one page of five episodes per series. */
|
||||
internal fun discoverSeriesEpisodes(transport: EmbyTransport, userId: String, token: () -> String,
|
||||
approved: List<SeriesCandidate>, checkActive: () -> Unit = {}): List<SeriesEpisodes> {
|
||||
require(EmbyClient.validId(userId))
|
||||
require(approved.size in 1..3 && approved.map { it.id }.distinct().size == approved.size)
|
||||
require(approved.all { EmbyClient.validId(it.id) })
|
||||
return approved.map { series ->
|
||||
checkActive()
|
||||
val response = transport.execute(EmbyRequest("GET", "/Shows/${series.id}/Episodes?UserId=$userId&StartIndex=0&Limit=5&Fields=MediaStreams&EnableImages=false&EnableUserData=false", token = token()))
|
||||
EmbyClient.expectSuccess(response.status, false)
|
||||
val body = EmbyClient.parse(response.body)
|
||||
val records = body.optJSONArray("Items") ?: throw EmbyCheckException("The provider did not return an episode sample.")
|
||||
val episodes = (0 until minOf(records.length(), 5)).mapNotNull { index ->
|
||||
val item = records.optJSONObject(index) ?: return@mapNotNull null
|
||||
val id = item.optString("Id")
|
||||
if (!EmbyClient.validId(id) || item.optString("Type") != "Episode") return@mapNotNull null
|
||||
val seriesId = item.optString("SeriesId")
|
||||
if (seriesId.isNotEmpty() && seriesId != series.id) return@mapNotNull null
|
||||
EpisodeCandidate(id, EmbyClient.clean(item.optString("Name"), 160).ifBlank { "Untitled episode" },
|
||||
item.optInt("ParentIndexNumber", -1).takeIf { it >= 0 },
|
||||
item.optInt("IndexNumber", -1).takeIf { it >= 0 },
|
||||
(item.optLong("RunTimeTicks", 0) / 10_000).takeIf { it in 1_000..SampleChannel.MAX_DURATION_MS }, episodeMediaLabel(item))
|
||||
}.distinctBy { it.id }.sortedWith(compareBy<EpisodeCandidate> { it.season ?: Int.MAX_VALUE }.thenBy { it.episode ?: Int.MAX_VALUE }.thenBy { it.id })
|
||||
SeriesEpisodes(series, episodes, body.optLong("TotalRecordCount", records.length().toLong()) > 5)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun episodeMediaLabel(item: org.json.JSONObject): String {
|
||||
val streams = item.optJSONArray("MediaStreams")
|
||||
val media = (0 until minOf(streams?.length() ?: 0, 32)).mapNotNull { streams?.optJSONObject(it) }
|
||||
val video = media.firstOrNull { it.optString("Type") == "Video" }
|
||||
val width = (video?.optInt("Width", 0) ?: item.optInt("Width", 0)).takeIf { it in 1..16384 }
|
||||
val height = (video?.optInt("Height", 0) ?: item.optInt("Height", 0)).takeIf { it in 1..16384 }
|
||||
val resolution = if (width != null && height != null) "${width}×${height}" else null
|
||||
val container = item.optString("Container").takeIf { it.isNotBlank() }?.let(::safeContainerLabel)
|
||||
val codecs = media.filter { it.optString("Type") in listOf("Video", "Audio") }
|
||||
.mapNotNull { EmbyClient.clean(it.optString("Codec"), 24).takeIf { value -> value.isNotBlank() } }.distinct().take(3)
|
||||
.joinToString(" / ").takeIf { it.isNotEmpty() }
|
||||
return listOfNotNull(resolution, container, codecs).joinToString(" • ")
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import android.os.Bundle
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.common.PlaybackException
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.ui.PlayerView
|
||||
import androidx.tv.material3.MaterialTheme
|
||||
import androidx.tv.material3.Text
|
||||
import kotlinx.coroutines.delay
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
internal val Navy = Color(0xFF071632)
|
||||
internal val Panel = Color(0xFF12356B)
|
||||
internal val Blue = Color(0xFF194C91)
|
||||
internal val Yellow = Color(0xFFFFDE59)
|
||||
internal val Muted = Color(0xFFB7CBE8)
|
||||
private fun elapsed(time: Long): String = "%02d:%02d".format(Locale.UK, time / 60000, (time / 1000) % 60)
|
||||
internal fun clock(time: Long) = SimpleDateFormat("HH:mm", Locale.UK).format(Date(time))
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
setContent { MaterialTheme { OrbitApp() } }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun OrbitButton(label: String, modifier: Modifier = Modifier, selected: Boolean = false,
|
||||
enabled: Boolean = true, onFocus: () -> Unit = {}, onClick: () -> Unit) {
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
Box(modifier.onFocusChanged { focused = it.isFocused; if (it.isFocused) onFocus() }
|
||||
.background(if (focused) Yellow else if (selected) Blue else Panel)
|
||||
.border(if (focused) 2.dp else 1.dp, if (focused) Color.White else Color(0xFF38629A))
|
||||
.clickable(enabled = enabled, onClick = onClick).padding(horizontal = 14.dp, vertical = 8.dp)) {
|
||||
Text(label, color = if (focused) Navy else Color.White, fontSize = 14.sp, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
||||
fontWeight = if (focused || selected) FontWeight.Bold else FontWeight.Normal)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OrbitApp() {
|
||||
var now by remember { mutableLongStateOf(System.currentTimeMillis()) }
|
||||
LaunchedEffect(Unit) { while (true) { now = System.currentTimeMillis(); delay(1000) } }
|
||||
var realChannelAvailable by remember { mutableStateOf(false) }
|
||||
var section by remember { mutableStateOf("TV Guide") }
|
||||
var tuned by remember { mutableIntStateOf(0) }
|
||||
var fullscreen by remember { mutableStateOf(false) }
|
||||
var selectedChannel by remember { mutableIntStateOf(0) }
|
||||
var selectedColumn by remember { mutableIntStateOf(0) }
|
||||
val selected = Schedule.guide(Schedule.channels[selectedChannel], now)[selectedColumn]
|
||||
var pinned by remember { mutableStateOf(false) }
|
||||
val tabFocus = remember { List(3) { FocusRequester() } }
|
||||
val programme = Schedule.programme(Schedule.channels[tuned], now)
|
||||
val context = androidx.compose.ui.platform.LocalContext.current
|
||||
val player = remember { ExoPlayer.Builder(context).build().apply {
|
||||
setMediaItem(MediaItem.fromUri("asset:///orbit-demo.mp4")); prepare(); playWhenReady = true
|
||||
} }
|
||||
DisposableEffect(player) { onDispose { player.release() } }
|
||||
var playbackError by remember { mutableStateOf<String?>(null) }
|
||||
DisposableEffect(player) {
|
||||
val listener = object : Player.Listener {
|
||||
override fun onPlayerError(error: PlaybackException) { playbackError = "Demo video could not play. Return to the guide and try again." }
|
||||
override fun onPlaybackStateChanged(state: Int) { if (state == Player.STATE_READY) playbackError = null }
|
||||
}
|
||||
player.addListener(listener)
|
||||
onDispose { player.removeListener(listener) }
|
||||
}
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
DisposableEffect(player, lifecycle, section, fullscreen, realChannelAvailable) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_STOP) player.pause()
|
||||
if (event == Lifecycle.Event.ON_START && ((section == "TV Guide" && !realChannelAvailable) || fullscreen)) player.play()
|
||||
}
|
||||
lifecycle.addObserver(observer)
|
||||
onDispose { lifecycle.removeObserver(observer) }
|
||||
}
|
||||
LaunchedEffect(section, fullscreen, realChannelAvailable) {
|
||||
if ((section == "TV Guide" && !realChannelAvailable) || fullscreen) player.play() else player.pause()
|
||||
}
|
||||
LaunchedEffect(tuned, programme.start) {
|
||||
player.seekTo(programme.offsetAt(System.currentTimeMillis())); if ((section == "TV Guide" && !realChannelAvailable) || fullscreen) player.play()
|
||||
}
|
||||
// Recheck on resume: a stopped app must rejoin the wall-clock schedule.
|
||||
DisposableEffect(lifecycle, tuned) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME) {
|
||||
val time = System.currentTimeMillis()
|
||||
player.seekTo(Schedule.programme(Schedule.channels[tuned], time).offsetAt(time))
|
||||
}
|
||||
}
|
||||
lifecycle.addObserver(observer)
|
||||
onDispose { lifecycle.removeObserver(observer) }
|
||||
}
|
||||
BackHandler(fullscreen || pinned || section != "TV Guide") {
|
||||
when { fullscreen -> fullscreen = false; pinned -> pinned = false; section == "Services" || section == "Connect Emby" -> section = "Menu"; else -> section = "TV Guide" }
|
||||
}
|
||||
LaunchedEffect(section, fullscreen) {
|
||||
if (!fullscreen) {
|
||||
val tab = when (section) { "TV Guide" -> 1; "Box Office" -> 2; else -> 0 }
|
||||
tabFocus[tab].requestFocus()
|
||||
}
|
||||
}
|
||||
Box(Modifier.fillMaxSize().background(Navy)) {
|
||||
if (fullscreen) {
|
||||
Video(player, Modifier.fillMaxSize())
|
||||
Column(Modifier.align(Alignment.BottomStart).fillMaxWidth().background(Navy.copy(alpha = .92f)).padding(24.dp)) {
|
||||
Text("${Schedule.channels[tuned].number} ${Schedule.channels[tuned].name}", color = Yellow, fontSize = 20.sp)
|
||||
Text(programme.title, color = Color.White, fontSize = 26.sp, fontWeight = FontWeight.Bold)
|
||||
Text(playbackError ?: "${clock(programme.start)}–${clock(programme.end)} • Demo signal ${elapsed(player.currentPosition)} / 30:00 • Back for guide", color = Muted, fontSize = 15.sp)
|
||||
}
|
||||
} else Column(Modifier.fillMaxSize().padding(horizontal = 36.dp, vertical = 16.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("◉ orbit", color = Color.White, fontSize = 30.sp, fontWeight = FontWeight.Bold)
|
||||
Text(" / Classic", color = Muted, fontSize = 19.sp)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(SimpleDateFormat("EEE d MMM HH:mm", Locale.UK).format(Date(now)), color = Color.White, fontSize = 17.sp)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
listOf("Menu", "TV Guide", "Box Office").forEachIndexed { index, title ->
|
||||
OrbitButton("${index + 1} $title", Modifier.focusRequester(tabFocus[index]),
|
||||
section == title, onClick = { section = title; pinned = false })
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
if (section == "TV Guide" && !realChannelAvailable) {
|
||||
Row(Modifier.fillMaxWidth().height(120.dp), horizontalArrangement = Arrangement.spacedBy(20.dp)) {
|
||||
Box(Modifier.width(256.dp).fillMaxHeight().border(1.dp, Muted)) {
|
||||
Video(player, Modifier.fillMaxSize())
|
||||
Text(if (playbackError == null) "Demo transmission" else "Video unavailable", Modifier.align(Alignment.BottomStart).background(Navy).padding(5.dp), color = Yellow, fontSize = 12.sp)
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(if (pinned) "Programme information" else "${Schedule.channels[selectedChannel].name} / ${clock(selected.start)}–${clock(selected.end)}", color = Yellow, fontSize = 15.sp)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(selected.title, color = Color.White, fontSize = 21.sp, fontWeight = FontWeight.Bold)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(selected.synopsis, color = Muted, fontSize = 16.sp)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(if (pinned) "Future programme • Back to browse" else "All programmes and video in this prototype are fictional.", color = Muted, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(Modifier.fillMaxWidth().background(Blue).padding(vertical = 6.dp)) {
|
||||
Text("Channel", Modifier.width(170.dp).padding(start = 12.dp), color = Color.White, fontSize = 14.sp)
|
||||
repeat(3) { Text(clock(Math.floorDiv(now, Schedule.SLOT) * Schedule.SLOT + it * Schedule.SLOT), Modifier.weight(1f).padding(start = 12.dp), color = Color.White, fontSize = 14.sp) }
|
||||
}
|
||||
Column(Modifier.weight(1f).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Schedule.channels.forEachIndexed { channelIndex, channel ->
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.width(165.dp).padding(start = 12.dp)) {
|
||||
Text(channel.number.toString(), color = Yellow, fontSize = 15.sp)
|
||||
Text(channel.name, color = Color.White, fontSize = 16.sp)
|
||||
}
|
||||
Schedule.guide(channel, now).forEachIndexed { columnIndex, show ->
|
||||
OrbitButton(show.title, Modifier.weight(1f), onFocus = {
|
||||
selectedColumn = columnIndex; selectedChannel = channelIndex; pinned = false
|
||||
}, onClick = {
|
||||
selectedColumn = columnIndex; selectedChannel = channelIndex
|
||||
if (now >= show.start && now < show.end) {
|
||||
tuned = channelIndex; fullscreen = true
|
||||
if (playbackError != null) player.prepare()
|
||||
player.seekTo(show.offsetAt(now)); player.play()
|
||||
} else pinned = true
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text("Arrows Browse OK Watch now / programme info Back Return", color = Muted, fontSize = 13.sp)
|
||||
} else if (section == "Menu") {
|
||||
OrbitMenu(Modifier.weight(1f), onNavigate = { section = it; pinned = false })
|
||||
} else if (section == "Connect Emby") {
|
||||
// Connection content is kept composed below to retain the temporary session.
|
||||
} else if (section == "Box Office") {
|
||||
OrbOffice(Modifier.weight(1f), onGuide = { section = "TV Guide" })
|
||||
} else if (section != "TV Guide") {
|
||||
Column(Modifier.fillMaxWidth().weight(1f).background(Panel).padding(28.dp)) {
|
||||
Text("Welcome to Orbit Interactive", color = Yellow, fontSize = 27.sp, fontWeight = FontWeight.Bold)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Text("OrbHive Bedlam is on the roadmap. Games, channel setup and theme selection will live here.", color = Color.White, fontSize = 21.sp)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Text("Coming later", color = Muted, fontSize = 16.sp)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
OrbitButton("Return to TV Guide", onClick = { section = "TV Guide" })
|
||||
}
|
||||
}
|
||||
EmbyConnectionScreen(Modifier.weight(1f), visible = section == "Connect Emby",
|
||||
mainGuide = section == "TV Guide" && realChannelAvailable,
|
||||
onChannelAvailable = { realChannelAvailable = it },
|
||||
onGuide = { section = "TV Guide" }, onBack = { section = "Menu" })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Video(player: ExoPlayer, modifier: Modifier) {
|
||||
AndroidView(modifier = modifier, factory = { context -> PlayerView(context).apply {
|
||||
useController = false; isFocusable = false; descendantFocusability = android.view.ViewGroup.FOCUS_BLOCK_DESCENDANTS
|
||||
this.player = player
|
||||
} }, update = { it.player = player }, onRelease = { it.player = null })
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.PathEffect
|
||||
import androidx.compose.ui.text.font.Font
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.tv.material3.Text
|
||||
|
||||
private val Barlow = FontFamily(Font(R.font.barlow_regular), Font(R.font.barlow_semibold, FontWeight.SemiBold))
|
||||
private val TicketType = FontFamily(Font(R.font.barlow_condensed_medium))
|
||||
private val Paper = Color(0xFFF7EAC8)
|
||||
|
||||
private data class OfficeEvent(val title: String, val collection: String, val time: String,
|
||||
val synopsis: String, val reference: String)
|
||||
private val officeEvents = listOf(
|
||||
OfficeEvent("The Last Shuttle Home", "Orbit premieres", "Tonight at 21:30",
|
||||
"One final journey brings an unlikely crew together. A fictional premiere for your own front-row seat.", "ORB-001"),
|
||||
OfficeEvent("Visitors at Dawn", "After dark", "Tonight at 23:00",
|
||||
"First contact arrives in the quietest corner of Earth. A fictional late-night science-fiction special.", "ORB-002")
|
||||
)
|
||||
|
||||
@Composable
|
||||
internal fun OrbitMenu(modifier: Modifier = Modifier, onNavigate: (String) -> Unit) {
|
||||
Row(modifier.fillMaxWidth().background(Panel).padding(24.dp), horizontalArrangement = Arrangement.spacedBy(30.dp)) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Your evening starts here.", color = Yellow, fontFamily = Barlow, fontWeight = FontWeight.SemiBold, fontSize = 30.sp)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text("Your collection. Your channels.\nYour television.", color = Color.White, fontFamily = Barlow, fontSize = 24.sp, lineHeight = 29.sp)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text("Orbit Classic", color = Muted, fontFamily = TicketType, fontSize = 25.sp)
|
||||
Text("The satellite spirit, in your universe.", color = Muted, fontFamily = Barlow, fontSize = 16.sp)
|
||||
}
|
||||
Column(Modifier.weight(1f).align(Alignment.CenterVertically), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
OrbitButton("Connect Emby / Check a small sample", Modifier.fillMaxWidth(), onClick = { onNavigate("Connect Emby") })
|
||||
OrbitButton("TV Guide / What's on now", Modifier.fillMaxWidth(), onClick = { onNavigate("TV Guide") })
|
||||
OrbitButton("OrbOffice / Special transmissions", Modifier.fillMaxWidth(), onClick = { onNavigate("Box Office") })
|
||||
OrbitButton("Services / Orbit Interactive", Modifier.fillMaxWidth(), onClick = { onNavigate("Services") })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun OrbOffice(modifier: Modifier = Modifier, onGuide: () -> Unit) {
|
||||
var selectedEvent by remember { mutableIntStateOf(0) }
|
||||
val event = officeEvents[selectedEvent]
|
||||
Row(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(24.dp)) {
|
||||
Column(Modifier.weight(1.55f).fillMaxHeight()) {
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
Text("OrbOffice", color = Yellow, fontFamily = TicketType, fontSize = 36.sp)
|
||||
Text(" Your front-row seat.", color = Muted, fontFamily = Barlow, fontSize = 17.sp, modifier = Modifier.padding(bottom = 5.dp))
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
AdmissionTicket(event, Modifier.fillMaxWidth().weight(1f))
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text("Preview ticket • Fictional event • Included in your collection", color = Muted, fontFamily = Barlow, fontSize = 13.sp)
|
||||
}
|
||||
Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text("Special transmissions", color = Color.White, fontFamily = Barlow, fontWeight = FontWeight.SemiBold, fontSize = 23.sp)
|
||||
officeEvents.forEachIndexed { index, item ->
|
||||
OrbitButton(item.collection, Modifier.fillMaxWidth(), selected = selectedEvent == index,
|
||||
onFocus = { selectedEvent = index }, onClick = { selectedEvent = index })
|
||||
}
|
||||
Text(event.synopsis, color = Muted, fontFamily = Barlow, fontSize = 18.sp, lineHeight = 23.sp)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text("Event playback comes with the Emby connection. For now, explore the ticket and the guide.", color = Muted, fontFamily = Barlow, fontSize = 14.sp)
|
||||
OrbitButton("Return to TV Guide", Modifier.fillMaxWidth(), onClick = onGuide)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AdmissionTicket(event: OfficeEvent, modifier: Modifier = Modifier) {
|
||||
Box(modifier.background(Paper)) {
|
||||
Canvas(Modifier.matchParentSize()) {
|
||||
val seam = size.width * .76f
|
||||
drawLine(Navy.copy(alpha = .45f), Offset(seam, 0f), Offset(seam, size.height),
|
||||
strokeWidth = 1.dp.toPx(), pathEffect = PathEffect.dashPathEffect(floatArrayOf(5.dp.toPx(), 5.dp.toPx())))
|
||||
for (i in 0..11) {
|
||||
val y = (i + .5f) * size.height / 12
|
||||
drawCircle(Navy, 5.dp.toPx(), Offset(0f, y))
|
||||
drawCircle(Navy, 5.dp.toPx(), Offset(size.width, y))
|
||||
}
|
||||
drawCircle(Navy, 9.dp.toPx(), Offset(seam, 0f))
|
||||
drawCircle(Navy, 9.dp.toPx(), Offset(seam, size.height))
|
||||
}
|
||||
Row(Modifier.fillMaxSize()) {
|
||||
Column(Modifier.weight(.76f).fillMaxHeight().padding(horizontal = 22.dp, vertical = 18.dp)) {
|
||||
Text("OrbOffice", color = Navy, fontFamily = TicketType, fontSize = 27.sp)
|
||||
Text(event.collection, color = Navy, fontFamily = Barlow, fontSize = 14.sp)
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Text(event.title, color = Navy, fontFamily = TicketType, fontSize = 33.sp, lineHeight = 35.sp, maxLines = 3)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(event.time, color = Navy, fontFamily = Barlow, fontWeight = FontWeight.SemiBold, fontSize = 18.sp)
|
||||
Text("One universe. Best seat in the house.", color = Navy.copy(alpha = .75f), fontFamily = Barlow, fontSize = 14.sp)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text("Admit one", Modifier.background(Yellow).padding(horizontal = 14.dp, vertical = 5.dp), color = Navy, fontFamily = TicketType, fontSize = 23.sp)
|
||||
}
|
||||
Column(Modifier.weight(.24f).fillMaxHeight().padding(horizontal = 10.dp, vertical = 22.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text("orbit", color = Navy, fontFamily = Barlow, fontWeight = FontWeight.SemiBold, fontSize = 21.sp)
|
||||
Text("Front row", color = Navy, fontFamily = TicketType, fontSize = 19.sp)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text("01", color = Navy, fontFamily = TicketType, fontSize = 52.sp)
|
||||
Text("Seat", color = Navy, fontFamily = Barlow, fontSize = 14.sp)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(event.reference, color = Navy, fontFamily = TicketType, fontSize = 17.sp)
|
||||
Text("Preview", color = Navy.copy(alpha = .65f), fontFamily = Barlow, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import android.content.Context
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.AtomicFile
|
||||
import java.io.File
|
||||
import java.security.KeyStore
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
internal object ConnectionCipher {
|
||||
private val aad = "tv.orbit.classic/remembered-connection/v1".toByteArray(Charsets.UTF_8)
|
||||
fun seal(key: SecretKey, plain: ByteArray): ByteArray {
|
||||
require(plain.size <= RememberedStateCodec.MAX_BYTES)
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key); cipher.updateAAD(aad)
|
||||
require(cipher.iv.size == 12)
|
||||
return byteArrayOf(1) + cipher.iv + cipher.doFinal(plain)
|
||||
}
|
||||
fun open(key: SecretKey, envelope: ByteArray): ByteArray {
|
||||
require(envelope.size in 29..(RememberedStateCodec.MAX_BYTES + 29) && envelope[0] == 1.toByte())
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, envelope.copyOfRange(1, 13)))
|
||||
cipher.updateAAD(aad)
|
||||
return cipher.doFinal(envelope.copyOfRange(13, envelope.size))
|
||||
}
|
||||
}
|
||||
|
||||
/** App-private, backup-excluded, authenticated ciphertext only. All operations serialize. */
|
||||
internal class RememberedConnectionStore private constructor(context: Context) {
|
||||
companion object {
|
||||
private var instance: RememberedConnectionStore? = null
|
||||
@Synchronized fun get(context: Context): RememberedConnectionStore = instance
|
||||
?: RememberedConnectionStore(context.applicationContext).also { instance = it }
|
||||
}
|
||||
@Synchronized fun invalidate() { generation++ }
|
||||
private val file = AtomicFile(File(context.noBackupFilesDir, "orbit-connection.v1"))
|
||||
private val alias = "orbit-connection-key-v1"
|
||||
private var generation = 0L
|
||||
@Synchronized fun ticket() = generation
|
||||
private fun key(create: Boolean): SecretKey {
|
||||
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
(store.getKey(alias, null) as? SecretKey)?.let { return it }
|
||||
check(create)
|
||||
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
|
||||
init(KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(256).setRandomizedEncryptionRequired(true).build())
|
||||
}.generateKey()
|
||||
}
|
||||
@Synchronized fun load(): RememberedState? {
|
||||
if (!file.baseFile.exists() && !File(file.baseFile.path + ".bak").exists()) return null
|
||||
return file.openRead().use { input ->
|
||||
val bytes = input.readBytesLimited(RememberedStateCodec.MAX_BYTES + 29)
|
||||
RememberedStateCodec.decode(ConnectionCipher.open(key(false), bytes))
|
||||
}
|
||||
}
|
||||
@Synchronized fun save(state: RememberedState, ticket: Long): Boolean {
|
||||
if (ticket != generation) return false
|
||||
val plain = RememberedStateCodec.encode(state)
|
||||
// Validate the same bounded schema before committing it.
|
||||
RememberedStateCodec.decode(plain)
|
||||
val encrypted = ConnectionCipher.seal(key(true), plain)
|
||||
val output = file.startWrite()
|
||||
try { output.write(encrypted); file.finishWrite(output) }
|
||||
catch (failure: Exception) { file.failWrite(output); throw failure }
|
||||
return true
|
||||
}
|
||||
@Synchronized fun clear() {
|
||||
generation++
|
||||
file.delete()
|
||||
KeyStore.getInstance("AndroidKeyStore").apply { load(null); if (containsAlias(alias)) deleteEntry(alias) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun java.io.InputStream.readBytesLimited(max: Int): ByteArray {
|
||||
val output = java.io.ByteArrayOutputStream()
|
||||
val buffer = ByteArray(8192)
|
||||
while (true) {
|
||||
val count = read(buffer); if (count < 0) break
|
||||
require(output.size() + count <= max)
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
return output.toByteArray()
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
// Intentionally not data classes: default toString must never expose an access token.
|
||||
internal class RememberedIdentity(val userId: String, val token: String?, val deviceId: String)
|
||||
internal class RememberedState(val identity: RememberedIdentity, val sample: EmbySample,
|
||||
val matches: List<SeriesMatches>, val approved: Set<String>, val episodes: List<SeriesEpisodes>?,
|
||||
val orbitOne: SampleChannel?, val toonami: SampleChannel?, val selectedNumber: Int,
|
||||
val afterDark: SampleChannel? = null, val darkMovies: List<AfterDarkMovie> = emptyList(), val approvedDark: Set<String> = emptySet()) {
|
||||
fun withoutToken() = RememberedState(RememberedIdentity(identity.userId, null, identity.deviceId), sample,
|
||||
matches, approved, episodes, orbitOne, toonami, selectedNumber, afterDark, darkMovies, approvedDark)
|
||||
}
|
||||
|
||||
internal object RememberedStateCodec {
|
||||
const val MAX_BYTES = 512 * 1024
|
||||
private fun arr(items: Iterable<JSONObject>) = JSONArray().also { a -> items.forEach { a.put(it) } }
|
||||
private fun candidate(s: SeriesCandidate) = JSONObject().put("id", s.id).put("title", s.title)
|
||||
.put("year", s.year ?: JSONObject.NULL).put("rating", s.rating).put("variant", s.variantLabel)
|
||||
private fun item(s: SampleItem) = JSONObject().put("id", s.id).put("title", s.title).put("type", s.type)
|
||||
.put("format", s.format).put("duration", s.durationMs ?: JSONObject.NULL)
|
||||
private fun channel(c: SampleChannel?) = c?.let { JSONObject().put("number", it.number).put("name", it.name)
|
||||
.put("entries", arr(it.lineup.map { m -> JSONObject().put("item", item(m.item)).put("source", m.sourceId).put("duration", m.durationMs) })) } ?: JSONObject.NULL
|
||||
fun encode(state: RememberedState): ByteArray {
|
||||
val i = state.identity
|
||||
val root = JSONObject().put("schema", 1).put("origin", HttpsEmbyTransport.SERVER)
|
||||
.put("user", i.userId).put("token", i.token ?: JSONObject.NULL).put("device", i.deviceId)
|
||||
.put("sample", arr(state.sample.items.map(::item))).put("total", state.sample.total ?: JSONObject.NULL)
|
||||
.put("matches", arr(state.matches.map { m -> JSONObject().put("requested", m.requested).put("more", m.moreAvailable).put("candidates", arr(m.candidates.map(::candidate))) }))
|
||||
.put("approved", JSONArray(state.approved.toList())).put("selected", if (state.selectedNumber == 102) 101 else state.selectedNumber)
|
||||
.put("selectedChannel", state.selectedNumber).put("afterDark", channel(state.afterDark))
|
||||
.put("darkMovies", arr(state.darkMovies.map { movie -> JSONObject().put("item", item(movie.item)).put("year", movie.year ?: JSONObject.NULL)
|
||||
.put("rating", movie.rating).put("genres", JSONArray(movie.genres)) }))
|
||||
.put("approvedDark", JSONArray(state.approvedDark.toList()))
|
||||
.put("one", channel(state.orbitOne)).put("toonami", channel(state.toonami))
|
||||
.put("episodes", state.episodes?.let { groups -> arr(groups.map { group -> JSONObject().put("series", candidate(group.series)).put("more", group.moreAvailable)
|
||||
.put("items", arr(group.episodes.map { e -> JSONObject().put("id", e.id).put("title", e.title)
|
||||
.put("season", e.season ?: JSONObject.NULL).put("episode", e.episode ?: JSONObject.NULL)
|
||||
.put("duration", e.durationMs ?: JSONObject.NULL).put("media", e.mediaLabel) })) }) } ?: JSONObject.NULL)
|
||||
return root.toString().toByteArray(Charsets.UTF_8).also { require(it.size <= MAX_BYTES) }
|
||||
}
|
||||
private fun text(o: JSONObject, key: String, max: Int, blank: Boolean = true): String = o.getString(key).also {
|
||||
require(it.length <= max && (blank || it.isNotBlank()) && it.none(Char::isISOControl))
|
||||
}
|
||||
private fun id(o: JSONObject, key: String) = text(o, key, 128, false).also { require(EmbyClient.validId(it)) }
|
||||
private fun list(o: JSONObject, key: String, max: Int): List<JSONObject> = o.getJSONArray(key).let { a ->
|
||||
require(a.length() <= max); (0 until a.length()).map { a.getJSONObject(it) }
|
||||
}
|
||||
private fun duration(o: JSONObject) = if (o.isNull("duration")) null else o.getLong("duration").also { require(it in 1..SampleChannel.MAX_DURATION_MS) }
|
||||
private fun readItem(o: JSONObject): SampleItem {
|
||||
val d = duration(o)
|
||||
return SampleItem(text(o, "title", 600, false), text(o, "type", 16).also { require(it in listOf("Movie", "Episode")) }, d?.div(60_000), text(o, "format", 160), id(o, "id"), d)
|
||||
}
|
||||
private fun readCandidate(o: JSONObject) = SeriesCandidate(id(o, "id"), text(o, "title", 160, false),
|
||||
if (o.isNull("year")) null else o.getInt("year").also { require(it in 1800..2200) }, text(o, "rating", 40), text(o, "variant", 40))
|
||||
private fun readChannel(o: JSONObject, key: String, number: Int): SampleChannel? {
|
||||
if (o.isNull(key)) return null
|
||||
val c = o.getJSONObject(key); require(c.getInt("number") == number)
|
||||
return SampleChannel(list(c, "entries", 15).map { m -> ScheduledMedia(readItem(m.getJSONObject("item")), id(m, "source"), requireNotNull(duration(m))) }, text(c, "name", 80, false), number)
|
||||
}
|
||||
fun decode(bytes: ByteArray): RememberedState {
|
||||
require(bytes.size <= MAX_BYTES)
|
||||
val o = JSONObject(bytes.toString(Charsets.UTF_8)); require(o.getInt("schema") == 1 && o.getString("origin") == HttpsEmbyTransport.SERVER)
|
||||
val token = if (o.isNull("token")) null else o.getString("token").also { require(it.isNotEmpty() && it.length <= 4096 && it.all { c -> c.code in 33..126 }) }
|
||||
val identity = RememberedIdentity(id(o, "user"), token, id(o, "device"))
|
||||
val sample = EmbySample(list(o, "sample", 20).map(::readItem), if (o.isNull("total")) null else o.getLong("total").also { require(it >= 0) })
|
||||
val matches = list(o, "matches", ToonamiSearches.size).map { m -> SeriesMatches(text(m, "requested", 80).also { require(it in ToonamiSearches) }, list(m, "candidates", 10).map(::readCandidate), m.getBoolean("more")) }
|
||||
require(matches.map { it.requested } == ToonamiSearches.take(matches.size))
|
||||
val approvedArray = o.getJSONArray("approved"); require(approvedArray.length() <= 3)
|
||||
val approved = (0 until approvedArray.length()).map { approvedArray.getString(it) }.toSet()
|
||||
require(approved.all { value -> matches.any { m -> m.candidates.any { it.id == value } } })
|
||||
val episodes = if (o.isNull("episodes")) null else list(o, "episodes", 3).map { group ->
|
||||
val series = readCandidate(group.getJSONObject("series")); require(series.id in approved)
|
||||
SeriesEpisodes(series, list(group, "items", 5).map { e -> EpisodeCandidate(id(e, "id"), text(e, "title", 160, false),
|
||||
if (e.isNull("season")) null else e.getInt("season").also { require(it >= 0) },
|
||||
if (e.isNull("episode")) null else e.getInt("episode").also { require(it >= 0) }, duration(e), text(e, "media", 200)) }, group.getBoolean("more"))
|
||||
}
|
||||
val one = readChannel(o, "one", 101); val toonami = readChannel(o, "toonami", 103)
|
||||
require(one == null || one.lineup.all { m -> sample.items.any { it.id == m.item.id } })
|
||||
val dark = readChannel(o, "afterDark", 102)
|
||||
require(dark == null || (dark.lineup.size in 2..3 && dark.lineup.all { it.item.type == "Movie" }))
|
||||
val darkMovies = if (!o.has("darkMovies")) emptyList() else list(o, "darkMovies", 60).map { movie ->
|
||||
val media = readItem(movie.getJSONObject("item")); require(media.type == "Movie")
|
||||
val genres = movie.getJSONArray("genres"); require(genres.length() <= 8)
|
||||
AfterDarkMovie(media, if (movie.isNull("year")) null else movie.getInt("year").also { require(it in 1800..2200) },
|
||||
text(movie, "rating", 40), (0 until genres.length()).map { i -> genres.getString(i).also { require(it.length <= 40 && it.none(Char::isISOControl)) } })
|
||||
}
|
||||
require(darkMovies.map { it.item.id }.distinct().size == darkMovies.size)
|
||||
val darkApproval = o.optJSONArray("approvedDark") ?: JSONArray()
|
||||
require(darkApproval.length() <= 3)
|
||||
val approvedDark = (0 until darkApproval.length()).map { darkApproval.getString(it) }.toSet()
|
||||
require(approvedDark.all { value -> darkMovies.any { it.item.id == value } })
|
||||
val selected = o.optInt("selectedChannel", o.getInt("selected")); require(selected in 101..103)
|
||||
return RememberedState(identity, sample, matches, approved, episodes, one, toonami, selected, dark, darkMovies, approvedDark)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
internal data class ScheduledMedia(val item: SampleItem, val sourceId: String, val durationMs: Long)
|
||||
internal data class SampleBroadcast(val media: ScheduledMedia, val startMs: Long) {
|
||||
val endMs: Long get() = startMs + media.durationMs
|
||||
fun offsetAt(timeMs: Long) = (timeMs - startMs).coerceIn(0, media.durationMs - 1)
|
||||
}
|
||||
|
||||
/** A repeating UTC timeline: it advances even when no screen or player exists. */
|
||||
internal class SampleChannel(entries: List<ScheduledMedia>, val name: String = "Orbit One", val number: Int = 101) {
|
||||
val lineup = entries.toList()
|
||||
companion object { const val MAX_DURATION_MS = 7 * 24 * 60 * 60 * 1000L }
|
||||
init {
|
||||
require(lineup.size in 2..15)
|
||||
require(lineup.map { it.item.id }.distinct().size == lineup.size)
|
||||
require(lineup.all { EmbyClient.validId(it.item.id) && EmbyClient.validId(it.sourceId) && it.durationMs in 1_000..MAX_DURATION_MS })
|
||||
}
|
||||
val cycleMs = lineup.sumOf { it.durationMs }
|
||||
fun at(timeMs: Long): SampleBroadcast {
|
||||
require(timeMs in -8_000_000_000_000_000L..8_000_000_000_000_000L)
|
||||
val position = Math.floorMod(timeMs, cycleMs)
|
||||
var cursor = 0L
|
||||
for (media in lineup) {
|
||||
if (position < cursor + media.durationMs) return SampleBroadcast(media, timeMs - position + cursor)
|
||||
cursor += media.durationMs
|
||||
}
|
||||
error("Unreachable channel position")
|
||||
}
|
||||
fun guide(timeMs: Long, count: Int = 6): List<SampleBroadcast> {
|
||||
require(count in 1..48)
|
||||
var current = at(timeMs)
|
||||
return List(count) { current.also { current = at(it.endMs) } }
|
||||
}
|
||||
fun transitionCheckOffset(timeMs: Long): Long {
|
||||
val programme = at(timeMs)
|
||||
val remaining = minOf(10_000L, programme.media.durationMs / 2).coerceAtLeast(1)
|
||||
return programme.endMs - remaining - timeMs
|
||||
}
|
||||
}
|
||||
|
||||
internal data class ScheduledPlayback(val channel: SampleChannel, val programme: SampleBroadcast,
|
||||
val next: SampleBroadcast, val clockOffsetMs: Long = 0) {
|
||||
fun nowMs() = System.currentTimeMillis() + clockOffsetMs
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.compose.ui.window.SecureFlagPolicy
|
||||
import androidx.tv.material3.Text
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
@Composable
|
||||
internal fun SampleChannelGuide(channel: SampleChannel, modifier: Modifier = Modifier,
|
||||
onTune: (Long) -> Unit, onBack: () -> Unit, otherChannels: List<SampleChannel> = emptyList(), onSwitch: (Int) -> Unit = {}) {
|
||||
var now by remember { mutableLongStateOf(System.currentTimeMillis()) }
|
||||
LaunchedEffect(Unit) { while (true) { delay(1000); now = System.currentTimeMillis() } }
|
||||
val shows = channel.guide(now)
|
||||
val tuneFocus = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) { tuneFocus.requestFocus() }
|
||||
BackHandler(onBack = onBack)
|
||||
val branding = ChannelBrands.forNumber(channel.number)
|
||||
Box(modifier.fillMaxWidth().background(if (branding != null) Navy else Panel)) {
|
||||
if (branding != null) Image(painterResource(branding.background), null, Modifier.matchParentSize(), contentScale = ContentScale.Crop, alpha = .65f)
|
||||
Column(Modifier.fillMaxSize().padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("TV Guide", color = Yellow, fontSize = 26.sp, fontWeight = FontWeight.Bold)
|
||||
Spacer(Modifier.weight(1f))
|
||||
otherChannels.forEach { other -> OrbitButton("${other.number} ${other.name}", onClick = { onSwitch(other.number) }) }
|
||||
Text(clock(now), color = Color.White, fontSize = 20.sp)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||
Column(Modifier.width(125.dp)) {
|
||||
Text(channel.number.toString(), color = Yellow, fontSize = 36.sp, fontWeight = FontWeight.Bold)
|
||||
if (branding != null) Image(painterResource(branding.logo), channel.name, Modifier.width(125.dp).height(40.dp))
|
||||
else Text(channel.name, color = Color.White, fontSize = 19.sp)
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("NOW ${clock(shows[0].startMs)}–${clock(shows[0].endMs)}", color = Yellow, fontSize = 15.sp)
|
||||
Text(shows[0].media.item.title, color = Color.White, fontSize = 23.sp, maxLines = 2)
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("NEXT ${clock(shows[1].startMs)}", color = Muted, fontSize = 15.sp)
|
||||
Text(shows[1].media.item.title, color = Color.White, fontSize = 21.sp, maxLines = 2)
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
items(shows.drop(1), key = { it.startMs }) { show ->
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
Row(Modifier.fillMaxWidth().onFocusChanged { focused = it.isFocused }.background(Blue)
|
||||
.border(1.dp, if (focused) Yellow else Blue).focusable().padding(10.dp), horizontalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||
Text("${clock(show.startMs)}–${clock(show.endMs)}", color = Yellow, fontSize = 15.sp, modifier = Modifier.width(125.dp))
|
||||
Text(show.media.item.title, color = Color.White, fontSize = 16.sp, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
OrbitButton("Watch channel", Modifier.focusRequester(tuneFocus), onClick = { onTune(0) })
|
||||
OrbitButton("Check transition", onClick = { onTune(channel.transitionCheckOffset(System.currentTimeMillis())) })
|
||||
OrbitButton("Menu", onClick = onBack)
|
||||
}
|
||||
Text("${channel.lineup.size} titles • Transition check joins near the end and may update your provider’s viewing history.", color = Muted, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ScheduledChannelPlayer(session: EmbySampleSession, channel: SampleChannel, clockOffsetMs: Long,
|
||||
onClose: () -> Unit) {
|
||||
var now by remember { mutableLongStateOf(System.currentTimeMillis() + clockOffsetMs) }
|
||||
LaunchedEffect(channel, clockOffsetMs) { while (true) { now = System.currentTimeMillis() + clockOffsetMs; delay(250) } }
|
||||
val shows = channel.guide(now, 2)
|
||||
val current = shows[0]
|
||||
val prepareMutex = remember(channel) { Mutex() }
|
||||
var prepared by remember(channel) { mutableStateOf<EmbyPlaybackPlan?>(null) }
|
||||
var preparedSlot by remember(channel) { mutableStateOf<Long?>(null) }
|
||||
var problem by remember(channel) { mutableStateOf<String?>(null) }
|
||||
var retryAttempt by remember(channel) { mutableIntStateOf(0) }
|
||||
// A new wall-clock slot disposes the old player before opening its successor.
|
||||
LaunchedEffect(channel, current.startMs, retryAttempt) {
|
||||
prepared = null; preparedSlot = null; problem = null
|
||||
try {
|
||||
val plan = prepareMutex.withLock {
|
||||
withContext(Dispatchers.IO) {
|
||||
session.prepare(current.media.item, preferredSourceId = current.media.sourceId)
|
||||
}
|
||||
}
|
||||
if (plan.durationMs == null || kotlin.math.abs(plan.durationMs - current.media.durationMs) > 2_000)
|
||||
throw EmbyCheckException("This programme's runtime changed. Return and rebuild the sample channel.")
|
||||
preparedSlot = current.startMs; prepared = plan
|
||||
} catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: EmbyCheckException) { problem = failure.message }
|
||||
catch (_: Exception) { problem = "This scheduled programme could not be opened. Return to the guide and try again." }
|
||||
}
|
||||
// Suppress the preceding plan immediately at a boundary while the effect schedules its replacement.
|
||||
val plan = prepared?.takeIf { it.item.id == current.media.item.id && preparedSlot == current.startMs && problem == null }
|
||||
if (plan != null) {
|
||||
key(current.startMs) {
|
||||
EmbyPlaybackDialog(session, plan, onClose,
|
||||
scheduled = ScheduledPlayback(channel, current, shows[1], clockOffsetMs))
|
||||
}
|
||||
} else Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false,
|
||||
decorFitsSystemWindows = false, securePolicy = SecureFlagPolicy.SecureOn)) {
|
||||
if (problem == null) ChannelTuningBackdrop(channel.number)
|
||||
else Box(Modifier.fillMaxSize().background(Navy)) {
|
||||
Column(Modifier.align(Alignment.Center).widthIn(max = 620.dp).padding(32.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(problem.orEmpty(), color = Color.White, fontSize = 20.sp)
|
||||
val retryFocus = remember { FocusRequester() }
|
||||
LaunchedEffect(problem) { retryFocus.requestFocus() }
|
||||
OrbitButton("Retry", Modifier.focusRequester(retryFocus), onClick = {
|
||||
problem = null
|
||||
retryAttempt++
|
||||
})
|
||||
OrbitButton("Return to TV guide", onClick = onClose)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ClassicTuningNumber(number: Int, modifier: Modifier = Modifier) {
|
||||
Text(number.toString(), modifier = modifier, color = Color(0xFF47FF52), fontSize = 46.sp,
|
||||
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
|
||||
fontWeight = FontWeight.Bold,
|
||||
style = androidx.compose.ui.text.TextStyle(shadow = androidx.compose.ui.graphics.Shadow(
|
||||
Color.Black, androidx.compose.ui.geometry.Offset(2f, 2f), 2f)))
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
/** Fixed UTC slots survive process restarts; only display formatting uses local time. */
|
||||
data class Programme(val title: String, val synopsis: String, val start: Long, val duration: Long) {
|
||||
val end: Long get() = start + duration
|
||||
fun offsetAt(now: Long): Long = (now - start).coerceIn(0, duration - 1)
|
||||
}
|
||||
data class Channel(val number: Int, val name: String, val shows: List<Pair<String, String>>)
|
||||
object Schedule {
|
||||
const val SLOT = 1_800_000L
|
||||
val channels = listOf(
|
||||
Channel(101, "Orbit One", listOf(
|
||||
"The Midnight Observatory" to "An astronomer follows a mysterious signal across the night sky.",
|
||||
"Small Town, Big Orbit" to "An eccentric village prepares for its annual space festival.",
|
||||
"Beyond the Blue" to "Explorers chart an ocean beneath an unfamiliar moon.",
|
||||
"The Last Shuttle Home" to "One final journey brings an unlikely crew together.")),
|
||||
Channel(202, "Orbit Sci-Fi", listOf(
|
||||
"Signal from Europa" to "A research team discovers that the ice is listening.",
|
||||
"Starbound Dispatch" to "Stories from the delivery route at the edge of the galaxy.",
|
||||
"Visitors at Dawn" to "First contact arrives in the quietest corner of Earth.",
|
||||
"Station Nine" to "Life, repairs and peculiar neighbours on a remote outpost.")),
|
||||
Channel(401, "Orbit Kids", listOf(
|
||||
"Moonbug Rangers" to "A brave little team protects a very big lunar garden.",
|
||||
"The Comet Club" to "Saturday adventures with the galaxy's most curious friends.",
|
||||
"Rocket Pocket" to "An inventor's tiny rocket causes enormous surprises.",
|
||||
"Planet of Puzzles" to "Every new world has a puzzle waiting to be solved."))
|
||||
)
|
||||
fun programme(channel: Channel, time: Long): Programme {
|
||||
val slot = Math.floorDiv(time, SLOT)
|
||||
val show = channel.shows[Math.floorMod(slot, channel.shows.size.toLong()).toInt()]
|
||||
return Programme(show.first, show.second, slot * SLOT, SLOT)
|
||||
}
|
||||
fun guide(channel: Channel, time: Long, count: Int = 3) =
|
||||
List(count) { programme(channel, time + it * SLOT) }
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.datasource.BaseDataSource
|
||||
import androidx.media3.datasource.DataSpec
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.net.InetAddress
|
||||
import java.net.URI
|
||||
import java.net.URL
|
||||
import javax.net.ssl.HttpsURLConnection
|
||||
|
||||
/** Redirect handling is explicit so provider credentials never follow a stream to a CDN. */
|
||||
internal class MediaDeliveryException(message: String) : IOException(message)
|
||||
|
||||
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
|
||||
internal class SecureMediaDataSource(private val session: EmbySampleSession) : BaseDataSource(true) {
|
||||
private var connection: HttpsURLConnection? = null
|
||||
private var stream: InputStream? = null
|
||||
private var currentUri: Uri? = null
|
||||
private var remaining = C.LENGTH_UNSET.toLong()
|
||||
private var opened = false
|
||||
override fun open(dataSpec: DataSpec): Long {
|
||||
transferInitializing(dataSpec)
|
||||
try {
|
||||
var address = session.mediaUrl(dataSpec.uri.toString())
|
||||
for (redirect in 0..5) {
|
||||
val host = URI(address).host
|
||||
if (InetAddress.getAllByName(host).any { !isPublicMediaAddress(it) }) throw MediaDeliveryException("Media delivery resolved to a non-public address.")
|
||||
val next = URL(address).openConnection() as HttpsURLConnection
|
||||
connection = next
|
||||
next.instanceFollowRedirects = false
|
||||
next.connectTimeout = 10_000
|
||||
next.readTimeout = 20_000
|
||||
next.setRequestProperty("User-Agent", "OrbitTV/0.16.0")
|
||||
next.setRequestProperty("Accept-Encoding", "identity")
|
||||
session.mediaHeaders(address).forEach { (key, value) -> next.setRequestProperty(key, value) }
|
||||
if (dataSpec.position != 0L || dataSpec.length != C.LENGTH_UNSET.toLong()) {
|
||||
val end = if (dataSpec.length == C.LENGTH_UNSET.toLong()) "" else (dataSpec.position + dataSpec.length - 1).toString()
|
||||
next.setRequestProperty("Range", "bytes=${dataSpec.position}-$end")
|
||||
}
|
||||
val status = next.responseCode
|
||||
if (status in listOf(301, 302, 303, 307, 308)) {
|
||||
val location = next.getHeaderField("Location") ?: throw MediaDeliveryException("The media redirect had no destination.")
|
||||
if (redirect == 5) throw MediaDeliveryException("The stream redirected too many times.")
|
||||
address = session.mediaUrl(location, address)
|
||||
next.disconnect(); connection = null
|
||||
continue
|
||||
}
|
||||
if (status !in 200..299) throw MediaDeliveryException("The media host returned HTTP $status.")
|
||||
if (status == 200 && dataSpec.position > 0) throw MediaDeliveryException("The media host did not support byte-range seeking.")
|
||||
if (status == 206 && !mediaRangeStartsAt(next.getHeaderField("Content-Range"), dataSpec.position))
|
||||
throw MediaDeliveryException("The media host returned an unexpected seek position.")
|
||||
currentUri = Uri.parse(address)
|
||||
val length = next.contentLengthLong
|
||||
remaining = if (dataSpec.length != C.LENGTH_UNSET.toLong()) dataSpec.length else if (length >= 0) length else C.LENGTH_UNSET.toLong()
|
||||
stream = next.inputStream
|
||||
opened = true; transferStarted(dataSpec)
|
||||
return remaining
|
||||
}
|
||||
throw MediaDeliveryException("The stream could not be opened.")
|
||||
} catch (failure: IOException) { close(); throw if (failure is MediaDeliveryException) failure else IOException("The secure media connection could not be opened.") }
|
||||
catch (_: Exception) { close(); throw IOException("The secure media connection could not be opened.") }
|
||||
}
|
||||
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
|
||||
if (length == 0) return 0
|
||||
if (remaining == 0L) return C.RESULT_END_OF_INPUT
|
||||
val count = if (remaining == C.LENGTH_UNSET.toLong()) length else minOf(length.toLong(), remaining).toInt()
|
||||
val read = try { stream?.read(buffer, offset, count) ?: C.RESULT_END_OF_INPUT }
|
||||
catch (_: IOException) { throw IOException("The media connection was interrupted.") }
|
||||
if (read == -1) {
|
||||
if (remaining > 0) throw IOException("The media stream ended before the expected length.")
|
||||
return C.RESULT_END_OF_INPUT
|
||||
}
|
||||
if (remaining != C.LENGTH_UNSET.toLong()) remaining -= read
|
||||
bytesTransferred(read)
|
||||
return read
|
||||
}
|
||||
override fun getUri(): Uri? = currentUri
|
||||
override fun getResponseHeaders(): Map<String, List<String>> = connection?.getHeaderField("Content-Type")?.let { mapOf("Content-Type" to listOf(it)) } ?: emptyMap()
|
||||
override fun close() {
|
||||
try { stream?.close() } catch (_: IOException) { }
|
||||
finally {
|
||||
stream = null; connection?.disconnect(); connection = null; currentUri = null
|
||||
if (opened) { opened = false; transferEnded() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun isPublicMediaAddress(address: InetAddress): Boolean {
|
||||
if (address.isAnyLocalAddress || address.isLoopbackAddress || address.isLinkLocalAddress || address.isSiteLocalAddress || address.isMulticastAddress) return false
|
||||
val bytes = address.address.map { it.toInt() and 255 }
|
||||
if (bytes.size == 16 && bytes[0] and 254 == 252) return false
|
||||
if (bytes.size == 4 && (bytes[0] == 0 || bytes[0] >= 224 || (bytes[0] == 100 && bytes[1] in 64..127) ||
|
||||
(bytes[0] == 198 && bytes[1] in 18..19) || (bytes[0] == 192 && bytes[1] == 0 && bytes[2] == 0))) return false
|
||||
return true
|
||||
}
|
||||
|
||||
internal fun mediaRangeStartsAt(header: String?, position: Long): Boolean {
|
||||
val match = Regex("bytes ([0-9]+)-([0-9]+)/(?:[0-9]+|\\*)", RegexOption.IGNORE_CASE).matchEntire(header.orEmpty()) ?: return false
|
||||
return match.groupValues[1].toLongOrNull() == position
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.net.URLEncoder
|
||||
|
||||
internal data class SeriesCandidate(val id: String, val title: String, val year: Int?, val rating: String, val variantLabel: String = "")
|
||||
internal data class SeriesMatches(val requested: String, val candidates: List<SeriesCandidate>, val moreAvailable: Boolean)
|
||||
internal val ToonamiSearches = listOf("Dragon Ball Z", "Batman Beyond", "Superman", "Powerpuff Girls", "ThunderCats",
|
||||
"Dragon Ball", "Sailor Moon", "Voltron", "ReBoot", "Beast Wars",
|
||||
"Jonny Quest", "Robotech", "Ronin Warriors", "Gundam Wing", "Tenchi Muyo",
|
||||
"Outlaw Star", "The Big O", "Cardcaptors", "Zoids", "Dragon Ball GT",
|
||||
"Naruto", "Samurai Jack", "Justice League")
|
||||
|
||||
/** At most five explicit series searches per action, ten candidates each. */
|
||||
internal fun discoverToonamiSeries(transport: EmbyTransport, userId: String, token: () -> String, startIndex: Int, checkActive: () -> Unit = {}): List<SeriesMatches> {
|
||||
require(EmbyClient.validId(userId))
|
||||
require(startIndex in 0..ToonamiSearches.size)
|
||||
return ToonamiSearches.drop(startIndex).take(5).map { requested ->
|
||||
checkActive()
|
||||
val term = URLEncoder.encode(requested, "UTF-8")
|
||||
val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&Recursive=true&IncludeItemTypes=Series&SearchTerm=$term&StartIndex=0&Limit=10&SortBy=SortName&SortOrder=Ascending&EnableImages=false&EnableUserData=false", token = token()))
|
||||
EmbyClient.expectSuccess(reply.status, false)
|
||||
val body = EmbyClient.parse(reply.body)
|
||||
val items = body.optJSONArray("Items") ?: throw EmbyCheckException("The provider did not return series search results.")
|
||||
val candidates = (0 until minOf(items.length(), 10)).mapNotNull { index ->
|
||||
val item = items.optJSONObject(index) ?: return@mapNotNull null
|
||||
val id = item.optString("Id")
|
||||
val title = EmbyClient.clean(item.optString("Name"), 160)
|
||||
if (item.optString("Type") != "Series" || !EmbyClient.validId(id) || title.isBlank()) return@mapNotNull null
|
||||
SeriesCandidate(id, title, item.optInt("ProductionYear").takeIf { it in 1800..2200 },
|
||||
EmbyClient.clean(item.optString("OfficialRating"), 40))
|
||||
}.distinctBy { it.id }
|
||||
SeriesMatches(requested, labelSeriesVariants(candidates), body.optLong("TotalRecordCount", items.length().toLong()) > 10)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun discoverToonamiSeries(transport: EmbyTransport, userId: String, token: () -> String): List<SeriesMatches> =
|
||||
discoverToonamiSeries(transport, userId, token, 0)
|
||||
|
||||
internal fun labelSeriesVariants(candidates: List<SeriesCandidate>): List<SeriesCandidate> {
|
||||
fun key(series: SeriesCandidate) = series.title.trim().lowercase(java.util.Locale.ROOT) to series.year
|
||||
val totals = candidates.groupingBy { key(it) }.eachCount()
|
||||
val seen = mutableMapOf<Pair<String, Int?>, Int>()
|
||||
return candidates.map { series ->
|
||||
val key = key(series)
|
||||
val index = (seen[key] ?: 0) + 1
|
||||
seen[key] = index
|
||||
series.copy(variantLabel = if ((totals[key] ?: 0) > 1) "Entry $index of ${totals[key]}" else "")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.tv.material3.Text
|
||||
|
||||
@Composable
|
||||
internal fun SeriesReviewScreen(matches: List<SeriesMatches>, approved: Set<String>, episodes: List<SeriesEpisodes>?,
|
||||
busy: Boolean, message: String?, modifier: Modifier,
|
||||
onToggle: (String) -> Unit, onMore: () -> Unit, onEpisodes: () -> Unit, onBuild: () -> Unit, onBack: () -> Unit) {
|
||||
val listState = rememberLazyListState()
|
||||
LaunchedEffect(episodes) { if (episodes != null) listState.scrollToItem(0) }
|
||||
BackHandler(onBack = onBack)
|
||||
Column(modifier.fillMaxWidth().background(Panel).padding(18.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("103 Toonami / Series check", color = Yellow, fontSize = 26.sp)
|
||||
Text("Choose up to three versions for this sample. Nothing is scheduled yet.", color = Muted, fontSize = 15.sp)
|
||||
if (busy) Text("Preparing sample…", color = Yellow, fontSize = 15.sp)
|
||||
message?.let { Text(it, color = Yellow, fontSize = 15.sp) }
|
||||
LazyColumn(Modifier.weight(1f), state = listState, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
episodes?.forEach { sample ->
|
||||
item("episodes-${sample.series.id}") {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text("Episode sample / ${sample.series.title} ${sample.series.variantLabel}", color = Yellow, fontSize = 21.sp)
|
||||
if (sample.episodes.isEmpty()) Text("No usable episodes returned in this page.", color = Muted, fontSize = 15.sp)
|
||||
sample.episodes.forEach { episode ->
|
||||
val order = if (episode.season != null && episode.episode != null) "S${episode.season} E${episode.episode}" else "Order unknown"
|
||||
val runtime = episode.durationMs?.let { "${it / 60_000} min" } ?: "Runtime unknown"
|
||||
Text("$order • ${episode.title} • $runtime", color = Color.White, fontSize = 16.sp)
|
||||
if (episode.mediaLabel.isNotBlank()) Text(episode.mediaLabel, color = Muted, fontSize = 14.sp)
|
||||
}
|
||||
Text(if (sample.moreAvailable) "Sample page only; more episodes exist." else "Sample page only.", color = Muted, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
matches.forEachIndexed { groupIndex, group ->
|
||||
item("heading-$groupIndex") {
|
||||
Text(group.requested, color = Yellow, fontSize = 21.sp)
|
||||
if (group.candidates.isEmpty()) Text("No series match returned by this search.", color = Muted, fontSize = 15.sp)
|
||||
if (group.moreAvailable) Text("Showing at most ten results; other versions may exist.", color = Muted, fontSize = 14.sp)
|
||||
}
|
||||
group.candidates.forEach { candidate ->
|
||||
item("$groupIndex-${candidate.id}") {
|
||||
val details = listOfNotNull(candidate.year?.toString(), candidate.rating.takeIf { it.isNotBlank() }, candidate.variantLabel.takeIf { it.isNotBlank() }).joinToString(" • ")
|
||||
Column {
|
||||
OrbitButton("${if (candidate.id in approved) "✓ Approved" else "+ Approve"} ${candidate.title}",
|
||||
Modifier.fillMaxWidth(), selected = candidate.id in approved, enabled = !busy && (candidate.id in approved || approved.size < 3), onClick = { onToggle(candidate.id) })
|
||||
if (details.isNotEmpty()) Text(details, color = Color.White, fontSize = 14.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text("${matches.size}/${ToonamiSearches.size} searches • ${approved.size}/3 series approved • Sample repeats; direct sources checked before scheduling.", color = Muted, fontSize = 14.sp)
|
||||
if (episodes != null) OrbitButton("Create playable 103", enabled = !busy, onClick = onBuild)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (matches.size < ToonamiSearches.size) OrbitButton("Check next five series", enabled = !busy, onClick = onMore)
|
||||
OrbitButton("Check sample episodes", enabled = !busy && approved.isNotEmpty(), onClick = onEpisodes)
|
||||
OrbitButton("Back", onClick = onBack)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
internal fun episodeSampleItem(series: SeriesCandidate, episode: EpisodeCandidate) = SampleItem(
|
||||
"${series.title} / S${episode.season ?: "?"} E${episode.episode ?: "?"} / ${episode.title}",
|
||||
"Episode", episode.durationMs?.div(60_000), "", episode.id, episode.durationMs)
|
||||
|
||||
/** Interleave the returned sample, preserving each show's known regular-episode order. */
|
||||
internal fun toonamiEpisodeOrder(samples: List<SeriesEpisodes>): List<SampleItem> {
|
||||
if (samples.size !in 1..3 || samples.map { it.series.id }.distinct().size != samples.size)
|
||||
throw EmbyCheckException("Check episodes for one to three approved series first.")
|
||||
val groups = samples.map { group ->
|
||||
val episodes = group.episodes
|
||||
if (episodes.size !in 1..5 || episodes.any { it.season == null || it.episode == null || it.season < 1 || it.episode < 1 })
|
||||
throw EmbyCheckException("This sample has missing episode order or specials. Choose another series for this test.")
|
||||
if (episodes.map { it.season to it.episode }.distinct().size != episodes.size)
|
||||
throw EmbyCheckException("This sample contains duplicate episode numbers. Choose another series version.")
|
||||
episodes.sortedWith(compareBy<EpisodeCandidate> { it.season }.thenBy { it.episode })
|
||||
.map { episodeSampleItem(group.series, it) }
|
||||
}
|
||||
val result = (0 until groups.maxOf { it.size }).flatMap { round -> groups.mapNotNull { it.getOrNull(round) } }
|
||||
if (result.size < 2 || result.map { it.id }.distinct().size != result.size)
|
||||
throw EmbyCheckException("This channel needs at least two distinct sample episodes.")
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user