import subprocess
import requests
import binascii
import base64
import re
from pywidevine.cdm import Cdm
from pywidevine.device import Device
from pywidevine.pssh import PSSH

MyWVD = "2.wvd"  # File WVD

def get_pssh_from_mpd(mpd_data):
    pssh_list = []
    psshs = re.findall(">([\S]+)</cenc:pssh", mpd_data)
    if psshs:
        for pssh in psshs:
            pesx = binascii.hexlify(base64.b64decode(pssh)).decode('utf-8')
            if "edef8ba9" in pesx:
                if pssh not in pssh_list:
                    pssh_list.append(pssh)
    
    if pssh_list:
        return pssh_list[0]
    else:
        return ''

def getKeys(url, urlLicence, token):
    # Scarica il file MPD
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
    }
    response = requests.get(url, headers=headers)
    if response.status_code != 200:
        print(f"Errore nel download del file MPD: {response.status_code}")
        return 'key:nofound'

    # Estrai il PSSH dal file MPD
    pssh = get_pssh_from_mpd(response.text)
    if not pssh:
        print("PSSH non trovato nel file MPD")
        return 'key:nofound'

    # Genera la licensing challenge
    pssh_stream = PSSH(pssh)
    device = Device.load(MyWVD)
    cdm = Cdm.from_device(device)
    session_id = cdm.open()
    challenge = cdm.get_license_challenge(session_id, pssh_stream)

    # Salva la challenge in un file temporaneo
    with open("challenge.bin", "wb") as f:
        f.write(challenge)
    
    # Esegui lo script PHP per gestire la licenza
    php_command = ["php", "license_handler.php", token, "challenge.bin", urlLicence]
    try:
        response = subprocess.check_output(php_command)
        license_data = response

        # Analizza la licenza con Widevine CDM
        cdm.parse_license(session_id, license_data)
        fkeys = ""
        for key in cdm.get_keys(session_id):
            if key.type != 'SIGNING':
                fkeys += key.kid.hex + ":" + key.key.hex()
        
        cdm.close(session_id)
        return fkeys
    except subprocess.CalledProcessError as e:
        print(f"Errore nell'esecuzione dello script PHP: {e}")
        cdm.close(session_id)
        return 'key:nofound'