0.101.0: Living Network Stage C, spotting what's new (report only): daily background library refresh, arrivals, new episodes by season and episode, booked works, Settings > New arrivals
Booking fingerprints identical to 0.100.1. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -55,6 +55,28 @@ internal class CatalogueStore private constructor(context: Context) : CatalogueS
|
||||
db.setTransactionSuccessful()
|
||||
} finally { db.endTransaction() }
|
||||
}
|
||||
/** Stage C: films and series with a premiere date from [fromDate] (yyyy-MM-dd) to [toDate], newest first. Read only. */
|
||||
@Synchronized fun releasedBetween(fromDate: String, toDate: String, limit: Int = 600): List<Arrival> =
|
||||
readableDatabase.rawQuery("SELECT id, type, title, year, premiere, provider_ids FROM items WHERE substr(premiere, 1, 10) >= ? AND substr(premiere, 1, 10) <= ? ORDER BY premiere DESC LIMIT $limit",
|
||||
arrayOf(fromDate, toDate)).use { c ->
|
||||
generateSequence { if (c.moveToNext()) c else null }.map { row ->
|
||||
val ids = runCatching { JSONObject(row.getString(5)).let { o -> o.keys().asSequence().associateWith { k -> o.optString(k) } } }.getOrDefault(emptyMap())
|
||||
val year = if (row.isNull(3)) null else row.getInt(3)
|
||||
Arrival(row.getString(0), row.getString(1), row.getString(2), year, row.getString(4).take(10), workKey(ids, row.getString(2), year), 0)
|
||||
}.toList()
|
||||
}
|
||||
/** Stage C: the work each of these library ids is, for telling which works a channel already holds. */
|
||||
@Synchronized fun worksOf(ids: Collection<String>): Map<String, String> = ids.chunked(400).flatMap { chunk ->
|
||||
readableDatabase.rawQuery("SELECT id, title, year, provider_ids FROM items WHERE id IN (${chunk.joinToString(",") { "?" }})", chunk.toTypedArray()).use { c ->
|
||||
generateSequence { if (c.moveToNext()) c else null }.map { row ->
|
||||
val ids2 = runCatching { JSONObject(row.getString(3)).let { o -> o.keys().asSequence().associateWith { k -> o.optString(k) } } }.getOrDefault(emptyMap())
|
||||
row.getString(0) to workKey(ids2, row.getString(1), if (row.isNull(2)) null else row.getInt(2))
|
||||
}.toList()
|
||||
}
|
||||
}.toMap()
|
||||
/** Whether the whole library has been read once: only after that is anything read new. */
|
||||
@Synchronized fun complete(): Boolean = summary().finished
|
||||
|
||||
@Synchronized fun summary(): CatalogueSummary {
|
||||
val db = readableDatabase
|
||||
fun count(where: String) = db.rawQuery("SELECT COUNT(*) FROM items WHERE $where", null).use { it.moveToFirst(); it.getLong(0) }
|
||||
|
||||
@@ -47,6 +47,29 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl
|
||||
}
|
||||
|
||||
/** Books the Drive-In's evenings from the film pools already on the box, so it asks the provider for nothing. */
|
||||
/**
|
||||
* Stage C, report only: once a day after 12:00, reads only the titles the library gained since its last position and
|
||||
* keeps them as new arrivals. Nothing here touches a plan, a pool or a channel. Until the whole library has been read
|
||||
* once, what's read is the baseline, not news.
|
||||
*/
|
||||
fun refreshArrivals(session: EmbySampleSession, userId: String, catalogue: CatalogueStore) {
|
||||
val now = clock()
|
||||
val (kept, last) = store.loadArrivals(userId)
|
||||
if (!arrivalsRefreshDue(last, now)) return
|
||||
val baseline = catalogue.complete()
|
||||
val found = mutableListOf<CatalogueRecord>()
|
||||
val sink = object : CatalogueSink {
|
||||
override fun position(userId: String) = catalogue.position(userId)
|
||||
override fun write(userId: String, records: List<CatalogueRecord>, nextStart: Long, total: Long?, finished: Boolean) {
|
||||
catalogue.write(userId, records, nextStart, total, finished); found += records
|
||||
}
|
||||
}
|
||||
val run = session.importCatalogue(sink, ARRIVALS_REFRESH_PAGES)
|
||||
val arrivals = if (baseline) found.map { arrivalOf(it, now) } else emptyList()
|
||||
store.saveArrivals(userId, mergeArrivals(kept, arrivals, now), now)
|
||||
Log.i("OrbitSchedule", "arrivals pages=${run.pages} read=${found.size} new=${arrivals.size} baseline=$baseline")
|
||||
}
|
||||
|
||||
fun topUpDriveIn(userId: String): ChannelPlan? {
|
||||
val now = clock()
|
||||
val existing = store.loadPlan(userId, DRIVE_IN_NUMBER)
|
||||
@@ -111,6 +134,11 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl
|
||||
if (read.carried > 0) Log.w("OrbitSchedule", "channel=$number poolRefreshPartial carried=${read.carried}")
|
||||
pool = ScheduleStore.SavedPool(read.series, fetched, signature)
|
||||
store.savePool(userId, number, pool)
|
||||
// Stage C, report only: episodes a show here didn't have at the previous read. Never touches the plan.
|
||||
if (cached != null) runCatching {
|
||||
val found = newEpisodes(number, cached.series, read.series, now)
|
||||
if (found.isNotEmpty()) { store.saveNewEpisodes(userId, mergeNewEpisodes(store.loadNewEpisodes(userId), found, now)); Log.i("OrbitSchedule", "channel=$number newEpisodes=${found.size}") }
|
||||
}
|
||||
}
|
||||
} catch (failure: EmbyCheckException) {
|
||||
Log.w("OrbitSchedule", "channel=$number poolReadFailed status=${failure.httpStatus} retryable=${failure.retryable} keptCache=${cached != null}")
|
||||
@@ -132,6 +160,12 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl
|
||||
avoid = { show, startMs, endMs -> others(show, startMs, endMs) }, shuffle = programming.shuffleEpisodes, mixed = programming::mixes,
|
||||
weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, stories = programming.storyGrouping) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
|
||||
if (plan !== existing) store.savePlan(userId, number, plan)
|
||||
// Stage C, report only: every work any plan books, so "not yet shown on Orbit" has evidence.
|
||||
if (plan !== existing) runCatching {
|
||||
val known = store.loadBooked(userId)
|
||||
val all = known + plan.entries.map { it.seriesId }
|
||||
if (all.size != known.size) store.saveBooked(userId, all.toList().takeLast(BOOKED_MAX).toSet())
|
||||
}
|
||||
store.saveProgress(userId, number, ScheduleStore.SavedProgress(progress?.enabled ?: true, airedCursor(base, plan.entries, now)))
|
||||
session.rememberScheduledItems(plan.entries.map { it.media.item })
|
||||
val planMs = android.os.SystemClock.elapsedRealtime() - started
|
||||
|
||||
@@ -66,7 +66,7 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI
|
||||
connection.connectTimeout = 10_000
|
||||
connection.readTimeout = request.readTimeoutMs ?: 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.100.1\"")
|
||||
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.101.0\"")
|
||||
request.token?.let { connection.setRequestProperty("X-Emby-Token", it) }
|
||||
if (request.method == "POST") {
|
||||
val bytes = request.body.orEmpty().toByteArray(Charsets.UTF_8)
|
||||
|
||||
@@ -268,6 +268,10 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
|
||||
try { driveInPlan = withContext(Dispatchers.IO) { scheduler.topUpDriveIn(active.accountId) } }
|
||||
catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (_: Exception) { /* Tried again next hour. */ }
|
||||
// Stage C's light daily library refresh, in the background. A failure changes nothing and is tried next hour.
|
||||
try { withContext(Dispatchers.IO) { scheduler.refreshArrivals(active, active.accountId, catalogue) } }
|
||||
catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: Exception) { android.util.Log.w("OrbitSchedule", "arrivals failed=${failure.javaClass.simpleName}") }
|
||||
delay(60 * 60_000L)
|
||||
}
|
||||
}
|
||||
@@ -483,8 +487,18 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
|
||||
return
|
||||
}
|
||||
if (session != null) {
|
||||
/** Stage C's report, read on demand from the box's own records and the catalogue. Read only. */
|
||||
fun loadArrivalsReport(): ArrivalsReport? {
|
||||
val active = session ?: return null
|
||||
val (arrivals, _) = scheduleStore.loadArrivals(active.accountId)
|
||||
val today = java.time.LocalDate.now()
|
||||
val released = catalogue.releasedBetween(today.minusDays(NEWLY_RELEASED_DAYS).toString(), today.toString())
|
||||
val poolIds = SmartChannels.flatMap { p -> scheduleStore.loadPool(active.accountId, p.number)?.series.orEmpty().map { it.id } }.toSet()
|
||||
val works = catalogue.worksOf(poolIds).entries.associate { (id, work) -> work to id }
|
||||
return arrivalsReport(arrivals, released, scheduleStore.loadNewEpisodes(active.accountId), works, scheduleStore.loadBooked(active.accountId), System.currentTimeMillis())
|
||||
}
|
||||
SettingsScreen(settingsSection, { settingsSection = it }, modifier, busy, message, HttpsEmbyTransport.SERVER, sample?.total,
|
||||
isOn = { scheduledChannels.containsKey(it) }, onSwitch = { programming, on -> setSmartSchedule(programming, on) }, onSuggestions = { openSuggestions(it) },
|
||||
arrivals = { detail, first -> NewArrivalsDetail(::loadArrivalsReport, first, detail) }, isOn = { scheduledChannels.containsKey(it) }, onSwitch = { programming, on -> setSmartSchedule(programming, on) }, onSuggestions = { openSuggestions(it) },
|
||||
onSignOut = { job?.cancel(); closeSession(forget = true) }, windingDown = windingDown, onWindDown = { on ->
|
||||
val tots = scheduledChannels[TOTS_NUMBER]
|
||||
val active = session
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import java.time.Instant
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
|
||||
/**
|
||||
* Living Network Stage C (approved by Paul on 4 November 2026): spotting what's new. Report only: these labels book
|
||||
* nothing, change no channel and promote nothing. They're the evidence Stage D's suggestions and What's On's "new
|
||||
* episodes" rule will use later, and even then only booked programmes are shown.
|
||||
*/
|
||||
internal const val NEW_TO_LIBRARY_DAYS = 14L
|
||||
internal const val NEWLY_RELEASED_DAYS = 60L
|
||||
internal const val ARRIVALS_KEPT_DAYS = 90L
|
||||
internal const val ARRIVALS_MAX = 2_000
|
||||
internal const val NEW_EPISODES_MAX = 500
|
||||
internal const val BOOKED_MAX = 20_000
|
||||
/** Pages of the library a daily refresh may read: a thousand new titles, far more than a day brings. */
|
||||
internal const val ARRIVALS_REFRESH_PAGES = 5
|
||||
/** The daily refresh runs once a day, after this local hour (What's On's edition turns over at 12:00 too). */
|
||||
internal const val ARRIVALS_REFRESH_HOUR = 12
|
||||
|
||||
/** A film or series the library gained, first seen by Orbit's daily refresh at [firstSeenMs]. */
|
||||
internal data class Arrival(val id: String, val type: String, val title: String, val year: Int?, val premiere: String, val work: String, val firstSeenMs: Long)
|
||||
|
||||
/** An episode a show already on a channel didn't have at the previous read of that channel's pool. */
|
||||
internal data class NewEpisode(val channel: Int, val show: String, val mark: EpisodeMark, val seenMs: Long)
|
||||
|
||||
/** One work, whichever copy of it: its TMDB, TVDB or IMDb id, else its title and year. */
|
||||
internal fun workKey(providerIds: Map<String, String>, title: String, year: Int?): String {
|
||||
val ids = providerIds.mapKeys { it.key.lowercase(java.util.Locale.ROOT) }
|
||||
return ids["tmdb"]?.let { "tmdb:$it" } ?: ids["tvdb"]?.let { "tvdb:$it" } ?: ids["imdb"]?.let { "imdb:$it" } ?: "title:${seriesKey(title)}:${year ?: ""}"
|
||||
}
|
||||
|
||||
internal fun arrivalOf(record: CatalogueRecord, nowMs: Long) =
|
||||
Arrival(record.id, record.type, record.title, record.year, record.premiere.take(10), workKey(record.providerIds, record.title, record.year), nowMs)
|
||||
|
||||
/** New arrivals added to what's kept: one per work, the first sighting kept, pruned by age and size. */
|
||||
internal fun mergeArrivals(kept: List<Arrival>, found: List<Arrival>, nowMs: Long): List<Arrival> {
|
||||
val oldest = nowMs - ARRIVALS_KEPT_DAYS * 24 * 60 * 60_000L
|
||||
return (kept + found).filter { it.firstSeenMs >= oldest }.distinctBy { it.work }.sortedByDescending { it.firstSeenMs }.take(ARRIVALS_MAX)
|
||||
}
|
||||
|
||||
/**
|
||||
* Episodes in [current] that [previous] didn't have, matched by show and season and episode, never by file: a pool that
|
||||
* switches to another copy of the same episodes has nothing new (American Dad! on 4 November looked like 399 new files).
|
||||
*/
|
||||
internal fun newEpisodes(channel: Int, previous: List<PoolSeries>, current: List<PoolSeries>, nowMs: Long): List<NewEpisode> {
|
||||
val before = previous.filter { !it.isFilm }.associate { seriesKey(it.title) to it.episodes.mapTo(HashSet()) { e -> e.mark } }
|
||||
return current.filter { !it.isFilm }.flatMap { show ->
|
||||
// A show new to the pool is a new arrival on the channel, not a run of new episodes.
|
||||
val known = before[seriesKey(show.title)] ?: return@flatMap emptyList()
|
||||
show.episodes.filter { it.mark !in known }.map { NewEpisode(channel, show.title, it.mark, nowMs) }
|
||||
}
|
||||
}
|
||||
|
||||
internal fun mergeNewEpisodes(kept: List<NewEpisode>, found: List<NewEpisode>, nowMs: Long): List<NewEpisode> {
|
||||
val oldest = nowMs - ARRIVALS_KEPT_DAYS * 24 * 60 * 60_000L
|
||||
return (kept + found).filter { it.seenMs >= oldest }.distinctBy { Triple(it.channel, seriesKey(it.show), it.mark) }.sortedByDescending { it.seenMs }.take(NEW_EPISODES_MAX)
|
||||
}
|
||||
|
||||
/** Whether today's refresh is due: once a day, after [ARRIVALS_REFRESH_HOUR]. */
|
||||
internal fun arrivalsRefreshDue(lastRefreshMs: Long?, nowMs: Long, zone: ZoneId = ZoneId.systemDefault()): Boolean {
|
||||
val now = Instant.ofEpochMilli(nowMs).atZone(zone)
|
||||
if (now.hour < ARRIVALS_REFRESH_HOUR) return false
|
||||
return lastRefreshMs == null || Instant.ofEpochMilli(lastRefreshMs).atZone(zone).toLocalDate().isBefore(now.toLocalDate())
|
||||
}
|
||||
|
||||
/** A line of the report: what it is, its labels, and the evidence for each. */
|
||||
internal data class ArrivalLine(val title: String, val type: String, val labels: List<String>, val evidence: String)
|
||||
|
||||
internal class ArrivalsReport(val newToLibrary: List<ArrivalLine>, val newlyReleased: List<ArrivalLine>, val newEpisodes: List<ArrivalLine>, val notYetOnOrbit: List<ArrivalLine>)
|
||||
|
||||
private fun date(ms: Long, zone: ZoneId) = Instant.ofEpochMilli(ms).atZone(zone).toLocalDate()
|
||||
|
||||
/**
|
||||
* The four lists, each line with its evidence. [released] is the library's titles with a premiere date in the last
|
||||
* [NEWLY_RELEASED_DAYS] days (read from the catalogue); [inPools] the works any channel's pool holds, by work key;
|
||||
* [booked] every work any plan has booked since Stage C began, by series id.
|
||||
*/
|
||||
internal fun arrivalsReport(arrivals: List<Arrival>, released: List<Arrival>, episodes: List<NewEpisode>, inPools: Map<String, String>, booked: Set<String>,
|
||||
nowMs: Long, zone: ZoneId = ZoneId.systemDefault()): ArrivalsReport {
|
||||
val today = date(nowMs, zone)
|
||||
fun isNew(a: Arrival) = !date(a.firstSeenMs, zone).isBefore(today.minusDays(NEW_TO_LIBRARY_DAYS))
|
||||
fun releasedRecently(a: Arrival) = a.premiere.takeIf { it.length == 10 }?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
|
||||
?.let { !it.isAfter(today) && !it.isBefore(today.minusDays(NEWLY_RELEASED_DAYS)) } == true
|
||||
fun labels(a: Arrival) = listOfNotNull("New to the library".takeIf { isNew(a) }, "Newly released".takeIf { releasedRecently(a) },
|
||||
"Not yet shown on Orbit".takeIf { inPools[a.work]?.let { id -> id !in booked } == true })
|
||||
fun line(a: Arrival, evidence: String) = ArrivalLine(a.title + (a.year?.let { " ($it)" } ?: ""), a.type, labels(a), evidence)
|
||||
val newToLibrary = arrivals.filter(::isNew).map { line(it, "First seen ${date(it.firstSeenMs, zone)}" + if (it.premiere.isNotEmpty()) ", premiered ${it.premiere}" else "") }
|
||||
val newlyReleased = released.filter(::releasedRecently).distinctBy { it.work }.sortedByDescending { it.premiere }
|
||||
.map { line(it, "Premiered ${it.premiere}") }
|
||||
val newEps = episodes.groupBy { it.channel to seriesKey(it.show) }.values.map { eps ->
|
||||
val first = eps.first()
|
||||
ArrivalLine(first.show, "Series", listOf("New episodes"), "${eps.size} new on channel ${first.channel}: " +
|
||||
eps.sortedBy { it.mark }.take(4).joinToString { "S${it.mark.season} E${it.mark.episode}" } + (if (eps.size > 4) " and ${eps.size - 4} more" else "") + ", found ${date(first.seenMs, zone)}")
|
||||
}
|
||||
val fresh = (arrivals + released).distinctBy { it.work }
|
||||
val notYet = fresh.filter { inPools[it.work]?.let { id -> id !in booked } == true }.map { line(it, "On a channel's list, not booked anywhere yet") }
|
||||
return ArrivalsReport(newToLibrary, newlyReleased, newEps, notYet)
|
||||
}
|
||||
|
||||
/** Settings › New arrivals: the four lists, read only. Nothing here books or changes anything. */
|
||||
@androidx.compose.runtime.Composable
|
||||
internal fun NewArrivalsDetail(load: () -> ArrivalsReport?, first: androidx.compose.ui.focus.FocusRequester, modifier: androidx.compose.ui.Modifier) {
|
||||
val report by androidx.compose.runtime.produceState<ArrivalsReport?>(null) { value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { runCatching(load).getOrNull() } }
|
||||
val rows = report?.let { r ->
|
||||
listOf("NEW TO THE LIBRARY" to r.newToLibrary, "NEWLY RELEASED" to r.newlyReleased, "NEW EPISODES ON A CHANNEL" to r.newEpisodes, "NOT YET SHOWN ON ORBIT" to r.notYetOnOrbit)
|
||||
}.orEmpty()
|
||||
androidx.compose.foundation.lazy.LazyColumn(modifier, verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(4.dp)) {
|
||||
item {
|
||||
androidx.tv.material3.Text(if (report == null) "Reading the library's records…" else "Found by the daily library check after 12:00. A report only: nothing here is booked or changed.",
|
||||
androidx.compose.ui.Modifier.focusRequester(first).focusable(), color = Muted, fontSize = 12.sp)
|
||||
}
|
||||
rows.forEach { (heading, lines) ->
|
||||
item { androidx.tv.material3.Text("$heading (${lines.size})", androidx.compose.ui.Modifier.padding(top = 8.dp), color = Yellow, fontFamily = Anton, fontSize = 15.sp) }
|
||||
if (lines.isEmpty()) item { androidx.tv.material3.Text("Nothing yet.", color = Muted, fontSize = 12.sp) }
|
||||
items(lines.take(60).size) { index ->
|
||||
val line = lines[index]
|
||||
var focused by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(false) }
|
||||
androidx.compose.foundation.layout.Column(androidx.compose.ui.Modifier.fillMaxWidth().onFocusChanged { focused = it.isFocused }.focusable()
|
||||
.background(if (focused) Blue else Panel, androidx.compose.foundation.shape.RoundedCornerShape(4.dp)).padding(horizontal = 10.dp, vertical = 5.dp)) {
|
||||
androidx.tv.material3.Text("${line.title} · ${line.type}", color = androidx.compose.ui.graphics.Color.White, fontSize = 13.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, maxLines = 1)
|
||||
androidx.tv.material3.Text((line.labels.joinToString(" · ") + " — " + line.evidence), color = Muted, fontSize = 11.sp, maxLines = 2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,6 +162,30 @@ internal class ScheduleStore(private val directory: File) {
|
||||
saved.keys().asSequence().associate { it.toLong() to saved.getInt(it) }
|
||||
}.orEmpty()
|
||||
|
||||
/** Stage C's records: new arrivals, new episodes, every work ever booked, and when the library was last refreshed. Report only. */
|
||||
fun saveArrivals(userId: String, arrivals: List<Arrival>, lastRefreshMs: Long?) =
|
||||
write(file("arrivals", 0), root(userId, 0).put("refreshed", lastRefreshMs ?: JSONObject.NULL).put("arrivals", JSONArray().also { saved ->
|
||||
arrivals.forEach { saved.put(JSONObject().put("i", it.id).put("k", it.type).put("t", it.title).put("y", it.year ?: JSONObject.NULL).put("p", it.premiere).put("w", it.work).put("f", it.firstSeenMs)) }
|
||||
}))
|
||||
fun loadArrivals(userId: String): Pair<List<Arrival>, Long?> = read(file("arrivals", 0), userId, 0) { root ->
|
||||
val saved = root.getJSONArray("arrivals")
|
||||
(0 until saved.length()).map { saved.getJSONObject(it) }.map {
|
||||
Arrival(validId(it.getString("i")), it.getString("k"), it.getString("t").take(160), if (it.isNull("y")) null else it.getInt("y"), it.getString("p").take(10), it.getString("w").take(120), it.getLong("f"))
|
||||
} to (if (root.isNull("refreshed")) null else root.getLong("refreshed"))
|
||||
} ?: (emptyList<Arrival>() to null)
|
||||
fun saveNewEpisodes(userId: String, episodes: List<NewEpisode>) =
|
||||
write(file("newepisodes", 0), root(userId, 0).put("episodes", JSONArray().also { saved ->
|
||||
episodes.forEach { saved.put(JSONObject().put("c", it.channel).put("t", it.show).put("n", JSONArray().put(it.mark.season).put(it.mark.episode)).put("f", it.seenMs)) }
|
||||
}))
|
||||
fun loadNewEpisodes(userId: String): List<NewEpisode> = read(file("newepisodes", 0), userId, 0) { root ->
|
||||
val saved = root.getJSONArray("episodes")
|
||||
(0 until saved.length()).map { saved.getJSONObject(it) }.map { NewEpisode(it.getInt("c"), it.getString("t").take(160), it.getJSONArray("n").let { n -> EpisodeMark(n.getInt(0), n.getInt(1)) }, it.getLong("f")) }
|
||||
}.orEmpty()
|
||||
fun saveBooked(userId: String, ids: Set<String>) = write(file("booked", 0), root(userId, 0).put("ids", JSONArray(ids.toList())))
|
||||
fun loadBooked(userId: String): Set<String> = read(file("booked", 0), userId, 0) { root ->
|
||||
val ids = root.getJSONArray("ids"); (0 until ids.length()).map { validId(ids.getString(it)) }.toSet()
|
||||
}.orEmpty()
|
||||
|
||||
/** Programme reminders set from What's On: channel, start, title and how far their reminders have got. */
|
||||
fun saveReminders(userId: String, reminders: List<ProgrammeReminder>) =
|
||||
write(file("reminders", 0), root(userId, 0).put("reminders", JSONArray().also { saved ->
|
||||
|
||||
@@ -33,7 +33,7 @@ internal class SecureMediaDataSource(private val session: EmbySampleSession) : B
|
||||
next.instanceFollowRedirects = false
|
||||
next.connectTimeout = 10_000
|
||||
next.readTimeout = 20_000
|
||||
next.setRequestProperty("User-Agent", "OrbitTV/0.100.1")
|
||||
next.setRequestProperty("User-Agent", "OrbitTV/0.101.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()) {
|
||||
|
||||
@@ -76,6 +76,7 @@ internal class OrbitSettings(context: Context) {
|
||||
internal enum class SettingsSection(val label: String, val icon: Int) {
|
||||
Channels("Channels", R.drawable.orbit_icon_all),
|
||||
Viewing("Watching", R.drawable.orbit_icon_entertainment),
|
||||
Arrivals("New arrivals", R.drawable.orbit_icon_movies),
|
||||
Account("Emby account", R.drawable.orbit_icon_profile),
|
||||
}
|
||||
|
||||
@@ -225,6 +226,7 @@ private fun AccountDetail(server: String, titles: Long?, onSignOut: () -> Unit,
|
||||
/** Everything behind the gear: a rail of sections on the left, and the chosen one beside it. */
|
||||
@Composable
|
||||
internal fun SettingsScreen(section: SettingsSection, onSection: (SettingsSection) -> Unit, modifier: Modifier, busy: Boolean, message: String?, server: String, titles: Long?,
|
||||
arrivals: @Composable (Modifier, FocusRequester) -> Unit,
|
||||
isOn: (Int) -> Boolean, onSwitch: (ChannelProgramming, Boolean) -> Unit, onSuggestions: (ChannelProgramming) -> Unit, onSignOut: () -> Unit,
|
||||
windingDown: Boolean, onWindDown: (Boolean) -> Unit) {
|
||||
val firstFocus = remember { FocusRequester() }
|
||||
@@ -247,6 +249,7 @@ internal fun SettingsScreen(section: SettingsSection, onSection: (SettingsSectio
|
||||
when (section) {
|
||||
SettingsSection.Channels -> ChannelsDetail(busy, message, isOn, onSwitch, onSuggestions, firstSwitch, channelList, detail)
|
||||
SettingsSection.Viewing -> ViewingDetail(isOn(TOTS_NUMBER), windingDown, onWindDown, firstSwitch, detail)
|
||||
SettingsSection.Arrivals -> arrivals(detail, firstSwitch)
|
||||
SettingsSection.Account -> AccountDetail(server, titles, onSignOut, firstSwitch, detail)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user