#!/usr/bin/python3
import sys
import os
import base64
import json
import datetime
import pytz
import uuid
import threading
import time
import websocket

# Add parent directory to path for o11 import
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import o11

from bs4 import BeautifulSoup
from pywidevine.cdm import Cdm
from pywidevine.device import Device
from pywidevine.pssh import PSSH

# Parse command line parameters
user = o11.parse_params(sys.argv, 'user')
password = o11.parse_params(sys.argv, 'password')
device = o11.parse_params(sys.argv, 'device')
pin = o11.parse_params(sys.argv, 'pin')

id = o11.parse_params(sys.argv, 'id')
action = o11.parse_params(sys.argv, 'action')

bind = o11.parse_params(sys.argv, 'bind')
proxy = o11.parse_params(sys.argv, 'proxy')
doh = o11.parse_params(sys.argv, 'doh')
worker = o11.parse_params(sys.argv, 'worker')

cdm = o11.parse_params(sys.argv, 'cdm')
drm = o11.parse_params(sys.argv, 'drm')
kid = o11.parse_params(sys.argv, 'kid')
pssh = o11.parse_params(sys.argv, 'pssh')
challenge = o11.parse_params(sys.argv, 'challenge')

heartbeaturl = o11.parse_params(sys.argv, 'heartbeaturl')
heartbeatparams = o11.parse_params(sys.argv, 'heartbeatparams')

# Session setup
o11Session = o11.session(bind=bind, proxy=proxy, worker=worker)
req = o11Session.get_session()
if doh != "":
    o11.dns(doh)

if challenge == "cert":
    challenge = "CAQ="

# Configuration
WVD_PATH = './WVD.wvd'
authFile = '/OnePlay_token.txt'
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))

USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'

token = ''
client_id = ''
server_id = ''
session_id = ''
messages = []

def get_auth():
    try:
        with open(SCRIPT_DIR + authFile, 'r') as f:
            return f.read().strip()
    except:
        return None

def save_auth(tok):
    with open(SCRIPT_DIR + authFile, 'w') as f:
        f.write(tok)

def on_message(ws, message):
    global messages
    data = json.loads(message)
    messages.append(data)

def on_error(ws, error):
    print(f'Websocket error: {error}', file=sys.stderr)

def get_message(schema, command=None, retry=1):
    global messages
    for m in messages[::-1]:
        if command and 'command' in m and m['command'] == command and 'schema' in m and m['schema'] == schema:
            messages.remove(m)
            return m
        else:
            if 'result' in m and 'schema' in m['result'] and m['result']['schema'] == schema:
                messages.remove(m)
                return m
    if retry <= 5:
        time.sleep(0.2 * retry)
        return get_message(schema, command, retry+1)
    raise Exception(f'Schema: {schema} not found')

def start_websocket():
    global client_id
    client_id = str(uuid.uuid4())
    ws = websocket.WebSocketApp(f"wss://ws.cms.jyxo.cz/websocket/{client_id}", on_message=on_message, on_error=on_error)
    ws.run_forever(reconnect=5)

def get_server_and_session_ids():
    global server_id, session_id
    data = get_message('ConnectionInitData')['data']
    server_id = data['serverId']
    session_id = data['sessionId']

def check_token(tok):
    headers = {'accept': '*/*', 'authorization': 'Bearer ' + tok, 'content-type': 'text/plain;charset=UTF-8', 'origin': 'https://www.oneplay.cz', 'referer': 'https://www.oneplay.cz/', 'user-agent': USER_AGENT}
    json_data = {"deviceInfo": {"deviceType": "web", "appVersion": "1.2.18-patch", "deviceManufacturer": "Unknown", "deviceOs": "Windows"}, "capabilities": {"async": "websockets"}, "payload": {"reason": "profile", "route": {"url": "https://www.oneplay.cz/", "title": "Domov"}}, "context": {"requestId": str(uuid.uuid4()), "clientId": client_id, "sessionId": session_id, "serverId": server_id}}
    response = req.post('https://http.cms.jyxo.cz/api/v3/app.init', headers=headers, json=json_data)
    response.raise_for_status()
    get_message('ApiCall', 'app.init')['response']['data']

