#!/usr/bin/python3
import sys
import os
import base64
import json
import datetime
import pytz
import hmac
import hashlib
from datetime import timezone
from urllib.parse import urlparse

# 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 = '/TVPlusTR_auth.json'
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/131.0.0.0 Safari/537.36'

access_token = ''
subscriber_id = ''
session_id = ''
vuid = ''
device_id = ''

def get_auth():
    try:
        return json.load(open(SCRIPT_DIR + authFile))
    except:
        return None

def save_auth(auth_data):
    json.dump(auth_data, open(SCRIPT_DIR + authFile, 'w'), indent=2)

def b(e, n, r, i):
    i = i[:i.rfind("/")] if "/" in i else i
    a = datetime.datetime(1970, 1, 1, tzinfo=timezone.utc)
    u = str(int((datetime.datetime.now(timezone.utc) - a).total_seconds()))
    c = str(e)
    d = base64.b64encode(u.encode()).decode()
    f = base64.b64encode(c.encode()).decode()
    m = "webtv"
    g = i + d + f + r + m
    v = w(n, g)
    y = v.replace("+", "-").replace("/", "_").rstrip("=")
    return y, d, f

def w(e, n):
    key = e.encode()
    message = n.encode()
    dig = hmac.new(key, message, hashlib.sha256)
    return base64.b64encode(dig.digest()).decode()

