#!/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 = '/BallySports_' + 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 = {'accept': '*/*', 'user-agent': user_agent, 'content-type': 'application/octet-stream'}
    response = req.get(init_url, headers=headers)
    return to_pssh(response.content)

def do_cdm_external(pssh_data, license_url, lic_token):
    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://www.ballysports.com', 'User-Agent': user_agent, 'x-dt-auth-token': lic_token, '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 = {'accept': '*/*', 'user-agent': user_agent, 'content-type': 'application/octet-stream'}
    response = req.get(url, headers=headers)
    soup = BeautifulSoup(response.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 ''
        init_url = base + init.replace('$Bandwidth$', bandwidth).replace('$RepresentationID$', rep_id)
        psshs = init_to_pssh(init_url)
        return psshs[-1] if psshs else None
    return None

def get_channels(token):
    headers = {'accept': 'application/json', 'authorization': 'Bearer ' + token, 'content-type': 'application/json', 'origin': 'https://www.ballysports.com', 'user-agent': user_agent}
    response = req.get('https://middleware.prod.gs.ballysports.com/hgml/08-2020/web-watch', headers=headers)
    return response.json().get('items', [{}])[0].get('items', [])

def get_single(token, channel_id):
    headers = {'accept': 'application/json', 'authorization': 'Bearer ' + token, 'content-type': 'application/json', 'origin': 'https://www.ballysports.com', 'user-agent': user_agent}
    params = {'drmType': 'widevine', 'format': 'DASH', 'appversion': '0.9.0', 'platform': 'Windows', 'osversion': '10', 'device_make': 'unknown', 'device_model': 'unknown', 'debug': 'false'}
    response = req.get('https://middleware.prod.gs.ballysports.com/video/' + channel_id, params=params, headers=headers)
    data = response.json()
    return data.get('url', '').split('?')[0], data.get('drm', {}).get('licenseUrl', ''), data.get('drm', {}).get('token', '')

def do_login_request(username, pwd):
    headers = {'accept': 'application/json', 'content-type': 'application/json', 'origin': 'https://www.ballysports.com', 'user-agent': user_agent}
    json_data = {'email': username, 'password': pwd, 'device_id': 'cb398106-60aa-44b7-8a48-1e307968789f', 'device_info': {'device_id': 'cb398106-60aa-44b7-8a48-1e307968789f', 'device_name': 'Windows PC', 'device_type': 'web_browser'}}
    response = req.post('https://middleware.prod.gs.ballysports.com/auth/login', headers=headers, json=json_data)
    data = response.json()
    return data.get('user_token', ''), data.get('refresh_token', '')

def do_token_refresh(token, refresh_token):
    headers = {'authorization': 'Bearer ' + token, 'accept': 'application/json', 'content-type': 'application/json', 'origin': 'https://www.ballysports.com', 'user-agent': user_agent}
    json_data = {'refresh_token': refresh_token}
    response = req.post('https://middleware.prod.gs.ballysports.com/auth/refresh', headers=headers, json=json_data)
    data = response.json()
    return data.get('user_token', ''), data.get('refresh_token', '')

def login():
    print("logging in...", file=sys.stderr)
    token, refresh_token = do_login_request(user, password)
    auth_data = {'token': token, 'refresh_token': refresh_token}
    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, refresh_token = do_token_refresh(auth['token'], auth['refresh_token'])
        auth['token'] = token
        auth['refresh_token'] = refresh_token
        json.dump(auth, open(os.path.abspath(os.path.dirname(__file__)) + authFile, 'w'))
    except:
        return "error"

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

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