def login():
    global token
    print("logging in...", file=sys.stderr)
    
    ws_thread = threading.Thread(target=start_websocket, daemon=True)
    ws_thread.start()
    time.sleep(1)
    get_server_and_session_ids()
    
    tok = get_auth()
    if not tok:
        print("No token found. Please add OnePlay bearer token to auth file.", file=sys.stderr)
        save_auth('')
        sys.exit(1)
    
    try:
        check_token(tok)
        token = tok
        print("logged in successfully", file=sys.stderr)
        return token
    except Exception as e:
        print(f"Login failed: {e}", file=sys.stderr)
        sys.exit(1)

def get_token():
    global token
    if token:
        return token
    return login()

def get_pssh_from_mpd(url):
    response = req.get(url, headers={'User-Agent': USER_AGENT})
    content_protections = BeautifulSoup(response.content, features="xml").findAll('ContentProtection')
    for cp in content_protections:
        if cp.get('schemeIdUri', '').lower() == 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed':
            pssh_elem = cp.find('cenc:pssh')
            if pssh_elem:
                return pssh_elem.text
    return None

def get_single(content_id):
    headers = {'accept': '*/*', 'authorization': 'Bearer ' + token, 'content-type': 'text/plain;charset=UTF-8', 'origin': 'https://www.oneplay.cz', 'referer': 'https://www.oneplay.cz/', 'user-agent': USER_AGENT}
    json_data = {"deviceInfo": {"deviceType": "web", "appVersion": "1.2.18-patch", "deviceManufacturer": "Unknown", "deviceOs": "Windows"}, "capabilities": {"async": "websockets"}, "payload": {"criteria": {"schema": "ContentCriteria", "contentId": content_id}, "startMode": "live"}, "context": {"customData": '{"startMode":"live"}', "requestId": str(uuid.uuid4()), "clientId": client_id, "sessionId": session_id, "serverId": server_id}, "playbackCapabilities": {"protocols": ["dash", "hls"], "drm": ["widevine", "fairplay"], "altTransfer": "Unicast", "subtitle": {"formats": ["vtt"], "locations": ["InstreamTrackLocation", "ExternalTrackLocation"]}, "liveSpecificCapabilities": {"protocols": ["dash", "hls"], "drm": ["widevine", "fairplay"], "altTransfer": "Unicast", "multipleAudio": False}}}
    response = req.post('https://http.cms.jyxo.cz/api/v3/content.play', headers=headers, json=json_data)
    try:
        data = get_message('ApiCall', 'content.play')['response']['data']
        asset = data['media']['stream']['assets'][0]
        lic_url = None
        lic_header_name = None
        lic_token = None
        if 'drm' in asset:
            lic_url = asset['drm'][0]['licenseAcquisitionURL']
            lic_header_name = asset['drm'][0]['drmAuthorization']['name']
            lic_token = asset['drm'][0]['drmAuthorization']['value']
        return asset['src'], lic_url, lic_header_name, lic_token
    except:
        return None, None, None, None

def do_cdm_internal(challenge_b64, lic_url, lic_header_name, lic_token):
    headers = {'accept': '*/*', 'origin': 'https://www.oneplay.cz', 'referer': 'https://www.oneplay.cz/', 'user-agent': USER_AGENT, lic_header_name: lic_token, 'content-type': 'application/octet-stream'}
    response = req.post(lic_url, headers=headers, data=base64.b64decode(challenge_b64))
    response_b64 = str(base64.b64encode(response.content), 'ascii')
    if response_b64.startswith('CA'):
        return response_b64
    return None

def do_cdm_external(pssh_b64, lic_url, lic_header_name, lic_token):
    try:
        pssh_obj = PSSH(pssh_b64)
        device_obj = Device.load(WVD_PATH)
        cdm_obj = Cdm.from_device(device_obj)
        session_id_cdm = cdm_obj.open()
        challenge_data = cdm_obj.get_license_challenge(session_id_cdm, pssh_obj)
        headers = {'accept': '*/*', 'origin': 'https://www.oneplay.cz', 'referer': 'https://www.oneplay.cz/', 'user-agent': USER_AGENT, lic_header_name: lic_token, 'content-type': 'application/octet-stream'}
        licence = req.post(lic_url, headers=headers, data=challenge_data)
        cdm_obj.parse_license(session_id_cdm, licence.content)
        keys = [f"{key.kid.hex}:{key.key.hex()}" for key in cdm_obj.get_keys(session_id_cdm) if key.type != 'SIGNING']
        cdm_obj.close(session_id_cdm)
        return keys
    except Exception as e:
        print(f'CDM external failed: {e}', file=sys.stderr)
        return None

def do_action():
    get_token()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        headers = {'accept': '*/*', 'authorization': 'Bearer ' + token, 'content-type': 'text/plain;charset=UTF-8', 'origin': 'https://www.oneplay.cz', 'referer': 'https://www.oneplay.cz/', 'user-agent': USER_AGENT}
        json_data = {"deviceInfo": {"deviceType": "web", "appVersion": "1.2.18-patch", "deviceManufacturer": "Unknown", "deviceOs": "Windows"}, "capabilities": {"async": "websockets"}, "payload": {"requestedOutput": {"channelSchedule": False}}, "context": {"requestId": str(uuid.uuid4()), "clientId": client_id, "sessionId": session_id, "serverId": server_id}}
        response = req.post('https://http.cms.jyxo.cz/api/v3/epg.display', headers=headers, json=json_data)
        try:
            data = get_message('ApiCall', 'epg.display')['response']['data']
            for ch in data.get('channelList', []):
                content_id = ch.get('action', {}).get('params', {}).get('payload', {}).get('criteria', {}).get('contentId', '')
                channel = {
                    'Name': ch.get('name', 'Unknown').replace('/', '-').replace(':D', ''),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"id={content_id}",
                    'CdmType': 'widevine',
                    'UseCdm': True,
                    'Cdm': f"id={content_id}",
                    'Video': 'best',
                    'OnDemand': True,
                    'SpeedUp': True,
                }
                output['Channels'].append(channel)
            print(json.dumps(output, indent=2))
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "events":
        output = {'Events': []}
        print(json.dumps(output, indent=2))
    
    elif action == "heartbeat":
        sys.exit()
    
    elif action == "manifest":
        try:
            content_id = id
            video_url, lic_url, lic_header_name, lic_token = get_single(content_id)
            if not video_url:
                return "error"
            output = {
                "Cdn": [{"Name": "default", "ManifestUrl": video_url}],
                "ManifestUrl": video_url,
                "Headers": {"Manifest": {'User-Agent': USER_AGENT}, "Media": {'User-Agent': USER_AGENT}},
                "Heartbeat": {"Url": '', "Params": '', "PeriodMs": 5*60*1000},
                "LicenseUrl": lic_url,
                "LicenseHeaderName": lic_header_name,
                "LicenseToken": lic_token
            }
            print(json.dumps(output))
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "cdm" and cdm == "internal":
        try:
            content_id = id
            video_url, lic_url, lic_header_name, lic_token = get_single(content_id)
            if lic_url and lic_header_name and lic_token:
                result = do_cdm_internal(challenge, lic_url, lic_header_name, lic_token)
                if result:
                    print(result)
                else:
                    return "error"
            else:
                return "error"
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "cdm" and cdm == "external":
        try:
            content_id = id
            video_url, lic_url, lic_header_name, lic_token = get_single(content_id)
            if lic_url and lic_header_name and lic_token:
                pssh_to_use = pssh if pssh else get_pssh_from_mpd(video_url)
                if pssh_to_use:
                    keys = do_cdm_external(pssh_to_use, lic_url, lic_header_name, lic_token)
                    if keys:
                        for key in keys:
                            print(key)
                    else:
                        return "error"
                else:
                    return "error"
            else:
                return "error"
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    else:
        print("invalid action: " + action, file=sys.stderr)

if do_action() == "error":
    login()
    do_action()
