#!/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 = '/MediasetInfinity_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'

token = ''

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 get_id_token(login_token, gmid):
    cookies = {'gmid': gmid}
    headers = {'accept': '*/*', 'content-type': 'application/x-www-form-urlencoded', 'origin': 'https://www.mediasetinfinity.es', 'referer': 'https://www.mediasetinfinity.es/', 'user-agent': USER_AGENT}
    data = {'APIKey': '4_S47BDGOsT5beXni9mKPjUw', 'cid': 'mediaset-web-mediaset.it programmi-mediaset Default', 'sdk': 'js_latest', 'login_token': login_token, 'authMode': 'cookie', 'pageURL': 'https://www.mediasetinfinity.es/directo/cuatro/', 'sdkBuild': '18051', 'format': 'json'}
    response = req.post('https://login.mediasetinfinity.es/accounts.getJWT', headers=headers, cookies=cookies, data=data)
    return response.json()['id_token']

def get_be_token(id_token):
    headers = {'accept': '*/*', 'content-type': 'application/json', 'origin': 'https://www.mediasetinfinity.es', 'referer': 'https://www.mediasetinfinity.es/', 'user-agent': USER_AGENT}
    json_data = {'appName': 'web//mediasetplay-web/1.0.19-da90cd4', 'gt': id_token, 'client_id': '8a8b2f2b-6672-44d3-bf4f-aedd9ce2a6e5', 'include': 'personas,adminBeToken'}
    response = req.post('https://services-ott-prod-fe.mediaset.net/esp/idm/v3.0/account/login', headers=headers, json=json_data)
    return response.json()['response']['adminBeToken']

def login():
    global token
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if not auth or 'login_token' not in auth:
        print("No auth found. Please add MediasetInfinity login_token and gmid to auth file.", file=sys.stderr)
        save_auth({'login_token': '', 'gmid': ''})
        sys.exit(1)
    
    try:
        id_token = get_id_token(auth['login_token'], auth['gmid'])
        token = get_be_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():
    global token
    if token:
        return token
    return login()

def get_pssh_from_mpd(url):
    headers = {'origin': 'https://www.mediasetinfinity.es', 'referer': 'https://www.mediasetinfinity.es/', 'user-agent': USER_AGENT}
    response = req.get(url, headers=headers)
    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(public_url):
    headers = {'Accept': 'application/json, text/plain, */*', 'Origin': 'https://www.mediasetinfinity.es', 'Referer': 'https://www.mediasetinfinity.es/', 'User-Agent': USER_AGENT}
    params = {'format': 'SMIL', 'auth': token, 'formats': 'MPEG-DASH', 'assetTypes': '4K,browser,captionNo,widevine,geoEU|geoNoLim:4K,browser,captionNo,geoEU|geoNoLim:HD,browser,captionNo,widevine,geoEU|geoNoLim:HD,browser,captionNo,geoEU|geoNoLim:HR,browser,captionNo,widevine,geoEU|geoNoLim:HR,browser,captionNo,geoEU|geoNoLim:SD,browser,captionNo,widevine,geoEU|geoNoLim:SD,browser,captionNo,geoEU|geoNoLim:SS,browser,captionNo,widevine,geoEU|geoNoLim:SS,browser,captionNo,geoEU|geoNoLim', 'balance': 'true', 'auto': 'true', 'tracking': 'true', 'delivery': 'Streaming'}
    response = req.get(public_url, headers=headers, params=params)
    try:
        soup = BeautifulSoup(response.content, features='lxml')
        url = soup.find('video')['src']
        tracking = soup.find('param')['value']
        t_parts = tracking.split('|')
        pid = None
        aid = None
        for t in t_parts:
            if 'pid' in t:
                pid = t.split('=')[-1]
            if 'aid' in t:
                aid = t.split('=')[-1]
        return url, pid, aid
    except:
        return None, None, None

def do_cdm_internal(challenge_b64, pid, aid):
    headers = {'origin': 'https://www.mediasetinfinity.es', 'referer': 'https://www.mediasetinfinity.es/', 'user-agent': USER_AGENT, 'content-type': 'application/octet-stream'}
    params = {'releasePid': pid, 'account': f'http://access.auth.theplatform.com/data/Account/{aid}', 'schema': '1.0', 'token': token}
    response = req.post('https://widevine.entitlement.theplatform.eu/wv/web/ModularDrm/getRawWidevineLicense', 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, pid, aid):
    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 = {'origin': 'https://www.mediasetinfinity.es', 'referer': 'https://www.mediasetinfinity.es/', 'user-agent': USER_AGENT, 'content-type': 'application/octet-stream'}
        params = {'releasePid': pid, 'account': f'http://access.auth.theplatform.com/data/Account/{aid}', 'schema': '1.0', 'token': token}
        licence = req.post('https://widevine.entitlement.theplatform.eu/wv/web/ModularDrm/getRawWidevineLicense', 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': []}
        headers = {'accept': 'application/json, text/plain, */*', 'origin': 'https://www.mediasetinfinity.es', 'referer': 'https://www.mediasetinfinity.es/', 'user-agent': USER_AGENT}
        response = req.get('https://services-ott-prod-fe.mediaset.net/esp/static/nownext/v3.0/nownext.json', headers=headers)
        try:
            data = response.json()
            for k, v in data.get('response', {}).get('listings', {}).items():
                tmp = next(iter(v['stations'].values()))
                channel = {
                    'Name': tmp.get('title', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"url={v.get('publicUrl', '')}",
                    'CdmType': 'widevine',
                    'UseCdm': True,
                    'Cdm': f"url={v.get('publicUrl', '')}",
                    '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:
            public_url = id.replace('url=', '')
            video_url, pid, aid = get_single(public_url)
            if not video_url:
                return "error"
            output = {
                "Cdn": [{"Name": "default", "ManifestUrl": video_url}],
                "ManifestUrl": video_url,
                "Headers": {"Manifest": {'User-Agent': USER_AGENT, 'Origin': 'https://www.mediasetinfinity.es', 'Referer': 'https://www.mediasetinfinity.es/'}, "Media": {'User-Agent': USER_AGENT, 'Origin': 'https://www.mediasetinfinity.es', 'Referer': 'https://www.mediasetinfinity.es/'}},
                "Heartbeat": {"Url": '', "Params": '', "PeriodMs": 5*60*1000},
                "Pid": pid,
                "Aid": aid
            }
            print(json.dumps(output))
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "cdm" and cdm == "internal":
        try:
            public_url = id.replace('url=', '')
            video_url, pid, aid = get_single(public_url)
            if pid and aid:
                result = do_cdm_internal(challenge, pid, aid)
                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:
            public_url = id.replace('url=', '')
            video_url, pid, aid = get_single(public_url)
            if pid and aid:
                pssh_to_use = pssh if pssh else get_pssh_from_mpd(video_url)
                if pssh_to_use:
                    keys = do_cdm_external(pssh_to_use, pid, aid)
                    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()
