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

# 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 = '/SweetTV_refresh.txt'
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'

headers = {
    'accept': 'application/json, text/plain, */*',
    'content-type': 'application/json',
    'origin': 'https://sweet.tv',
    'referer': 'https://sweet.tv/',
    'user-agent': USER_AGENT,
}

token = ''

def get_auth():
    try:
        with open(SCRIPT_DIR + authFile, 'r') as f:
            return f.read().strip()
    except:
        return None

def save_auth(refresh_token):
    with open(SCRIPT_DIR + authFile, 'w') as f:
        f.write(refresh_token)

def do_refresh(refresh_token):
    json_data = {
        'device': {
            'type': 'DT_Web_Browser',
            'sub_type': 'DST_WINDOWS',
            'application': {'type': 'AT_SWEET_TV_Player'},
            'model': USER_AGENT,
            'firmware': {'versionCode': 1, 'versionString': '6.3.38'},
            'supported_drm': {'widevine_modular': True},
            'screen_info': {'aspectRatio': 6, 'width': 2560, 'height': 1440},
        },
        'refresh_token': refresh_token,
    }
    response = req.post('https://api.sweet.tv/AuthenticationService/Token.json', headers=headers, json=json_data)
    return response.json()['access_token']

def login():
    global token
    print("logging in...", file=sys.stderr)
    
    refresh_token = get_auth()
    if not refresh_token:
        print("No refresh token found. Please add SweetTV refresh token to auth file.", file=sys.stderr)
        save_auth('')
        sys.exit(1)
    
    try:
        token = do_refresh(refresh_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 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 get_pssh_from_mpd(url):
    response = req.get(url, headers={'User-Agent': USER_AGENT})
    try:
        soup = BeautifulSoup(response.content, features="xml")
        init = soup.find('SegmentTemplate')['initialization']
        bandwidth = soup.find('Representation')['bandwidth']
        rep_id = soup.find('Representation')['id']
        base_url = soup.find('BaseURL').text
        init_url = base_url + init.replace('$Bandwidth$', bandwidth).replace('$RepresentationID$', rep_id)
        init_response = req.get(init_url, headers={'User-Agent': USER_AGENT})
        return to_pssh(init_response.content)[-1]
    except:
        return None

def get_single(channel_id):
    single_headers = {
        'accept': 'application/json, text/plain, */*',
        'authorization': 'Bearer ' + token,
        'content-type': 'application/json',
        'origin': 'https://sweet.tv',
        'referer': 'https://sweet.tv/',
        'user-agent': USER_AGENT,
    }
    json_data = {'channel_id': channel_id, 'multistream': True}
    response = req.post('https://api.sweet.tv/TvService/OpenStream.json', headers=single_headers, json=json_data)
    try:
        data = response.json()
        if 'drm_type' not in data or data['drm_type'] == 'DRM_NONE':
            return data.get('chrome_cast_url'), False
        elif data['drm_type'] == 'DRM_WIDEVINE':
            return data['url'], True
        return None, False
    except:
        return None, False

def do_cdm_internal(challenge_b64):
    lic_headers = {
        'accept': '*/*',
        'origin': 'https://sweet.tv',
        'referer': 'https://sweet.tv/',
        'user-agent': USER_AGENT,
        'content-type': 'application/octet-stream',
    }
    response = req.post('https://drm.sweet.tv/proxy.php', headers=lic_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):
    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)
        lic_headers = {
            'accept': '*/*',
            'origin': 'https://sweet.tv',
            'referer': 'https://sweet.tv/',
            'user-agent': USER_AGENT,
            'content-type': 'application/octet-stream',
        }
        licence = req.post('https://drm.sweet.tv/proxy.php', headers=lic_headers, data=challenge_data)
        cdm_obj.parse_license(session_id, licence.content)
        keys = []
        for key in cdm_obj.get_keys(session_id):
            if key.type != 'SIGNING':
                keys.append(f"{key.kid.hex}:{key.key.hex()}")
        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': []}
        ch_headers = {
            'accept': 'application/json, text/plain, */*',
            'authorization': 'Bearer ' + token,
            'content-type': 'application/json',
            'origin': 'https://sweet.tv',
            'referer': 'https://sweet.tv/',
            'user-agent': USER_AGENT,
        }
        json_data = {'epg_limit_prev': 3, 'epg_limit_next': 3, 'need_epg': True, 'need_list': True, 'need_categories': True, 'need_offsets': False, 'need_hash': False, 'need_icons': False, 'need_big_icons': False}
        response = req.post('https://api.sweet.tv/TvService/GetChannels.json', headers=ch_headers, json=json_data)
        try:
            data = response.json()
            for ch in data.get('list', []):
                channel = {
                    'Name': ch.get('name', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"id={ch.get('id', '')}",
                    'CdmType': 'widevine' if ch.get('drm') else 'none',
                    'UseCdm': ch.get('drm', False),
                    'Cdm': f"id={ch.get('id', '')}",
                    '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:
            channel_id = int(id)
            video_url, is_drm = get_single(channel_id)
            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},
                "IsDrm": is_drm
            }
            print(json.dumps(output))
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "cdm" and cdm == "internal":
        try:
            result = do_cdm_internal(challenge)
            if result:
                print(result)
            else:
                return "error"
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "cdm" and cdm == "external":
        try:
            channel_id = int(id)
            video_url, _ = get_single(channel_id)
            pssh_to_use = pssh if pssh else get_pssh_from_mpd(video_url)
            if pssh_to_use:
                keys = do_cdm_external(pssh_to_use)
                if keys:
                    for key in keys:
                        print(key)
                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()