def get_access_token(username, refresh_token, dev_id):
    headers = {'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'Origin': 'https://tvplus.com.tr', 'Referer': 'https://tvplus.com.tr/', 'User-Agent': USER_AGENT}
    json_data = {'device': {'device_id': dev_id, 'device_type': 'OTT', 'category': 'PC', 'brand': 'Chrome', 'os_type': 'Windows', 'app_version': '5.2.9'}, 'device_id': dev_id, 'refresh_token': refresh_token, 'uri': 'https://tvplus.com.tr/hizli-giris', 'username': username, 'api_version': 'v1.11.0'}
    response = req.post('https://mwottapi.tvplus.com.tr/api/auth/token', headers=headers, json=json_data)
    data = response.json()
    return data['data']['access_token'], data['data']['crm_subscriber_id']

def authenticate(username, acc_token, dev_id):
    headers = {'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'Origin': 'https://tvplus.com.tr', 'Referer': 'https://tvplus.com.tr/', 'User-Agent': USER_AGENT}
    json_data = {'authenticator': acc_token, 'terminaltype': 'webtv', 'terminalvendor': 'chrome/131.0.0.0', 'osversion': 'Win32', 'userType': 1, 'mac': dev_id, 'terminalid': dev_id, 'utcEnable': '1', 'timezone': 'Europe/Istanbul', 'userid': username, 'authType': 0}
    response = req.post('https://syhottvsc03.tvplus.com.tr:33207/EPG/JSON/Authenticate', headers=headers, json=json_data)
    response.raise_for_status()
    data = response.json()
    return response.cookies.get_dict()['JSESSIONID'], data['caDeviceInfo'][0]['VUID'], dev_id

def login():
    global access_token, subscriber_id, session_id, vuid, device_id
    print("logging in...", file=sys.stderr)
    
    auth = get_auth()
    if not auth or 'username' not in auth:
        print("No auth found. Please add TVPlusTR username, refresh_token, device_id to auth file.", file=sys.stderr)
        save_auth({'username': '', 'refresh_token': '', 'device_id': ''})
        sys.exit(1)
    
    try:
        acc_token, sub_id = get_access_token(auth['username'], auth['refresh_token'], auth['device_id'])
        sess_id, vu, dev_id = authenticate(auth['username'], acc_token, auth['device_id'])
        access_token = acc_token
        subscriber_id = sub_id
        session_id = sess_id
        vuid = vu
        device_id = dev_id
        print("logged in successfully", file=sys.stderr)
        return access_token
    except Exception as e:
        print(f"Login failed: {e}", file=sys.stderr)
        sys.exit(1)

def get_session():
    global access_token
    if access_token:
        return access_token
    return login()

def get_ip():
    headers = {'Accept': 'application/json, text/plain, */*', 'Origin': 'https://tvplus.com.tr', 'Referer': 'https://tvplus.com.tr/', 'User-Agent': USER_AGENT, 'X-Auth-Token': access_token}
    response = req.get('https://mwottapi.tvplus.com.tr/api/client-config/ip-address', headers=headers)
    try:
        return response.json()['data']['ipAddress']
    except:
        return None

def get_url(playurl):
    duration = 43200
    private_key = 'M45ln389KcC23u7bd711hHR3hTp6Fr69'
    ip = get_ip()
    parsed_url = urlparse(playurl)
    path = parsed_url.path
    if not duration or not private_key or not ip or not path:
        return None
    st, ts, e = b(duration, private_key, ip, path)
    headers = {'Accept': '*/*', 'Origin': 'https://tvplus.com.tr', 'Referer': 'https://tvplus.com.tr/', 'User-Agent': USER_AGENT}
    params = {'proxy_url': playurl + f'&st={st}&ts={ts}&e={e}' + f'&app_version=chrome,WebTV,OSVersion=Win32,AppVersion=5.2.10,webtv&custom_sid={base64.b64encode(subscriber_id.encode()).decode()}'}
    try:
        response = req.get('https://switch-api.tvplus.com.tr/pl/', params=params, headers=headers)
        response.raise_for_status()
        return response.url
    except:
        return None

def get_lic_token():
    headers = {'Accept': 'application/json, text/plain, */*', 'Origin': 'https://tvplus.com.tr', 'Referer': 'https://tvplus.com.tr/', 'User-Agent': USER_AGENT, 'X-AUTH-TOKEN': access_token}
    response = req.get(f'https://mwottapi.tvplus.com.tr/api/client-config/veri-matrix/{vuid}', headers=headers)
    try:
        return response.json()['data']['token']
    except:
        return None

def get_pssh_from_mpd(url):
    headers = {'User-Agent': USER_AGENT, 'Origin': 'https://switch-api.tvplus.com.tr', 'Referer': 'https://switch-api.tvplus.com.tr/'}
    response = req.get(url, headers=headers)
    content_protections = BeautifulSoup(response.content, features="xml").findAll('ContentProtection')
    for cp in content_protections:
        if cp.get('schemeIdUri', '').lower() == 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed':
            pssh_elem = cp.find('cenc:pssh')
            if pssh_elem:
                return pssh_elem.text
    return None

def do_cdm_internal(challenge_b64, lic_token):
    headers = {'Accept': '*/*', 'Origin': 'https://tvplus.com.tr', 'Referer': 'https://tvplus.com.tr/', 'User-Agent': USER_AGENT, 'authorization': lic_token, 'Content-Type': 'application/x-www-form-urlencoded'}
    params = {'deviceId': vuid}
    response = req.post('https://widevine.tvplus.com.tr/multidrm/widevine', headers=headers, params=params, 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, lic_token):
    try:
        pssh_obj = PSSH(pssh_b64)
        device_obj = Device.load(WVD_PATH)
        cdm_obj = Cdm.from_device(device_obj)
        session_id_cdm = cdm_obj.open()
        challenge_data = cdm_obj.get_license_challenge(session_id_cdm, pssh_obj)
        headers = {'Accept': '*/*', 'Origin': 'https://tvplus.com.tr', 'Referer': 'https://tvplus.com.tr/', 'User-Agent': USER_AGENT, 'authorization': lic_token, 'Content-Type': 'application/x-www-form-urlencoded'}
        params = {'deviceId': vuid}
        licence = req.post('https://widevine.tvplus.com.tr/multidrm/widevine', headers=headers, params=params, data=challenge_data)
        cdm_obj.parse_license(session_id_cdm, licence.content)
        keys = [f"{key.kid.hex}:{key.key.hex()}" for key in cdm_obj.get_keys(session_id_cdm) if key.type != 'SIGNING']
        cdm_obj.close(session_id_cdm)
        return keys
    except Exception as e:
        print(f'CDM external failed: {e}', file=sys.stderr)
        return None

def do_action():
    get_session()
    
    if action == "login":
        login()
        sys.exit()
    
    if action == "channels":
        output = {'Channels': []}
        cookies = {'XSESSIONID': session_id, 'JSESSIONID': session_id}
        headers = {'Accept': 'application/json, text/plain, */*', 'Origin': 'https://tvplus.com.tr', 'Referer': 'https://tvplus.com.tr/', 'User-Agent': USER_AGENT}
        response = req.post('https://syhottvsc03.tvplus.com.tr:33207/EPG/JSON/ChannelList', cookies=cookies, headers=headers, json={})
        try:
            data = response.json()
            for ch in data.get('channellist', []):
                channel = {
                    'Name': ch.get('name', 'Unknown'),
                    'Mode': 'live',
                    'SessionManifest': True,
                    'ManifestScript': f"playurl={ch.get('playurl', '')}",
                    'CdmType': 'widevine',
                    'UseCdm': True,
                    'Cdm': f"playurl={ch.get('playurl', '')}",
                    '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:
            playurl = id.replace('playurl=', '')
            playurls = playurl.split('|')
            video_url = None
            for p in playurls:
                video_url = get_url(p)
                if video_url:
                    break
            if not video_url:
                return "error"
            output = {
                "Cdn": [{"Name": "default", "ManifestUrl": video_url}],
                "ManifestUrl": video_url,
                "Headers": {"Manifest": {'User-Agent': USER_AGENT, 'Origin': 'https://switch-api.tvplus.com.tr', 'Referer': 'https://switch-api.tvplus.com.tr/'}, "Media": {'User-Agent': USER_AGENT, 'Origin': 'https://switch-api.tvplus.com.tr', 'Referer': 'https://switch-api.tvplus.com.tr/'}},
                "Heartbeat": {"Url": '', "Params": '', "PeriodMs": 5*60*1000}
            }
            print(json.dumps(output))
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "cdm" and cdm == "internal":
        try:
            playurl = id.replace('playurl=', '')
            playurls = playurl.split('|')
            video_url = None
            for p in playurls:
                video_url = get_url(p)
                if video_url:
                    break
            if video_url:
                lic_token = get_lic_token()
                if lic_token:
                    result = do_cdm_internal(challenge, lic_token)
                    if result:
                        print(result)
                    else:
                        return "error"
                else:
                    return "error"
            else:
                return "error"
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return "error"
    
    elif action == "cdm" and cdm == "external":
        try:
            playurl = id.replace('playurl=', '')
            playurls = playurl.split('|')
            video_url = None
            for p in playurls:
                video_url = get_url(p)
                if video_url:
                    break
            if video_url:
                lic_token = get_lic_token()
                if lic_token:
                    pssh_to_use = pssh if pssh else get_pssh_from_mpd(video_url)
                    if pssh_to_use:
                        keys = do_cdm_external(pssh_to_use, lic_token)
                        if keys:
                            for key in keys:
                                print(key)
                        else:
                            return "error"
                    else:
                        return "error"
                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()
