<?php
/**
 * Project:        M.VuiZ.Net
 * Author:         nampt.me <admin@vuiz.net>
 * Copyright:      © 2025 vuiz.net All rights reserved.
 */
error_reporting(0);

$msg = [];

try {
	$url = isset($_POST['link']) ? htmlspecialchars(rawurldecode($_POST['link'])) : '';

	if (empty($url)) {
		throw new Exception('Link video phải ở dạng https://www.facebook.com/<strong>[user_name]</strong>/videos/<strong>[id_video]</strong>/ !', 1);
	}


	$data = auto($url);

	$download = ''; $stream = '';
	if ($sdLink = getSDLink($data)) {
		$download .= ' <a rel="noreferrer noopener" target="_blank" href="'.$sdLink.'"><button type="button" class="btn btn-success"><i class="fa fa-cloud-download"></i> Download Low Quality</button></a> ';
		$stream = $sdLink;
	}
	if ($hdLink = getHDLink($data)) {
		$download .= ' <a rel="noreferrer noopener" target="_blank" href="'.$hdLink.'"><button type="button" class="btn btn-success"><i class="fa fa-cloud-download"></i> Download High Quality</button></a> ';
		$stream = $hdLink;
	}

	$title = str_replace(PHP_EOL, '', getTitle($data));
	$thumb = getThumbnail($data);

	if(!empty($title) && !empty($stream) && !empty($download))
	{
		$msg['success'] = '
		<div class="menu">
			<div style="padding-bottom:15px;font-size: 16px;text-align:center;" ><b>'.$title.'</b></div>
			<div class="embed-responsive embed-responsive-16by9" style="text-align:center;"><div class="embed-responsive-item" id="player"></div></div>
			<script defer>
				$("head").append(\'<meta name="referrer" content="no-referrer" />\');
				var playerInstance = jwplayer("player");
				jwDefaults.key = "9dOyFG96QFb9AWbR+FhhislXHfV1gIhrkaxLYfLydfiYyC0s";
				playerInstance.setup({
					id: "player",
					title: "'.$title.'",
					controls: true,
					playbackRateControls: true,
					abouttext: "VuiZ.Net",
					aboutlink: "https://m.vuiz.net/",
					logo: {
					    file: "https://m.vuiz.net/template/images/logovideoplayer.png",
					    logoBar: "https://m.vuiz.net/template/images/logovideoplayer.png",
					    link: "https://m.vuiz.net/",
					    position: "control-bar"
					},
					file: "'.$stream.'", //A link to the HLS manifest
					image: "'.$thumb.'", // Poster image that will show up before the stream begins
				});
			</script>
			<div style="padding-top:15px; text-align: center;">
				'.$download.'
			</div>
		</div>';
	} else {
		throw new Exception('Không lấy được link, vui lòng thử lại sau !', 1);
	}
} catch (Exception $e) {
	$msg['error'] = $e->getMessage();
}

echo json_encode($msg, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);


function cleanStr($str)
{
	return html_entity_decode(strip_tags($str), ENT_QUOTES, 'UTF-8');
}

function getSDLink($curl_content)
{
	$regex = '/sd_src_no_ratelimit:"([^"]+)"/';
	$playable_url = get_string_between($curl_content, '"playable_url":"', '"');
	if (preg_match($regex, $curl_content, $match)) {
	    return $match[1];
	} else if (preg_match('/sd_src:"([^"]+)"/', $curl_content, $match)) {
	    return $match[1];
	} else if (!empty($playable_url)) {
	    return str_replace("\/", "/", $playable_url);
	}

	return false;
}

function getHDLink($curl_content)
{
	$regex = '/hd_src_no_ratelimit:"([^"]+)"/';
	$playable_url = get_string_between($curl_content, '"playable_url_quality_hd":"', '"');
	if (preg_match($regex, $curl_content, $match)) {
	    return $match[1];
	} else if (preg_match('/hd_src:"([^"]+)"/', $curl_content, $match)) {
	    return $match[1];
	} else if (!empty($playable_url)) {
	    return str_replace("\/", "/", $playable_url);
	}
	return false;
}

function getTitle($curl_content)
{
	$og_title = get_string_between($curl_content, 'property="og:title" content="', '"');
	$page_title = get_string_between($curl_content, '<title id="pageTitle">', '</title>');
	$json_title = get_string_between($curl_content, '"is_show_video":false,"name":"', '"');
	if (!empty($og_title)) {
	    return cleanStr($og_title);
	} else if (!empty($page_title)) {
	    return cleanStr($page_title);
	} else if (!empty($json_title)) {
	    return cleanStr($json_title);
	} else {
	    return "Facebook Video";
	}
}

function getThumbnail($curl_content)
{
	$json_thumbnail = get_string_between($curl_content, '"thumbnailImage":{"uri":"', '"');
	if (preg_match('/og:image"\s*content="([^"]+)"/', $curl_content, $match)) {
	    return cleanStr($match[1]);
	} else if (preg_match('@<meta property="twitter:image" content="(.*?)" />@si', $curl_content, $match)) {
	    return cleanStr($match[1]);
	} else if (!empty($json_thumbnail)) {
	    return str_replace("\/", "/", urldecode($json_thumbnail));
	} else {
	    return "https://www.facebook.com/images/fb_icon_325x325.png";
	}
}

function get_string_between($string, $start, $end)
{
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

function auto($dkm) {
	$ch = @curl_init();
	curl_setopt($ch, CURLOPT_URL, $dkm);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36');
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
	    "authority: www.facebook.com",
	    "cache-control: max-age=0",
	    "upgrade-insecure-requests: 1",
	    "accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
	    "sec-fetch-site: none",
	    "sec-fetch-mode: navigate",
	    "sec-fetch-user: ?1",
	    "sec-fetch-dest: document"
	));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_TIMEOUT, 60);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
	
	$nd = curl_exec($ch);
	curl_close($ch);
	return $nd;
}