#!/usr/bin/env python3
# tkrec — ติดคีบทัวร์นาเมนต์ live recorder (runs 24/7 on the Lightsail box)
# - polls TikTok every 10 s for @UNIQUE_ID; when live, asks the logged-in Chrome (CDP :9222) for the stream URL
# - records with ffmpeg as 6-s HLS segments, part by part; a dropped stream is re-fetched and continued, nothing already on disk is lost
# - uploads finished segments to tidkeep KV (rec:<slug>/...) while recording, writes live.m3u8 every few seconds and the VOD playlist at the end
# - writes its status to KV key tkrec:status so it can be monitored without SSH
import os, sys, json, time, re, subprocess, threading, datetime, urllib.request, urllib.parse, base64, traceback
HOME = os.path.expanduser('~'); CFG = json.load(open(os.path.join(HOME, '.tkrec', 'config.json')))
UID = CFG['uniqueId']; ROOT = os.path.join(HOME, 'tkrec'); REC = os.path.join(ROOT, 'rec'); os.makedirs(REC, exist_ok=True)
RECKEY = CFG['rec_key']; SITE = CFG.get('site', 'https://tidkeep.owen-t.com')
BKK = datetime.timezone(datetime.timedelta(hours=7))
def now(): return datetime.datetime.now(BKK)
def log(*a):
    s = now().strftime('%d/%m %H:%M:%S ') + ' '.join(str(x) for x in a); print(s, flush=True)
    with open(os.path.join(ROOT, 'tkrec.log'), 'a') as f: f.write(s + '\n')
STATUS = {'uid': UID, 'state': 'idle', 'since': now().isoformat(), 'slug': None, 'parts': 0, 'segments': 0, 'uploaded': 0, 'chrome': None, 'err': None}
def kv_put(key, data, ctype):
    """Upload through the tidkeep site (POST /api/rec/put, REC_KEY) — key is 'tkrec:status' or '<slug>/<file>' (stored as rec:<slug>/<file>)."""
    k = key[4:] if key.startswith('rec:') else key
    for a in range(4):
        try:
            req = urllib.request.Request(SITE + '/api/rec/put?' + urllib.parse.urlencode({'k': k, 'type': ctype}), data=data, method='POST')
            req.add_header('x-rec-key', RECKEY); req.add_header('content-type', ctype); req.add_header('User-Agent', 'tkrec/1')
            with urllib.request.urlopen(req, timeout=120) as r:
                if json.loads(r.read().decode()).get('ok'): return True
        except Exception as e: log('upload', k, 'retry', a, str(e)[:120])
        time.sleep(3)
    return False
def push_status(**kw):
    STATUS.update(kw); STATUS['at'] = now().isoformat()
    try: kv_put('tkrec:status', json.dumps(STATUS, ensure_ascii=False).encode(), 'application/json')
    except Exception: pass
def room_status():
    try:
        req = urllib.request.Request(f'https://www.tiktok.com/api-live/user/room/?aid=1988&uniqueId={UID}&sourceType=54',
                                     headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)'})
        with urllib.request.urlopen(req, timeout=15) as r: d = json.loads(r.read().decode())['data']
        return int(d['user'].get('status') or 0), str(d['user'].get('roomId') or '')
    except Exception as e: return -1, str(e)[:80]
def stream_url(uid=None):
    uid = uid or UID
    """Ask the logged-in Chrome (remote debugging on :9222) for the live pull URL. Returns (flv, err)."""
    try:
        from playwright.sync_api import sync_playwright
        with sync_playwright() as p:
            b = p.chromium.connect_over_cdp('http://127.0.0.1:9222', timeout=15000)
            ctx = b.contexts[0] if b.contexts else b.new_context()
            pg = ctx.new_page(); pg.goto('https://www.tiktok.com/live', wait_until='domcontentloaded', timeout=45000)
            js = """async (u) => { const d = await fetch('/api-live/user/room/?aid=1988&uniqueId='+u+'&sourceType=54',{credentials:'include'}).then(r=>r.json());
              const lr = d.data.liveRoom||{}; const sd = lr.streamData; if(!sd) return {err:'no stream (not logged in or age gate)', status:d.data.user.status};
              const txt = JSON.stringify(sd).replace(/\\\\u002F/g,'/').replace(/\\\\/g,''); const urls = txt.match(/https:\\/\\/[^"'\\s]+?\\.flv[^"'\\s]*/g) || [];
              const pick = urls.find(x=>x.includes('_hd')) || urls.find(x=>x.includes('_sd')) || urls[0]; return pick ? {flv:pick, n:urls.length} : {err:'no flv url in streamData', status:d.data.user.status}; }"""
            r = pg.evaluate(js, uid); pg.close()
            if r.get('flv'): return r['flv'], None
            return None, r.get('err', 'unknown')
    except Exception as e: return None, 'chrome: ' + str(e)[:160]
