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

# 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
from Crypto.Util.Padding import unpad
from Crypto.Cipher import AES
from Crypto.Hash import MD5

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

headers = {
    'accept': '*/*',
    'origin': 'https://dstv.stream',
    'referer': 'https://dstv.stream/',
    'user-agent': USER_AGENT,
}

def get_auth():
    try:
        return json.load(open(SCRIPT_DIR + authFile))
    except:
        return None

def save_auth(auth_data):
    json.dump(auth_data, open(SCRIPT_DIR + authFile, 'w'), indent=2)

def decrypt(ciphertext_b64):
    password = '@#$2345678@#$%^'
    encryptedData = base64.b64decode(ciphertext_b64)
    salt = encryptedData[8:16]
    ciphertext = encryptedData[16:]
    
    derived = b''
    while len(derived) < 48:
        hasher = MD5.new()
        hasher.update(derived[-16:] + password.encode('utf-8') + salt)
        derived += hasher.digest()
    
    key = derived[0:32]
    iv = derived[32:48]
    
    cipher = AES.new(key, AES.MODE_CBC, iv)
    return unpad(cipher.decrypt(ciphertext), 16).decode().replace('"', '')

def do_refresh(token, id_token):
    refresh_headers = {
        'content-type': 'application/json',
        'origin': 'https://dstv.stream',
        'referer': 'https://dstv.stream/',
        'user-agent': USER_AGENT,
    }
    json_data = {'idToken': id_token, 'accessToken': token}
    response = req.post('https://ssl.dstv.com/connect/connect-authtoken/v2/accesstoken/refresh', params={'build_nr': '1.0.4'}, headers=refresh_headers, json=json_data)
    data = response.json()
    return data['accessToken'], data['idToken']

