import base64, hashlib, hmac, html, json, re, 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_directplay_cookiejar.txt'
Path(jar).unlink(missing_ok=True)
cookie=ck('sotgee')
def run(cmd):
    return subprocess.run(cmd,capture_output=True,text=True)
def curl(url, name, extra=None):
    cmd=['curl','-sS','-D',name+'.h','-o',name+'.b','--max-time','30','-c',jar,'-b',jar,'-H',f'Cookie: sotlab_session={cookie}','-H','X-Requested-With: XMLHttpRequest']
    if extra: cmd += extra
    cmd.append(url)
    r=run(cmd)
    h=Path(name+'.h').read_text(errors='replace') if Path(name+'.h').exists() else ''
    b=Path(name+'.b').read_text(errors='replace') if Path(name+'.b').exists() else ''
    return r.returncode,h,b
curl('https://music.sotlab.co.uk/login.php','/tmp/dp_login')
url='https://music.sotlab.co.uk/server/ajax.server.php?page=stream&action=directplay&object_type=song&object_id=1'
rc,h,b=curl(url,'/tmp/dp_ajax')
print('AJAX_HEAD',' | '.join(h.splitlines()[:20]))
print('AJAX_BODY',b[:3000])
print('AJAX_MARKERS',{m:(m in b or m in h) for m in ['error','Access Denied','Unauthorized','play/index.php','stream','url','media']})
urls=sorted(set(re.findall(r'https://music\.sotlab\.co\.uk[^"\'<>\\ ]+', b) + re.findall(r'/(?:play|stream|server)/[^"\'<>\\ ]+', b)))
print('EXTRACTED',urls[:20])
for u in urls[:5]:
    full=html.unescape(u if u.startswith('http') else 'https://music.sotlab.co.uk'+u)
    rc,h2,b2=curl(full,'/tmp/dp_stream',['-L','-r','0-4095'])
    raw=Path('/tmp/dp_stream.b').read_bytes()[:80] if Path('/tmp/dp_stream.b').exists() else b''
    print('STREAM',full,'rc',rc,'HEAD',' | '.join(h2.splitlines()[:18]),'RAW',raw)