def ffmpeg_part(url, d, part):
    cmd = ['ffmpeg', '-nostdin', '-hide_banner', '-loglevel', 'warning', '-rw_timeout', '20000000', '-i', url, '-c', 'copy',
           '-f', 'hls', '-hls_time', '6', '-hls_list_size', '0', '-hls_segment_filename', f'{d}/{part}_%05d.ts', f'{d}/{part}.m3u8']
    with open(f'{d}/ffmpeg.log', 'a') as lf: return subprocess.call(cmd, stdout=lf, stderr=lf)
class Uploader(threading.Thread):
    def __init__(self, slug, d): super().__init__(daemon=True); self.slug, self.d, self.done, self.stop = slug, d, set(), False
    def listed(self):
        out = []
        for pl in sorted(f for f in os.listdir(self.d) if re.match(r'p\d+\.m3u8$', f)):
            for line in open(os.path.join(self.d, pl)):
                line = line.strip()
                if line.endswith('.ts'): out.append(line)
        return out
    def live_playlist(self):
        segs = []; tgt = 6
        for pl in sorted(f for f in os.listdir(self.d) if re.match(r'p\d+\.m3u8$', f)):
            lines = [l.strip() for l in open(os.path.join(self.d, pl))]; dur = None
            for l in lines:
                if l.startswith('#EXT-X-TARGETDURATION'): tgt = max(tgt, int(l.split(':')[1]))
                if l.startswith('#EXTINF'): dur = l
                elif l.endswith('.ts') and l in self.done: segs.append((dur, l))
        tail = segs[-6:]
        if not tail: return None
        seq = max(0, len(segs) - len(tail))
        return '\n'.join(['#EXTM3U', '#EXT-X-VERSION:3', f'#EXT-X-TARGETDURATION:{tgt}', f'#EXT-X-MEDIA-SEQUENCE:{seq}'] + [x for d_, s in tail for x in (d_, f'/v/{self.slug}/{s}')]) + '\n'
    def run(self):
        last_live = 0
        while True:
            for f in self.listed():
                if f not in self.done and kv_put(f'rec:{self.slug}/{f}', open(os.path.join(self.d, f), 'rb').read(), 'video/mp2t'):
                    self.done.add(f); push_status(uploaded=len(self.done), segments=len(self.listed()))
            if time.time() - last_live > 4:
                pl = self.live_playlist()
                if pl: kv_put(f'rec:{self.slug}/live.m3u8', pl.encode(), 'application/vnd.apple.mpegurl'); last_live = time.time()
            if self.stop and all(f in self.done for f in self.listed()):
                out = ['#EXTM3U', '#EXT-X-VERSION:3', '#EXT-X-PLAYLIST-TYPE:VOD']; tgt = 6; body = []
                pls = sorted(f for f in os.listdir(self.d) if re.match(r'p\d+\.m3u8$', f))
                for i, pl in enumerate(pls):
                    lines = [l.strip() for l in open(os.path.join(self.d, pl))]
                    for l in lines:
                        if l.startswith('#EXT-X-TARGETDURATION'): tgt = max(tgt, int(l.split(':')[1]))
                    if i > 0: body.append('#EXT-X-DISCONTINUITY')
                    for l in lines:
                        if l.startswith('#EXTINF'): body.append(l)
                        elif l.endswith('.ts'): body.append(f'/v/{self.slug}/{l}')
                out.insert(2, f'#EXT-X-TARGETDURATION:{tgt}'); out += body + ['#EXT-X-ENDLIST']
                ok = kv_put(f'rec:{self.slug}/index.m3u8', '\n'.join(out).encode() + b'\n', 'application/vnd.apple.mpegurl')
                open(os.path.join(self.d, 'UPLOADED'), 'w').write(str(ok)); log('VOD playlist uploaded', ok, len(self.done), 'segments'); return
            time.sleep(5)
def finish_live(slug, d, up):
    """Runs in the background so a new live (next player) is picked up immediately."""
    up.join(timeout=3 * 3600)
    try: subprocess.call(['bash', '-c', f'ffmpeg -nostdin -loglevel error -y -i "concat:$(ls {d}/p*_*.ts | sort | tr "\\n" "|" | sed "s/|$//")" -c copy {d}/full.mp4'])
    except Exception: pass
    log('finished', slug)
def record_live(room0):
    slug = 'r-' + now().strftime('%y%m%d-%H%M'); d = os.path.join(REC, slug); os.makedirs(d, exist_ok=True)
    log('LIVE start', slug, 'room', room0); push_status(state='live', slug=slug, room=room0, parts=0, segments=0, uploaded=0, err=None)
    up = Uploader(slug, d); up.start(); n = 0; miss = 0
    while True:
        url, err = stream_url()
        if not url:
            log('no stream url:', err); push_status(err=err, chrome='fail' if err.startswith('chrome') else 'ok')
            st, room = room_status()
            if st != 2 or room != room0: miss += 1
            if miss >= 6: break
            time.sleep(10); continue
        push_status(chrome='ok', err=None)
        n += 1; part = f'p{n:02d}'; push_status(parts=n)
        rc = ffmpeg_part(url, d, part); log('ffmpeg', part, 'ended rc', rc)
        time.sleep(3)
        st, room = room_status()
        if st == 2 and room != room0: log('new live room', room, '- closing', slug); break   # next player started a new live
        if st != 2:
            for k in range(6):   # 60 s grace: TikTok can flip to 4 for a moment
                time.sleep(10); st, room = room_status()
                if st == 2: break
            if st != 2 or room != room0: break
    open(os.path.join(d, 'DONE'), 'w').write('1'); up.stop = True; log('LIVE over', slug, 'parts', n)
    push_status(state='idle', slug=slug)
    threading.Thread(target=finish_live, args=(slug, d, up), daemon=True).start()