def login():
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if not auth or 'token' not in auth:
        print("No auth found. Please add DSTV tokens to auth file.", file=sys.stderr)
        save_auth({
            'token': 'ENTER b0538d762cb1174b74aab704b9274b0030c262447d37947cfc3d5d63e2c924c0 value here',
            'id_token': 'ENTER 9b25dee1e443eb52139e96b2f66ed1f3fcf81224f3e13ce38175521e3613ace3 value here'
        })
        sys.exit(1)
    
    try:
        token = auth['token']
        id_token = auth['id_token']
        
        # Try to decrypt if encrypted
        try:
            token = decrypt(token)
            id_token = decrypt(id_token)
        except:
            pass
        
        token, id_token = do_refresh(token, id_token)
        save_auth({'token': token, 'id_token': id_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():
    return login()

def get_manifest_token(channel_tag, token):
    mt_headers = {
        'accept': '*/*',
        'authorization': token,
        'origin': 'https://dstv.stream',
        'referer': 'https://dstv.stream/',
        'user-agent': USER_AGENT,
    }
    response = req.post('https://ssl.dstv.com/api/dstv_now/play_stream/access_token', params={'channel_tag': channel_tag}, headers=mt_headers, json={})
    try:
        return response.json()['access_token']
    except:
        return None

def get_session(token):
    session_headers = {
        'accept': '*/*',
        'authorization': token,
        'content-type': 'application/json',
        'origin': 'https://dstv.stream',
        'referer': 'https://dstv.stream/',
        'user-agent': USER_AGENT,
    }
    json_data = {
        'device_type': 'web',
        'session_type': 'streaming',
        'device_name': 'chrome',
        'os': 'Windows',
        'os_version': '10.0',
        'drm': 'widevine',
        'hdcp': 'Available',
        'security_level': 'L3',
    }
    response = req.post('https://ssl.dstv.com/api/vod-auth/entitlement/session', headers=session_headers, json=json_data)
    try:
        return response.json()['session']
    except:
        return None

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 do_cdm_internal(challenge_b64, channel_tag, session_token):
    decoded = jwt.decode(session_token, options={"verify_signature": False})
    params = {
        'CrmId': decoded['aid'],
        'AccountId': decoded['aid'],
        'ContentId': channel_tag,
        'ls_session': session_token,
    }
    lic_headers = {
        'accept': '*/*',
        'origin': 'https://dstv.stream',
        'referer': 'https://dstv.stream/',
        'user-agent': USER_AGENT,
        'content-type': 'application/octet-stream',
    }
    response = req.post('https://licensev2.dstv.com/widevine/getLicense', headers=lic_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, channel_tag, session_token):
    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)
        
        decoded = jwt.decode(session_token, options={"verify_signature": False})
        params = {
            'CrmId': decoded['aid'],
            'AccountId': decoded['aid'],
            'ContentId': channel_tag,
            'ls_session': session_token,
        }
        lic_headers = {
            'accept': '*/*',
            'origin': 'https://dstv.stream',
            'referer': 'https://dstv.stream/',
            'user-agent': USER_AGENT,
            'content-type': 'application/octet-stream',
        }
        
        licence = req.post('https://licensev2.dstv.com/widevine/getLicense', headers=lic_headers, params=params, data=challenge_data)
        cdm_obj.parse_license(session_id, licence.content)
        
        keys = []
        for key in cdm_obj.get_keys(session_id):
            if key.type != 'SIGNING':
                keys.append(f"{key.kid.hex}:{key.key.hex()}")
        
        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():
    token = get_token()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        
        decoded = jwt.decode(token, options={"verify_signature": False})
        ch_headers = {
            'accept': '*/*',
            'authorization': token,
            'content-type': 'application/json',
            'origin': 'https://dstv.stream',
            'referer': 'https://dstv.stream/',
            'user-agent': USER_AGENT,
        }
        
        response = req.get(f"https://ssl.dstv.com/api/cs-mobile/v7/epg-service/channels/events;genre=ALL;;country={decoded['country']};packageId={decoded['package']}", headers=ch_headers)
        
        try:
            data = response.json()
            for item in data.get('items', []):
                stream_url = item.get('streams', [{}])[0].get('playerUrl', '').split('?')[0] if item.get('streams') else ''
                channel = {
                    'Name': item.get('name', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"id={item.get('id', '')}&url={stream_url}",
                    'CdmType': 'widevine',
                    'UseCdm': True,
                    'Cdm': f"id={item.get('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:
            params_dict = {}
            for param in id.split('&'):
                if '=' in param:
                    k, v = param.split('=', 1)
                    params_dict[k] = v
            
            channel_tag = params_dict.get('id', '')
            base_url = params_dict.get('url', '')
            
            manifest_token = get_manifest_token(channel_tag, token)
            if not manifest_token:
                return "error"
            
            stream_url = base_url + '/.mpd?hdnts=' + manifest_token
            
            output = {
                "Cdn": [{"Name": "default", "ManifestUrl": stream_url}],
                "ManifestUrl": stream_url,
                "Headers": {"Manifest": {'User-Agent': USER_AGENT}, "Media": {'User-Agent': USER_AGENT}},
                "Heartbeat": {"Url": '', "Params": '', "PeriodMs": 5*60*1000},
                "ChannelTag": channel_tag
            }
            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
            
            channel_tag = params_dict.get('id', '')
            session_token = get_session(token)
            
            if session_token:
                result = do_cdm_internal(challenge, channel_tag, session_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:
            params_dict = {}
            for param in id.split('&'):
                if '=' in param:
                    k, v = param.split('=', 1)
                    params_dict[k] = v
            
            channel_tag = params_dict.get('id', '')
            base_url = params_dict.get('url', '')
            
            session_token = get_session(token)
            if not session_token:
                return "error"
            
            pssh_to_use = pssh
            if not pssh_to_use and base_url:
                manifest_token = get_manifest_token(channel_tag, token)
                if manifest_token:
                    stream_url = base_url + '/.mpd?hdnts=' + manifest_token
                    pssh_to_use = get_pssh_from_mpd(stream_url)
            
            if pssh_to_use:
                keys = do_cdm_external(pssh_to_use, channel_tag, session_token)
                if keys:
                    for key in keys:
                        print(key)
                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()
