import requests
import json
import subprocess
import os
import time
import re
from termcolor import colored
from datetime import datetime, timedelta

# Function to sanitize filename
def sanitize_filename(title):
    # Remove any characters that are invalid in filenames
    return re.sub(r'[\/:*?"<>|]', '', title).strip()

# Load login credentials
with open('credentials.txt') as f:
    credentials = json.load(f)
email = credentials['email']
password = credentials['password']

# API endpoints
login_url = "https://www.withny.fun/api/auth/login"
stream_url_template = "https://www.withny.fun/api/streams/{}/playback-url"

# Headers and token storage
headers = {
    "Content-Type": "application/json"
}
token = None
processes = [None] * 100

# Login and get bearer token
def login():
    global token
    data = {
        "email": email,
        "password": password
    }
    response = requests.post(login_url, headers=headers, json=data)
    if response.status_code == 200:
        token = response.json().get('token')
        print("Login successful. Token obtained.")
    else:
        print(colored(f"Login failed with status code {response.status_code}","light_red"))
        response.raise_for_status()

# Check URL for UUID and process
def process_url(url, index):
    global processes
    headers_with_token = headers.copy()
    headers_with_token['Authorization'] = f'Bearer {token}'
    urlproper="https://www.withny.fun/api/streams?username=" + url
    try:
        response = requests.get(urlproper, headers=headers_with_token)
        response.raise_for_status()
        content = response.json()
        time.sleep(1)
        uuid = None
        title = None
        username = None
        for item in content:
            if 'uuid' in item:
                uuid = item['uuid']
            if 'title' in item:
                title = item['title']
            if uuid and title:
                break
        
        if uuid:
            playback_url = stream_url_template.format(uuid)
            response = requests.get(playback_url, headers=headers_with_token)
            response.raise_for_status()
            m3u8_url = response.text.strip()
            m3u8_url = m3u8_url.replace('"', '')

            if m3u8_url:
#                print(f"Found m3u8 URL: {m3u8_url}")
                timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
                if title:
                    sanitized_username = sanitize_filename(url)
                    sanitized_title = sanitize_filename(title)
                    output_file = f"{timestamp} {url} {sanitized_title}.mkv"
                else:
                    output_file = f"{timestamp} {url}.mkv"
                
                # Prepare the yt-dlp command
                command = [
                    'yt-dlp', m3u8_url,
                    '--add-header', 'Referer:https://www.withny.fun/',
                    '--add-header', 'Origin:https://www.withny.fun/',
                    '-o', output_file
                ]

                # Print the command for debugging
#                print(f"Running command: {' '.join(command)}")

                # Run the command in the background
                process = subprocess.Popen(command, shell=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                processes[index] = process
                print(colored(f"{url} is live, saving as {output_file}","light_green"))
            else:
                print(colored("No m3u8 URL found...","light_red"))
        else:
            print(colored(f"{url} does not appear to be live.","light_yellow"))
    except requests.RequestException as e:
        print(colored(f"Request failed: {e}","light_red"))

# Main loop
def main():
    last_login_time = datetime.now()  # Track the last login time
    login()

    while True:
        # Check if 12 hours have passed since the last login
        if datetime.now() - last_login_time >= timedelta(hours=12):
            login()
            last_login_time = datetime.now()  # Update the last login time
        
        # Load channels from files
        with open('channels.txt') as f:
            urls = [line.strip() for line in f]
        for i, url in enumerate(urls):
            # Check if the recording process is still running
            if processes[i] is not None and processes[i].poll() is None:
                print(colored(f"Already recording {url}, skipping...","light_cyan"))
                continue

            # Process the URL
            process_url(url, i)

        print(colored("Taking a breather...","light_magenta"))
        time.sleep(10)

if __name__ == "__main__":
    main()
