"""Previous episode, timed auto-skip with remote cancellation, server-picker Back and resume refresh. Requires the **debug** build (test intents and run-as). Playback runs as validation, so it reports no Plex progress. The refresh check moves one Continue Watching offset and restores it; the auto-skip preferences are restored as found. """ import json,pathlib,re,sys,time,urllib.request,urllib.parse sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent)) from device import adb,ROOT,screenshot from verify_ui import key,snapshot,focus,labels,wait,focused,text,launch from repro_runtime import await_ready PREFS='shared_prefs/preferences.xml' INTRO_EPISODE=11621 # The Big Bang Theory 10x24: intro marker 117.4-146.7 s SILO_FIRST,SILO_SECOND=7599,8594 def logs(tag='KaleidoPlayback'):return adb('logcat','-d','-s',f'{tag}:I','AndroidRuntime:E','*:S').decode(errors='replace') def wait_log(needle,timeout=30,tag='KaleidoPlayback'): deadline=time.monotonic()+timeout while time.monotonic() '+PREFS+'"',data=xml.encode()) def with_int(xml,name,value): entry=f'' pattern=re.compile(r'') return pattern.sub(entry,xml) if pattern.search(xml) else xml.replace('',f' {entry}\n') def auto_skip(): start(INTRO_EPISODE,112000) wait_log('AUTOSKIP countdown intro seconds=5') root=wait(lambda r:'Skipping intro' in labels(r),'Pending skip reads "Skipping intro", without a number') assert not any(re.search(r'Skip(ping)? intro.*\d',l) for l in labels(root)),'Skip button shows a numeric countdown' screenshot('auto-skip-pending') wait_log(f'AUTOSKIP intro item={INTRO_EPISODE}',timeout=15) assert 'AUTOSKIP cancelled' not in logs() print('PASS intro skips itself after the countdown, shown as a fill rather than a number',flush=True) for code,name in ((20,'Down'),(4,'Back')): start(INTRO_EPISODE,112000) wait_log('AUTOSKIP countdown intro') key(code);wait_log('AUTOSKIP cancelled intro',timeout=5) time.sleep(7) assert f'AUTOSKIP intro item={INTRO_EPISODE}' not in logs(),f'{name} did not cancel the automatic skip' root=wait(lambda r:'Skip intro' in labels(r),'Manual Skip intro stays available after cancelling') assert adb('shell','pidof','tv.kaleido.app').strip(),'Player process exited' assert 'Skipping intro' not in labels(root) print(f'PASS {name} cancels the automatic skip and leaves the player open',flush=True) screenshot('auto-skip-cancelled') key(4);key(4) def previous_episode(): start(SILO_SECOND,90000) key(127);focused('Play');screenshot('player-bar-episode') key(21);focused('Back 10 seconds');key(21);focused('Previous episode');key(23) await_ready(SILO_FIRST) assert 'FATAL EXCEPTION' not in logs(),'Previous episode crashed' print('PASS Previous episode replaced the player with the earlier episode',flush=True) time.sleep(2);key(127);focused('Play') # The series' first episode has no previous one once its season list has loaded. wait(lambda r:'Next episode' in labels(r) and 'Previous episode' not in labels(r),'No Previous episode on the first episode') key(21);focused('Back 10 seconds');key(21) assert 'Back 10 seconds' in focus(snapshot()) or 'Exit playback' in focus(snapshot()) print('PASS first episode offers Next but not Previous',flush=True) key(4);key(4) def server_picker(): launch();key(22,4);focused('Settings');key(23);focused('Switch account');key(22) if 'Choose server' not in focus(snapshot()):print('SKIP no account-linked server list (server-token session)');key(4);return key(23);text('Choose your Plex server');screenshot('server-picker') key(4) wait(lambda r:'Choose your Plex server' not in labels(r) and 'Choose server' in labels(r),'Back closes the server picker over Settings') assert adb('shell','pidof','tv.kaleido.app').strip() key(22) # Choose server again, now via the Cancel button if 'Choose server' not in focus(snapshot()):key(21) focused('Choose server');key(23);text('Choose your Plex server') for _ in range(12): if focus(snapshot())=='Cancel':break key(20) focused('Cancel');key(23) wait(lambda r:'Choose your Plex server' not in labels(r) and 'Choose server' in labels(r),'Cancel closes the server picker') print('PASS Back and Cancel close Settings > Choose server',flush=True) key(4) def plex(path,params): env=dict(l.strip().split('=',1) for l in (ROOT/'.env').read_text().splitlines() if '=' in l and not l.startswith('#')) url=env['PLEX_SERVER_URL'].strip('"\'').rstrip('/')+path+'?'+urllib.parse.urlencode(params) req=urllib.request.Request(url,headers={'X-Plex-Token':env['PLEX_TOKEN'].strip('"\''),'Accept':'application/json','X-Plex-Client-Identifier':'kaleido-development','X-Plex-Product':'Kaleido'}) with urllib.request.urlopen(req,timeout=20) as r:return r.read() def offset(item,field='viewOffset'): from inspect_server import get return int(get(f'/library/metadata/{item}')['Metadata'][0].get(field,0)) def set_offset(item,ms):plex('/:/progress',{'key':str(item),'identifier':'com.plexapp.plugins.library','time':str(ms),'state':'stopped'}) def refresh(): original=offset(SILO_FIRST) # Continue Watching progress is compared in 5% steps; move by more than one step each time. step=offset(SILO_FIRST,'duration')*6//100 try: launch();time.sleep(4);adb('logcat','-c') # Watched elsewhere while Kaleido is in the background: shown promptly on return. key('KEYCODE_HOME');time.sleep(3) set_offset(SILO_FIRST,original+step) adb('shell','am','start','-n','tv.kaleido.app/.MainActivity') began=time.monotonic();wait_log('APPLIED',timeout=10,tag='KaleidoSync') print(f'PASS returning to Kaleido applied Continue Watching changes in {time.monotonic()-began:.1f}s',flush=True) # Watched elsewhere while Kaleido stays open: the background poll picks it up. time.sleep(3);adb('logcat','-c');set_offset(SILO_FIRST,original+2*step);began=time.monotonic() wait_log('APPLIED',timeout=25,tag='KaleidoSync') print(f'PASS open Kaleido applied a progress change from another device in {time.monotonic()-began:.1f}s',flush=True) finally: set_offset(SILO_FIRST,original) assert offset(SILO_FIRST)==original,'Fixture progress was not restored' if __name__=='__main__': phases=sys.argv[1:] or ['previous_episode','auto_skip','server_picker','refresh'] original=read_prefs() try: if 'auto_skip' in phases: write_prefs(with_int(with_int(original,'autoSkipIntroSeconds',5),'autoSkipCreditsSeconds',0)) for phase in phases:globals()[phase]() finally: write_prefs(original) adb('shell','am','start','-n','tv.kaleido.app/.MainActivity')