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

def get_channels(cookies):
    headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'referer': 'https://televio.hr/epg', 'user-agent': user_agent}
    response = req.get('https://televio.hr/home', headers=headers, cookies={**cookies, 'streamQuality': '60'})
    soup = BeautifulSoup(response.content, features="lxml")
    data = json.loads(soup.find('script', {'id': 'player.playlist'}).text)
    return [v for k, v in data.items()]

def do_login_request(username, pwd):
    headers = {'authority': 'televio.hr', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'user-agent': user_agent}
    response = req.get('https://televio.hr/welcome/login', headers=headers)
    cookies = response.cookies.get_dict()
    headers = {'Host': 'televio.hr', 'User-Agent': user_agent, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'en-GB,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Content-Type': 'application/x-www-form-urlencoded', 'Origin': 'https://televio.hr', 'Referer': 'https://televio.hr/welcome/login'}
    data = {'username': username, 'password': pwd, 'login': 'Prijavi se', '_do': 'userLoginControl-signInForm-submit'}
    response = req.post('https://televio.hr/welcome/login', headers=headers, data=data, allow_redirects=False, cookies=cookies)
    loc = response.headers.get('Location', '')
    cookies.update(response.cookies.get_dict())
    headers = {'Host': 'televio.hr', 'User-Agent': user_agent, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'en-GB,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Referer': 'https://televio.hr/welcome/login'}
    response = req.get(loc, headers=headers, cookies=cookies, allow_redirects=False)
    loc = response.headers.get('Location', '').split('?')[0]
    response = req.get(loc, headers=headers, cookies=cookies, allow_redirects=False)
    profile_id = response.headers.get('x-ott-userid', '')
    response = req.get(f'https://televio.hr/profile?profileId={profile_id}&do=switchProfile', headers=headers, allow_redirects=False, cookies=cookies)
    cookies.update(response.cookies.get_dict())
    return cookies

def login():
    print("logging in...", file=sys.stderr)
    cookies = do_login_request(user, password)
    auth_data = {'cookies': cookies}
    json.dump(auth_data, open(os.path.abspath(os.path.dirname(__file__)) + authFile, 'w'))
    print("logged in successfully", file=sys.stderr)

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

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['name'], 'Mode': "live", 'SessionManifest': True, 'ManifestScript': 'url=' + c['url'], 'CdmType': "clear", 'UseCdm': False, 'Video': 'best'})
        print(json.dumps(output, indent=2))
    elif action == "events":
        output = {'Events': []}
        for c in get_channels(cookies):
            output['Events'].append({'Name': c['name'], 'Mode': "live", 'SessionManifest': True, 'ManifestScript': 'url=' + c['url'], 'CdmType': "clear", 'UseCdm': False, '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":
        url = id.replace('url=', '') if id.startswith('url=') else id
        output = {"Cdn": [], "ManifestUrl": url, "Headers": {"Manifest": {'User-Agent': user_agent}, "Media": {'User-Agent': user_agent}}}
        print(json.dumps(output))

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