import base64, hashlib, hmac, subprocess, time
from pathlib import Path
secret=Path('/srv/apps/sotlab-users/data/session_secret').read_bytes()
def ck(username):
    ts=str(int(time.time()))
    payload=f'{username}:{ts}'
    sig=hmac.new(secret, payload.encode(), hashlib.sha256).hexdigest()
    return base64.urlsafe_b64encode(f'{payload}:{sig}'.encode()).decode()
jar='/tmp/music_stream_cookiejar.txt'
Path(jar).unlink(missing_ok=True)
cookie=ck('sotgee')
def curl(url, name, extra=None):
    cmd=['curl','-sS','-D',name+'.h','-o',name+'.b','--max-time','45','-c',jar,'-b',jar,'-H',f'Cookie: sotlab_session={cookie}']
    if extra: cmd += extra
    cmd.append(url)
    r=subprocess.run(cmd,capture_output=True,text=True)
    h=Path(name+'.h').read_text(errors='replace') if Path(name+'.h').exists() else ''
    raw=Path(name+'.b').read_bytes() if Path(name+'.b').exists() else b''
    return r.returncode,h,raw
for url,name,extra in [
    ('https://music.sotlab.co.uk/login.php','/tmp/slogin',None),
    ('https://music.sotlab.co.uk/stream.php?action=play_item&object_type=song&object_id=1','/tmp/sstream',['-L','-r','0-65535']),
]:
    rc,h,raw=curl(url,name,extra)
    print('URL',url,'rc',rc)
    print('HEAD',' | '.join(h.splitlines()[:30]))
    print('RAW_PREFIX',raw[:64])
    print('LEN',len(raw),'HTML?',raw.lstrip().startswith(b'<!DOCTYPE') or raw.lstrip().startswith(b'<html'))
