1
0
Fork 0
mirror of https://github.com/DanielnetoDotCom/YouPHPTube synced 2025-10-03 09:49:28 +02:00

Now the shorts AI can create portrait and square shorts

This commit is contained in:
Daniel Neto 2024-03-13 10:52:15 -03:00
parent df4b4436c1
commit 24539738ed
15 changed files with 333 additions and 185 deletions

View file

@ -128,16 +128,12 @@ class Page {
$rtl = 'rtl';
}
echo "<body class=\"{$global['bodyClass']} {$rtl} {$this->bodyClass}\">";
//echo '<div id="_avideoPageLoader">';
//$loaderParts = Layout::getLoaderDefault();
//echo $loaderParts['css'];
//echo $loaderParts['html'];
//echo '</div>';
//echo '<div style="display: none;" id="_avideoPageContent">';
$this->getNavBar();
//echo '<div id="_avideoPageContentLoading" class="progress"><div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"><span class="sr-only">Loading...</span></div></div>';
//echo '<div id="_avideoPageContent">';
echo $this->bodyContent;
$this->getFooter();
//echo '</div>';
$this->getFooter();
echo "</body>";
}

View file

@ -1,36 +1,69 @@
<?php
function cutVideoWithFFmpeg($inputFile, $startTimeInSeconds, $endTimeInSeconds, $outputFile)
function cutVideoWithFFmpeg($inputFile, $startTimeInSeconds, $endTimeInSeconds, $outputFile, $aspectRatio)
{
// Ensure start and end times are numeric
$startTimeInSeconds = (int)$startTimeInSeconds;
$endTimeInSeconds = (int)$endTimeInSeconds;
// Define aspect ratio dimensions
$aspectRatioDimensions = [
Video::ASPECT_RATIO_ORIGINAL,
Video::ASPECT_RATIO_SQUARE,
Video::ASPECT_RATIO_VERTICAL,
Video::ASPECT_RATIO_HORIZONTAL,
];
// Validate aspect ratio parameter
if (!in_array($aspectRatio, $aspectRatioDimensions)) {
_error_log('cutVideoWithFFmpeg: Invalid aspect ratio parameter');
return false;
}
make_path($outputFile);
// Use ffprobe to get video dimensions
$ffprobeCommand = get_ffprobe()." -v error -select_streams v:0 -show_entries stream=width,height -of csv=s=x:p=0 {$inputFile}";
$ffprobeCommand = removeUserAgentIfNotURL($ffprobeCommand);
_error_log("cutAndAdaptVideoWithFFmpeg start shell_exec($ffprobeCommand)");
$videoDimensions = shell_exec($ffprobeCommand);
_error_log("cutAndAdaptVideoWithFFmpeg response ($videoDimensions)");
list($width, $height) = explode('x', trim($videoDimensions));
$cropParams = calculateCenterCrop($width, $height, $aspectRatio);
// Calculate crop dimensions
$cropDimension = "{$cropParams['newWidth']}:{$cropParams['newHeight']}:{$cropParams['x']}:{$cropParams['y']}";
// Escape arguments to ensure command is safe to execute
$escapedInputFile = escapeshellarg($inputFile);
$escapedOutputFile = escapeshellarg($outputFile);
$escapedStartTime = escapeshellarg($startTimeInSeconds);
$escapedEndTime = escapeshellarg($endTimeInSeconds);
$escapedCropDimension = escapeshellarg($cropDimension);
// Construct the FFmpeg command
$cmd = get_ffmpeg() . " -ss {$escapedStartTime} -to {$escapedEndTime} -i {$escapedInputFile} -c copy {$escapedOutputFile}";
$cmd = get_ffmpeg() . " -ss {$escapedStartTime} -to {$escapedEndTime} -i {$escapedInputFile} -vf \"crop={$escapedCropDimension}\" -c:a copy {$escapedOutputFile}";
$cmd = removeUserAgentIfNotURL($cmd);
// Execute the command
_error_log('cutVideoWithFFmpeg start ' . $cmd);
_error_log('cutAndAdaptVideoWithFFmpeg start ' . $cmd);
exec($cmd, $output, $returnVar);
// Check if the command was executed successfully
if ($returnVar === 0) {
_error_log('cutVideoWithFFmpeg success ' . $outputFile);
_error_log('cutAndAdaptVideoWithFFmpeg success ' . $outputFile);
return true; // Command executed successfully
} else {
_error_log('cutVideoWithFFmpeg error ');
_error_log('cutAndAdaptVideoWithFFmpeg error ');
return false; // Command failed
}
}
function getDurationFromFile($file)
{
global $config, $getDurationFromFile;

View file

@ -7107,7 +7107,7 @@ function get_ffprobe() {
function removeUserAgentIfNotURL($cmd)
{
if (!preg_match('/ -i [\'"]?https?:/', $cmd)) {
if (!preg_match('/ -i [\'"]?https?:/i', $cmd) && !preg_match('/ffprobe.*[\'"]?https?:/i', $cmd)) {
$cmd = preg_replace('/-user_agent "[^"]+"/', '', $cmd);
}
return $cmd;
@ -10212,6 +10212,46 @@ function checkFileModified($filePath) {
}
}
function calculateCenterCrop($originalWidth, $originalHeight, $aspectRatio) {
// Define aspect ratio dimensions
$aspectRatioDimensions = [
Video::ASPECT_RATIO_SQUARE => ['width' => 1, 'height' => 1],
Video::ASPECT_RATIO_VERTICAL => ['width' => 9, 'height' => 16],
Video::ASPECT_RATIO_HORIZONTAL => ['width' => 16, 'height' => 9],
];
// Validate aspect ratio parameter
if (!array_key_exists($aspectRatio, $aspectRatioDimensions)) {
return false; // Invalid aspect ratio
}
// Get aspect ratio dimensions
$targetWidth = $aspectRatioDimensions[$aspectRatio]['width'];
$targetHeight = $aspectRatioDimensions[$aspectRatio]['height'];
// Calculate scaling factors for width and height
$scaleWidth = $originalHeight * $targetWidth / $targetHeight;
$scaleHeight = $originalWidth * $targetHeight / $targetWidth;
// Determine new width, height, x, and y for center cropping
if ($scaleWidth > $originalWidth) {
// Use scaled height
$newWidth = $originalWidth;
$newHeight = $scaleHeight;
$x = 0;
$y = ($originalHeight - $scaleHeight) / 2;
} else {
// Use scaled width
$newWidth = $scaleWidth;
$newHeight = $originalHeight;
$x = ($originalWidth - $scaleWidth) / 2;
$y = 0;
}
return ['newWidth' => $newWidth, 'newHeight' => $newHeight, 'x' => $x, 'y' => $y];
}
require_once __DIR__.'/functionSecurity.php';
require_once __DIR__.'/functionMySQL.php';
require_once __DIR__.'/functionDocker.php';

View file

@ -143,6 +143,11 @@ if (!class_exists('Video')) {
public static $urlTypeShort = 'URLShort';
private $categoryWasChanged = false;
const ASPECT_RATIO_ORIGINAL = '';
const ASPECT_RATIO_SQUARE = '1:1';
const ASPECT_RATIO_VERTICAL = '9:16';
const ASPECT_RATIO_HORIZONTAL = '16:9';
public function __construct($title = "", $filename = "", $id = 0, $refreshCache = false)
{
global $global;
@ -6479,7 +6484,7 @@ if (!class_exists('Video')) {
$a = '<a videos_id="' . $videos_id . '"
href="' . $href . '"
embed="' . $embed . '"
title="' . $title . '" alternativeLink="' . $alternativeLink . '">';
title="' . $title . '" alternativeLink="' . $alternativeLink . '" class="ajaxLoad">';
if ($addLink) {
$img = $a . $img . '</a>';
}

View file

@ -573,6 +573,11 @@ class AI extends PluginAbstract
if (preg_match('/[0-9]{2}:[0-9]{2}:[0-9]{2}/i', $obj->startTimeInSeconds)) {
$obj->startTimeInSeconds = durationToSeconds($obj->startTimeInSeconds);
}
$aspectRatio = Video::ASPECT_RATIO_HORIZONTAL;
if(!empty($obj->aspectRatio)){
$aspectRatio = $obj->aspectRatio;
}
_error_log('AI:videoCut start ' . $ai->getJson() . "{$obj->startTimeInSeconds} => {$obj->endTimeInSeconds}");
$vid = Video::getVideoLight($obj->videos_id);
$sources = getVideosURLOnly($vid['filename'], false);
@ -591,7 +596,7 @@ class AI extends PluginAbstract
if (!empty($newVideos_id)) {
_error_log('AI:videoCut new video saved videos_id=' . $newVideos_id);
$outputFile = Video::getPathToFile("{$videoFileName}.mp4");
cutVideoWithFFmpeg($source['url'], $obj->startTimeInSeconds, $obj->endTimeInSeconds, $outputFile);
cutVideoWithFFmpeg($source['url'], $obj->startTimeInSeconds, $obj->endTimeInSeconds, $outputFile, $aspectRatio);
$video = new Video('', '', $newVideos_id);
if (file_exists($outputFile)) {

View file

@ -35,8 +35,10 @@ $obj->videos_id = $videos_id;
$obj->startTimeInSeconds = $_REQUEST['startTimeInSeconds'];
$obj->endTimeInSeconds = $_REQUEST['endTimeInSeconds'];
$obj->users_id = User::getId();
$obj->title = $_REQUEST['title'];
$obj->description = $_REQUEST['description'];
$obj->aspectRatio = empty($_REQUEST['aspectRatio'])? Video::ASPECT_RATIO_HORIZONTAL:$_REQUEST['aspectRatio'];
$obj->title = $obj->aspectRatio.' '.$_REQUEST['title'];
//$obj->title = $_REQUEST['title'];
$ai = new Ai_scheduler(0);
$ai->setAi_scheduler_type(Ai_scheduler::$typeCutVideo);

View file

@ -28,6 +28,6 @@
if (typeof loadAIUsage == 'function') {
loadAIUsage();
}
avideoToastSuccess('AI '+json.type+" received");
avideoToastSuccess('AI ' + json.type + ' received');
}
</script>

View file

@ -59,7 +59,10 @@ function getShortsButtons($key)
global $bookmark;
$buttons = array();
$buttons[] = '<button class="btn btn-primary" onclick="playVideoSegmentFromIndex(' . $key . ');" data-toggle="tooltip" title="' . __('Play') . '" type="button"><i class="fa-solid fa-play"></i></button>';
$buttons[] = '<button class="btn btn-success" onclick="submitVideoForm(' . $key . ');" data-toggle="tooltip" title="' . __('Save Cut') . '" type="button"><i class="fa-solid fa-scissors"></i></button>';
$buttons[] = '<button class="btn btn-success" onclick="submitVideoForm(' . $key . ', \''.Video::ASPECT_RATIO_ORIGINAL.'\');" data-toggle="tooltip" title="' . __('Save Cut Original') . '" type="button"><i class="fa-solid fa-scissors"></i></button>';
$buttons[] = '<button class="btn btn-success" onclick="submitVideoForm(' . $key . ', \''.Video::ASPECT_RATIO_HORIZONTAL.'\');" data-toggle="tooltip" title="' . __('Save Cut Horizontal') . '" type="button"><i class="fa-solid fa-desktop"></i></button>';
$buttons[] = '<button class="btn btn-success" onclick="submitVideoForm(' . $key . ', \''.Video::ASPECT_RATIO_VERTICAL.'\');" data-toggle="tooltip" title="' . __('Save Cut Vertical') . '" type="button"><i class="fa-solid fa-mobile-screen-button"></i></button>';
$buttons[] = '<button class="btn btn-success" onclick="submitVideoForm(' . $key . ', \''.Video::ASPECT_RATIO_SQUARE.'\');" data-toggle="tooltip" title="' . __('Save Cut Square') . '" type="button"><i class="fa-regular fa-square-full"></i></button>';
if ($bookmark) {
$buttons[] = '<button class="btn btn-warning" onclick="bookmarkFromIndex(' . $key . ');" data-toggle="tooltip" title="' . __('Bookmark') . '" type="button"><i class="fa-solid fa-bookmark"></i></button>';
}

View file

@ -71,7 +71,7 @@ echo AVideoPlugin::afterVideoJS();
});
}
function submitVideoForm(index) {
function submitVideoForm(index, aspectRatio) {
modal.showPleaseWait();
var startTimeInSeconds = durationToSeconds($('#startTimeInSeconds' + index).val());
var endTimeInSeconds = durationToSeconds($('#endTimeInSeconds' + index).val());
@ -88,7 +88,7 @@ echo AVideoPlugin::afterVideoJS();
// Perform the AJAX request
$.ajax({
url: webSiteRootURL + 'plugin/AI/cutVideo.json.php', // Replace with your server endpoint
url: webSiteRootURL + 'plugin/AI/cutVideo.json.php?aspectRatio='+aspectRatio, // Replace with your server endpoint
type: 'POST',
data: formData,
success: function(response) {

View file

@ -100,7 +100,7 @@ if (empty($MediaMetadata)) {
} else if (mediaId) {
videos_id = mediaId;
console.log('updateMediaSessionMetadata mediaId', mediaId);
} else if (isLive) {
} else if (typeof isLive !== 'undefined' && isLive) {
key = isLive.key;
live_servers_id = isLive.live_servers_id;
live_schedule_id = isLive.live_schedule_id;

View file

@ -31,15 +31,23 @@ function expand() {
});
isCompressed = false;
}
function isCompressedVar(){
if(typeof isCompressed === 'undefined'){
return false;
}
return !empty(isCompressed);
}
function toogleEC() {
if (!empty(isCompressed)) {
if (isCompressedVar()) {
expand();
} else {
compress();
}
}
$(document).ready(function () {
if (!empty(isCompressed)) {
$(function () {
if (isCompressedVar()) {
compress();
} else {
expand();

View file

@ -18,6 +18,21 @@ body.fullscreen {
overflow: hidden;
}
#_avideoPageContentLoading{
display: none;
}
body._avideoPageContentLoading #_avideoPageContentLoading{
display: unset;
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 99999;
width: 100vw;
height: 5px;
}
.nopadding {
padding: 0 !important;
margin: 0 !important;
@ -2036,13 +2051,3 @@ body.ypt-is-compressed #videoCol {
.loadInfiniteScrollButton:disabled .fas.fa-angle-double-down {
display: none;
}
/*
#_avideoPageLoader{
display: none !important;
}
#_avideoPageContent{
display: unset !important;
}
*/

View file

@ -3,22 +3,9 @@ global $global, $config;
if (!isset($global['systemRootPath'])) {
require_once '../videos/configuration.php';
}
require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php';
?>
<!DOCTYPE html>
<html lang="<?php echo getLanguage(); ?>">
<head>
<title><?php echo __("Help") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?></title>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
$_page = new Page(array('Help'));
?>
<div class="container">
<div class="panel panel-default">
<div class="panel-body">
@ -53,7 +40,12 @@ require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php';
<hr />
<h3><?php echo __('Issues on github'); ?></h3>
<p><?php echo __('If you want to tell us, what is not working for you, this is great and helps us, to make the software more stable.'); ?></p>
<p><?php echo __('Some information can help us, to find your problem faster'); ?>:</p> <ul><li><?php echo __('Content of'); ?> <a href='<?php echo $global['webSiteRootURL']; ?>videos/avideo.log'>videos/avideo.log</a></li><li><?php echo __('Content of'); ?> <a href='<?php echo $global['webSiteRootURL']; ?>videos/avideo.js.log'>videos/avideo.js.log</a></li><li><?php echo __('If public: your domain, so we can see the error directly'); ?></li></ul>
<p><?php echo __('Some information can help us, to find your problem faster'); ?>:</p>
<ul>
<li><?php echo __('Content of'); ?> <a href='<?php echo $global['webSiteRootURL']; ?>videos/avideo.log'>videos/avideo.log</a></li>
<li><?php echo __('Content of'); ?> <a href='<?php echo $global['webSiteRootURL']; ?>videos/avideo.js.log'>videos/avideo.js.log</a></li>
<li><?php echo __('If public: your domain, so we can see the error directly'); ?></li>
</ul>
<p><?php echo __('If you can, clear the log-files, reproduce the error and send them. This helps to reduce old or repeating information.'); ?></p>
<hr />
<?php } ?>
@ -61,16 +53,42 @@ require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php';
<p><?php echo __('Here you find information about how to handle videos.'); ?></p>
<h3><?php echo __('Add videos'); ?></h3>
<p><?php echo __('There are various kinds of media you can integrate here. They are working different'); ?>:</p>
<table class='table'><thead><tr>
<th><?php echo __('Mediatype'); ?></th><th><?php echo __('How to set'); ?></th><th><?php echo __('Notes'); ?></th>
<table class='table'>
<thead>
<tr>
<th><?php echo __('Mediatype'); ?></th>
<th><?php echo __('How to set'); ?></th>
<th><?php echo __('Notes'); ?></th>
</tr>
</thead><tbody>
<tr><td><?php echo __('Audio'); ?></td><td><?php echo __('Via encoder or direct upload'); ?></td><td><?php echo __('Via encoder, most formats are possible, but you need to enable the Extract audio-option. With direct upload, only MP3 and OGG is allowed'); ?></td></tr>
<tr><td><?php echo __('Video'); ?></td><td><?php echo __('Via encoder or direct upload'); ?></td><td><?php echo __('Via encoder, most formats are possible. With direct upload, only MP4 is allowed'); ?></td></tr>
<tr><td><?php echo __('Embedded'); ?></td><td><?php echo __('My videos->Embed a video link->Embedded'); ?></td><td><?php echo __('Only direct mp3- or ogg-files - if you download it with the link, it should be a movie-file. No google-drive or stream-hoster. Also, do not mix https and http.'); ?></td></tr>
<tr><td><?php echo __('Direct audio-link (mp3 or ogg)'); ?></td><td><?php echo __('My videos->Embed a video link->Choose Direct audio-link (mp3 or ogg)'); ?></td><td><?php echo __('Only direct mp3- or ogg-files - if you download it with the link, it should be a movie-file. No google-drive or stream-hoster. Also, do not mix https and http.'); ?></td></tr>
<tr><td><?php echo __('Direct video-link (mp4)'); ?></td><td><?php echo __('My videos->Embed a video->Choose Direct video-link (mp4)'); ?></td><td><?php echo __('Only direct mp4-files - if you download it with the link, it should be a movie-file. No google-drive or stream-hoster. Also, do not mix https and http.'); ?></td></tr>
</tbody></table>
</thead>
<tbody>
<tr>
<td><?php echo __('Audio'); ?></td>
<td><?php echo __('Via encoder or direct upload'); ?></td>
<td><?php echo __('Via encoder, most formats are possible, but you need to enable the Extract audio-option. With direct upload, only MP3 and OGG is allowed'); ?></td>
</tr>
<tr>
<td><?php echo __('Video'); ?></td>
<td><?php echo __('Via encoder or direct upload'); ?></td>
<td><?php echo __('Via encoder, most formats are possible. With direct upload, only MP4 is allowed'); ?></td>
</tr>
<tr>
<td><?php echo __('Embedded'); ?></td>
<td><?php echo __('My videos->Embed a video link->Embedded'); ?></td>
<td><?php echo __('Only direct mp3- or ogg-files - if you download it with the link, it should be a movie-file. No google-drive or stream-hoster. Also, do not mix https and http.'); ?></td>
</tr>
<tr>
<td><?php echo __('Direct audio-link (mp3 or ogg)'); ?></td>
<td><?php echo __('My videos->Embed a video link->Choose Direct audio-link (mp3 or ogg)'); ?></td>
<td><?php echo __('Only direct mp3- or ogg-files - if you download it with the link, it should be a movie-file. No google-drive or stream-hoster. Also, do not mix https and http.'); ?></td>
</tr>
<tr>
<td><?php echo __('Direct video-link (mp4)'); ?></td>
<td><?php echo __('My videos->Embed a video->Choose Direct video-link (mp4)'); ?></td>
<td><?php echo __('Only direct mp4-files - if you download it with the link, it should be a movie-file. No google-drive or stream-hoster. Also, do not mix https and http.'); ?></td>
</tr>
</tbody>
</table>
<hr />
<h3><?php echo __('Edit videos'); ?></h3>
<p><?php echo __('After you add any kind of video, you can find it in'); ?> <?php echo __('My videos'); ?></p>
@ -98,20 +116,7 @@ require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php';
</div>
</div>
</div><!--/.container-->
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
<script>
$(document).ready(function () {
});
</script>
</body>
</html>
<?php
include $global['systemRootPath'].'objects/include_end.php';
$_page->print();
?>

View file

@ -23,7 +23,7 @@
</div>
</li>
<li style="width: 100%; text-align: center;">
<a class="navbar-brand" id="mainNavbarLogo" href="<?php echo empty($advancedCustom->logoMenuBarURL) ? getHomePageURL() : $advancedCustom->logoMenuBarURL; ?>">
<a class="navbar-brand ajaxLoad" id="mainNavbarLogo" href="<?php echo empty($advancedCustom->logoMenuBarURL) ? getHomePageURL() : $advancedCustom->logoMenuBarURL; ?>">
<img src="<?php echo getURL($config->getLogo()); ?>" alt="<?php echo str_replace('"', '', $config->getWebSiteTitle()); ?>" class="img-responsive " width="250" height="70">
<?php
if (isFirstPage()) {

View file

@ -1,6 +1,10 @@
/*experimental load page*/
// 1. Query a URL and process its contents
// Modified queryAndProcessURL function to execute replaceInlineJS after all scripts are loaded
function queryAndProcessURL(url) {
if ($('#_avideoPageContent').length) {
$('body').addClass('_avideoPageContentLoading');
console.log('a.ajaxLoad _avideoPageContent is present locally');
var urlA = addQueryStringParameter(url, 'avideoIframe', 1);
$.ajax({
url: urlA,
@ -9,22 +13,47 @@ function queryAndProcessURL(url) {
// Assuming response is the full HTML of the page
const tempDiv = $('<div></div>').html(response);
// 2. Add new CSS files
if (!tempDiv.find('#_avideoPageContent').length) {
console.log('a.ajaxLoad _avideoPageContent NOT is present remotely');
document.location = url;
} else {
console.log('a.ajaxLoad _avideoPageContent is present remotely');
// When all scripts are loaded, execute replaceInlineJS
addNewScriptFiles(tempDiv).done(function () {
// Only execute replaceInlineJS if replacePrincipalContainer was successful
const replaceResult = replacePrincipalContainer(tempDiv);
if(replaceResult){
// Add new CSS files
addNewCSSFiles(tempDiv);
// 3. Replace .principalContainer HTML
replacePrincipalContainer(tempDiv);
// 7. Change the page title
// Change the page title
changePageTitle(tempDiv);
// 8. Replace all <meta> tags
// Replace all <meta> tags
replaceMetaTags(tempDiv);
// 9. Change the current URL (using the History API for SPA behavior)
replaceInlineJS(tempDiv);
makeAjaxLoad();
// Change the current URL (using the History API for SPA behavior)
history.pushState({}, '', url);
}else{
console.log('a.ajaxLoad replacePrincipalContainer fail');
document.location = url;
}
$('body').removeClass('_avideoPageContentLoading');
});
}
}
});
} else {
console.log('a.ajaxLoad _avideoPageContent is NOT present locally');
document.location = url;
}
}
// Add new CSS files that are not already present
@ -41,46 +70,47 @@ function addNewCSSFiles(tempDiv) {
// Replace the .principalContainer HTML or the entire body's content
function replacePrincipalContainer(tempDiv) {
// Clone the #mainNavBar to re-insert it later
var mainNavBarClone = $('#mainNavBar').clone();
// Check if #_avideoPageContent exists in the tempDiv
const newPrincipalContainer = tempDiv.find('#_avideoPageContent').html();
// Check for .principalContainer in the response
const newPrincipalContainer = tempDiv.find('.principalContainer').html();
if (newPrincipalContainer) {
console.log('replacePrincipalContainer principalContainer');
$('.principalContainer').html(newPrincipalContainer);
} else {
// If no .principalContainer, replace the body's content directly
console.log('replacePrincipalContainer with direct response');
document.body.innerHTML = tempDiv.find('body').html(); // Use .html() on tempDiv directly
// Replace the content of #_avideoPageContent with newPrincipalContainer
$('#_avideoPageContent').html(newPrincipalContainer);
// Prepend the cloned #mainNavBar to the body or to a specific container within the body
//$('body').prepend(mainNavBarClone);
}
// Clone body classes from tempDiv and replace existing body classes
// const tempBodyClasses = tempDiv.find('body').attr('class');
//$('body').attr('class', tempBodyClasses);
// Continue with additional operations
// 4. Add new script files
//addNewScriptFiles(tempDiv);
addNewScriptFiles(tempDiv);
// 5. Replace inline CSS
//replaceInlineCSS(tempDiv);
replaceInlineCSS(tempDiv);
// 6. Replace inline JS
//replaceInlineJS(tempDiv);
replaceInlineJS(tempDiv);
return true;
}
return false;
}
// Add new script files that are not already present
function addNewScriptFiles(tempDiv) {
const promises = [];
$('script[src]').each(function () {
const currentSrc = $(this).attr('src');
tempDiv.find('script[src]').each(function () {
if (currentSrc !== $(this).attr('src') && !$('body').find(`script[src="${$(this).attr('src')}"]`).length) {
// Load script asynchronously and push the promise to the promises array
const promise = $.getScript($(this).attr('src'));
promises.push(promise);
$('body').append($(this).clone());
}
});
});
// Return a promise that resolves when all scripts are loaded
return $.when.apply($, promises);
}
// Replace inline CSS
@ -108,3 +138,19 @@ function replaceMetaTags(tempDiv) {
$('head').append($(this).clone());
});
}
function makeAjaxLoad(){
// Bind function to all <a> tags with class .ajaxLoad
$('a.ajaxLoad').each(function () {
$(this).on('click', function (event) {
event.preventDefault(); // Prevent default click action
console.log('a.ajaxLoad clicked');
var url = $(this).attr('href');
queryAndProcessURL(url);
});
});
}
$(function () {
makeAjaxLoad();
});