Recover from slow provider pages during import (0.20.0)
The full import stopped at position 65,200 and each retry failed. Gives catalogue pages a longer timeout, retries slow pages at smaller sizes, stops asking for a total after the first page, and reports what happened. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -7,7 +7,10 @@ internal data class CatalogueRecord(val id: String, val type: String, val title:
|
||||
val genres: List<String>, val studios: List<String>, val providerIds: Map<String, String>, val premiere: String, val runtimeMs: Long?,
|
||||
val originalTitle: String = "", val tags: List<String> = emptyList())
|
||||
internal class CataloguePage(val records: List<CatalogueRecord>, val rawCount: Int, val total: Long?)
|
||||
internal data class CatalogueRun(val pages: Int, val records: Int, val finished: Boolean)
|
||||
internal data class CatalogueRun(val pages: Int, val records: Int, val finished: Boolean) {
|
||||
var pageSize = CATALOGUE_PAGE_SIZE
|
||||
var slowestMs = 0L
|
||||
}
|
||||
|
||||
/** Each write is one transaction, so an interrupted import resumes from the last whole page. */
|
||||
internal interface CatalogueSink {
|
||||
@@ -19,6 +22,10 @@ internal const val CATALOGUE_PAGE_SIZE = 200
|
||||
internal const val CATALOGUE_PAGES_PER_RUN = 5
|
||||
internal const val CATALOGUE_PAGES_FULL_RUN = 5_000
|
||||
internal const val CATALOGUE_PAUSE_MS = 1_500L
|
||||
internal const val CATALOGUE_MIN_PAGE_SIZE = 25
|
||||
internal const val CATALOGUE_MAX_ATTEMPTS = 5
|
||||
internal const val CATALOGUE_BACKOFF_MS = 5_000L
|
||||
internal const val CATALOGUE_READ_TIMEOUT_MS = 60_000
|
||||
|
||||
private fun names(array: JSONArray?, limit: Int = 8): List<String> = (0 until minOf(array?.length() ?: 0, 32)).mapNotNull { index ->
|
||||
when (val value = array?.opt(index)) {
|
||||
@@ -47,28 +54,52 @@ private fun catalogueRecord(row: JSONObject): CatalogueRecord? {
|
||||
}
|
||||
|
||||
/** Oldest first, so titles added during an import land after the current position. */
|
||||
internal fun fetchCataloguePage(transport: EmbyTransport, userId: String, token: () -> String, start: Long): CataloguePage {
|
||||
require(EmbyClient.validId(userId) && start >= 0)
|
||||
val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&Recursive=true&IncludeItemTypes=Movie,Series&StartIndex=$start&Limit=$CATALOGUE_PAGE_SIZE&SortBy=DateCreated&SortOrder=Ascending&Fields=Genres,OfficialRating,OriginalTitle,PremiereDate,ProductionYear,ProviderIds,Studios,Tags&EnableImages=false&EnableUserData=false", token = token()))
|
||||
internal fun fetchCataloguePage(transport: EmbyTransport, userId: String, token: () -> String, start: Long,
|
||||
limit: Int = CATALOGUE_PAGE_SIZE, withTotal: Boolean = true): CataloguePage {
|
||||
require(EmbyClient.validId(userId) && start >= 0 && limit in 1..CATALOGUE_PAGE_SIZE)
|
||||
// Counting the whole library is costly, so only the first page asks for the total.
|
||||
val count = if (withTotal) "" else "&EnableTotalRecordCount=false"
|
||||
val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&Recursive=true&IncludeItemTypes=Movie,Series&StartIndex=$start&Limit=$limit&SortBy=DateCreated&SortOrder=Ascending&Fields=Genres,OfficialRating,OriginalTitle,PremiereDate,ProductionYear,ProviderIds,Studios,Tags&EnableImages=false&EnableUserData=false$count", token = token(), readTimeoutMs = CATALOGUE_READ_TIMEOUT_MS))
|
||||
EmbyClient.expectSuccess(reply.status, false)
|
||||
val page = EmbyClient.parse(reply.body)
|
||||
val rows = page.optJSONArray("Items") ?: throw EmbyCheckException("The provider did not return a catalogue page.")
|
||||
val count = minOf(rows.length(), CATALOGUE_PAGE_SIZE)
|
||||
val records = (0 until count).mapNotNull { rows.optJSONObject(it)?.let(::catalogueRecord) }.distinctBy { it.id }
|
||||
val rowCount = minOf(rows.length(), limit)
|
||||
val records = (0 until rowCount).mapNotNull { rows.optJSONObject(it)?.let(::catalogueRecord) }.distinctBy { it.id }
|
||||
val total = if (page.has("TotalRecordCount")) page.optLong("TotalRecordCount", -1).takeIf { it >= 0 } else null
|
||||
return CataloguePage(records, count, total)
|
||||
return CataloguePage(records, rowCount, total)
|
||||
}
|
||||
|
||||
/** One explicit run, either five pages or the whole library. A rate-limit or login failure stops it; finished pages stay saved. */
|
||||
/**
|
||||
* One explicit run, either five pages or the whole library. A rate-limit or login failure stops it at once.
|
||||
* A slow or dropped page is retried with smaller pages and a growing wait, then the run stops. Finished pages stay saved.
|
||||
*/
|
||||
internal fun importCatalogue(transport: EmbyTransport, userId: String, token: () -> String, sink: CatalogueSink,
|
||||
maxPages: Int = CATALOGUE_PAGES_PER_RUN, pause: () -> Unit = {}, checkActive: () -> Unit = {}, onPage: () -> Unit = {}): CatalogueRun {
|
||||
maxPages: Int = CATALOGUE_PAGES_PER_RUN, pause: () -> Unit = {}, checkActive: () -> Unit = {}, onPage: () -> Unit = {},
|
||||
backoff: (Int) -> Unit = {}, onRetry: (Int) -> Unit = {}): CatalogueRun {
|
||||
require(maxPages in 1..CATALOGUE_PAGES_FULL_RUN)
|
||||
var start = sink.position(userId)
|
||||
var pages = 0
|
||||
var written = 0
|
||||
var size = CATALOGUE_PAGE_SIZE
|
||||
var failures = 0
|
||||
var slowest = 0L
|
||||
fun result(finished: Boolean) = CatalogueRun(pages, written, finished).also { it.pageSize = size; it.slowestMs = slowest }
|
||||
while (pages < maxPages) {
|
||||
checkActive()
|
||||
val page = fetchCataloguePage(transport, userId, token, start)
|
||||
val began = System.currentTimeMillis()
|
||||
val page = try {
|
||||
fetchCataloguePage(transport, userId, token, start, size, start == 0L)
|
||||
} catch (failure: EmbyCheckException) {
|
||||
if (!failure.retryable) throw failure
|
||||
if (++failures >= CATALOGUE_MAX_ATTEMPTS)
|
||||
throw EmbyCheckException("${failure.message} Stopped at position $start after $failures tries, the last asking for $size titles.", retryable = true)
|
||||
size = maxOf(CATALOGUE_MIN_PAGE_SIZE, size / 2)
|
||||
onRetry(size)
|
||||
backoff(failures)
|
||||
continue
|
||||
}
|
||||
failures = 0
|
||||
slowest = maxOf(slowest, System.currentTimeMillis() - began)
|
||||
checkActive()
|
||||
val next = start + page.rawCount
|
||||
val finished = page.rawCount == 0 || page.total?.let { next >= it } == true
|
||||
@@ -77,8 +108,8 @@ internal fun importCatalogue(transport: EmbyTransport, userId: String, token: ()
|
||||
pages++
|
||||
written += page.records.size
|
||||
onPage()
|
||||
if (finished) return CatalogueRun(pages, written, true)
|
||||
if (finished) return result(true)
|
||||
if (pages < maxPages) pause()
|
||||
}
|
||||
return CatalogueRun(pages, written, false)
|
||||
return result(false)
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ internal fun CatalogueScreen(summary: CatalogueSummary?, busy: Boolean, canRun:
|
||||
}
|
||||
Column(modifier.fillMaxWidth().background(Navy).padding(18.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("Library import test", color = Yellow, fontSize = 26.sp)
|
||||
Text("Saves film and series details on this box. Channels and schedules are not changed, and no episodes are read. Importing everything takes about half an hour.", color = Color.White, fontSize = 15.sp)
|
||||
Text("Saves film and series details on this box. Channels and schedules are not changed, and no episodes are read. Importing everything can take a while, as later pages are slower.", color = Color.White, fontSize = 15.sp)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OrbitButton(if (busy) "Importing…" else if (summary?.finished == true) "Import finished" else "Import everything", enabled = canRun && summary?.finished != true, onClick = { onRun(true) })
|
||||
OrbitButton("Import next 1,000", enabled = canRun && summary?.finished != true, onClick = { onRun(false) })
|
||||
|
||||
@@ -7,10 +7,10 @@ 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 class EmbyCheckException(message: String, val httpStatus: Int? = null, val retryable: Boolean = false) : 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 EmbyRequest(val method: String, val path: String, val body: String? = null, val token: String? = null, val readTimeoutMs: Int? = null)
|
||||
internal class EmbyReply(val status: Int, val body: String)
|
||||
internal fun interface EmbyTransport { fun execute(request: EmbyRequest): EmbyReply }
|
||||
|
||||
@@ -39,9 +39,9 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI
|
||||
connection.requestMethod = request.method
|
||||
connection.instanceFollowRedirects = false
|
||||
connection.connectTimeout = 10_000
|
||||
connection.readTimeout = if (request.path == "/Sessions/Logout") 5_000 else 15_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.19.0\"")
|
||||
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.20.0\"")
|
||||
request.token?.let { connection.setRequestProperty("X-Emby-Token", it) }
|
||||
if (request.method == "POST") {
|
||||
val bytes = request.body.orEmpty().toByteArray(Charsets.UTF_8)
|
||||
@@ -57,7 +57,8 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI
|
||||
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.") }
|
||||
catch (_: java.net.SocketTimeoutException) { throw EmbyCheckException("The provider took too long to answer.", retryable = true) }
|
||||
catch (_: java.io.IOException) { throw EmbyCheckException("The provider could not be reached. Check your connection and try again.", retryable = true) }
|
||||
finally { connection.disconnect() }
|
||||
}
|
||||
}
|
||||
@@ -130,7 +131,7 @@ internal class EmbyClient(private val transport: EmbyTransport = HttpsEmbyTransp
|
||||
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).")
|
||||
else -> throw EmbyCheckException("The provider could not complete this check (HTTP $status).", retryable = status >= 500)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,9 +245,12 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
|
||||
active.importCatalogue(catalogue, if (everything) CATALOGUE_PAGES_FULL_RUN else CATALOGUE_PAGES_PER_RUN,
|
||||
pause = { Thread.sleep(CATALOGUE_PAUSE_MS) }, checkActive = { context.ensureActive() },
|
||||
// The summary counts the whole table, so it refreshes every few pages, not on each one.
|
||||
onPage = { if (++pages % 5 == 0) { val latest = catalogue.summary(); scope.launch { catalogueSummary = latest } } })
|
||||
onPage = { if (++pages % 5 == 0) { val latest = catalogue.summary(); scope.launch { catalogueSummary = latest; message = null } } },
|
||||
backoff = { attempt -> Thread.sleep(CATALOGUE_BACKOFF_MS * attempt) },
|
||||
onRetry = { size -> scope.launch { message = "The provider is slow here. Retrying with $size titles at a time…" } })
|
||||
}
|
||||
catalogueRun = "Last run: ${result.records} titles in ${result.pages} pages, ${(System.currentTimeMillis() - started) / 1000} seconds."
|
||||
message = null
|
||||
catalogueRun = "Last run: ${result.records} titles in ${result.pages} pages, ${(System.currentTimeMillis() - started) / 1000} seconds. Slowest page ${result.slowestMs / 1000} seconds, ${result.pageSize} titles per page."
|
||||
} catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: EmbyCheckException) { message = failure.message + " Finished pages are saved." }
|
||||
catch (_: Exception) { message = "The import stopped. Finished pages are saved, and it can carry on later." }
|
||||
|
||||
@@ -149,8 +149,9 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
|
||||
|
||||
fun checkMetadataCoverage(checkActive: () -> Unit = {}): List<MetadataCoverage> =
|
||||
auditMetadataCoverage(transport, userId, ::currentToken, checkActive)
|
||||
fun importCatalogue(sink: CatalogueSink, maxPages: Int = CATALOGUE_PAGES_PER_RUN, pause: () -> Unit = {}, checkActive: () -> Unit = {}, onPage: () -> Unit = {}): CatalogueRun =
|
||||
importCatalogue(transport, userId, ::currentToken, sink, maxPages, pause, checkActive, onPage)
|
||||
fun importCatalogue(sink: CatalogueSink, maxPages: Int = CATALOGUE_PAGES_PER_RUN, pause: () -> Unit = {}, checkActive: () -> Unit = {}, onPage: () -> Unit = {},
|
||||
backoff: (Int) -> Unit = {}, onRetry: (Int) -> Unit = {}): CatalogueRun =
|
||||
importCatalogue(transport, userId, ::currentToken, sink, maxPages, pause, checkActive, onPage, backoff, onRetry)
|
||||
fun checkAfterDarkMovies(genre: String): List<AfterDarkMovie> {
|
||||
val found = discoverAfterDarkMovies(transport, userId, ::currentToken, genre)
|
||||
currentToken()
|
||||
|
||||
@@ -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.19.0")
|
||||
next.setRequestProperty("User-Agent", "OrbitTV/0.20.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()) {
|
||||
|
||||
Reference in New Issue
Block a user