#!/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')
token_param = o11.parse_params(sys.argv, 'token')

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 = '/NowPlayer_' + 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, 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 = {'Origin': 'https://nowplayer.now.com', 'Referer': 'https://nowplayer.now.com/', 'User-Agent': user_agent, 'Content-Type': 'application/x-www-form-urlencoded'}
    data = json.dumps({'rawLicenseRequestBase64': base64.b64encode(challenge_data).decode(), 'drmToken': lic_token})
    licence = req.post('https://fwp.now.com/wrapperWV', headers=lic_headers, data=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)
    location = response.url.split('?')[0]
    soup = BeautifulSoup(response.content, features="xml")
    init = soup.find('SegmentTemplate')['initialization']
    bandwidth = soup.find('Representation')['bandwidth']
    rep_id = soup.find('Representation')['id']
    loc_parts = location.split('/')
    loc_parts.pop()
    init_url = '/'.join(loc_parts) + '/' + init.replace('$Bandwidth$', bandwidth).replace('$RepresentationID$', rep_id)
    psshs = init_to_pssh(init_url)
    return psshs[0] if psshs else None

def get_channels(cookies):
    headers = {'User-Agent': user_agent}
    response = req.get('https://nowplayer.now.com/channels', cookies=cookies, headers=headers)
    soup = BeautifulSoup(response.content, features='lxml')
    channels = soup.findAll("a", {"class": "thumbnail"})
    result = []
    for c in channels:
        result.append({'title': c.get('alt', ''), 'id': c.get('href', '').split('/')[3] if '/' in c.get('href', '') else ''})
    return result

def get_single(cookies, channel_id):
    headers = {'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Origin': 'https://nowplayer.now.com', 'Referer': 'https://nowplayer.now.com/liveplayer/332', 'User-Agent': user_agent, 'X-Requested-With': 'XMLHttpRequest'}
    data = {'channelNo': channel_id}
    response = req.post('https://nowplayer.now.com/liveplayer/play/', cookies=cookies, headers=headers, data=data)
    resp_data = response.json()
    return resp_data.get('asset', [None])[0], resp_data.get('drmToken', '')

def login():
    print("Please set NOWSESSIONID in token file manually", file=sys.stderr)
    auth_data = {'NOWSESSIONID': token_param if token_param else ''}
    json.dump(auth_data, open(os.path.abspath(os.path.dirname(__file__)) + authFile, 'w'))
    print("Token file created - add your NOWSESSIONID", file=sys.stderr)

def get_auth():
    auth = json.load(open(os.path.abspath(os.path.dirname(__file__)) + authFile))
    return {'NOWSESSIONID': auth['NOWSESSIONID']}

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

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