Fix playback lifecycle, server-change and navigation bugs from review
Playback - A preparation finishing after Home no longer starts playing in the background; the post-play countdown only runs while Kaleido is on screen. - Closing or backgrounding during preparation keeps the requested resume position instead of reporting the player's unprepared 0. - Progress, scrobble and transcode-stop reports stay pinned to the server the title came from, even after a server change. Networking - Cancelling a request now cancels its OkHttp call, so timeouts such as the 3-second server-stop check actually return on time. - Connection discovery accepts the most preferred answering address without waiting for slower, less preferred probes. State and navigation - Server/account changes clear episode queues, shuffle, version choices, episode selections and search. - Leaving Search cancels its pending request. - Version selection updates the format badges and technical line. - Down from the Home tab enters the rows when there is no featured title. - Back (or a new Cancel button) closes Settings > Choose server. - One unavailable show no longer discards the whole New Seasons row. Release - package_release.py and CI check the APK's own versionName/versionCode (and that it is not debuggable) via scripts/verify_distribution.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4780bdcdb2
commit
bdc37db05d
12 changed files with 160 additions and 35 deletions
|
|
@ -30,6 +30,14 @@ class BrowsePolicyTest {
|
|||
assertEquals(listOf("unknown1","unknown2","s1"),result.take(3).map{it.id})
|
||||
assertTrue(groupRecentSeasons(emptyList()){error("Empty row")}.isEmpty())
|
||||
}
|
||||
@Test fun recentSeasonsSurviveOneUnavailableShow()=runBlocking {
|
||||
val newest=title("s4","season").copy(parentId="gone",parentTitle="Missing",title="Season 4")
|
||||
val older=title("s3","season").copy(parentId="gone",parentTitle="Missing",title="Season 3")
|
||||
val other=title("s9","season").copy(parentId="show-c",parentTitle="Other",title="Season 9")
|
||||
val result=groupRecentSeasons(listOf(newest,older,other)){throw PlexException("This item is no longer available.",404)}
|
||||
assertEquals(listOf("s4","s9"),result.map{it.id})
|
||||
assertEquals("Missing · Season 4",result.first().title)
|
||||
}
|
||||
|
||||
@Test fun partiallyWatchedShowUsesEpisodeCountsEvenWithViewCount() {
|
||||
val show=Title.parse(JSONObject("""{"type":"show","viewCount":12,"leafCount":30,"viewedLeafCount":10}"""))
|
||||
|
|
|
|||
|
|
@ -177,6 +177,8 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
|
|||
}
|
||||
scrolling.join()
|
||||
}
|
||||
/** The first card of the first row: where Down goes when Home has no hero to hold focus. */
|
||||
suspend fun enterFirstRow(){hubs.firstOrNull{it.items.isNotEmpty()}?.let{hub->val item=hub.items.first();anticipateCard(item);moveToRow(hub.id,item.id)}}
|
||||
suspend fun moveToHero()=coroutineScope {
|
||||
heroActive=true
|
||||
val scrolling=launch{list.animateBrowseTo(0)}
|
||||
|
|
@ -244,6 +246,8 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
|
|||
// Discover is fixed above the catalog. Enter it immediately, without resetting
|
||||
// or waiting for two lazy lists to lay out. The next Down explicitly enters row 0.
|
||||
if(!home)runCatching{local.section.requestFocus()}
|
||||
// Continue Watching and other rows can exist without an eligible featured title.
|
||||
else if(activeFeature.value==null)navigationJob[0]=scope.launch{enterFirstRow()}
|
||||
else {
|
||||
if(heroActive)runCatching{heroFocus.requestFocus()}
|
||||
navigationJob[0]=scope.launch{moveToHero()}
|
||||
|
|
@ -291,7 +295,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
|
|||
if(key=="discovery-entry"&&!home)runCatching{local.section.requestFocus()}
|
||||
return
|
||||
}
|
||||
if(key=="home-feature"){if(home&&feature!=null)moveToHero();return}
|
||||
if(key=="home-feature"){if(home&&feature!=null)moveToHero()else if(home)enterFirstRow();return}
|
||||
val card=hubs.firstNotNullOfOrNull{hub->hub.items.firstOrNull{"${hub.id}:${it.id}"==key}?.let{hub to it}}
|
||||
if(card!=null){moveToRow(card.first.id,card.second.id);return}
|
||||
if(requesters[key]?.let{runCatching{it.requestFocus()}.getOrDefault(false)}==true)return
|
||||
|
|
|
|||
|
|
@ -97,7 +97,8 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
|
|||
var playbackReturn by mutableIntStateOf(0); private set
|
||||
private var retryAction:(()->Unit)?=null
|
||||
private var previousTab="home"
|
||||
private val mediaChoices=mutableMapOf<String,Int>()
|
||||
/** Observable, so the version button, format badges and technical line all follow a new choice. */
|
||||
private val mediaChoices=androidx.compose.runtime.mutableStateMapOf<String,Int>()
|
||||
/** The episode a season or episode page shows, by page id. Focus in its season row chooses it. */
|
||||
val episodeSelections=androidx.compose.runtime.mutableStateMapOf<String,String>()
|
||||
var query by mutableStateOf(""); private set
|
||||
|
|
@ -325,23 +326,36 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
|
|||
}
|
||||
fun beginAccountLink(){linkingAccount=true;linkAccount()}
|
||||
fun cancelAccountLink(){authJob?.cancel();pin=null;servers=emptyList();accountToken=session?.accountToken.orEmpty();linkingAccount=false}
|
||||
/** Rating keys are only unique per server: drop per-title state when the server or account changes. */
|
||||
private fun clearServerState(){
|
||||
searchJob?.cancel();searchJob=null;query="";searchResults=SearchResults()
|
||||
episodeContextJob?.cancel();episodeContextJob=null;episodeTransitionJob?.cancel();episodeTransitionJob=null
|
||||
episodeQueue=emptyList();relatedShows=emptyList();shuffleEpisodes=null;transitioningEpisode=false
|
||||
mediaChoices.clear();episodeSelections.clear()
|
||||
}
|
||||
fun chooseServer(server: Server) = launchLoad {
|
||||
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery()
|
||||
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery();clearServerState()
|
||||
val s=api.connect(server,accountToken); application.secure.save(s);api.session=s;session=s;servers=emptyList();linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome()
|
||||
}
|
||||
fun manualConnect(address: String, token: String) = launchLoad {
|
||||
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery()
|
||||
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery();clearServerState()
|
||||
require(address.startsWith("https://")||address.startsWith("http://")){"Enter a complete http:// or https:// server address."}
|
||||
require(token.isNotBlank()){ "Enter an access token." }
|
||||
val s=api.validate(Session("",token.trim(),address.trim().trimEnd('/'),"Plex",""))
|
||||
authJob?.cancel();application.secure.save(s);api.session=s;session=s;linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome()
|
||||
}
|
||||
fun signOut(){loadJob?.cancel();initializeJob?.cancel();application.secure.clear();api.session=null;session=null;homeHubs=emptyList();discoverHubs=emptyList();clearDiscovery();sections=emptyList();library=emptyList();sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();pages=listOf(Page());servers=emptyList();accountToken="";linkAccount()}
|
||||
fun signOut(){loadJob?.cancel();initializeJob?.cancel();clearServerState();application.secure.clear();api.session=null;session=null;homeHubs=emptyList();discoverHubs=emptyList();clearDiscovery();sections=emptyList();library=emptyList();sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();pages=listOf(Page());servers=emptyList();accountToken="";linkAccount()}
|
||||
/** Back or Cancel from the server picker: keep the current server, or start over with a new sign-in code. */
|
||||
fun dismissServerPicker(){
|
||||
loadJob?.cancel();busy=false
|
||||
if(session==null){servers=emptyList();linkAccount()}else cancelAccountLink()
|
||||
}
|
||||
fun switchServer()=launchLoad { require(accountToken.isNotBlank()){ "This connection uses a server token. Sign out to link a Plex account." };servers=api.servers(accountToken) }
|
||||
fun tab(kind: String){
|
||||
if(pages.size==1&&page.kind==kind)return
|
||||
// Search and Settings return to the browsing tab they were opened from.
|
||||
if(kind in listOf("search","settings")&&pages.first().kind in listOf("home","movies","tv"))previousTab=pages.first().kind
|
||||
if(kind!="search"){searchJob?.cancel();searchJob=null}
|
||||
cancelAnticipation();loadJob?.cancel();busy=false;focusId="";if(kind in listOf("movies","tv")){allTitles=false;categories=false;genre="";libraryJumpIndex=-1;libraryJumpLetter=null};pages=listOf(Page(kind));loadPage(true)
|
||||
}
|
||||
fun open(item: Title){detailsCache[item.id]=item;episodeSelections.remove(item.id);pages=pages+Page(if(item.type in listOf("collection","season")) "group" else "details",item.id,item.title,focusId);loadPage()}
|
||||
|
|
@ -361,7 +375,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
|
|||
}
|
||||
/** The version (Plex Media) chosen for this title in this session; the first version by default. */
|
||||
fun mediaIndex(item:Title)=(mediaChoices[item.id] ?: 0).coerceIn(0,(item.media.size-1).coerceAtLeast(0))
|
||||
fun chooseMedia(item:Title,index:Int){mediaChoices[item.id]=index;detail=detail?.let{if(it.id==item.id)it.copy()else it}}
|
||||
fun chooseMedia(item:Title,index:Int){mediaChoices[item.id]=index}
|
||||
fun openActor(actor:CastMember){
|
||||
if(actor.id.isBlank())return
|
||||
pages=pages+Page("actor",actor.id,actor.name,focusId,actor);focusId="";loadPage()
|
||||
|
|
|
|||
|
|
@ -48,6 +48,8 @@ data class TimelineReport(val position: Long,val state: String,val duration: Lon
|
|||
class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
|
||||
private val app=vm.application
|
||||
val api=vm.api
|
||||
/** The server this title belongs to. Progress reports finish after close and must not follow a server change. */
|
||||
private val server=api.session
|
||||
val scope=CoroutineScope(SupervisorJob()+Dispatchers.Main.immediate)
|
||||
val selector=DefaultTrackSelector(app)
|
||||
private val sourceFactory=DefaultMediaSourceFactory(DefaultDataSource.Factory(app,OkHttpDataSource.Factory(api.http).setDefaultRequestProperties(api.headers().filterKeys{it!="Accept"})))
|
||||
|
|
@ -103,6 +105,8 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
|
|||
private var streamStart=0L
|
||||
private var preparing=false
|
||||
private var closed=false
|
||||
/** False while the app is stopped (Home, another app): a pending preparation must not start playing. */
|
||||
private var foreground=true
|
||||
private val prepareMutex=Mutex()
|
||||
private val streamSelectionMutex=Mutex()
|
||||
private var fallbackPending=false
|
||||
|
|
@ -113,15 +117,15 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
|
|||
/** Set once the server ends this session (dashboard Stop); nothing may reconnect or fall back after it. */
|
||||
private var serverStopped=false
|
||||
private val reportJob=app.scope.launch {
|
||||
val watched=WatchedProgress{api.watched(item,true);withContext(Dispatchers.Main){vm.refreshWatched(item)}}
|
||||
val watched=WatchedProgress{api.watched(item,true,server);withContext(Dispatchers.Main){if(api.session==server)vm.refreshWatched(item)}}
|
||||
for(r in reports) {
|
||||
if(synced) {
|
||||
runCatching {api.timeline(item,r.position,r.state,r.duration,streamSession)}.onFailure {Log.w("KaleidoPlayback","Timeline sync unavailable")}
|
||||
runCatching {api.timeline(item,r.position,r.state,r.duration,streamSession,server)}.onFailure {Log.w("KaleidoPlayback","Timeline sync unavailable")}
|
||||
.getOrNull()?.let{if(!r.final)withContext(Dispatchers.Main){stoppedByServer(it)}}
|
||||
runCatching{watched.report(r.position,r.duration,vm.watchedPercent)}
|
||||
.onFailure{Log.w("KaleidoPlayback","Watched status sync unavailable")}
|
||||
}
|
||||
if(r.final){if(mode>0)runCatching{api.stopTranscode(streamSession)};break}
|
||||
if(r.final){if(mode>0)runCatching{api.stopTranscode(streamSession,server)};break}
|
||||
}
|
||||
}
|
||||
init {
|
||||
|
|
@ -191,7 +195,7 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
|
|||
private suspend fun checkServerStopped(offset:Long):Boolean {
|
||||
if(serverStopped)return true
|
||||
if(!synced)return false
|
||||
val termination=withTimeoutOrNull(3000){runCatching{api.timeline(item,offset,"buffering",duration,streamSession)}.getOrNull()} ?: return false
|
||||
val termination=withTimeoutOrNull(3000){runCatching{api.timeline(item,offset,"buffering",duration,streamSession,server)}.getOrNull()} ?: return false
|
||||
stoppedByServer(termination);return true
|
||||
}
|
||||
private fun fallback(reason:String) {
|
||||
|
|
@ -216,7 +220,7 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
|
|||
player.stop()
|
||||
selector.parameters=selector.buildUponParameters().clearOverrides().build()
|
||||
try {
|
||||
if(mode>0)runCatching{api.stopTranscode(streamSession)}
|
||||
if(mode>0)runCatching{api.stopTranscode(streamSession,server)}
|
||||
mode=newMode;streamSession=UUID.randomUUID().toString();streamStart=offset
|
||||
partIndex=partFor(parts,offset)
|
||||
val partOffsetMs=(offset-partOffset).coerceAtLeast(0)
|
||||
|
|
@ -250,7 +254,7 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
|
|||
}
|
||||
// Plex HLS exposes the part's original timeline, including a seek-start offset:
|
||||
// never add the requested offset again.
|
||||
player.setMediaItem(builder.build(),partOffsetMs);player.prepare();player.playWhenReady=resume;player.setPlaybackSpeed(playbackRate)
|
||||
player.setMediaItem(builder.build(),partOffsetMs);player.prepare();player.playWhenReady=resume&&foreground;player.setPlaybackSpeed(playbackRate)
|
||||
Log.i("KaleidoPlayback","PREPARE item=${item.id} mode=$mode offset=$offset part=${partIndex+1}/${parts.size} media=${mediaIndex+1}/${item.media.size} local=$local")
|
||||
}catch(e:CancellationException){throw e}catch(e:Exception){
|
||||
audit?.event("prepareFailure",org.json.JSONObject().put("mode",newMode).put("kind",e.javaClass.simpleName).put("httpStatus",(e as? PlexException)?.status))
|
||||
|
|
@ -271,7 +275,10 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
|
|||
/** Moves the pending seek target; repeated presses accumulate into one seek after [settle] ms. */
|
||||
fun scrubBy(delta:Long,settle:Long=650){scrubPosition=((scrubPosition ?: position)+delta).coerceIn(0,duration);seekJob?.cancel();seekJob=scope.launch{delay(settle);commitScrub()}}
|
||||
fun commitScrub(){val target=scrubPosition ?: return;scrubPosition=null;seekTo(target)}
|
||||
fun pause(){player.pause();position=currentPosition();report("paused")}
|
||||
fun pause(){player.pause();if(!preparing)position=currentPosition();report("paused")}
|
||||
/** The app left the foreground: pause, and keep any preparation still in flight paused. */
|
||||
fun enterBackground(){foreground=false;pause()}
|
||||
fun enterForeground(){foreground=true}
|
||||
fun select(type:Int,groupIndex:Int,trackIndex:Int) {
|
||||
val group=tracks.groups[groupIndex];selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,false).setOverrideForType(TrackSelectionOverride(group.mediaTrackGroup,listOf(trackIndex))).build()
|
||||
}
|
||||
|
|
@ -323,7 +330,7 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) {
|
|||
}
|
||||
}
|
||||
}
|
||||
fun close(){if(closed)return;position=currentPosition();closed=true;scope.cancel();audit?.finish(mode);report("stopped",true);reports.close();mediaSession.release();player.release()}
|
||||
fun close(){if(closed)return;if(!preparing)position=currentPosition();closed=true;scope.cancel();audit?.finish(mode);report("stopped",true);reports.close();mediaSession.release();player.release()}
|
||||
}
|
||||
/** The single playback quality preference: the original stream, then conversions from highest to lowest resolution. */
|
||||
enum class StreamQuality(val label:String,val width:Int,val height:Int,val kbps:Int) {
|
||||
|
|
|
|||
|
|
@ -19,6 +19,9 @@ 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.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.currentStateAsState
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
@Composable internal fun PlaybackOptions(vm:KaleidoViewModel,controller:PlaybackController,item:Title,menu:Int,open:(Int)->Unit,close:()->Unit) {
|
||||
|
|
@ -49,8 +52,11 @@ internal fun speedLabel(speed:Float)=if(speed==1f)"Normal" else "${speed.toStrin
|
|||
val countdown=if(vm.shuffling&&vm.autoplaySeconds==0)5 else vm.autoplaySeconds
|
||||
var autoplay by remember{mutableStateOf(countdown>0)}
|
||||
var seconds by remember{mutableIntStateOf(countdown)}
|
||||
LaunchedEffect(autoplay,upcoming?.id) {
|
||||
if(autoplay&&upcoming!=null&&countdown>0){seconds=countdown;android.util.Log.i("KaleidoPlayback","AUTOPLAY countdown item=${item.id} next=${upcoming.id}");repeat(countdown){delay(1000);seconds--};android.util.Log.i("KaleidoPlayback","AUTOPLAY starting next=${upcoming.id}");next()}
|
||||
// The countdown runs only while Kaleido is on screen; leaving it restarts on return.
|
||||
val lifecycle by LocalLifecycleOwner.current.lifecycle.currentStateAsState()
|
||||
val onScreen=lifecycle.isAtLeast(Lifecycle.State.STARTED)
|
||||
LaunchedEffect(autoplay,upcoming?.id,onScreen) {
|
||||
if(autoplay&&onScreen&&upcoming!=null&&countdown>0){seconds=countdown;android.util.Log.i("KaleidoPlayback","AUTOPLAY countdown item=${item.id} next=${upcoming.id}");repeat(countdown){delay(1000);seconds--};android.util.Log.i("KaleidoPlayback","AUTOPLAY starting next=${upcoming.id}");next()}
|
||||
}
|
||||
val season=vm.episodeQueue.filter{it.parentId==item.parentId}
|
||||
LazyColumn(Modifier.fillMaxSize().background(Color.Black.copy(alpha=.93f)),contentPadding=PaddingValues(horizontal=Cinema.gutter,vertical=29.dp),verticalArrangement=Arrangement.spacedBy(15.dp)) {
|
||||
|
|
|
|||
|
|
@ -109,8 +109,10 @@ import kotlinx.coroutines.delay
|
|||
}
|
||||
DisposableEffect(controller) {
|
||||
activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
val observer=LifecycleEventObserver{_,event->if(event==Lifecycle.Event.ON_STOP)controller.pause()}
|
||||
val observer=LifecycleEventObserver{_,event->when(event){Lifecycle.Event.ON_STOP->controller.enterBackground();Lifecycle.Event.ON_START->controller.enterForeground();else->{}}}
|
||||
owner.lifecycle.addObserver(observer)
|
||||
// Created while already stopped (e.g. a next episode loading behind Home): start paused.
|
||||
if(!owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED))controller.enterBackground()
|
||||
onDispose{owner.lifecycle.removeObserver(observer);activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);controller.close()}
|
||||
}
|
||||
LaunchedEffect(controls,interaction,controller.isPlaying,trackMenu) {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
package tv.kaleido.app
|
||||
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import okhttp3.FormBody
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.OkHttpClient
|
||||
|
|
@ -31,16 +34,24 @@ class PlexApi(val clientId: String) {
|
|||
put("X-Plex-Client-Identifier",clientId);put("X-Plex-Platform","Android");put("X-Plex-Device","Android TV");put("X-Plex-Device-Name","Kaleido TV")
|
||||
if(!token.isNullOrBlank()) put("X-Plex-Token",token)
|
||||
}
|
||||
suspend fun request(url: String, token: String? = session?.serverToken, method: String = "GET", form: Map<String,String> = emptyMap()): String = withContext(Dispatchers.IO) {
|
||||
suspend fun request(url: String, token: String? = session?.serverToken, method: String = "GET", form: Map<String,String> = emptyMap()): String = coroutineScope {
|
||||
val req=Request.Builder().url(url).apply { headers(token).forEach { (k,v) -> header(k,v) }; if(method!="GET") method(method,FormBody.Builder().apply { form.forEach { (k,v)->add(k,v) } }.build()) }.build()
|
||||
http.newCall(req).execute().use { r -> if(!r.isSuccessful) throw PlexException(when(r.code){401,403->"Plex rejected this session. Sign in again or check server access.";404->"This item is no longer available.";else->"Plex could not complete the request (${r.code})."},r.code); r.body?.string() ?: "{}" }
|
||||
val call=http.newCall(req)
|
||||
// execute() blocks until the server answers; a cancelled caller (a timeout, a replaced load) aborts the call.
|
||||
val abort=launch(start=CoroutineStart.UNDISPATCHED){try{awaitCancellation()}finally{call.cancel()}}
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
call.execute().use { r -> if(!r.isSuccessful) throw PlexException(when(r.code){401,403->"Plex rejected this session. Sign in again or check server access.";404->"This item is no longer available.";else->"Plex could not complete the request (${r.code})."},r.code); r.body?.string() ?: "{}" }
|
||||
}
|
||||
} finally { abort.cancel() }
|
||||
}
|
||||
fun url(path: String, params: Map<String,String> = emptyMap()): String {
|
||||
val s=session ?: throw PlexException("Choose a Plex server first.")
|
||||
/** [server] pins a request to one server; by default it follows the current session. */
|
||||
fun url(path: String, params: Map<String,String> = emptyMap(), server: Session? = session): String {
|
||||
val s=server ?: throw PlexException("Choose a Plex server first.")
|
||||
require(!path.startsWith("http")) { "Expected a server-relative Plex path" }
|
||||
return (s.server.trimEnd('/')+"/"+path.trimStart('/')).toHttpUrl().newBuilder().apply { params.forEach { (k,v)->addQueryParameter(k,v) } }.build().toString()
|
||||
}
|
||||
suspend fun container(path: String, params: Map<String,String> = emptyMap()): JSONObject = withContext(Dispatchers.Default){JSONObject(request(url(path,params)).ifBlank{"{}"}).optJSONObject("MediaContainer") ?: JSONObject()}
|
||||
suspend fun container(path: String, params: Map<String,String> = emptyMap(), server: Session? = session): JSONObject = withContext(Dispatchers.Default){JSONObject(request(url(path,params,server),server?.serverToken).ifBlank{"{}"}).optJSONObject("MediaContainer") ?: JSONObject()}
|
||||
suspend fun validate(s: Session): Session {
|
||||
val j=JSONObject(request(s.server.trimEnd('/')+"/",s.serverToken)).getJSONObject("MediaContainer")
|
||||
if(j.optString("machineIdentifier").isBlank()) throw PlexException("This address is not a Plex Media Server.")
|
||||
|
|
@ -59,9 +70,12 @@ class PlexApi(val clientId: String) {
|
|||
// Try TLS connections first; local HTTP remains available for servers without TLS.
|
||||
var last: Throwable? = null
|
||||
for (group in server.connections.partition { it.startsWith("https://") }.toList()) {
|
||||
val results=group.map { address -> async { runCatching { validate(Session(account,server.token,address,server.name,server.id)) } } }.awaitAll()
|
||||
results.firstOrNull { it.isSuccess }?.getOrNull()?.let { return@coroutineScope it }
|
||||
last=results.lastOrNull()?.exceptionOrNull() ?: last
|
||||
// Probe together, but accept in preference order (local first, relay last): the best
|
||||
// answering address wins without waiting for slower, less preferred probes to time out.
|
||||
val attempts=group.map { address -> async { runCatching { validate(Session(account,server.token,address,server.name,server.id)) } } }
|
||||
try {
|
||||
for (attempt in attempts) attempt.await().onSuccess { return@coroutineScope it }.onFailure { last=it }
|
||||
} finally { attempts.forEach { it.cancel() } }
|
||||
}
|
||||
throw PlexException("Cannot reach ${server.name}. Check that the server is online and reachable from this TV.")
|
||||
}
|
||||
|
|
@ -131,10 +145,10 @@ class PlexApi(val clientId: String) {
|
|||
}
|
||||
/** Removes an in-progress title from Continue Watching without changing its watched state. */
|
||||
suspend fun removeFromContinueWatching(item:Title){request(url("/actions/removeFromContinueWatching",mapOf("ratingKey" to item.id)),method="PUT")}
|
||||
suspend fun watched(item: Title, watched: Boolean) { container(if(watched) "/:/scrobble" else "/:/unscrobble",mapOf("key" to item.id,"identifier" to "com.plexapp.plugins.library")) }
|
||||
suspend fun watched(item: Title, watched: Boolean, server: Session? = session) { container(if(watched) "/:/scrobble" else "/:/unscrobble",mapOf("key" to item.id,"identifier" to "com.plexapp.plugins.library"),server) }
|
||||
/** Reports progress; a stream the server stopped (Plex dashboard "Stop", or shutdown) comes back as a termination. */
|
||||
suspend fun timeline(item: Title, position: Long, state: String, duration: Long, sessionId: String): PlaybackTermination? {
|
||||
val c=container("/:/timeline",mapOf("ratingKey" to item.id,"key" to item.key,"state" to state,"time" to position.coerceAtLeast(0).toString(),"duration" to duration.coerceAtLeast(0).toString(),"identifier" to "com.plexapp.plugins.library","session" to sessionId))
|
||||
suspend fun timeline(item: Title, position: Long, state: String, duration: Long, sessionId: String, server: Session? = session): PlaybackTermination? {
|
||||
val c=container("/:/timeline",mapOf("ratingKey" to item.id,"key" to item.key,"state" to state,"time" to position.coerceAtLeast(0).toString(),"duration" to duration.coerceAtLeast(0).toString(),"identifier" to "com.plexapp.plugins.library","session" to sessionId),server)
|
||||
return if(c.has("terminationCode"))PlaybackTermination(c.optInt("terminationCode",-1),c.optString("terminationText"))else null
|
||||
}
|
||||
suspend fun selectStreams(part: Part, audio: String? = null, subtitle: String? = null) {
|
||||
|
|
@ -153,7 +167,7 @@ class PlexApi(val clientId: String) {
|
|||
val hevcAvailable=android.media.MediaCodecList(android.media.MediaCodecList.REGULAR_CODECS).codecInfos.any{!it.isEncoder&&it.supportedTypes.any{type->type.equals("video/hevc",true)}}
|
||||
put("X-Plex-Client-Profile-Extra",if(mode==1&&hevcAvailable)"append-transcode-target-codec(type=videoProfile&context=streaming&protocol=hls&videoCodec=hevc)"else "")
|
||||
}
|
||||
suspend fun stopTranscode(sessionId: String) { container("/video/:/transcode/universal/stop",mapOf("session" to sessionId)) }
|
||||
suspend fun stopTranscode(sessionId: String, server: Session? = session) { container("/video/:/transcode/universal/stop",mapOf("session" to sessionId),server) }
|
||||
}
|
||||
|
||||
/** Index of the part containing [time] on the title's combined timeline. */
|
||||
|
|
|
|||
|
|
@ -1,14 +1,19 @@
|
|||
package tv.kaleido.app
|
||||
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
|
||||
/** Preserve newest-first order. A multi-season addition opens the real show's season list. */
|
||||
/**
|
||||
* Preserve newest-first order. A multi-season addition opens the real show's season list; if that
|
||||
* show can't be loaded, its newest season stands in rather than discarding the whole row.
|
||||
*/
|
||||
internal suspend fun groupRecentSeasons(seasons:List<Title>,loadShow:suspend (String)->Title):List<Title> = coroutineScope {
|
||||
seasons.distinctBy{it.id}.groupBy{it.parentId.ifBlank{"season:${it.id}"}}.values.take(18).map { group->async {
|
||||
val season=group.first()
|
||||
if(group.size>1&&season.parentId.isNotBlank())loadShow(season.parentId)
|
||||
else season.copy(title=listOf(season.parentTitle,season.title).filter{it.isNotBlank()}.joinToString(" · "))
|
||||
val single=season.copy(title=listOf(season.parentTitle,season.title).filter{it.isNotBlank()}.joinToString(" · "))
|
||||
if(group.size>1&&season.parentId.isNotBlank())try{loadShow(season.parentId)}catch(e:CancellationException){throw e}catch(_:Exception){single}
|
||||
else single
|
||||
}}.awaitAll()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -118,8 +118,9 @@ import java.io.File
|
|||
splashExit.animateTo(1f,tween(StartupExitMillis,easing=LinearEasing));startup=false
|
||||
}
|
||||
}
|
||||
BackHandler(enabled=vm.linkingAccount||vm.playing!=null||vm.pages.size>1||vm.page.kind!="home"){
|
||||
if(vm.linkingAccount)vm.cancelAccountLink()else vm.back()
|
||||
// The server picker covers every page, so Back closes it before navigating underneath.
|
||||
BackHandler(enabled=vm.servers.isNotEmpty()||vm.linkingAccount||vm.playing!=null||vm.pages.size>1||vm.page.kind!="home"){
|
||||
if(vm.servers.isNotEmpty())vm.dismissServerPicker()else if(vm.linkingAccount)vm.cancelAccountLink()else vm.back()
|
||||
}
|
||||
NavigationSounds(vm.navigationSounds&&!startup) {
|
||||
Box(Modifier.fillMaxSize().background(Ink).onPreviewKeyEvent{vm.lastInteraction=android.os.SystemClock.uptimeMillis();startup}) {
|
||||
|
|
@ -197,7 +198,7 @@ val sortLabels=listOf("titleSort:asc" to "Title: A–Z","titleSort:desc" to "Tit
|
|||
Spacer(Modifier.height(14.dp));OutlinedTextField(address,{address=it},label={Text("Server URL")},singleLine=true,modifier=Modifier.fillMaxWidth());Spacer(Modifier.height(10.dp));OutlinedTextField(token,{token=it},label={Text("Access token")},singleLine=true,visualTransformation=PasswordVisualTransformation(),modifier=Modifier.fillMaxWidth());Spacer(Modifier.height(18.dp));TvButton("Connect",primary=true,onClick={vm.manualConnect(address,token)});Spacer(Modifier.height(10.dp));TvButton("Use Plex account",onClick=back)
|
||||
}
|
||||
@Composable fun ServerPicker(vm: KaleidoViewModel) {
|
||||
Column(Modifier.fillMaxSize().padding(60.dp),verticalArrangement=Arrangement.spacedBy(18.dp)){Brand();Spacer(Modifier.height(20.dp));Text("Choose your Plex server",color=Color.White,fontSize=32.sp,fontWeight=FontWeight.Bold);vm.servers.forEachIndexed{i,s->TvButton(s.name,initialFocus=i==0,onClick={vm.chooseServer(s)})}}
|
||||
Column(Modifier.fillMaxSize().padding(60.dp),verticalArrangement=Arrangement.spacedBy(18.dp)){Brand();Spacer(Modifier.height(20.dp));Text("Choose your Plex server",color=Color.White,fontSize=32.sp,fontWeight=FontWeight.Bold);vm.servers.forEachIndexed{i,s->TvButton(s.name,initialFocus=i==0,onClick={vm.chooseServer(s)})};if(vm.session!=null){Spacer(Modifier.height(6.dp));TvButton("Cancel",onClick={vm.dismissServerPicker()})}}
|
||||
}
|
||||
@Composable fun EmptyState(title: String,message: String){Column(Modifier.padding(52.dp),verticalArrangement=Arrangement.spacedBy(12.dp)){Text(title,color=Color.White,fontSize=26.sp,fontWeight=FontWeight.Bold);Text(message,color=Muted,fontSize=14.sp)}}
|
||||
@Composable fun ErrorDialog(message: String,dismiss: ()->Unit,retry: ()->Unit) {Dialog(onDismissRequest=dismiss){Column(Modifier.width(390.dp).clip(RoundedCornerShape(12.dp)).background(Panel).padding(23.dp)){Text("Something needs attention",color=Accent,fontSize=20.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold);Text(message,color=Muted,fontSize=12.sp,lineHeight=19.sp,modifier=Modifier.padding(vertical=17.dp));Row(horizontalArrangement=Arrangement.spacedBy(9.dp)){TvButton("Try again",primary=true,initialFocus=true,onClick=retry);TvButton("Dismiss",onClick=dismiss)}}}}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue