#!/usr/bin/python3
import sys
import os
import base64
import json
import datetime
import pytz

# 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 = '/TodTV_refresh.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 = ''

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

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

def do_refresh(refresh_token):
    cookies = {'MW_REFRESH_TOKEN': refresh_token}
    headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9', 'referer': 'https://www.tod.tv/en/live/watch/bein-sports-5003196', 'user-agent': USER_AGENT}
    response = req.get('https://www.tod.tv/en', cookies=cookies, headers=headers)
    response.raise_for_status()
    cookies_dict = response.cookies.get_dict()
    return cookies_dict['MW_JWT'], cookies_dict['MW_REFRESH_TOKEN']

def login():
    global token
    print("logging in...", file=sys.stderr)
    
    refresh_token = get_auth()
    if not refresh_token:
        print("No refresh token found. Please add TodTV MW_REFRESH_TOKEN to auth file.", file=sys.stderr)
        save_auth('')
        sys.exit(1)
    
    try:
        new_token, new_refresh = do_refresh(refresh_token)
        save_auth(new_refresh)
        token = new_token
        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})
    try:
        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
    except:
        pass
    return None

def get_viewing_option(url_slug):
    cookies = {'MW_JWT': token}
    headers = {'accept': '*/*', 'content-type': 'text/plain;charset=UTF-8', 'origin': 'https://www.tod.tv', 'referer': 'https://www.tod.tv/', 'user-agent': USER_AGENT}
    data = '{"requestInit":{"cache":"no-store"},"headerOptions":{},"url":"http://tod2-mw-content-prod.mw-content.svc.cluster.local/api/v1/contents/' + url_slug + '"}'
    response = req.post('https://www.tod.tv/api/service', cookies=cookies, headers=headers, data=data)
    try:
        return response.json()['data']['viewOption']['id']
    except:
        return None

def get_single(content_id, request_type, content_type, view_option_id):
    cookies = {'MW_JWT': token}
    headers = {'accept': '*/*', 'content-type': 'text/plain;charset=UTF-8', 'origin': 'https://www.tod.tv', 'referer': 'https://www.tod.tv/', 'user-agent': USER_AGENT}
    data = {'contentId': content_id, 'playRequestType': request_type, 'internetConnectionType': 'WIFI', 'streamFormatType': 'DASH', 'alternativeStreamFormat': 'HLS', 'contentType': content_type}
    if view_option_id:
        data['viewOptionId'] = view_option_id
    json_data = {'requestInit': {'method': 'POST', 'body': json.dumps(data)}, 'skipAPIKeyControl': False, 'url': 'http://tod2-mw-play-prod.mw-play.svc.cluster.local/api/v1/play/cdn'}
    response = req.post('https://www.tod.tv/api/service', cookies=cookies, headers=headers, json=json_data)
    try:
        data = response.json()
        cdn_infos = data['data']['cdnInfos'][0]
        return cdn_infos['cdnUri'], cdn_infos['cdnProvider'], cdn_infos['mediaId'], data['data']['hashValue']
    except:
        return None, None, None, None

def get_ticket(content_id, cdn_provider, cdn_uri, hash_value, view_option_id, request_type):
    cookies = {'MW_JWT': token}
    headers = {'accept': '*/*', 'content-type': 'text/plain;charset=UTF-8', 'origin': 'https://www.tod.tv', 'referer': 'https://www.tod.tv/', 'user-agent': USER_AGENT}
    data = {'contentId': content_id, 'assetId': content_id, 'cdnProvider': cdn_provider, 'cdnUri': cdn_uri, 'hashValue': hash_value, 'playRequestType': request_type, 'streamFormatType': 'DASH', 'alternativeStreamFormat': 'HLS', 'rulesetModel': [], 'packageTags': []}
    if view_option_id:
        data['viewOptionId'] = view_option_id
    json_data = {'requestInit': {'method': 'POST', 'body': json.dumps(data)}, 'skipAPIKeyControl': False, 'url': 'http://tod2-mw-play-prod.mw-play.svc.cluster.local/api/v1/play/ticket'}
    response = req.post('https://www.tod.tv/api/service', cookies=cookies, headers=headers, json=json_data)
    try:
        data = response.json()
        cdn_token = None
        lic_token = None
        for t in data['data']['tickets']:
            if t['ticketType'] == 'CDN':
                cdn_token = t['ticket']
            elif t['ticketType'] == 'DRM':
                lic_token = t['ticket']
        return cdn_token, lic_token
    except:
        return None, None

