#!/usr/bin/python3
import sys
import os
import o11
import json
import datetime
import pytz
import base64
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 = '/StcTV_' + user + '.tokens'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'

def find_wv_pssh_offsets(raw):
    offsets = []
    offset = 0
    while True:
        offset = raw.find(b'pssh', offset)
        if offset == -1:
            break
        size = int.from_bytes(raw[offset-4:offset], byteorder='big')
        pssh_offset = offset - 4
        offsets.append(raw[pssh_offset:pssh_offset+size])
        offset += size
    return offsets

def to_pssh(content):
    wv_offsets = find_wv_pssh_offsets(content)
    return [base64.b64encode(wv_offset).decode() for wv_offset in wv_offsets]

def init_to_pssh(init_url):
    headers = {'origin': 'https://web.stctv.com', 'referer': 'https://web.stctv.com/', 'user-agent': user_agent}
    response = req.get(init_url, headers=headers)
    psshs = to_pssh(response.content)
    return psshs[-1] if psshs else None

def do_cdm_external(pssh_data, license_url):
    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': '*/*', 'Origin': 'https://web.stctv.com', 'Referer': 'https://web.stctv.com/', 'User-Agent': user_agent, 'Content-Type': 'application/octet-stream'}
    licence = req.post(license_url, headers=lic_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

def get_pssh_from_mpd(url):
    headers = {'origin': 'https://web.stctv.com', 'referer': 'https://web.stctv.com/', 'user-agent': user_agent}
    response = req.get(url, headers=headers, allow_redirects=False)
    location = response.headers.get('Location', url)
    response2 = req.get(location, headers=headers)
    soup = BeautifulSoup(response2.content, features="xml")
    seg_template = soup.find('SegmentTemplate')
    if seg_template:
        init = seg_template.get('initialization', '')
        rep = soup.find('Representation')
        bandwidth = rep.get('bandwidth', '')
        rep_id = rep.get('id', '')
        base_url = soup.find('BaseURL')
        base = base_url.text if base_url else ''
        loc_parts = location.split('/')
        loc_parts.pop()
        init_url = '/'.join(loc_parts) + '/' + base + init.replace('$Bandwidth$', bandwidth).replace('$RepresentationID$', rep_id)
        return init_to_pssh(init_url), location.split('?')[0]
    return None, location

def get_channels(token):
    headers = {'content-type': 'application/json', 'identitytoken': token, 'origin': 'https://web.stctv.com', 'referer': 'https://web.stctv.com/', 'user-agent': user_agent}
    params = {'productKey': 'stc-tv', 'visibility': 'visible', 'country': 'SA', 'device': 'PC', 'deviceType': 'wcp_chrome'}
    response = req.get('https://jawwy2-prod.intigral-ott.net/bolt/v2/webB2CGDMPrdExy0sVDlZMzNDdUyZ/channels', headers=headers, params=params)
    return response.json()['data']['channels']

def get_single(channel_url, auth_token):
    headers = {'Accept': '*/*', 'Origin': 'https://web.stctv.com', 'Referer': 'https://web.stctv.com/', 'User-Agent': user_agent, 'content-type': 'application/json'}
    params = {'format': 'SMIL', 'switch': 'dash', 'auth': auth_token}
    response = req.get(channel_url, headers=headers, params=params)
    soup = BeautifulSoup(response.content, features='lxml')
    video = soup.find('video')
    return video['src'] + '?response=200&bk-ml=1' if video else None

def get_license_url(token, auth_token, username):
    headers = {'content-type': 'application/json', 'identitytoken': token, 'authorization': auth_token, 'origin': 'https://web.stctv.com', 'referer': 'https://web.stctv.com/', 'user-agent': user_agent}
    response = req.get(f'https://jawwy2-prod.intigral-ott.net/bolt/v1/webB2CGDMPrdExy0sVDlZMzNDdUyZ/users/{username}/devices?productKey=stc-tv&', headers=headers)
    return response.json()['data'][0]['widevineLicenceUrl']

def do_login_request(username, pwd):
    headers = {'Content-Type': 'application/json; charset=utf-8', 'User-Agent': 'okhttp/4.10.0'}
    json_data = {"username": username, "password": pwd, "userAgent": "android", "tokenNeeded": True}
    response = req.post('https://jawwy2-prod.intigral-ott.net/identity-v2/v3/9fbe70fa/login/credentials?productKey=stc-tv', headers=headers, json=json_data)
    return response.json()['data']

def login():
    print("logging in...", file=sys.stderr)
    auth = do_login_request(user, password)
    token = auth['identityToken']
    auth_token = auth['authToken']
    username = auth['username']
    license_url = get_license_url(token, auth_token, username)
    auth_data = {'identityToken': token, 'authToken': auth_token, 'username': username, 'licenseUrl': license_url}
    json.dump(auth_data, open(os.path.abspath(os.path.dirname(__file__)) + authFile, 'w'))
    print("logged in successfully", file=sys.stderr)

def do_action():
    if action == "login":
        login()
        sys.exit()
    try:
        auth = json.load(open(os.path.abspath(os.path.dirname(__file__)) + authFile))
        token = auth['identityToken']
        auth_token = auth['authToken']
        license_url = auth['licenseUrl']
    except:
        return "error"

    if action == "channels":
        output = {'Channels': []}
        for c in get_channels(token):
            output['Channels'].append({'Name': c['channelTitle'], 'Mode': "live", 'SessionManifest': True, 'ManifestScript': 'url=' + c['tuningURLs']['liveURL'], 'CdmType': "widevine", 'UseCdm': True, 'Cdm': 'url=' + c['tuningURLs']['liveURL'], 'Video': 'best'})
        print(json.dumps(output, indent=2))
    elif action == "events":
        output = {'Events': []}
        for c in get_channels(token):
            output['Events'].append({'Name': c['channelTitle'], 'Mode': "live", 'SessionManifest': True, 'ManifestScript': 'url=' + c['tuningURLs']['liveURL'], 'CdmType': "widevine", 'UseCdm': True, 'Cdm': 'url=' + c['tuningURLs']['liveURL'], '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":
        channel_url = id.replace('url=', '') if id.startswith('url=') else id
        url = get_single(channel_url, auth_token)
        pssh_data, manifest_url = get_pssh_from_mpd(url)
        output = {"Cdn": [], "ManifestUrl": manifest_url, "Headers": {"Manifest": {'User-Agent': user_agent}, "Media": {'User-Agent': user_agent}}, "LicenseUrl": license_url}
        if pssh_data:
            output['Pssh'] = pssh_data
        print(json.dumps(output))
    elif action == "cdm" and cdm_param == "external":
        channel_url = id.replace('url=', '') if id.startswith('url=') else id
        url = get_single(channel_url, auth_token)
        pssh_data, manifest_url = get_pssh_from_mpd(url)
        if pssh_data:
            for key in do_cdm_external(pssh_data, license_url):
                print(key)

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