diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index 5bdb08d..f74d6b2 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -35,6 +35,11 @@ jobs: if test -f distribution/Kaleido.apk; then (cd distribution && sha256sum -c Kaleido.apk.sha256) .tools/sdk/build-tools/35.0.0/apksigner verify --verbose --print-certs distribution/Kaleido.apk + # The APK's own manifest must carry the advertised version (and, for a tag, version.properties'). + case "${{ github.ref }}" in + refs/tags/v*) python3 scripts/verify_distribution.py --release ;; + *) python3 scripts/verify_distribution.py ;; + esac fi - name: Publish signed tag release if: startsWith(github.ref, 'refs/tags/v') diff --git a/app/src/androidTest/java/tv/kaleido/app/BrowsePolicyTest.kt b/app/src/androidTest/java/tv/kaleido/app/BrowsePolicyTest.kt index b8516c7..ee3607a 100644 --- a/app/src/androidTest/java/tv/kaleido/app/BrowsePolicyTest.kt +++ b/app/src/androidTest/java/tv/kaleido/app/BrowsePolicyTest.kt @@ -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}""")) diff --git a/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt b/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt index dc97639..3d79371 100644 --- a/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt +++ b/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt @@ -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 diff --git a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt index c9fef64..c0d170c 100644 --- a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt +++ b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt @@ -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() + /** Observable, so the version button, format badges and technical line all follow a new choice. */ + private val mediaChoices=androidx.compose.runtime.mutableStateMapOf() /** The episode a season or episode page shows, by page id. Focus in its season row chooses it. */ val episodeSelections=androidx.compose.runtime.mutableStateMapOf() 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() diff --git a/app/src/main/java/tv/kaleido/app/Playback.kt b/app/src/main/java/tv/kaleido/app/Playback.kt index a7ec7e6..b5686c0 100644 --- a/app/src/main/java/tv/kaleido/app/Playback.kt +++ b/app/src/main/java/tv/kaleido/app/Playback.kt @@ -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) { diff --git a/app/src/main/java/tv/kaleido/app/PlaybackExtras.kt b/app/src/main/java/tv/kaleido/app/PlaybackExtras.kt index c135f38..c2c8ce5 100644 --- a/app/src/main/java/tv/kaleido/app/PlaybackExtras.kt +++ b/app/src/main/java/tv/kaleido/app/PlaybackExtras.kt @@ -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)) { diff --git a/app/src/main/java/tv/kaleido/app/PlayerControls.kt b/app/src/main/java/tv/kaleido/app/PlayerControls.kt index 6d00eaf..a1dcf43 100644 --- a/app/src/main/java/tv/kaleido/app/PlayerControls.kt +++ b/app/src/main/java/tv/kaleido/app/PlayerControls.kt @@ -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) { diff --git a/app/src/main/java/tv/kaleido/app/PlexApi.kt b/app/src/main/java/tv/kaleido/app/PlexApi.kt index 54ad770..b6ab9c5 100644 --- a/app/src/main/java/tv/kaleido/app/PlexApi.kt +++ b/app/src/main/java/tv/kaleido/app/PlexApi.kt @@ -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 = emptyMap()): String = withContext(Dispatchers.IO) { + suspend fun request(url: String, token: String? = session?.serverToken, method: String = "GET", form: Map = 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 = 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 = 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 = emptyMap()): JSONObject = withContext(Dispatchers.Default){JSONObject(request(url(path,params)).ifBlank{"{}"}).optJSONObject("MediaContainer") ?: JSONObject()} + suspend fun container(path: String, params: Map = 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. */ diff --git a/app/src/main/java/tv/kaleido/app/RecentSeasons.kt b/app/src/main/java/tv/kaleido/app/RecentSeasons.kt index 6bc6953..464378f 100644 --- a/app/src/main/java/tv/kaleido/app/RecentSeasons.kt +++ b/app/src/main/java/tv/kaleido/app/RecentSeasons.kt @@ -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,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() } diff --git a/app/src/main/java/tv/kaleido/app/Screens.kt b/app/src/main/java/tv/kaleido/app/Screens.kt index 1a7ac91..a2cec41 100644 --- a/app/src/main/java/tv/kaleido/app/Screens.kt +++ b/app/src/main/java/tv/kaleido/app/Screens.kt @@ -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)}}}} diff --git a/scripts/package_release.py b/scripts/package_release.py index 1915294..4f413d0 100644 --- a/scripts/package_release.py +++ b/scripts/package_release.py @@ -4,6 +4,9 @@ ROOT=pathlib.Path(__file__).resolve().parents[1] version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text(encoding='utf-8').splitlines() if '=' in l) apk=ROOT/'app/build/outputs/apk/release/app-release.apk' if not apk.exists():raise SystemExit('Run Build.ps1 -Release first.') +# The APK left by an earlier build must not be published under this version's name. +from verify_distribution import check_apk +check_apk(apk,version['versionName'],int(version['versionCode'])) out=ROOT/'distribution';out.mkdir(exist_ok=True) shutil.copyfile(apk,out/'Kaleido.apk') digest=hashlib.sha256(apk.read_bytes()).hexdigest() diff --git a/scripts/verify_distribution.py b/scripts/verify_distribution.py new file mode 100644 index 0000000..da972d6 --- /dev/null +++ b/scripts/verify_distribution.py @@ -0,0 +1,56 @@ +"""Check that an APK really is the release it is published as. + +Used by package_release.py before staging, and by CI against the checked-in distribution: +a stale or debug APK must not pass because its checksum and manifest were regenerated around it. +""" +import argparse, hashlib, json, os, pathlib, re, shutil, subprocess, sys +ROOT=pathlib.Path(__file__).resolve().parents[1] +PACKAGE='tv.kaleido.app' + +def properties(): + return dict(l.split('=',1) for l in (ROOT/'version.properties').read_text(encoding='utf-8').splitlines() if '=' in l) + +def aapt2(): + names=['aapt2.exe','aapt2'] if os.name=='nt' else ['aapt2'] + roots=[ROOT/'.tools/sdk']+[pathlib.Path(os.environ[k]) for k in ('ANDROID_HOME','ANDROID_SDK_ROOT') if os.environ.get(k)] + for root in roots: + tools=sorted((root/'build-tools').glob('*'),key=lambda p:[int(x) if x.isdigit() else 0 for x in p.name.split('.')],reverse=True) if (root/'build-tools').is_dir() else [] + for folder in tools: + for name in names: + if (folder/name).is_file():return str(folder/name) + found=shutil.which('aapt2') + if found:return found + raise SystemExit('aapt2 was not found. Install Android build-tools or set ANDROID_HOME.') + +def badging(apk): + """(package, versionName, versionCode, debuggable) from the APK's own manifest.""" + out=subprocess.run([aapt2(),'dump','badging',str(apk)],capture_output=True,text=True,check=True).stdout + m=re.search(r"^package: name='([^']+)' versionCode='(\d+)' versionName='([^']+)'",out,re.M) + if not m:raise SystemExit(f'Could not read the version of {apk}.') + return m.group(1),m.group(3),int(m.group(2)),'application-debuggable' in out + +def check_apk(apk,version_name,version_code): + package,name,code,debuggable=badging(apk) + problems=[] + if package!=PACKAGE:problems.append(f'package is {package}, expected {PACKAGE}') + if (name,code)!=(version_name,version_code):problems.append(f'APK is {name} ({code}), expected {version_name} ({version_code}); rebuild it') + if debuggable:problems.append('APK is a debuggable build, not the release') + if problems:raise SystemExit(f'{apk}: '+'; '.join(problems)+'.') + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--release',action='store_true',help='also require the distribution to match version.properties (tag builds)') + args=parser.parse_args() + out=ROOT/'distribution';apk=out/'Kaleido.apk' + if not apk.exists():print('No distribution to verify.');return + digest=hashlib.sha256(apk.read_bytes()).hexdigest() + if (out/'Kaleido.apk.sha256').read_text().split()[0]!=digest:raise SystemExit('Kaleido.apk does not match Kaleido.apk.sha256.') + manifest=json.loads((out/'latest.json').read_text(encoding='utf-8')) + check_apk(apk,manifest['version'],int(manifest['versionCode'])) + if args.release: + version=properties() + if (manifest['version'],int(manifest['versionCode']))!=(version['versionName'],int(version['versionCode'])): + raise SystemExit('distribution/latest.json does not match version.properties; run scripts/package_release.py.') + print('Distribution verified:',manifest['version'],f"({manifest['versionCode']})",'SHA-256',digest) + +if __name__=='__main__':main()