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

# 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 = '/TeliaPlaySE_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'
REGION_CODE = 'SE'
REGION_DOMAIN = 'teliaplay.se'

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 do_refresh(refresh_token, device_id):
    headers = {'accept': '*/*', 'content-type': 'application/json', 'origin': f'https://www.{REGION_DOMAIN}', 'referer': f'https://www.{REGION_DOMAIN}/', 'tv-client-boot-id': str(uuid.uuid4()), 'tv-client-name': 'web', 'user-agent': USER_AGENT, 'x-country': REGION_CODE}
    json_data = {'deviceId': device_id, 'deviceType': 'WEB', 'refreshToken': refresh_token}
    response = req.post(f'https://logingateway.{REGION_DOMAIN}/logingateway/rest/v1/login/refresh', headers=headers, json=json_data)
    response.raise_for_status()
    data = response.json()
    return data['accessToken'], data['refreshToken']

def login():
    global token
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if not auth or 'refresh_token' not in auth:
        print("No auth found. Please add TeliaPlaySE refresh_token and device_id to auth file.", file=sys.stderr)
        save_auth({'refresh_token': '', 'device_id': ''})
        sys.exit(1)
    
    try:
        new_token, new_refresh = do_refresh(auth['refresh_token'], auth['device_id'])
        save_auth({'refresh_token': new_refresh, 'device_id': auth['device_id']})
        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_single(channel_id, content_type):
    headers = {'accept': '*/*', 'authorization': 'Bearer ' + token, 'client': 'web-player', 'content-type': 'application/json', 'origin': f'https://www.{REGION_DOMAIN}', 'referer': f'https://www.{REGION_DOMAIN}/', 'tv-client-boot-id': str(uuid.uuid4()), 'user-agent': USER_AGENT, 'x-country': REGION_CODE}
    params = {'country': REGION_CODE}
    json_data = {'whiteLabelBrand': 'TELIA', 'watchMode': 'LIVE', 'accessControl': 'SUBSCRIPTION', 'device': {'packagings': ['DASH_MP4_CTR', 'HLS_CMAF_CBCS', 'HLS_TS_CBCS'], 'drmType': 'WIDEVINE', 'capabilities': ['YOSPACE_DASH', 'CHANNEL_DVR', 'YOSPACE_VOD'], 'screen': {'height': 1440, 'width': 2560}, 'tvClient': {'name': 'web', 'vendorModel': 'windows_desktop'}}, 'preferences': {'audioLanguage': [], 'accessibility': []}}
    response = req.post(f'https://streaminggateway.clientapi-prod.live.tv.telia.net/streaminggateway/rest/secure/v2/streamingticket/{content_type.upper()}/{channel_id}', params=params, headers=headers, json=json_data)
    try:
        data = response.json()
        stream = data['streams'][0]
        lic_url = None
        lic_headers = None
        if 'drm' in stream and 'licenseUrl' in stream['drm'] and 'headers' in stream['drm']:
            lic_url = stream['drm']['licenseUrl']
            lic_headers = stream['drm']['headers']
        return stream['url'], lic_url, lic_headers
    except:
        return None, None, None

def do_cdm_internal(challenge_b64, lic_url, lic_headers):
    headers = {'accept': '*/*', 'origin': f'https://www.{REGION_DOMAIN}', 'referer': f'https://www.{REGION_DOMAIN}/', 'user-agent': USER_AGENT, 'content-type': 'application/octet-stream'}
    headers.update(lic_headers)
    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_headers):
    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': '*/*', 'origin': f'https://www.{REGION_DOMAIN}', 'referer': f'https://www.{REGION_DOMAIN}/', 'user-agent': USER_AGENT, 'content-type': 'application/octet-stream'}
        headers.update(lic_headers)
        licence = req.post(lic_url, headers=headers, 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': '*/*', 'authorization': 'Bearer ' + token, 'content-type': 'application/json', 'origin': f'https://www.{REGION_DOMAIN}', 'referer': f'https://www.{REGION_DOMAIN}/', 'tv-client-boot-id': str(uuid.uuid4()), 'tv-client-name': 'web', 'user-agent': USER_AGENT, 'x-country': REGION_CODE}
        query = 'query getEpgOverviewChannels { channels(limit: 999, offset: 0, regionalChannelsSelection: [], userAccessFilter: null) { pageInfo { nextPageOffset hasNextPage totalCount } channelItems { id name analytics { contentId linkType contentType } recordAndWatch icons2 { compact { dark { source } } large { dark { source } } } isFavorite inEngagement playback { play { playbackSpec { videoId videoIdType watchMode accessControl } } }  } } }'
        payload = {'operationName': 'getEpgOverviewChannels', 'query': query}
        response = req.post('https://graphql-telia.t6a.net/graphql', headers=headers, json=payload)
        try:
            data = response.json()
            for ch in data['data']['channels']['channelItems']:
                channel = {
                    'Name': ch.get('name', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"cid={ch.get('analytics', {}).get('contentId', '')}&ctype={ch.get('analytics', {}).get('contentType', 'CHANNEL')}",
                    'CdmType': 'widevine',
                    'UseCdm': True,
                    'Cdm': f"cid={ch.get('analytics', {}).get('contentId', '')}&ctype={ch.get('analytics', {}).get('contentType', 'CHANNEL')}",
                    '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_id = params_dict.get('cid', '')
            content_type = params_dict.get('ctype', 'CHANNEL')
            video_url, lic_url, lic_headers = get_single(channel_id, content_type)
            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,
                "LicenseHeaders": lic_headers
            }
            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_id = params_dict.get('cid', '')
            content_type = params_dict.get('ctype', 'CHANNEL')
            video_url, lic_url, lic_headers = get_single(channel_id, content_type)
            if lic_url and lic_headers:
                result = do_cdm_internal(challenge, lic_url, lic_headers)
                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_id = params_dict.get('cid', '')
            content_type = params_dict.get('ctype', 'CHANNEL')
            video_url, lic_url, lic_headers = get_single(channel_id, content_type)
            if lic_url and lic_headers:
                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_headers)
                    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()
