Skip to content

Commit

Permalink
everything works again. Shows "downloading" and then jumps to 100% be…
Browse files Browse the repository at this point in the history
…fore going blank for install
  • Loading branch information
N6REJ committed Aug 3, 2024
1 parent d390220 commit b39ebc8
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 73 deletions.
24 changes: 16 additions & 8 deletions core/classes/actions/class.action.quickPick.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@ public function checkQuickpickJson()
// Get the creation time of the local file if it exists
if ( file_exists( $this->jsonFilePath ) ) {
$localFileCreationTime = filectime( $this->jsonFilePath );
} else {
}
else {
$result = $this->rebuildQuickpickJson();
}

Expand Down Expand Up @@ -424,17 +425,24 @@ public function fetchAndUnzipModule(string $moduleUrl, string $module): array
Util::logDebug( 'Module Type: ' . $moduleType );

// Get module type
$destination = $this->getModuleDestinationPath( $moduleType, $moduleName );
$destination = $this->getModuleDestinationPath( $moduleType, $moduleName );
Util::logDebug( 'Destination: ' . $destination );


// Retrieve the file path from the URL using the bearsamppCore module,
// passing the module URL and temporary file path, with the use Progress Bar parameter set to true.
$result = $bearsamppCore->getFileFromUrl($moduleUrl, $tmpFilePath, true);
$result = $bearsamppCore->getFileFromUrl( $moduleUrl, $tmpFilePath, true );

// Check if $result is false
if ( $result === false ) {
Util::logError( 'Failed to retrieve file from URL: ' . $moduleUrl );

return ['error' => 'Failed to retrieve file from URL'];
}

// Determine the file extension and call the appropriate unzipping function
$fileExtension = pathinfo( $tmpFilePath, PATHINFO_EXTENSION );
Util::logDebug( 'File extension: ' . $fileExtension );

if ( $fileExtension === '7z' ) {
if ( !$bearsamppCore->unzip7zFile( $tmpFilePath, $destination ) ) {
return ['error' => 'Failed to unzip .7z file. File: ' . $tmpFilePath . ' could not be unzipped', 'Destination: ' . $destination];
Expand All @@ -451,7 +459,7 @@ public function fetchAndUnzipModule(string $moduleUrl, string $module): array
return ['error' => 'Unsupported file extension'];
}

return ['success' => 'Module fetched and unzipped successfully'];
return ['success' => 'Module installed successfully'];
}

/**
Expand All @@ -470,13 +478,13 @@ public function getModuleDestinationPath(string $moduleType, string $moduleName)
{
global $bearsamppRoot;
if ( $moduleType === 'application' ) {
$destination = $bearsamppRoot->getAppsPath() . '/' . $moduleName . '/';
$destination = $bearsamppRoot->getAppsPath() . '/' . strtolower( $moduleName ) . '/';
}
elseif ( $moduleType === 'binary' ) {
$destination = $bearsamppRoot->getBinPath() . '/' . $moduleName . '/';
$destination = $bearsamppRoot->getBinPath() . '/' . strtolower( $moduleName ) . '/';
}
elseif ( $moduleType === 'tools' ) {
$destination = $bearsamppRoot->getToolsPath() . '/' . $moduleName . '/';
$destination = $bearsamppRoot->getToolsPath() . '/' . strtolower( $moduleName ) . '/';
}
else {
$destination = '';
Expand Down
23 changes: 7 additions & 16 deletions core/classes/class.core.php
Original file line number Diff line number Diff line change
Expand Up @@ -538,11 +538,13 @@ public function unzip7zFile($filePath, $destination)
* This method attempts to retrieve the content from the provided URL and save it to the specified file path.
* If any error occurs during fetching or saving, it logs the error and returns an error message.
* If the operation is successful, it returns the file path.
* The method also logs the file size if the input stream is a valid resource.
*
* @param string $moduleUrl The URL from which to fetch the file content.
* @param string $filePath The path where the file content should be saved.
* @param string $moduleUrl The URL from which to fetch the file content.
* @param string $filePath The path where the file content should be saved.
* @param bool $progressBar Optional. Whether to display a progress bar during the download process. Default is false.
*
* @return array|string Returns the file path if successful, or an array with an error message if an error occurs.
* @return array Returns the file path if successful, or an array with an error message if an error occurs.
*/
public function getFileFromUrl(string $moduleUrl, string $filePath, $progressBar = false)
{
Expand All @@ -563,19 +565,8 @@ public function getFileFromUrl(string $moduleUrl, string $filePath, $progressBar
return ['error' => 'Error saving module'];
}

// Ensure $inputStream is a valid file resource
if ( is_resource( $inputStream ) ) {
// Get file statistics
$fileStats = fstat( $inputStream );
// Extract the file size
$fileSize = $fileStats['size'];
// Output the file size
Util::logError( 'File size: ' . $fileSize . ' bytes' );
}

// Read and write in chunks to avoid memory overload
$bufferSize = 32768; // 32KB
$steps = $fileSize / $bufferSize;
$bufferSize = 8096; // 8KB
$bytesRead = 0;

while ( !feof( $inputStream ) ) {
Expand All @@ -585,7 +576,7 @@ public function getFileFromUrl(string $moduleUrl, string $filePath, $progressBar

// Send progress update
if ( $progressBar ) {
$progress = min( 100, ($bytesRead / $fileSize) * 100 );
$progress = $bytesRead;
echo json_encode( ['progress' => $progress] );
ob_flush();
flush();
Expand Down
15 changes: 12 additions & 3 deletions core/resources/homepage/ajax/ajax.quickpick.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@

$response = array();

$response = array();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$module = isset($_POST['module']) ? $_POST['module'] : null;
$version = isset($_POST['version']) ? $_POST['version'] : null;
Expand All @@ -53,11 +55,18 @@
$response['message'] .= "\nEdit Bearsampp.conf to use new version then";
$response['message'] .= "\nRight click on menu and choose reload.";
}
} else {
error_log('Error in response: ' . json_encode($response));
}
echo json_encode($response);
error_log('Response: ' . json_encode($response));
} else {
echo json_encode(['error' => 'Invalid module or version.']);
$response = ['error' => 'Invalid module or version.'];
}
} else {
echo json_encode(['error' => 'Invalid request method.']);
$response = ['error' => 'Invalid request method.'];
}

