<?php

use XcVm\Core\Config\ConfigReader;
use XcVm\Core\Util\Encryption;

/**
 * HLS encryption key endpoint
 *
 * @package XC_VM_Web_Stream
 * @author  Divarion_D <https://github.com/Divarion-D>
 * @copyright 2025-2026 Vateron Media
 * @link    https://github.com/Vateron-Media/XC_VM
 * @license AGPL-3.0 https://www.gnu.org/licenses/agpl-3.0.html
 */

header('Access-Control-Allow-Origin: *');
$rSettings = igbinary_unserialize(file_get_contents(CACHE_TMP_PATH . 'settings'));
$rServers = igbinary_unserialize(file_get_contents(CACHE_TMP_PATH . 'servers'));
if (!defined('SERVER_ID')) define('SERVER_ID', intval(ConfigReader::get('server_id')));

if (empty($rSettings['live_streaming_pass'])) {
	generate404();
}

if (isset($_GET['token'])) {
	$rIP = getuserip();
	$rTokenArray = explode('/', Encryption::decrypt($_GET['token'], $rSettings['live_streaming_pass'], OPENSSL_EXTRA));
	$rIPMatch = ($rSettings['ip_subnet_match'] ? implode('.', array_slice(explode('.', $rTokenArray[0]), 0, -1)) == implode('.', array_slice(explode('.', $rIP), 0, -1)) : $rTokenArray[0] == $rIP);

	if (is_array($rTokenArray) && ($rIPMatch || !$rSettings['restrict_same_ip'])) {
		header('Content-Type: application/octet-stream');
		header('X-Content-Type-Options: nosniff');
		echo file_get_contents(STREAMS_PATH . intval($rTokenArray[1]) . '_.key');
		exit();
	}
}

generate404();
function getuserip() {
	return $_SERVER['REMOTE_ADDR'];
}
