<?php
$id = $_GET['id'];
$eventId = $_GET['eventId'];
$mediaId = $_GET['mediaId'];
$time = $_GET['time'];
$token=file_get_contents('tk'); 
$endpoint = 'https://star.playback.edge.bamgrid.com/events/'.$eventId.'/media/'.$mediaId.'/scenarios/restricted-drm-ctr-sw';
$headers = [
    'Host: star.playback.edge.bamgrid.com',
    'Accept: application/vnd.media-service+json; version=5',
    'Authorization: '.$token,
    'Accept: vnd.dss.edge+json; version=1',
    'User-Agent: BAMSDK/v8.1.3 (star-22bcaf0a 2.13.0-rc3.0; v4.0/v8.1.0; android; phone) Xiaomi Mi 9T (RKQ1.200826.002 test-keys; Linux; 11; API 30)',
    'Content-Type: application/json',
];

$data = '{"playback":{"attributes":{"resolution":{"max":["1080x720"]},"assetInsertionStrategy":"NONE","playbackInitializationContext":"online"},"tracking":{"playbackSessionId":""},"adTracking":{"limitAdTrackingEnabled":"NO","deviceAdId":"a9be6699-f599-40ba-9772-1d86101588a2"}}}';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$response = curl_exec($ch);

if ($response === false) {
    echo "Falha na solicitação: " . curl_error($ch);
} else {
$url2=json_decode($response,true);
}
//$url=($url2['stream']['complete'][0]['url']);
$url=($url2['stream']['slide'][0]['url']);
curl_close($ch);

	$token=file_get_contents('tk');
function extractFirstPsshFromM3u8($m3u8Content) {
    $pattern = '/#EXT-X-KEY:METHOD=SAMPLE-AES-CTR,KEYFORMAT="[^"]+",KEYFORMATVERSIONS="[^"]+",URI="data:text\/plain;base64,([^"]+)"/';

    if (preg_match($pattern, $m3u8Content, $matches)) {
        $pssh = str_replace('data:text/plain;base64,', '', $matches[1]);
        return $pssh;
    }

    return null;
}

$novaUrl = str_replace("ctr-minimum-sliding.m3u8", "cmaf-cenc-ctr-1200K/1200_slide.m3u8", $url);
$novaUrl2 = str_replace("ctr-minimum-sliding.m3u8", "ctr-all-complete.m3u8", $url);
//
//$linkM3u8 = $novaUrl;
//print_r('{"url":"'.$novaUrl2.'",');
print_r('{"url":"'.$url.'",');
$linkM3u8 = $novaUrl;

$context = stream_context_create([
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ],
    'http' => [
        'header' => 'User-Agent: BAMSDK/v8.1.3 (star-22bcaf0a 2.13.0-rc3.0; v4.0/v8.1.0; android; phone) Xiaomi Mi 9T (RKQ1.200826.002 test-keys; Linux; 11; API 30)'
    ]
]);

// Tente baixar o arquivo M3U8
$m3u8Content = @file_get_contents($linkM3u8, false, $context);

if ($m3u8Content === false) {
    echo "Falha ao baixar o arquivo M3U8.";
} else {
    $pssh = extractFirstPsshFromM3u8($m3u8Content);

    if ($pssh !== null) {
        echo '"Pssh": ' . '"'.$pssh.'",';
    } else {
        echo "Nenhum PSSH encontrado.";
    }
}


$headers = "accept: \"*/*\"\ncontent-length: \"316\"\nConnection: keep-alive\nAuthorization: Bearer " . $token;

$proxy = "";
$cache = true;
$build= "google/sdk_gphone_x86/generic_x86:8.0.0/OSR1.180418.026/6741039:userdebug/dev-keysx";

$data = array(
    "license" => "https://star.playback.edge.bamgrid.com/widevine/v1/channel/obtain-license",
    "headers" => $headers,
    "pssh" => $pssh,
    "proxy" => $proxy,
    "cache" => $cache,
    "buildInfo" => "google/sdk_gphone_x86/generic_x86:8.0.0/OSR1.180418.026/6741039:userdebug/dev-keys"
);
$jsonPayload = json_encode($data);
$jsonPayload2 = json_encode($data2);
$ch = curl_init();

$headers = array(
    'Host: 000.000.000.00',
    'Connection: keep-alive',
    'Content-Length: ' . strlen($jsonPayload),
    'sec-ch-ua: "Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
    'Accept: application/json, text/plain, */*',
    'Content-Type: application/json');

curl_setopt($ch, CURLOPT_URL, 'http://000.000.000.00/api');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Se você quiser ignorar a verificação SSL, descomente as linhas abaixo
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$response = curl_exec($ch);
if ($response === false) {
    echo 'Error reading the response.';
} else {
	echo '"Key":';
	$string=json_decode($response, true)['keys'][0]['key'];
	$parts = preg_split('/:/', $string);
    print_r ('"'.$parts[1].'",');
    echo '"KeyId":';
    print_r ('"'.$parts[0].'"}');
}
curl_close($ch);
