Skip to content

Commit

Permalink
ncp-web: use SSE to display process output in real time. Exit status …
Browse files Browse the repository at this point in the history
…green/red
  • Loading branch information
nachoparker committed Aug 24, 2017
1 parent edccf4a commit f044c6d
Show file tree
Hide file tree
Showing 9 changed files with 231 additions and 7 deletions.
34 changes: 34 additions & 0 deletions ncp-web/green-circle.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 3 additions & 2 deletions ncp-web/index.php
@@ -1,5 +1,5 @@
<!--
NextcloudPi Web Panel javascript library
NextcloudPi Web Panel frontend
Copyleft 2017 by Ignacio Nunez Hernanz <nacho _a_t_ ownyourbits _d_o_t_ com>
GPL licensed (see end of file) * Use at your own risk!
Expand All @@ -20,7 +20,7 @@
session_start();

// security headers
header("Content-Security-Policy: default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';");
header("Content-Security-Policy: default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self'; object-src 'self';");
header("X-XSS-Protection: 1; mode=block");
header("X-Content-Type-Options: nosniff");
header("X-Robots-Tag: none");
Expand Down Expand Up @@ -117,6 +117,7 @@
<div id="config-button-wrapper">
<button id="config-button">Run</button>
<img id="loading-gif" src="loading-small.gif">
<div id="circle-retstatus" class="icon-red-circle"></div>
</div>
</form>
<textarea readonly id="details-box" rows="25" cols="60"></textarea>
Expand Down
7 changes: 5 additions & 2 deletions ncp-web/ncp-launcher.php
Expand Up @@ -11,6 +11,7 @@
include ('csrf.php');

session_start();
ignore_user_abort( true );

if ( $_POST['action'] == "cfgreq" )
{
Expand Down Expand Up @@ -97,9 +98,11 @@

// Get new token
echo '{ "token": "' . getCSRFToken() . '",';
echo ' "output": ';
echo ' "output": "" , ';
echo ' "ret": ';

echo json_encode( shell_exec( 'bash -c "sudo /home/www/ncp-launcher.sh ' . $file . '"' ) ) . ' }';
exec( 'bash -c "sudo /home/www/ncp-launcher.sh ' . $file . '"' , $output , $ret );
echo '"' . $ret . '" }';
}

else if ( $_POST['action'] == "poweroff" )
Expand Down
93 changes: 93 additions & 0 deletions ncp-web/ncp-output.php
@@ -0,0 +1,93 @@
<?php
///
// Dispatcher of SSE events with the contents of the NCP log
//
// Copyleft 2017 by Ignacio Nunez Hernanz <nacho _a_t_ ownyourbits _d_o_t_ com>
// GPL licensed (see end of file) * Use at your own risk!
//
// More at https://ownyourbits.com/2017/02/13/nextcloud-ready-raspberry-pi-image/
///

header('Content-Type: text/event-stream; charset=utf-8');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.


/**
* Constructs the SSE data format and flushes that data to the client.
* ( from html5rocks.com )
*
* @param string $id Timestamp/id of this connection.
* @param string $msg Line of text that should be transmitted.
*/
function sendMsg($id, $msg)
{
echo "id: $id" . PHP_EOL;
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}

/**
* Pings the client-browser to force detection of closed socket
*/
function pingClient()
{
echo ' ';
ob_flush();
flush();
}

/**
* Imitates 'tail --follow' functionality, and sends lines as SSE events
* , while pinging browser to detect closed tab.
* ( based on stack overflow )
*/
function follow($file)
{
$size = 0;
while (true)
{
clearstatcache();
$currentSize = filesize($file);
if ($size == $currentSize)
{
usleep(200000); // 0.2s
// if the user refreshes the tab >5 times, it won't load because it doesn't detect closed socket
// , and all workers are in use
pingClient();
continue;
}

$fh = fopen($file, "r");
fseek($fh, $size);

while ($line = fgets($fh))
sendMsg( 'output' , $line );

fclose($fh);
$size = $currentSize;
}
}

session_write_close();
echo str_pad('',1024*1024*4); // make sure the browser buffer becomes full
follow( '/run/ncp.log' );

// License
//
// This script is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This script is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this script; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330,
// Boston, MA 02111-1307 USA
?>
12 changes: 12 additions & 0 deletions ncp-web/ncp.css
Expand Up @@ -1113,6 +1113,18 @@ select {
background-image: url('poweroff.svg');
}