echo json_encode($response);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log('JSON encoding error: ' . json_last_error_msg());
}
22 changes: 17 additions & 5 deletions core/resources/homepage/css/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -401,12 +401,24 @@ div#InternetState {
animation: spin 2s linear infinite;
}

@-webkit-keyframes spin {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); }
.spinner {
border: 4px solid rgba(0, 0, 0, 0.1);
border-left-color: #000;
border-radius: 50%;
width: 20px;
height: 20px;
animation: spin 1s linear infinite;
position: absolute;
right: 10px; /* Adjust as needed */
top: 50%;
transform: translateY(-50%);
}

@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
75 changes: 34 additions & 41 deletions core/resources/homepage/js/quickpick.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ function hideall() {

}
async function installModule(moduleName, version) {
const url = AJAX_URL; // Ensure this variable is defined and points to your server-side script handling the AJAX requests.
const url = AJAX_URL;
const senddata = new URLSearchParams();
const progress = document.getElementById('progress');
const progressbar = document.getElementById('progress-bar');
Expand All @@ -140,7 +140,7 @@ async function installModule(moduleName, version) {
downloadversion.innerText = version;
senddata.append('module', moduleName);
senddata.append('version', version);
senddata.append('proc', 'quickpick'); // Setting 'proc' to 'quickpick'
senddata.append('proc', 'quickpick');

const options = {
method: 'POST',
Expand All @@ -157,54 +157,47 @@ async function installModule(moduleName, version) {
}

const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let receivedLength = 0;
let chunks = [];
const decoder = new TextDecoder();
let responseText = '';

while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
chunks.push(value);
receivedLength += value.length;

const progress = (receivedLength / contentLength) * 100;
progressbar.style.width = progress + '%';
progressbar.innerText = `Downloading ${moduleName} ${version} (${Math.round(progress)}%)`;
}
if (done) break;
responseText += decoder.decode(value, { stream: true });

// Process each JSON object separately
const parts = responseText.split('}{').map((part, index, arr) => {
if (index === 0) return part + '}';
if (index === arr.length - 1) return '{' + part;
return '{' + part + '}';
});

const responseText = new TextDecoder("utf-8").decode(new Uint8Array(chunks.flat()));
console.log('Response Text:', responseText); // Log the response text

try {
const data = JSON.parse(responseText);
if (data.error) {
console.error('Error:', data.error);
window.alert(`Error: ${data.error}`);
} else {
console.log(data);
window.alert(data.message);
for (const part of parts) {
try {
const data = JSON.parse(part);
if (data.progress) {
console.log('Progress:', data.progress);
// Update progress bar or other UI elements here
const progressValue = data.progress;
progressbar.style.width = progressValue + '%';
progressbar.setAttribute('aria-valuenow', progressValue);
progressbar.innerText = progressValue + '%';
} else if (data.success) {
console.log(data);
window.alert(data.message);
} else if (data.error) {
console.error('Error:', data.error);
window.alert(`Error: ${data.error}`);
}
} catch (error) {
// Ignore JSON parse errors for incomplete parts
}
}
} catch (error) {
console.error('Failed to parse response:', error);
window.alert('Failed to parse response: ' + error.message);
}
} catch (error) {
console.error('Failed to install module:', error);
window.alert('Failed to install module: ' + error.message);
} finally {
location.reload();
//location.reload();
}
}

function setProgress(progpercent) {
const progress = document.getElementById('progress');
const progressbar = document.getElementById('progress-bar');
const downloadmodule = document.getElementById('download-module');
const downloadversion = document.getElementById('download-version');

progressbar.innerText="Downloading ".concat(downloadmodule.innerText).concat(' ').concat(downloadversion.innerText).concat(' - ').concat(progpercent).concat('%');
progressbar.ariaValueNow=progpercent;
progress.style.display="block";
}

0 comments on commit b39ebc8

Please sign in to comment.