#!/usr/bin/python3
import sys
import os
import o11
import json
import datetime
import pytz
import uuid
from pywidevine.cdm import Cdm
from pywidevine.device import Device
from pywidevine.pssh import PSSH
from bs4 import BeautifulSoup

WVD_PATH = './WVD.wvd'

user = o11.parse_params(sys.argv, 'user')
password = o11.parse_params(sys.argv, 'password')

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_param = o11.parse_params(sys.argv, 'cdm')
challenge = o11.parse_params(sys.argv, 'challenge')

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

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

authFile = '/CytaVision_' + user + '.tokens'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'

def do_cdm_external(pssh_data, license_url, custom_data_token, cookies):
    pssh_obj = PSSH(pssh_data)
    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)
    lic_headers = {'Accept': '*/*', 'AcquireLicense.CustomData': custom_data_token, 'CADeviceType': 'Widevine OTT Client', 'Origin': 'https://ott.cytavision.com.cy', 'Referer': 'https://ott.cytavision.com.cy/EPG/WEBTV/index.html', 'Content-Type': 'application/octet-stream', 'User-Agent': user_agent}
    licence = req.post(license_url, headers=lic_headers, data=challenge_data, cookies=cookies)
    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

def get_pssh_from_mpd(url):
    headers = {'Accept': '*/*', 'Origin': 'https://ott.cytavision.com.cy', 'Referer': 'https://ott.cytavision.com.cy/', 'User-Agent': user_agent}
    response = req.get(url, headers=headers, verify=False)
    for cp in BeautifulSoup(response.content, features="xml").findAll('ContentProtection'):
        if cp.get('schemeIdUri') == 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed':
            pssh_tag = cp.find('cenc:pssh')
            if pssh_tag:
                return pssh_tag.text
    return None

def get_channels(cookies):
    headers = {'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json;charset=UTF-8', 'Origin': 'https://ott.cytavision.com.cy', 'Referer': 'https://ott.cytavision.com.cy/EPG/WEBTV/index.html', 'User-Agent': user_agent, 'X_CSRFToken': cookies.get('CSRFSESSION', '')}
    data = '{"isReturnAllMedia":"1"}'
    response = req.post('https://ott.cytavision.com.cy/VSP/V3/QueryAllChannel', cookies=cookies, headers=headers, data=data)
    return response.json().get('channelDetails', [])

def request_stream(cookies, channel_id, media_id):
    headers = {'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json;charset=UTF-8', 'Origin': 'https://ott.cytavision.com.cy', 'Referer': 'https://ott.cytavision.com.cy/EPG/WEBTV/index.html', 'User-Agent': user_agent, 'X_CSRFToken': cookies.get('CSRFSESSION', '')}
    data = {'channelID': channel_id, 'mediaID': media_id, 'businessType': 'BTV', 'checkLock': {'checkType': '0'}, 'isReturnProduct': '1', 'isHTTPS': '1'}
    response = req.post('https://ott.cytavision.com.cy/VSP/V3/PlayChannel', cookies=cookies, headers=headers, json=data)
    resp_data = response.json()
    triggers = resp_data.get('authorizeResult', {}).get('triggers', [{}])[0]
    return resp_data.get('playURL', ''), triggers.get('licenseURL', ''), triggers.get('customData', '')

def do_login_request(username, pwd, device_id=None):
    if not device_id:
        device_id = str(uuid.uuid4())
    headers = {'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json;charset=UTF-8', 'Origin': 'https://ott.cytavision.com.cy', 'Referer': 'https://ott.cytavision.com.cy/EPG/WEBTV/index.html', 'User-Agent': user_agent}
    data = {'authenticateBasic': {'authType': '1', 'clientPasswd': pwd, 'userID': username, 'userType': '1', 'isSupportWebpImgFormat': '0', 'timeZone': 'Europe/Athens', 'VUID': '1'}, 'authenticateDevice': {'CADeviceInfos': [{'CAdeviceID': device_id, 'CADeviceType': '7'}], 'physicalDeviceID': device_id, 'deviceModel': 'PC'}}
    response = req.post('https://ott.cytavision.com.cy/VSP/V3/Authenticate', headers=headers, json=data)
    resp_data = response.json()
    msg = resp_data.get('result', {}).get('retMsg', '')
    if 'upper limit' in msg:
        device_id = resp_data.get('devices', [{}])[0].get('physicalDeviceID', '')
        return do_login_request(username, pwd, device_id)
    return response.cookies.get_dict()

def login():
    print("logging in...", file=sys.stderr)
    cookies = do_login_request(user, password)
    auth_data = {'cookies': cookies}
    json.dump(auth_data, open(os.path.abspath(os.path.dirname(__file__)) + authFile, 'w'))
    print("logged in successfully", file=sys.stderr)

def get_auth():
    auth = json.load(open(os.path.abspath(os.path.dirname(__file__)) + authFile))
    cookies = do_login_request(user, password)
    return cookies

def do_action():
    if action == "login":
        login()
        sys.exit()
    try:
        cookies = get_auth()
    except:
        return "error"

    if action == "channels":
        output = {'Channels': []}
        for c in get_channels(cookies):
            media_id = ''
            for pc in c.get('physicalChannels', []):
                if len(pc.get('multiBitrates', [])) > 0:
                    media_id = pc.get('ID', '')
            output['Channels'].append({'Name': c['name'], 'Mode': "live", 'SessionManifest': True, 'ManifestScript': 'ch=' + c['ID'] + '&media=' + media_id, 'CdmType': "widevine", 'UseCdm': True, 'Cdm': 'ch=' + c['ID'] + '&media=' + media_id, 'Video': 'best'})
        print(json.dumps(output, indent=2))
    elif action == "events":
        output = {'Events': []}
        for c in get_channels(cookies):
            media_id = ''
            for pc in c.get('physicalChannels', []):
                if len(pc.get('multiBitrates', [])) > 0:
                    media_id = pc.get('ID', '')
            output['Events'].append({'Name': c['name'], 'Mode': "live", 'SessionManifest': True, 'ManifestScript': 'ch=' + c['ID'] + '&media=' + media_id, 'CdmType': "widevine", 'UseCdm': True, 'Cdm': 'ch=' + c['ID'] + '&media=' + media_id, 'Video': 'best', 'Autostart': True, 'Start': int(datetime.datetime.now(pytz.UTC).timestamp()), 'End': int((datetime.datetime.now(pytz.UTC) + datetime.timedelta(hours=4)).timestamp())})
        print(json.dumps(output, indent=2))
    elif action == "manifest":
        params = dict(p.split('=', 1) for p in id.split('&') if '=' in p)
        channel_id = params.get('ch', '')
        media_id = params.get('media', '')
        url, license_url, custom_data = request_stream(cookies, channel_id, media_id)
        pssh_data = get_pssh_from_mpd(url)
        output = {"Cdn": [], "ManifestUrl": url, "Headers": {"Manifest": {'User-Agent': user_agent}, "Media": {'User-Agent': user_agent}}, "LicenseUrl": license_url, "CustomData": custom_data, "Cookies": cookies}
        if pssh_data:
            output['Pssh'] = pssh_data
        print(json.dumps(output))
    elif action == "cdm" and cdm_param == "external":
        params = dict(p.split('=', 1) for p in id.split('&') if '=' in p)
        channel_id = params.get('ch', '')
        media_id = params.get('media', '')
        url, license_url, custom_data = request_stream(cookies, channel_id, media_id)
        pssh_data = get_pssh_from_mpd(url)
        if pssh_data and license_url:
            for key in do_cdm_external(pssh_data, license_url, custom_data, cookies):
                print(key)

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