def login_check():
    """Which TikTok account is signed in on the recorder's Chrome (age-restricted lives need one)."""
    try:
        from playwright.sync_api import sync_playwright
        with sync_playwright() as p:
            b = p.chromium.connect_over_cdp('http://127.0.0.1:9222', timeout=15000)
            pages = [x for c in b.contexts for x in c.pages if 'tiktok.com' in x.url]
            pg = pages[0] if pages else b.contexts[0].new_page()
            if 'tiktok.com' not in pg.url: pg.goto('https://www.tiktok.com/', wait_until='domcontentloaded', timeout=45000)
            r = pg.evaluate("""async()=>{try{const d=await fetch('/passport/web/account/info/?aid=1459',{credentials:'include'}).then(r=>r.json()); return d&&d.data&&d.data.username ? d.data.username : ''}catch(e){return 'ERR '+e}}""")
            return r or 'LOGGED-OUT'
    except Exception as e: return 'chrome: ' + str(e)[:120]
UPDATE_URL = 'https://img.owen-t.com/tk-0418ae8bf227/tkrec-latest.py'
def get_cmd():
    try:
        req = urllib.request.Request(SITE + '/api/rec/cmd', headers={'x-rec-key': RECKEY, 'User-Agent': 'tkrec/1'})
        with urllib.request.urlopen(req, timeout=15) as r: return json.loads(r.read().decode()).get('cmd')
    except Exception: return None
def run_cmd(c):
    """Fixed set of remote operations only (no arbitrary shell)."""
    op = c.get('op'); res = {'id': c.get('id'), 'op': op, 'at': now().isoformat()}
    if op == 'check': res['login'] = login_check(); push_status(login=res['login'])
    elif op == 'update':
        try:
            req = urllib.request.Request(UPDATE_URL, headers={'User-Agent': 'tkrec/1'}); code = urllib.request.urlopen(req, timeout=60).read()
            tmp = os.path.join(ROOT, 'tkrec.new.py'); open(tmp, 'wb').write(code)
            ok = subprocess.call([sys.executable, '-m', 'py_compile', tmp]) == 0; res['compiled'] = ok
            if ok: os.replace(tmp, os.path.abspath(__file__)); res['updated'] = True
        except Exception as e: res['err'] = str(e)[:200]
    elif op == 'restart': res['restart'] = True
    else: res['err'] = 'unknown op'
    kv_put('tkrec:result', json.dumps(res, ensure_ascii=False).encode(), 'application/json')
    if res.get('updated') or res.get('restart'): log('exiting for', op); os._exit(0)   # systemd restarts the service
def main():
    log('tkrec started for @' + UID); push_status(state='idle', chrome=None, login=login_check())
    last_chrome = 0; last_login = time.time(); last_cmd = 0; done_ids = set()
    while True:
        st, info = room_status()
        if st == 2:
            try: record_live(info)
            except Exception: log('record_live crashed', traceback.format_exc()[-400:]); push_status(state='idle', err='crash')
        else:
            if time.time() - last_chrome > 300:   # heartbeat: is Chrome reachable?
                try:
                    with urllib.request.urlopen('http://127.0.0.1:9222/json/version', timeout=5) as r: push_status(chrome='ok', last_status=st)
                except Exception: push_status(chrome='down', last_status=st)
                last_chrome = time.time()
            if time.time() - last_login > 3600: push_status(login=login_check()); last_login = time.time()   # hourly
            if time.time() - last_cmd > 30:
                last_cmd = time.time(); c = get_cmd()
                if c and c.get('id') and c['id'] not in done_ids: done_ids.add(c['id']); run_cmd(c)
        time.sleep(10)
if __name__ == '__main__':
    if len(sys.argv) > 2 and sys.argv[1] == 'livetest':
        u = sys.argv[2]; url, err = stream_url(u); print('stream', u, 'ok' if url else err)
        if url:
            rc = subprocess.call(['ffmpeg', '-nostdin', '-loglevel', 'error', '-y', '-rw_timeout', '20000000', '-i', url, '-t', '30', '-c', 'copy', ROOT + '/livetest.mp4']); print('ffmpeg rc', rc)
            print(subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration,size', '-of', 'csv=p=0', ROOT + '/livetest.mp4'], capture_output=True, text=True).stdout.strip())
            print('upload', kv_put('livetest/test.mp4', open(ROOT + '/livetest.mp4', 'rb').read(), 'video/mp4'))
        sys.exit()
    if len(sys.argv) > 1 and sys.argv[1] == 'test':
        print('room:', room_status()); print('stream:', stream_url()); sys.exit()
    main()