.icon-red-circle {
background-image: url('red-circle.svg');
padding: 8px;
display: none;
}

.icon-green-circle {
background-image: url('green-circle.svg');
padding: 8px;
}


#expand #expandDisplayName {
padding: 8px;
opacity: 0.6;
Expand Down
35 changes: 33 additions & 2 deletions ncp-web/ncp.js
Expand Up @@ -19,6 +19,25 @@ function errorMsg()

$(function()
{
// Event source to receive process output in real time
if (!!window.EventSource)
var source = new EventSource('ncp-output.php');
else
$('#config-box-title').fill( "Browser not supported" );

source.addEventListener('message', function(e)
{
if ( e.origin != 'https://' + window.location.hostname + ':4443')
{
$('#details-box').fill( "Invalid origin" );
return;
}

var textarea = $('#details-box');
textarea.fill( textarea.text() + e.data + '\n' );
textarea[0].scrollTop = textarea[0].scrollHeight;
}, false);

// Show selected option configuration box
$( 'li' , '#app-navigation' ).on('click', function(e)
{
Expand All @@ -38,6 +57,7 @@ $(function()
var ret = $.parseJSON( result );
if ( ret.token )
$('#csrf-token').set( { value: ret.token } );
$('#circle-retstatus').hide();
$('#config-box').ht( ret.output );
$('#config-box-title').fill( $( 'input' , '#' + selectedID ).get( '.value' ) );
$('#config-box-wrapper').show();
Expand All @@ -64,6 +84,11 @@ $(function()
cfg[item.name] = item.value;
} );

// reset box
$('#details-box').fill();
$('#details-box').show();
$('#circle-retstatus').hide();

// request
$.request('post', 'ncp-launcher.php', { action:'launch',
ref:selectedID ,
Expand All @@ -74,8 +99,14 @@ $(function()
var ret = $.parseJSON( result );
if ( ret.token )
$('#csrf-token').set( { value: ret.token } );
$('#details-box').fill(ret.output);
$('#details-box').show();
if ( ret.ret ) // means that the process was launched
{
if ( ret.ret == '0' ) $('#circle-retstatus').set( '+icon-green-circle' );
else $('#circle-retstatus').set( '-icon-green-circle' );
$('#circle-retstatus').show();
}
else // print error from server instead
$('#details-box').fill(ret.output);
$('#config-button').set('@disabled',null);
$('#loading-gif').hide();
confLock = false;
Expand Down
33 changes: 33 additions & 0 deletions ncp-web/red-circle.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 4 additions & 1 deletion nextcloudpi.sh
Expand Up @@ -60,7 +60,10 @@ DIR=/usr/local/etc/nextcloudpi-config.d
test -f $DIR/$1 || { echo "File not found"; exit 1; }
source /usr/local/etc/library.sh
cd $DIR
launch_script $1
touch /run/ncp.log
chmod 640 /run/ncp.log
chown root:www-data /run/ncp.log
launch_script $1 &> /run/ncp.log
EOF
chmod 700 /home/www/ncp-launcher.sh
echo "www-data ALL = NOPASSWD: /home/www/ncp-launcher.sh , /sbin/halt" >> /etc/sudoers
Expand Down
14 changes: 14 additions & 0 deletions update.sh
Expand Up @@ -119,6 +119,20 @@ sed -i 's|www-data.*|www-data ALL = NOPASSWD: /home/www/ncp-launcher.sh , /sbin/
# fix fail2ban misconfig in stretch
rm -f /etc/fail2ban/jail.d/defaults-debian.conf

# update ncp-launcher to support realtime updates with SSE
cat > /home/www/ncp-launcher.sh <<'EOF'
#!/bin/bash
DIR=/usr/local/etc/nextcloudpi-config.d
test -f $DIR/$1 || { echo "File not found"; exit 1; }
source /usr/local/etc/library.sh
cd $DIR
touch /run/ncp.log
chmod 640 /run/ncp.log
chown root:www-data /run/ncp.log
launch_script $1 &> /run/ncp.log
EOF
chmod 700 /home/www/ncp-launcher.sh

# License
#
# This script is free software; you can redistribute it and/or modify it
Expand Down

0 comments on commit f044c6d

Please sign in to comment.