def do_cdm_internal(challenge_b64, lic_token, media_id):
    headers = {'accept': 'application/base64', 'authorization': 'Bearer ' + lic_token, 'content-type': 'application/octet-stream', 'origin': 'https://www.tod.tv', 'referer': 'https://www.tod.tv/', 'user-agent': USER_AGENT}
    params = {'contentId': media_id}
    response = req.post('https://digiturk.live.ott.irdeto.com/licenseServer/widevine/v1/digiturk/license', headers=headers, params=params, 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_token, media_id):
    try:
        pssh_obj = PSSH(pssh_b64)
        device_obj = Device.load(WVD_PATH)
        cdm_obj = Cdm.from_device(device_obj)
        session_id = cdm_obj.open()
        challenge_data = cdm_obj.get_license_challenge(session_id, pssh_obj)
        headers = {'accept': 'application/base64', 'authorization': 'Bearer ' + lic_token, 'content-type': 'application/octet-stream', 'origin': 'https://www.tod.tv', 'referer': 'https://www.tod.tv/', 'user-agent': USER_AGENT}
        params = {'contentId': media_id}
        licence = req.post('https://digiturk.live.ott.irdeto.com/licenseServer/widevine/v1/digiturk/license', headers=headers, params=params, data=challenge_data)
        cdm_obj.parse_license(session_id, licence.content)
        keys = [f"{key.kid.hex}:{key.key.hex()}" for key in cdm_obj.get_keys(session_id) if key.type != 'SIGNING']
        cdm_obj.close(session_id)
        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': []}
        cookies = {'MW_JWT': token, 'langCode': 'en'}
        headers = {'accept': '*/*', 'content-type': 'text/plain;charset=UTF-8', 'origin': 'https://www.tod.tv', 'referer': 'https://www.tod.tv/', 'user-agent': USER_AGENT, 'x-dtreferer': 'https://www.tod.tv/en/live-tv'}
        data = '{"requestInit":{"method":"GET"},"skipAPIKeyControl":false,"url":"http://tod2-mw-play-prod.mw-play.svc.cluster.local/api/v1/channels"}'
        response = req.post('https://www.tod.tv/api/service', cookies=cookies, headers=headers, data=data)
        try:
            data = response.json()
            for ch in data['data']['channels']:
                watch_info = ch.get('watchInfo', {})
                channel = {
                    'Name': ch.get('title', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"cid={ch.get('id', '')}&ctype={ch.get('contentType', 'CHANNEL')}&rtype={watch_info.get('playRequestType', 'LIVE')}&vopt={watch_info.get('viewOptionId', '')}",
                    'CdmType': 'widevine',
                    'UseCdm': True,
                    'Cdm': f"cid={ch.get('id', '')}&ctype={ch.get('contentType', 'CHANNEL')}&rtype={watch_info.get('playRequestType', 'LIVE')}&vopt={watch_info.get('viewOptionId', '')}",
                    '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:
            params_dict = {}
            for param in id.split('&'):
                if '=' in param:
                    k, v = param.split('=', 1)
                    params_dict[k] = v
            content_id = params_dict.get('cid', '')
            content_type = params_dict.get('ctype', 'CHANNEL')
            request_type = params_dict.get('rtype', 'LIVE')
            view_option_id = params_dict.get('vopt', '') or None
            cdn_uri, cdn_provider, media_id, hash_value = get_single(content_id, request_type, content_type, view_option_id)
            if not cdn_uri:
                return "error"
            cdn_token, lic_token = get_ticket(content_id, cdn_provider, cdn_uri, hash_value, view_option_id, request_type)
            if not cdn_token:
                return "error"
            video_url = f'{cdn_uri}?{cdn_token}' if '?' not in cdn_uri else f'{cdn_uri}&{cdn_token}'
            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},
                "LicenseToken": lic_token,
                "MediaId": media_id
            }
            print(json.dumps(output))
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "cdm" and cdm == "internal":
        try:
            params_dict = {}
            for param in id.split('&'):
                if '=' in param:
                    k, v = param.split('=', 1)
                    params_dict[k] = v
            content_id = params_dict.get('cid', '')
            content_type = params_dict.get('ctype', 'CHANNEL')
            request_type = params_dict.get('rtype', 'LIVE')
            view_option_id = params_dict.get('vopt', '') or None
            cdn_uri, cdn_provider, media_id, hash_value = get_single(content_id, request_type, content_type, view_option_id)
            if cdn_uri:
                cdn_token, lic_token = get_ticket(content_id, cdn_provider, cdn_uri, hash_value, view_option_id, request_type)
                if lic_token:
                    result = do_cdm_internal(challenge, lic_token, media_id)
                    if result:
                        print(result)
                    else:
                        return "error"
                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:
            params_dict = {}
            for param in id.split('&'):
                if '=' in param:
                    k, v = param.split('=', 1)
                    params_dict[k] = v
            content_id = params_dict.get('cid', '')
            content_type = params_dict.get('ctype', 'CHANNEL')
            request_type = params_dict.get('rtype', 'LIVE')
            view_option_id = params_dict.get('vopt', '') or None
            cdn_uri, cdn_provider, media_id, hash_value = get_single(content_id, request_type, content_type, view_option_id)
            if cdn_uri:
                cdn_token, lic_token = get_ticket(content_id, cdn_provider, cdn_uri, hash_value, view_option_id, request_type)
                if lic_token:
                    video_url = f'{cdn_uri}?{cdn_token}' if '?' not in cdn_uri else f'{cdn_uri}&{cdn_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_token, media_id)
                        if keys:
                            for key in keys:
                                print(key)
                        else:
                            return "error"
                    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()
