diff --git a/app.js b/app.js index 0358fd2..46ee3cf 100644 --- a/app.js +++ b/app.js @@ -1,5 +1,7 @@ // dependencies -const dotenv = require('dotenv').config(), +const + conf = require('./conf.json'), + data = require('./db.json'), express = require('express'), bodyParser = require('body-parser'), path = require('path'), @@ -12,39 +14,40 @@ const dotenv = require('dotenv').config(), socket = require('socket.io'), chalk = require('chalk'), nodemailer = require('nodemailer'), - { gzip, ungzip } = require('node-gzip'), - // other objects + { gzip, ungzip } = require('node-gzip') + +// other +const app = express(), stdin = process.openStdin(), transporter = nodemailer.createTransport({ service: 'gmail', auth: { - user: process.env.MAIL_USER, - pass: process.env.MAIL_PASS + user: conf.mail.user, + pass: conf.mail.pass } }) // ssl credentials -if (process.env.CERT_KEY && process.env.CERT_CRT && process.env.CERT_CA) +if (conf.cert.key && conf.cert.crt && conf.cert.ca && conf.cert.enable) credentials = { - key: fs.readFileSync(process.env.CERT_KEY, 'utf8'), - cert: fs.readFileSync(process.env.CERT_CRT, 'utf8'), - ca: fs.readFileSync(process.env.CERT_CA, 'utf8') + key: fs.readFileSync(conf.cert.key, 'utf8'), + cert: fs.readFileSync(conf.cert.crt, 'utf8'), + ca: fs.readFileSync(conf.cert.ca, 'utf8') } class DataBase { constructor(json) { - this.data = JSON.parse(json) + this.data = json this.config = { szkola: true, lockdown: false, dlog: false, // sensor to server log llog: false, // info to file log hostname: 'smart-home', // pseudo-hostname - redir: false, // https redirection + redir: false, // force https verbose: 3, // max log lvl - pt: false // prace techniczne } this.stats = { network: {}, @@ -1098,75 +1101,63 @@ app }); app.use(function (err, req, res, next) { - return res.status(404).send("lol"); + return res.status(404).send("404"); }); // server setup -if (typeof credentials != 'undefined') { - console.log(credentials) - const httpsServer = https.createServer(credentials, app) -} + const httpServer = http.createServer(app), io = new socket() .attach(httpServer) -if (typeof credentials != 'undefined') +if (conf.cert.enable) { + const httpsServer = https.createServer(credentials, app) io.attach(httpsServer) +} +// stdin input listener stdin.addListener("data", function (d) { c = d.toString().trim(); try { console.log(eval(c)); - } catch (error) { - console.error(error); + } catch (e) { + console.error(e); } }); // load user database from db.json and start listening -fs.readFile(path.join(__dirname, 'db.json'), function (err, data) { - if (err) { - console.log(err); - } else { +global.db = new DataBase(data); - global.db = new DataBase(data); +db.onReady = function () { - db.onReady = function () { + Exe.log({ + action: "info", + data: "DataBase ready" + }, 1); - Exe.log({ - action: "info", - data: "DataBase ready" - }, 1); + // db.getDevices() + // setInterval(function(db){ + // db.getDevices() + // }, 120*1e3, db) - // db.getDevices() - // setInterval(function(db){ - // db.getDevices() - // }, 120*1e3, db) + db.schedule._check() +} - db.schedule._check() - } - - // http standard server - httpServer.listen(process.env.PORT_MAIN, function () { - Exe.log({ - action: "info", - data: `Server listening on port ${process.env.PORT_MAIN}` - }, 1); - }); - - // https secure server - if (typeof credentials != 'undefined') - httpsServer.listen(process.env.PORT_SSL, function () { - Exe.log({ - action: "info", - data: `Server listening on port ${process.env.PORT_SSL}` - }, 1); - }); - - } +// http standard server +httpServer.listen(conf.ports.main, function () { + Exe.log({ + action: "info", + data: `Server listening on port ${conf.ports.main}` + }, 1); }); -// data logging -// setInterval(function(){ if(!config.lockdown)varlog(); }, 60000); +// https secure server +if (conf.cert.enable) httpsServer.listen(conf.ports.ssl, function () { + Exe.log({ + action: "info", + data: `Server listening on port ${conf.ports.ssl}` + }, 1); +}); // socketio events io.on('connection', function (socket) { // connection established event @@ -1221,23 +1212,20 @@ io.on('connection', function (socket) { // connection established event }); app.get('/', function (req, res) { - // check if cleint is on local network - if (req.ip.startsWith("::ffff:192.168")) var local = true; - else var local = false; - // https redirection - if (req.protocol != 'https' && !local && !db.config.redir && typeof credentials != 'undefined') { + if ( + req.protocol != 'https' + && !req.ip.startsWith("::ffff:192.168") + && !db.config.redir + && conf.cert.enable + ) { res.redirect('https://' + req.hostname + req.originalUrl); } else { - if (db.config.pt && !local) { // temporary lockout - res.send("Trwają prace techniczne, zapraszam później"); - } else { - res.render('pages/index', { - vars: { - hostname: db.config.hostname - } - }); - } + res.render('pages/index', { + vars: { + hostname: db.config.hostname + } + }); } }); diff --git a/conf.json b/conf.json new file mode 100644 index 0000000..cd63fbe --- /dev/null +++ b/conf.json @@ -0,0 +1,16 @@ +{ + "mail": { + "user": "", + "pass": "" + }, + "cert": { + "enable": false, + "key": "", + "crt": "", + "ca": "" + }, + "ports": { + "main": 3000, + "ssl": 443 + } +} \ No newline at end of file diff --git a/public/main.js b/public/main.js index c33f974..f11ee97 100644 --- a/public/main.js +++ b/public/main.js @@ -1,712 +1,945 @@ -class Tools{ - static getCookie(cname){ - var name = cname + "="; - var decodedCookie = decodeURIComponent(document.cookie); - var ca = decodedCookie.split(';'); - for(var i = 0; i /g, ">") - .replace(/"/g, """) - .replace(/'/g, "'") - } - - /*static argq(arg){ // join quotes in arg array - var v = 0; - var g = []; - for (var ar in arg) { - if((arg[ar].startsWith("\"")) || (arg[ar].startsWith("\'"))){ - v=1; - // g.push(arg[ar].slice(1)); - if((arg[ar].endsWith("\"")) || (arg[ar].endsWith("\'"))){ - g.push(arg[ar].slice(1, arg[ar].length-1)); - v=0; - } - else - g.push(arg[ar].slice(1)); - - continue; - }; - if((arg[ar].endsWith("\"")) || (arg[ar].endsWith("\'"))){ - v=0; - g[g.length-1] += " "+arg[ar].slice(0, arg[ar].length-1); - // g[g.length-1] = g[g.length-1].slice(1, g[g.length-1].length-1); - continue; - }; - - if(!v){ - g.push(arg[ar]); - }else{ - g[g.length-1] += " "+arg[ar] - } - } - return g - }*/ - - static isDefined(...d){ - - for(let key in d){ - if(typeof d[key] != "undefined") - return d[key] - } - return undefined - } - - static isNotEmpty(v, d){ - if(typeof v == "") - return d + if (type instanceof Node) + this.element = [type] + else if (type instanceof NodeList) + this.element = type else - return v + this.element = [document.createElement(type)] } - static isWhat(what){ - if(what) - if(what.name) - if(what.name!="") - return "[function "+what.name+"]" - - return "["+typeof what+" "+(what ? what.constructor.name:"Undefined")+"]"; - } - - static getStackTrace(){ - - var obj = {}; // create stack trace object - - try{ - Error.captureStackTrace(obj, getStackTrace); // capture stack to obj - }catch(error){ - return error // on error return - } - - obj = obj.stack.split("\n").slice(1); // split on newline, remove first element - for(let trace in obj){ - obj[trace] = obj[trace].slice(4); // remove whitespace at the beginning - } - - return obj - - } - - static makeID(n){ // generate random base 64 string - var out = ""; - var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"; - - for (var i = 0; i < n; i++) - out += chars.charAt(Math.floor(Math.random() * chars.length)); - - return out; - } - - static search(key, value, array){ - - if(value === true) return 0 - if(value === false) return array.length-1 - for(var i=0; i < array.length; i++){ - if(array[i][key] === value) { - return i; - } - } - - } -} - -class ToHtml{ - static toTree(obj, mdepth){ - // returns html (ul list) tree - - var typeOf = function(o){ - var t = typeof o; - - if(o instanceof Array) return "array"; - if(o instanceof RegExp) return "regex"; - if(o === null) return "null"; - - return t - } - - var contentType = function(v, name){ - - var type = typeOf(v) - - switch(type){ - - case 'number': return $("").append( name ? name : "number" ) - case 'string': return $("").append( name ? name : "string" ) - case 'boolean': return $("").append( name ? name : "boolean" ) - case 'function': return $("").append( name ? name : "function" ) - case 'array': return $("").append( name ? name : "array" ) - case 'object': return $("").append( name ? name : "object" ) - case 'regex': return $("").append( name ? name : "regex" ) - case 'null': return $("").append( name ? name : "null" ) - case 'undefined': return $("").append( name ? name : "undefined" ) - default: return $("").append( name ? name : "?" ) + addClass(...classNames) { + for (let key of classNames) { + for (let e of this.element) { + if (e.classList) + e.classList.add(key); + else + e.className += ' ' + key; } } - - var $collapse = function(n){ - if(n){ - return $("") - .addClass("collapse") - .append( - $("") - .addClass('icon-plus-squared') - ) - }else{ - return $("") - .addClass("collapse") - .append( - $("") - .addClass('icon-minus-squared') - ) - } - } - - var $recur = function(obj, depth){ - - let m = Tools.isDefined(mdepth, Config.treeDepth, 4); - const maxd = m<=7 ? m : 7; // max depth - const maxn = 50; // max level length - const maxs = 150; // max string length - const maxc = 2; // level to collapse after - - var $list = $(""); - - var i = 0; - for(let key in obj){ - i++; - if(i > maxn){ - continue - } - - var content = obj[key]; // content - var type = typeOf(obj[key]); // content type - - - switch(type){ - case 'object': - case 'array': - if($.isEmptyObject(content)){ // is content epmty - $list.append( // empty object - $("
  • ") - .append( contentType(content, key) ) - .append( ": " ) - .append( `[empty]` ) - ) - }else{ // content not empty - if(depth > maxd){ // is max depth reached - $list.append( // function description (max depth reached) - $("
  • ") - .append( contentType(content, key) ) - .append( ": " ) - .append( `${ Tools.isWhat(content) }` ) - ) - }else{ // max depth not reached - $list.append( // continue recursion - $("
  • ") - .append( contentType(content, key) ) - .append( ": " ) - .append( // collapse button - $collapse( depth >= maxc ) - ) - .append( $recur(content, depth+1) ) - ) - } - } - break; - - case 'function': - $list.append( - $("
  • ") - .append( contentType(content, key) ) - .append( ": " ) - .append( - `${ Tools.isWhat(content) }` - ) - ) - break; - - default: - $list.append( - $("
  • ") - .append( contentType(content, key) ) - .append( ": " ) - .append( content ) - ) - break; - } - - } - - if(i > maxn){ - - $list.append( - $("
  • ") - .append( - $("") - .append( `... ${i-maxn} more` ) - ) - ) - - } - - if(depth > maxc){ - $list.hide() - } - - return $list - - } - - if( typeOf(obj)!="array" && typeOf(obj)!="object" ) - return $("").append(contentType(obj)).append(": ").append(obj+"") - - var $ascii = $("") - .addClass("ascii") - .append( - $("
  • ") - .append( contentType(obj) ) - .append( - $collapse(false) - ) - .append( $recur(obj, 1) ) - ) - - return $ascii; - + return this } - static toTable(content){ - // returns html table from 2d array - - var $table = $("
    ") - - for(let row of content){ - let tr = $("") - for(let col of row){ - tr.append( - $("").append( col+"" ) - ) - } - $table.append( tr ) - } - - return $table - - } - - static toGraph(data, x, y){ - // returns chart.js graph - - var id = Tools.makeID(6); - - return `
    ` - } - - static toSyntax(data, lang){ - if(lang){ - var langs = []; - langs.push(lang) - } - var hl = hljs.highlightAuto(data, lang); - var out = ""; - - var r = /(\<.*?\>)(.*?)(\<\/[\S]*?\>)/g; - - out = hl.value.replace(r, function(match, beg, mid, end){ - // console.log(beg+"|"+mid+"|"+end); - // console.log(beg+ mid.replace(/\n/g, `[\n]`) +end) - return beg+mid.replace(/\n/g, `${end}\n${beg}`)+end - }) - - // var match = r.exec(hl.value); - // while (match != null) { - // console.log(match[0]) - // out += match[1] + match[2].replace("\n", `${match[3]}\n${match[2]}`) + match[3] - // match = r.exec(hl.value); - // } - - - var lines = out.split("\n"); - var code = $("") - .append(``) - - /*for(let index in lines){ - code.append( - $("") - .addClass('hljs-newline') - .append(lines[index]) - // .prop( "data-int", " ".repeat( (lines.length.toString().length) - ((parseInt(index)+1).toString().length) ) + (parseInt(index)+1) ) - ) - .append("\n") - }*/ - code.append(hl.value) - - return $("
    ").append( code )
    -
    -		/*for(let index in lines){
    -			indexed+=`${lines[index]}\n`
    -		}
    -
    -		return `
    ${indexed}
    `*/ - } - -} - -class ChangeDom{ - static updateInfo(res){ - // refresh status informations - - // var rp = JSON.parse(res); // parse json - - if(($(".info0")[0]) && (res.type=="uptime")){ - $(".info0").html(res["uptime"]); - $(".info1").html(res["load1"]); - $(".info2").html(res["load2"]); - $(".info3").html(res["load3"]); - $(".info4").html(res["memory"]); - $(".info5").html(res["users"]);} - // update uptime section - - if(($(".info6")[0]) && (res.type=="stats")){ - $(".info6").html(res["tempout"]); - $(".info7").html(res["tempin"]); - $(".info8").html(res["humout"]); - $(".info9").html(res["humin"]);} - // update stats section - - if(($(".info10")[0]) && (res.type=="network")){ - var nl = ""; - for (var i = 0; i < res['network'].length; i++) { - nl += "
  • "+res['network'][i]+"
  • "; - } - nl += '
  • Raspberry
  • '; - $(".info10").html(nl);} - // update devices section - } - - static setStyle(){ - /*setstyle: function setstyle(name){ // set style theme - if(!name) var name = ""; - - if(name != ""){ - log("Style: "+name, "info"); - Tools.setCookie("style", name); - $('head').append(''); - }else{ - log("Style "+name+" doesn't exist, using default preset", "warning"); - setstyle("default"); - } - },*/ - } - -} - -function mesparse(data, amount, con){ // parse mesenger chat information - var response = ""; - var perf = performance.now(); - - // check if json is loaded\ - if(typeof data != "undefined"){ - - // check if participants are defined\ - if(typeof data.participants != "undefined"){ - - l = []; // links - p = 0; // pics - a = []; // unique words - ac = []; // unique words counter - w = 0; // word counter - d = [0,0,0,0,0,0,0] // weekdays - h = new Array(24).fill(0); - - // unique words by participant - for(let key in data.participants){ - data.participants[key].w = []; + removeClass(...classNames) { + for (let key of classNames) { + for (let e of this.element) { + if (e.classList) + e.classList.remove(key); + else + e.className = e.className.replace(new RegExp(`\\b${key}\\b`), ""); } - // check if messages are defined\ - if(typeof data.messages != "undefined"){ + } + return this + } - // parse every message in file - for(let key in data.messages){ + setProp(properties) { + for (let prop in properties) { + for (let e of this.element) { + e.setAttribute(prop, properties[prop]) + } + } + return this + } - // check if content is present - if(typeof data.messages[key].content != "undefined"){ - - let x = new Date(); - x.setTime(data.messages[key].timestamp_ms); - d[x.getDay()]+=1; - h[x.getHours()]+=1; - - // check if message is a photo - if(data.messages[key].photos){ - p++; - continue; - } - - data.messages[key].content = data.messages[key].content.replace(/ +(?= )/g,''); - words = data.messages[key].content.split(" "); - - for(let word in words){ - - let i = a.indexOf(words[word]); - if(i==-1){ - a.push(words[word]); - ac.push(1); - }else{ - ac[i]+=1; - } - - for(let p in data.participants){ - if(data.messages[key].sender_name == data.participants[p].name) - data.participants[p].w.push(words[word]) - } - // if(data.messages[key].sender_name == "Sebastian Fudalej") s.push(words[word]); - // else if(data.messages[key].sender_name == "Mateusz Pstrucha") m.push(words[word]); - w++; + append(...children) { + for (let child of children) { + var content = typeof child == 'string' ? document.createTextNode(child) : (child instanceof H ? child.element : child) + if (!(content instanceof Node)) { + if ((content instanceof NodeList) || (content instanceof Array)) { + for (var e of this.element) { + for (var se of content) { + e.appendChild(se) } } - - // break if requested amount is parsed - if(typeof amount!="undefined") - if(amount > 0) - if(key==amount) break; - } - - // merging words and count arrays - b=[]; - for(let key in a){ - b.push([a[key], ac[key]]); - } - - // sorting words by count - b.sort(function (a, b) { - if (a[1] === b[1]) { - return 0; - } - else { - return (a[1] > b[1]) ? -1 : 1; - } - }); - - response += "
    "+con.returnError("Done", "ok"); - response += "
    #### "+data.title+": ####" - - // top #10 words - let v = b.slice(0, 10); - var tp = []; - for(let key in v){ - tp.push([ ""+decodeURIComponent(escape(v[key][0]))+"", v[key][1] ]); - } - response += ToHtml.toTable(tp); - - // words by participant - var partic = []; - for(let key in data.participants){ - partic.push([""+decodeURIComponent(escape(data.participants[key].name))+"",data.participants[key].w.length]) - // response += "
    "+decodeURIComponent(escape(data.participants[key].name))+" words: "+data.participants[key].w.length; - } - response += ToHtml.toTable(partic); - - // response += ToHtml.toTable([ - // ["Monday", d[0]], - // ["Tuesday", d[1]], - // ["Wednesday", d[2]], - // ["Thursday", d[3]], - // ["Friday", d[4]], - // ["Saturday", d[5]], - // ["Sunday", d[6]] - // ]) - - // let hrs = []; - // for(let hours in h){ - // hrs.push([hours+":00", h[hours]]); - // } - - response += ToHtml.toGraph({ - type: 'line', - data: { - labels: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23], - datasets: [{ - label: '# per hour of day', - data: h, - backgroundColor: "#ffffff66", - borderColor: "#ffffff66", - borderWidth: 1 - }] - }, - options: { - maintainAspectRatio: false, - responsive: false, - scales: { - yAxes: [{ - ticks: { - beginAtZero:true - } - }] - } - } - }, 400, 200); - - response += ToHtml.toGraph({ - type: 'line', - data: { - labels: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], - datasets: [{ - label: '# per weekday', - data: d, - backgroundColor: "#ffffff66", - borderColor: "#ffffff66", - borderWidth: 1 - }] - }, - options: { - maintainAspectRatio: false, - responsive: false, - scales: { - yAxes: [{ - ticks: { - beginAtZero:true - } - }] - } - } - }, 400, 200); - - response += ToHtml.toTable([ - ["Total messages", data.messages.length], - ["Total words", w], - ["Unique words", a.length], - ["Total photos", p], - - ["Parsing time", (performance.now()-perf)+"ms"] - ]) - - // response += "
    "+"Unique words: "+a.length; - // response += "
    "+"Total photos: "+p; - // response += "
    "+"Total words: "+w; - // response += "
    "+"Parsing time: "+(performance.now()-perf)+"ms"; - - }else{ - response += "
    "+con.returnError("JSON structure invalid", "error"); + continue + } else + throw new Error("Invalid input argument") } - }else{ - response += "
    "+con.returnError("Invalid message file", "error"); + + for (let e of this.element) { + e.appendChild(content) + } + } - }else{ - response += "
    "+con.returnError("No json data loaded", "error"); + return this } - return response; -} - -function mesall(data, amount, con){ // parse mesenger chat information - var response = ""; - var perf = performance.now(); - - // check if json is loaded - response += "
    "+con.returnError("Checking data", "info"); - if(typeof data != "undefined"){ - - // check if participants are defined - response += "
    "+con.returnError("Loading participants", "info"); - if(typeof data.participants != "undefined"){ - - response += "
    "+con.returnError("Initializing variables", "info"); - var colors = {}; - - // unique words by participant - for(let key in data.participants){ - switch(key){ - case "0": - colors[data.participants[key].name] = "txgrn"; - break; - case "1": - colors[data.participants[key].name] = "txblu"; - break; - case "2": - colors[data.participants[key].name] = "txcya"; - break; - case "3": - colors[data.participants[key].name] = "txyel"; - break; - case "4": - colors[data.participants[key].name] = "txorn"; - break; - case "5": - colors[data.participants[key].name] = "txred"; - break; - case "6": - colors[data.participants[key].name] = "txpnk"; - break; - case "7": - colors[data.participants[key].name] = "txred"; - break; - default: - colors[data.participants[key].name] = "txdrk"; - break; - } - - } - - // check if messages are defined - response += "
    "+con.returnError("Parsing messages", "info"); - if(typeof data.messages != "undefined"){ - - // parse every message in file - var messages = data.messages.slice().reverse() - for(let key in messages){ - let col = colors[messages[key].sender_name] ? colors[messages[key].sender_name] : "txdrk"; - con.log("<"+col+">"+decodeURIComponent(escape(messages[key].sender_name))+": "+decodeURIComponent(escape(messages[key].content))); - - // break if requested amount is parsed - if(typeof amount!="undefined") - if(amount > 0) - if(key==amount) break; - } - - }else{ - response += "
    "+con.returnError("JSON structure invalid", "error"); - } - }else{ - response += "
    "+con.returnError("Invalid message file", "error"); - } - }else{ - response += "
    "+con.returnError("No json data loaded", "error"); + remove() { + this.element.forEach(e => { + e.parentNode.removeChild(e) + }) } - return null; + siblings() { + + var siblings = [] + + for (let e of this.element) { + var sibling = e.parentNode.firstChild; + + // Loop through each sibling and push to the array + while (sibling) { + if (sibling.nodeType === 1 && sibling !== e) { + siblings.push(sibling); + } + sibling = sibling.nextSibling + } + } + + return siblings; + }; + + data(obj) { + if (typeof obj == 'string') { + return this.element[0].dataset[obj] + } + for (let key in obj) { + this.element[0].dataset[key] = obj[key] + } + return this + } + + ready(fn) { + document.addEventListener('DOMContentLoaded', fn, false); + } + + on(e, t, f) { + switch (arguments.length) { + default: + case 1: throw new Error("Invalid arguments set") + case 2: + var ename = arguments[0], + target = '*', + fn = arguments[1] + break + case 3: + var ename = arguments[0], + target = arguments[1] + fn = arguments[2] + break + } + + for (let e of this.element) { + e.addEventListener(ename, e => { + if (e.target.matches(target)) + fn() + }); + } + + return this + + } + + static sel(selector) { + if (selector instanceof Node) return new H(selector) + return new H(document.querySelectorAll(selector)) + } } -class Elements{ - constructor($wind){ +function getCookie(cname) { + /** + * Get cookie + * @param {string} cname cookie name + * + * @returns {string} cookie content (undefined if doesn't exist) + */ - if(typeof $wind == "undefined"){ + var name = cname + "="; + var decodedCookie = decodeURIComponent(document.cookie); + var ca = decodedCookie.split(';'); + for (var i = 0; i < ca.length; i++) { + var c = ca[i]; + while (c.charAt(0) == ' ') { + c = c.substring(1); + } + if (c.indexOf(name) == 0) + return c.substring(name.length, c.length); + + } + return undefined; +} + +function setCookie(cname, cvalue, exdays) { + /** + * Set cookie + * @param cname cookie name + * @param cvalue cookie value + * @param exdays cookie expiry in days + * + * @returns {undefined} + */ + + var d = new Date(); + isDefined(exdays, 3650); + d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); + document.cookie = cname + "=" + cvalue + ";expires=" + d.toUTCString() + ";path=/"; +} + +// function escapeh(unsafe) { +// if (typeof unsafe != "string") return unsafe; +// return unsafe +// .replace(/&/g, "&") +// .replace(//g, ">") +// .replace(/"/g, """) +// .replace(/'/g, "'") +// } + +// function argq(arg){ +// var v = 0; +// var g = []; +// for (var ar in arg) { +// if((arg[ar].startsWith("\"")) || (arg[ar].startsWith("\'"))){ +// v=1; +// // g.push(arg[ar].slice(1)); +// if((arg[ar].endsWith("\"")) || (arg[ar].endsWith("\'"))){ +// g.push(arg[ar].slice(1, arg[ar].length-1)); +// v=0; +// } +// else +// g.push(arg[ar].slice(1)); + +// continue; +// }; +// if((arg[ar].endsWith("\"")) || (arg[ar].endsWith("\'"))){ +// v=0; +// g[g.length-1] += " "+arg[ar].slice(0, arg[ar].length-1); +// // g[g.length-1] = g[g.length-1].slice(1, g[g.length-1].length-1); +// continue; +// }; + +// if(!v){ +// g.push(arg[ar]); +// }else{ +// g[g.length-1] += " "+arg[ar] +// } +// } +// return g +// } + +function isDefined(...d) { + /** + * Check if argument is defined + * @param {...mixed} d any variable + * + * @returns {mixed} first given variable not of type 'undefined' + */ + + for (let key in d) { + if (typeof d[key] != "undefined") + return d[key] + } + return undefined +} + +function isNotEmpty(...d) { + /** + * Check if argument is not an empty string + * @param {...string} d any string + * + * @returns {string} first given string that is not empty + */ + + if (typeof v == "") + return d + else + return v +} + +function isWhat(what) { + /** + * Get short description of a variable + * @param {mixed} what + * + * @returns {string} [type Name|Type] + */ + + if (what) + if (what.name) + if (what.name != "") + return "[function " + what.name + "]" + + return "[" + typeof what + " " + (what ? what.constructor.name : "Undefined") + "]"; +} + +function getStackTrace() { + /** + * Get current call stack trace + * + * @returns {array} list of caller names + */ + + var obj = {}; // create stack trace object + + try { + Error.captureStackTrace(obj, getStackTrace); // capture stack to obj + } catch (error) { + return error // on error return + } + + obj = obj.stack.split("\n").slice(1); // split on newline, remove first element + for (let trace in obj) { + obj[trace] = obj[trace].slice(4); // remove whitespace at the beginning + } + + return obj + +} + +function makeID(n) { + /** + * Generate base64 id + * @param {int} n output length + * + * @returns {string} generated base64 string identificator + */ + + var out = ""; + var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"; + + for (var i = 0; i < n; i++) + out += chars.charAt(Math.floor(Math.random() * chars.length)); + + return out; +} + +function download(content, filename) { + /** + * Download variable as file + * @param {mixed} content any variable + * @param {string} filename name of downloaded file + * + * @returns {undefined} + */ + + var createObjectURL = (window.URL || window.webkitURL || {}).createObjectURL || function () { }; + var blob = null; + var mimeString = "application/octet-stream"; + window.BlobBuilder = window.BlobBuilder || + window.WebKitBlobBuilder || + window.MozBlobBuilder || + window.MSBlobBuilder; + + + if (window.BlobBuilder) { + var bb = new BlobBuilder(); + bb.append(content); + blob = bb.getBlob(mimeString); + } else { + blob = new Blob([content], { type: mimeString }); + } + var url = createObjectURL(blob); + var a = document.createElement("a"); + a.href = url + a.download = filename; + a.innerHTML = ""; + document.body.appendChild(a); + a.click() + a.remove() +} + +function toTree(obj, mdepth){ + /** + * Creates tree visualization of variable + * @param {any} obj variable to visualize + * @param {number} mdepth max visualization depth + * + * @returns {H} html visualization + */ + + var typeOf = function (o) { + var t = typeof o; + + if (o instanceof Array) return "array"; + if (o instanceof RegExp) return "regex"; + if (o === null) return "null"; + + return t + } + + var contentType = function (v, name) { + + var type = typeOf(v) + + switch (type) { + + case 'number': return $("").append(name ? name : "number") + case 'string': return $("").append(name ? name : "string") + case 'boolean': return $("").append(name ? name : "boolean") + case 'function': return $("").append(name ? name : "function") + case 'array': return $("").append(name ? name : "array") + case 'object': return $("").append(name ? name : "object") + case 'regex': return $("").append(name ? name : "regex") + case 'null': return $("").append(name ? name : "null") + case 'undefined': return $("").append(name ? name : "undefined") + default: return $("").append(name ? name : "?") + } + + } + + var $collapse = function (n) { + if (n) { + return $("") + .addClass("collapse") + .append( + $("") + .addClass('icon-plus-squared') + ) + } else { + return $("") + .addClass("collapse") + .append( + $("") + .addClass('icon-minus-squared') + ) + } + } + + var $recur = function (obj, depth) { + + let m = isDefined(mdepth, Config.treeDepth, 4); + const maxd = m <= 7 ? m : 7; // max depth + const maxn = 50; // max level length + const maxs = 150; // max string length + const maxc = 2; // level to collapse after + + var $list = $(""); + + var i = 0; + for (let key in obj) { + i++; + if (i > maxn) { + continue + } + + var content = obj[key]; // content + var type = typeOf(obj[key]); // content type + + + switch (type) { + case 'object': + case 'array': + if ($.isEmptyObject(content)) { // is content epmty + $list.append( // empty object + $("
  • ") + .append(contentType(content, key)) + .append(": ") + .append(`[empty]`) + ) + } else { // content not empty + if (depth > maxd) { // is max depth reached + $list.append( // function description (max depth reached) + $("
  • ") + .append(contentType(content, key)) + .append(": ") + .append(`${isWhat(content)}`) + ) + } else { // max depth not reached + $list.append( // continue recursion + $("
  • ") + .append(contentType(content, key)) + .append(": ") + .append( // collapse button + $collapse(depth >= maxc) + ) + .append($recur(content, depth + 1)) + ) + } + } + break; + + case 'function': + $list.append( + $("
  • ") + .append(contentType(content, key)) + .append(": ") + .append( + `${isWhat(content)}` + ) + ) + break; + + default: + $list.append( + $("
  • ") + .append(contentType(content, key)) + .append(": ") + .append(content) + ) + break; + } + + } + + if (i > maxn) { + + $list.append( + $("
  • ") + .append( + $("") + .append(`... ${i - maxn} more`) + ) + ) + + } + + if (depth > maxc) { + $list.hide() + } + + return $list + + } + + if (typeOf(obj) != "array" && typeOf(obj) != "object") + return $("").append(contentType(obj)).append(": ").append(obj + "") + + var $ascii = $("") + .addClass("ascii") + .append( + $("
  • ") + .append(contentType(obj)) + .append( + $collapse(false) + ) + .append($recur(obj, 1)) + ) + + return $ascii; + +} + +function toTable(content){ + /** + * Creates html table from 2D array + * @param {array} content 2d array + * + * @returns {H} html table from array + */ + + var $table = $("
    ") + + for (let row of content) { + let tr = $("") + for (let col of row) { + tr.append( + $("").append(col + "") + ) + } + $table.append(tr) + } + + return $table + +} + +function toGraph(data, x, y){ + /** + * Create chart.js graph + * @param {object} data chart.js configuration object + * @param {number} x graph width + * @param {number} y grap height + * + * @returns {H} chart.js html element with init script + */ + + var id = makeID(6); + + return `
    ` +} + +function toSyntax(data, lang){ + /** + * Text syntax highlighting + * @param {string} data text to highlight + * @param [lang] syntax language + */ + + if (lang) { + var langs = []; + langs.push(lang) + } + var hl = hljs.highlightAuto(data, lang); + var out = ""; + + var r = /(\<.*?\>)(.*?)(\<\/[\S]*?\>)/g; + + out = hl.value.replace(r, function (match, beg, mid, end) { + // console.log(beg+"|"+mid+"|"+end); + // console.log(beg+ mid.replace(/\n/g, `[\n]`) +end) + return beg + mid.replace(/\n/g, `${end}\n${beg}`) + end + }) + + // var match = r.exec(hl.value); + // while (match != null) { + // console.log(match[0]) + // out += match[1] + match[2].replace("\n", `${match[3]}\n${match[2]}`) + match[3] + // match = r.exec(hl.value); + // } + + + var lines = out.split("\n"); + var code = $("") + .append(``) + + /*for(let index in lines){ + code.append( + $("") + .addClass('hljs-newline') + .append(lines[index]) + // .prop( "data-int", " ".repeat( (lines.length.toString().length) - ((parseInt(index)+1).toString().length) ) + (parseInt(index)+1) ) + ) + .append("\n") + }*/ + code.append(hl.value) + + return $("
    ").append(code)
    +
    +	/*for(let index in lines){
    +		indexed+=`${lines[index]}\n`
    +	}
    +
    +	return `
    ${indexed}
    `*/ +} + +// function updateInfo(res) { +// // refresh status informations + +// // var rp = JSON.parse(res); // parse json + +// if (($(".info0")[0]) && (res.type == "uptime")) { +// $(".info0").html(res["uptime"]); +// $(".info1").html(res["load1"]); +// $(".info2").html(res["load2"]); +// $(".info3").html(res["load3"]); +// $(".info4").html(res["memory"]); +// $(".info5").html(res["users"]); +// } +// // update uptime section + +// if (($(".info6")[0]) && (res.type == "stats")) { +// $(".info6").html(res["tempout"]); +// $(".info7").html(res["tempin"]); +// $(".info8").html(res["humout"]); +// $(".info9").html(res["humin"]); +// } +// // update stats section + +// if (($(".info10")[0]) && (res.type == "network")) { +// var nl = ""; +// for (var i = 0; i < res['network'].length; i++) { +// nl += "
  • " + res['network'][i] + "
  • "; +// } +// nl += '
  • Raspberry
  • '; +// $(".info10").html(nl); +// } +// // update devices section +// } + +// function setStyle() { +// setstyle: function setstyle(name){ // set style theme +// if(!name) var name = ""; + +// if(name != ""){ +// log("Style: "+name, "info"); +// setCookie("style", name); +// $('head').append(''); +// }else{ +// log("Style "+name+" doesn't exist, using default preset", "warning"); +// setstyle("default"); +// } +// }, +// } + +// function mesparse(data, amount, con) { // parse mesenger chat information +// var response = ""; +// var perf = performance.now(); + +// // check if json is loaded\ +// if (typeof data != "undefined") { + +// // check if participants are defined\ +// if (typeof data.participants != "undefined") { + +// l = []; // links +// p = 0; // pics +// a = []; // unique words +// ac = []; // unique words counter +// w = 0; // word counter +// d = [0, 0, 0, 0, 0, 0, 0] // weekdays +// h = new Array(24).fill(0); + +// // unique words by participant +// for (let key in data.participants) { +// data.participants[key].w = []; +// } + +// // check if messages are defined\ +// if (typeof data.messages != "undefined") { + +// // parse every message in file +// for (let key in data.messages) { + +// // check if content is present +// if (typeof data.messages[key].content != "undefined") { + +// let x = new Date(); +// x.setTime(data.messages[key].timestamp_ms); +// d[x.getDay()] += 1; +// h[x.getHours()] += 1; + +// // check if message is a photo +// if (data.messages[key].photos) { +// p++; +// continue; +// } + +// data.messages[key].content = data.messages[key].content.replace(/ +(?= )/g, ''); +// words = data.messages[key].content.split(" "); + +// for (let word in words) { + +// let i = a.indexOf(words[word]); +// if (i == -1) { +// a.push(words[word]); +// ac.push(1); +// } else { +// ac[i] += 1; +// } + +// for (let p in data.participants) { +// if (data.messages[key].sender_name == data.participants[p].name) +// data.participants[p].w.push(words[word]) +// } +// // if(data.messages[key].sender_name == "Sebastian Fudalej") s.push(words[word]); +// // else if(data.messages[key].sender_name == "Mateusz Pstrucha") m.push(words[word]); +// w++; +// } +// } + +// // break if requested amount is parsed +// if (typeof amount != "undefined") +// if (amount > 0) +// if (key == amount) break; +// } + +// // merging words and count arrays +// b = []; +// for (let key in a) { +// b.push([a[key], ac[key]]); +// } + +// // sorting words by count +// b.sort(function (a, b) { +// if (a[1] === b[1]) { +// return 0; +// } +// else { +// return (a[1] > b[1]) ? -1 : 1; +// } +// }); + +// response += "
    " + con.returnError("Done", "ok"); +// response += "
    #### " + data.title + ": ####" + +// // top #10 words +// let v = b.slice(0, 10); +// var tp = []; +// for (let key in v) { +// tp.push(["" + decodeURIComponent(escape(v[key][0])) + "", v[key][1]]); +// } +// response += toTable(tp); + +// // words by participant +// var partic = []; +// for (let key in data.participants) { +// partic.push(["" + decodeURIComponent(escape(data.participants[key].name)) + "", data.participants[key].w.length]) +// // response += "
    "+decodeURIComponent(escape(data.participants[key].name))+" words: "+data.participants[key].w.length; +// } +// response += toTable(partic); + +// // response += toTable([ +// // ["Monday", d[0]], +// // ["Tuesday", d[1]], +// // ["Wednesday", d[2]], +// // ["Thursday", d[3]], +// // ["Friday", d[4]], +// // ["Saturday", d[5]], +// // ["Sunday", d[6]] +// // ]) + +// // let hrs = []; +// // for(let hours in h){ +// // hrs.push([hours+":00", h[hours]]); +// // } + +// response += toGraph({ +// type: 'line', +// data: { +// labels: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], +// datasets: [{ +// label: '# per hour of day', +// data: h, +// backgroundColor: "#ffffff66", +// borderColor: "#ffffff66", +// borderWidth: 1 +// }] +// }, +// options: { +// maintainAspectRatio: false, +// responsive: false, +// scales: { +// yAxes: [{ +// ticks: { +// beginAtZero: true +// } +// }] +// } +// } +// }, 400, 200); + +// response += toGraph({ +// type: 'line', +// data: { +// labels: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], +// datasets: [{ +// label: '# per weekday', +// data: d, +// backgroundColor: "#ffffff66", +// borderColor: "#ffffff66", +// borderWidth: 1 +// }] +// }, +// options: { +// maintainAspectRatio: false, +// responsive: false, +// scales: { +// yAxes: [{ +// ticks: { +// beginAtZero: true +// } +// }] +// } +// } +// }, 400, 200); + +// response += toTable([ +// ["Total messages", data.messages.length], +// ["Total words", w], +// ["Unique words", a.length], +// ["Total photos", p], + +// ["Parsing time", (performance.now() - perf) + "ms"] +// ]) + +// // response += "
    "+"Unique words: "+a.length; +// // response += "
    "+"Total photos: "+p; +// // response += "
    "+"Total words: "+w; +// // response += "
    "+"Parsing time: "+(performance.now()-perf)+"ms"; + +// } else { +// response += "
    " + con.returnError("JSON structure invalid", "error"); +// } +// } else { +// response += "
    " + con.returnError("Invalid message file", "error"); +// } +// } else { +// response += "
    " + con.returnError("No json data loaded", "error"); +// } + +// return response; +// } + +// function mesall(data, amount, con) { // parse mesenger chat information +// var response = ""; +// var perf = performance.now(); + +// // check if json is loaded +// response += "
    " + con.returnError("Checking data", "info"); +// if (typeof data != "undefined") { + +// // check if participants are defined +// response += "
    " + con.returnError("Loading participants", "info"); +// if (typeof data.participants != "undefined") { + +// response += "
    " + con.returnError("Initializing variables", "info"); +// var colors = {}; + +// // unique words by participant +// for (let key in data.participants) { +// switch (key) { +// case "0": +// colors[data.participants[key].name] = "txgrn"; +// break; +// case "1": +// colors[data.participants[key].name] = "txblu"; +// break; +// case "2": +// colors[data.participants[key].name] = "txcya"; +// break; +// case "3": +// colors[data.participants[key].name] = "txyel"; +// break; +// case "4": +// colors[data.participants[key].name] = "txorn"; +// break; +// case "5": +// colors[data.participants[key].name] = "txred"; +// break; +// case "6": +// colors[data.participants[key].name] = "txpnk"; +// break; +// case "7": +// colors[data.participants[key].name] = "txred"; +// break; +// default: +// colors[data.participants[key].name] = "txdrk"; +// break; +// } + +// } + +// // check if messages are defined +// response += "
    " + con.returnError("Parsing messages", "info"); +// if (typeof data.messages != "undefined") { + +// // parse every message in file +// var messages = data.messages.slice().reverse() +// for (let key in messages) { +// let col = colors[messages[key].sender_name] ? colors[messages[key].sender_name] : "txdrk"; +// con.log("<" + col + ">" + decodeURIComponent(escape(messages[key].sender_name)) + ": " + decodeURIComponent(escape(messages[key].content))); + +// // break if requested amount is parsed +// if (typeof amount != "undefined") +// if (amount > 0) +// if (key == amount) break; +// } + +// } else { +// response += "
    " + con.returnError("JSON structure invalid", "error"); +// } +// } else { +// response += "
    " + con.returnError("Invalid message file", "error"); +// } +// } else { +// response += "
    " + con.returnError("No json data loaded", "error"); +// } + +// return null; +// } + +class Elements { + constructor($wind) { + + if (typeof $wind == "undefined") { var $wind = $("
    ") .addClass("wind") .append( @@ -776,8 +1009,8 @@ class Elements{ this.$commin = $wind.children(".commline").children(".commin"); this.$jsonl = $wind.children(".jsonl"); - this.$commin.on("blur", function(){ - if($(this).closest(".wind").data("con").scroll){ + this.$commin.on("blur", function () { + if ($(this).closest(".wind").data("con").scroll) { this.focus(); } }) @@ -787,74 +1020,74 @@ class Elements{ this.icons = {}; this.icons.$trash = icons.children("i.icon-trash"); - this.icons.$trash.on("click", function(){ + this.icons.$trash.on("click", function () { $(this).closest(".wind").data("con").clear(); }) this.icons.$levelDown = icons.children("i.icon-level-down"); - this.icons.$levelDown.on("click", function(){ + this.icons.$levelDown.on("click", function () { $(this).closest(".wind").data("con").scrollBottom(true); }) this.icons.$volume = icons.children("i.icon-volume-up"); this.icons.$lock = icons.children("i.icon-lock-open"); - this.icons.$lock.change = function(){ + this.icons.$lock.change = function () { var con = $wind.data("con") - if(!con.scroll){ + if (!con.scroll) { this.removeClass(); this.addClass("icon-lock-open"); con.scroll = true; con.elements.$commin.focus(); - }else{ + } else { this.removeClass(); this.addClass("icon-lock"); con.scroll = false; } } - this.icons.$lock.on("click", function(){ + this.icons.$lock.on("click", function () { $(this).closest(".wind").data("con").elements.icons.$lock.change(); }); this.icons.$connection = icons.children("i.icon-unlink"); - this.icons.$connection.blink = function(){ + this.icons.$connection.blink = function () { this.addClass("txgrn glow"); - setTimeout(function(icon){ + setTimeout(function (icon) { icon.removeClass("txgrn glow"); }, 200, this); } - this.icons.$connection.on("click", function(){ + this.icons.$connection.on("click", function () { $(this).closest(".wind").data("con").executeCom("connection"); }) - this.icons.$lock.enable = function(){ + this.icons.$lock.enable = function () { this.removeClass(); this.addClass("icon-lock-closed"); } - this.icons.$lock.disable = function(){ + this.icons.$lock.disable = function () { this.removeClass(); this.addClass("icon-lock"); } - this.icons.$connection.enable = function(){ + this.icons.$connection.enable = function () { this.removeClass(); this.addClass("icon-link"); } - this.icons.$connection.disable = function(){ + this.icons.$connection.disable = function () { this.removeClass(); this.addClass("icon-unlink"); } this.$commline = $wind.children(".commline"); - this.$commline.enable = function(){ + this.$commline.enable = function () { this.children(".commin").prop('disabled', false); this.css("filter", "grayscale(0%)"); } - this.$commline.disable = function(){ + this.$commline.disable = function () { this.children(".commin").prop('disabled', true); this.css("filter", "grayscale(1000%)"); } - this.$commuser.change = function(user, badge){ + this.$commuser.change = function (user, badge) { this.html(user); this.removeClass(); this.addClass(badge); @@ -865,8 +1098,8 @@ class Elements{ } -class Request{ - constructor(com){ +class Request { + constructor(com) { this.com = com.c; this.arg = com.arg; this.dir = com.arg; @@ -878,10 +1111,10 @@ class Request{ } -class Com{ - constructor(cc, data, con){ +class Com { + constructor(cc, data, con) { this.con = con; // parent Con object - this.id = Tools.makeID(15); // base64 ID + this.id = makeID(15); // base64 ID this.cc = cc; // full command from input (string) this.c = data.c; // executed command (string) @@ -892,7 +1125,7 @@ class Com{ this.$ud = undefined; // Com UserData this.$sr = undefined // server response this.formatted = undefined; // formatted server response data (mixed) - this.stack = Tools.getStackTrace(); // current stack trace (array) + this.stack = getStackTrace(); // current stack trace (array) this.timer = undefined; this.time = performance.now(); @@ -904,7 +1137,7 @@ class Com{ } // append Com object to Con.commands - append(){ + append() { this.$elem = $("
    ") .prop("id", this.id) .addClass("command") @@ -913,23 +1146,23 @@ class Com{ .addClass("ud") .append( $("") - .addClass(this.con.udata.badge) - .append(this.con.udata.login) + .addClass(this.con.udata.badge) + .append(this.con.udata.login) ) .append("@") .append( $("") - .append(document.title) + .append(document.title) ) .append(":") .append( $("") - .append(this.con.elements.$commpath.html()) + .append(this.con.elements.$commpath.html()) ) .append(" $ ") .append( $("") - .append(this.cc) + .append(this.cc) ) ) .data("com", this); @@ -938,11 +1171,11 @@ class Com{ } - receive(data){ + receive(data) { this.res = data; - switch(this.res.flag){ + switch (this.res.flag) { default: case 0: // standard response, append data as plaintext this.formatted = this.res.data; @@ -953,10 +1186,10 @@ class Com{ this.con.auth(this.res.udata); - Tools.setCookie("user", r.user); - Tools.setCookie("session", r.session); + setCookie("user", r.user); + setCookie("session", r.session); - if((r.user == "") && (r.session=="")) + if ((r.user == "") && (r.session == "")) this.log('Loged out succesfully', "ok"); else this.log('Loged in succesfully', "ok"); @@ -983,38 +1216,38 @@ class Com{ case 8: // auth this.con.auth(this.response.data); break; - case 9: // ToHtml.toTree - this.formatted = ToHtml.toTree(this.res.data); + case 9: // toTree + this.formatted = toTree(this.res.data); this.insertResponse(); break; - case 10: // ToHtml.toTable - this.formatted = ToHtml.toTable(this.res.data); + case 10: // toTable + this.formatted = toTable(this.res.data); this.insertResponse(); break; - case 11: // ToHtml.toSyntax - this.formatted = ToHtml.toSyntax(this.res.data); + case 11: // toSyntax + this.formatted = toSyntax(this.res.data); this.insertResponse(); break; case 12: // ping this.formatted = - `${this.res.data} [${Math.floor(((performance.now() - this.time)-this.res.time[this.res.time.length-1][0]) * 1000) / 1000} ms]`; + `${this.res.data} [${Math.floor(((performance.now() - this.time) - this.res.time[this.res.time.length - 1][0]) * 1000) / 1000} ms]`; this.insertResponse(); break; } } - local(){ + local() { - switch(this.c){ + switch (this.c) { default: - if(this.con.socket.connected!=true){ + if (this.con.socket.connected != true) { this.log("socket disconnected", "error"); this.insertResponse(); return 1; } - switch(this.c){ + switch (this.c) { default: return 0; break; case "welcome": @@ -1049,9 +1282,9 @@ class Com{ break; case "eval": - try{ - this.formatted = ToHtml.toTree(eval(this.arg.join(" "))); - }catch(error){ + try { + this.formatted = toTree(eval(this.arg.join(" "))); + } catch (error) { console.error(error); this.log(error, "error"); } @@ -1059,7 +1292,7 @@ class Com{ break; case "json": - switch(this.arg[0]){ + switch (this.arg[0]) { default: this.formatted = `length: ${jsond.length}`; this.insertResponse(); @@ -1071,7 +1304,7 @@ class Com{ break; case "messenger": - switch(this.arg[1]){ + switch (this.arg[1]) { default: this.formatted = mesparse(this.con.jsond, this.arg[1], this.con); this.insertResponse(); @@ -1085,7 +1318,7 @@ class Com{ break; case "tree": - this.formatted = ToHtml.toTree(jsond); + this.formatted = toTree(jsond); this.insertResponse(); break; } @@ -1104,36 +1337,36 @@ class Com{ } - remove(){ + remove() { this.$elem.remove(); } - stopLoading(){ - this.ud.attr("loading", null); + stopLoading() { + this.$ud.attr("loading", null); } - startLoading(){ - this.ud.attr("loading", " "); + startLoading() { + this.$ud.attr("loading", " "); this.time = performance.now() } - addForm(obj, type){ + addForm(obj, type) { this.con.scrollBottom(); // scroll to EOP this.con.elements.$commline.disable(); // disable commline var form = $("
    ") // create form Node - for(let key in obj.label){ // for every label add label Node + for (let key in obj.label) { // for every label add label Node form.append( - $("") - .append(`${obj.label[key]}: `) - .append( - $("") - .prop("type", obj.type[key]) - .prop("name", obj.name[key]) - ) - .append("
    ") - ) + $("") + .append(`${obj.label[key]}: `) + .append( + $("") + .prop("type", obj.type[key]) + .prop("name", obj.name[key]) + ) + .append("
    ") + ) } this.$elem.append(form); // add form to Com elem @@ -1141,26 +1374,26 @@ class Com{ } - sendForm(){ + sendForm() { - var form = this.$elem.find("form"); // find Com form - var obj = {}; // create response object + var form = this.$elem.find("form"); // find Com form + var obj = {}; // create response object - this.removeForm(); // disable form + this.removeForm(); // disable form - form.children("label").each(function(index){ - // add each input value to response object with property name from input name - obj[ $(this).children("input").prop('name') ] = $(this).children("input").val() != "on" ? $(this).children("input").val() : $(this).children("input").is(":checked"); - }); + form.children("label").each(function (index) { + // add each input value to response object with property name from input name + obj[$(this).children("input").prop('name')] = $(this).children("input").val() != "on" ? $(this).children("input").val() : $(this).children("input").is(":checked"); + }); - this.arg = obj; // set Com arguments as response object - this.send(); // send Com + this.arg = obj; // set Com arguments as response object + this.send(); // send Com - } + } - removeForm(){ + removeForm() { - this.$elem.find("form").children("label").each(function(index){ // form label of Com + this.$elem.find("form").children("label").each(function (index) { // form label of Com $(this).children("input").prop('readonly', true); // set each input to 'readonly' }); @@ -1168,11 +1401,11 @@ class Com{ } - insertResponse(){ + insertResponse() { this.stopLoading(); // stop loading animation - if(this.res === null) return; // if response is null (server timed out) stop + if (this.res === null) return; // if response is null (server timed out) stop this.timeout(true); // server responded ok @@ -1190,12 +1423,12 @@ class Com{ } - timeout(ok){ + timeout(ok) { - if(ok){ // server responded - if(this.timer) clearTimeout(this.timer); // clear timer + if (ok) { // server responded + if (this.timer) clearTimeout(this.timer); // clear timer this.time = performance.now() - this.time; // calculate response time - }else{ // server timed-out + } else { // server timed-out this.log("Server timeout", "error"); // add error message this.res = null; this.insertResponse(); @@ -1203,26 +1436,26 @@ class Com{ } - send(){ - if(this.res) return; // if response is defined, stop + send() { + if (this.res) return; // if response is defined, stop this.startLoading(); // start loading animation this.req = new Request(this); // create Request object this.con.socket.emit("com", this.req); // send Request object - this.timer = setTimeout(function(com){ // set server timeout + this.timer = setTimeout(function (com) { // set server timeout com.timeout(false); // call server response timeout }, this.con.timeout, this); // Con.timeout time, Com object } } -class Con{ +class Con { - constructor($wind){ + constructor($wind) { - this.id = Tools.makeID(6) // Con ID + this.id = makeID(6) // Con ID this.socket = undefined; // socket connection object this.elements = new Elements($wind); // DOM elements object @@ -1232,34 +1465,34 @@ class Con{ counter: 0, commands: [""], - push(com){ + push(com) { this.commands.push(com) this.counter = 0 return this }, - increment(){ + increment() { this.counter++ - if(this.counter>this.commands.length-1) this.counter = 0 + if (this.counter > this.commands.length - 1) this.counter = 0 return this }, - decrement(){ + decrement() { this.counter-- - if(this.counter<0) this.counter = this.commands.length-1 + if (this.counter < 0) this.counter = this.commands.length - 1 return this }, - current(){ + current() { return this.commands[this.counter] }, - get up(){ + get up() { this.decrement() return this.commands[this.counter] }, - get down(){ + get down() { this.increment() return this.commands[this.counter] } @@ -1278,7 +1511,7 @@ class Con{ // auth credentials this.credentials = { - token: Tools.getCookie("token") + token: getCookie("token") } // trigger ready event after init @@ -1286,51 +1519,51 @@ class Con{ } - set uAuth(val){ + set uAuth(val) { this.log(`Auth flag change: ${val}`, "warning", 2); - if((val === true) || (val === false)) + if ((val === true) || (val === false)) this.udataExp = val - if(!val) this.log("User auth data expired", "warning", 2) + if (!val) this.log("User auth data expired", "warning", 2) } - get uAuth(){ + get uAuth() { return this.udataExp } - receive(res){ + receive(res) { this.log(`Received Com #${res.id} data`, "info", 3); this.getCom(res.id).receive(res); } - auth(udata){ + auth(udata) { this.udata = udata; this.uAuth = true; con.log("Auth data received", "ok", 2); this.elements.$commuser.change(this.udata.login, this.udata.badge); - if(!this.fAuth) this.firstAuth() + if (!this.fAuth) this.firstAuth() } - tryAuth(){ + tryAuth() { con.socket.emit("auth", con.credentials); con.log("Requesting authentication", "info", 2); } - removeCom(id){ + removeCom(id) { this.log("Removing Com #${id} element", "warning", 2); - for(let key in this.coms){ - if(this.coms[key].id===id){ + for (let key in this.coms) { + if (this.coms[key].id === id) { this.coms[key].remove(); this.log("Com #${id} removed", "info", 2); return true @@ -1342,10 +1575,10 @@ class Con{ } - getCom(id){ + getCom(id) { - for(let key in this.coms){ - if(this.coms[key].id==id) return this.coms[key]; + for (let key in this.coms) { + if (this.coms[key].id == id) return this.coms[key]; } this.log(`Com #${id} not found`, "error", 2); @@ -1353,13 +1586,13 @@ class Con{ } - get lastCom(){ - return this.coms[con.coms.length-1] + get lastCom() { + return this.coms[con.coms.length - 1] } - clear(){ + clear() { - for(let com of this.coms){ + for (let com of this.coms) { this.log(`Removing Com #${com.id}`, "info", 2); com.remove(); } @@ -1368,7 +1601,7 @@ class Con{ } - executeCom(val){ + executeCom(val) { this.log(`Force Com execute: ${val}`, "info", 2); this.elements.$commin.val(val); @@ -1376,15 +1609,15 @@ class Con{ } - log(data, opt, lvl){ + log(data, opt, lvl) { - var lvl = Tools.isDefined(lvl, 1); + var lvl = isDefined(lvl, 1); - if(lvl > this.verbose) return + if (lvl > this.verbose) return - var opt = Tools.isDefined(opt, ""); + var opt = isDefined(opt, ""); - switch(opt){ + switch (opt) { default: case "info": opt = ['txblu', 'Info']; break; case "warning": opt = ['txyel', 'Warning']; break; @@ -1397,20 +1630,20 @@ class Con{ .addClass('inline') .append( $('') - .addClass( opt[0] ) - .append( "#".repeat(lvl) ) - .append( ` ${opt[1]}: ` ) + .addClass(opt[0]) + .append("#".repeat(lvl)) + .append(` ${opt[1]}: `) ) .append(data) - if(this instanceof Con){ + if (this instanceof Con) { var lastlog = this.elements.$commands.children().last(); - if(lastlog.text() == out.text()){ + if (lastlog.text() == out.text()) { let tx = lastlog.children('tx') - if(!lastlog.hasClass('duplicate')) lastlog.addClass('duplicate') + if (!lastlog.hasClass('duplicate')) lastlog.addClass('duplicate') - let d = Tools.isDefined(tx.attr('data-duplicate'), 1) + let d = isDefined(tx.attr('data-duplicate'), 1) d = parseInt(d) d += 1 d = d.toString() @@ -1419,22 +1652,22 @@ class Con{ return } - this.elements.$commands.append( out ); + this.elements.$commands.append(out); this.scrollBottom(false) - }else if(this instanceof Com){ - this.elem.append( out ) + } else if (this instanceof Com) { + this.$elem.append(out) } } - commandlineParse(){ // command send event + commandlineParse() { // command send event - if(this.elements.$commin.is(":hidden")) return; // if commandline is blocked (hidden), stop executing + if (this.elements.$commin.is(":hidden")) return; // if commandline is blocked (hidden), stop executing var c = this.elements.$commin.val(); // get command query this.elements.$commin.val(""); // clear commandline input - if(c=="") return; + if (c == "") return; this.history.push(c) @@ -1443,12 +1676,12 @@ class Con{ var cc = c; - if(c.indexOf(' ') > -1){ // check for for arguments + if (c.indexOf(' ') > -1) { // check for for arguments var arg = c.split(" "); // split string c = arg.shift(); - }else arg = []; // if the arent any arguments specified, set var to empty json + } else arg = []; // if the arent any arguments specified, set var to empty json - // arg = Tools.argq(arg); // join quotes + // arg = argq(arg); // join quotes c = c.toLowerCase(); // command to lowercase (for mobile) @@ -1462,58 +1695,58 @@ class Con{ // } // } - var com = new Com(cc, {c: c, arg: arg}, this); + var com = new Com(cc, { c: c, arg: arg }, this); this.coms.push(com); // if(c=="m") com.content = this.returnError("-> "+arg[0]+": "+arg[1], "message"); com.append(); // append executed command to div - if(com.local()) return; // local command parsing + if (com.local()) return; // local command parsing com.send(); } - getScroll(){ // get scroll distance to bottom + getScroll() { // get scroll distance to bottom - var s = this.elements.$wind.scrollTop()-(this.elements.$wind.prop('scrollHeight')-this.elements.$wind.outerHeight()); - if(s>=0)s=0; - else s = s*-1; + var s = this.elements.$wind.scrollTop() - (this.elements.$wind.prop('scrollHeight') - this.elements.$wind.outerHeight()); + if (s >= 0) s = 0; + else s = s * -1; return s } - scrollBottom(f){ // scroll to the bottom + scrollBottom(f) { // scroll to the bottom - let force = Tools.isDefined(f, false); - if(force) return; + let force = isDefined(f, false); + if (force) return; let a = this.elements.$commands.children(); let b = this.elements.$commands.children().children(); var to = 0; - for(let index of a) + for (let index of a) to += index.scrollHeight - for(let index of b) + for (let index of b) to += index.scrollHeight - this.elements.$commands.stop().animate({scrollTop: to}, 200, 'swing', function(){}); + this.elements.$commands.stop().animate({ scrollTop: to }, 200, 'swing', function () { }); } - updateInputWidth(){ - var w = this.elements.$ud.width()+20; + updateInputWidth() { + var w = this.elements.$ud.width() + 20; this.elements.$commin.css({ 'width': `calc(100% - ${w}px)` }); return w; } - commandHistory(key){ + commandHistory(key) { // if(key==38) // this.elements.commin.val(this.history.up); // else if(key==40) // this.elements.commin.val(this.history.down); - this.elements.$commin.val( key==38 ? this.history.up : (key==40?this.history.down:"") ); + this.elements.$commin.val(key == 38 ? this.history.up : (key == 40 ? this.history.down : "")); this.elements.$commin.focus(); } @@ -1540,26 +1773,26 @@ class Con{ // this.elements.commin.val(this.lastc[this.lc]); // } - readJson(data){ - var file = data.target.files[0]; - var reader = new FileReader(); + readJson(data) { + var file = data.target.files[0]; + var reader = new FileReader(); reader.con = $(this).closest(".wind").data("con"); - reader.onload = function(event){ - try{ + reader.onload = function (event) { + try { this.con.jsond = JSON.parse(event.target.result); this.con.log("JSON loaded", "ok"); - }catch(error){ + } catch (error) { this.con.log(`JSON parsing error: ${error}`, "error"); } - } + } reader.readAsText(file, "UTF-8"); } - firstAuth(){ - if(location.hash != ""){ + firstAuth() { + if (location.hash != "") { this.log(`Executing command from URI (${location.hash.slice(1)})`, "info", 3) this.executeCom(decodeURIComponent(location.hash.slice(1))); } @@ -1573,7 +1806,7 @@ class Con{ } // Con init ready event - ready(){ + ready() { $(this.elements.$wind).prop("id", this.id); // attach Con id to DOM $(this.elements.$wind).data("con", this); // attach Con object to DOM @@ -1582,18 +1815,18 @@ class Con{ // socket event register function modification (pass additional parameter) this.socket.originalOn = this.socket.on; - this.socket.on = function(event, data, callback){ - return this.originalOn.call(this, event, (e) => callback(e, data)); + this.socket.on = function (event, data, callback) { + return this.originalOn.call(this, event, (e) => callback(e, data)); }; // socket connecting start event - this.socket.on('connecting', this, function(data, con){ + this.socket.on('connecting', this, function (data, con) { con.log("Conecting...", "info", 2); }); // socket disconnected event - this.socket.on("disconnect", this, function(data, con){ + this.socket.on("disconnect", this, function (data, con) { con.log(`Disconnected from server: ${data}`, "warning"); con.elements.icons.$connection.disable(); con.uAuth = false @@ -1601,13 +1834,13 @@ class Con{ }) // socket connection error event - this.socket.on("connect_error", this, function(data, con){ + this.socket.on("connect_error", this, function (data, con) { con.log(data, "error"); }) // socket succesfully connected event - this.socket.on('connect', this, function(data, con){ + this.socket.on('connect', this, function (data, con) { con.log("Conected to the server", "ok"); con.elements.icons.$connection.enable(); @@ -1616,7 +1849,7 @@ class Con{ }); // dynamic (refreshed) data update - this.socket.on("dynamic", this, function(data, con){ + this.socket.on("dynamic", this, function (data, con) { con.elements.icons.$connection.blink(); console.log(data) // /ChangeDom.updateInfo(data); @@ -1624,69 +1857,69 @@ class Con{ }) // message broadcast (private & public) event - this.socket.on("broadcast", this, function(data, con){ + this.socket.on("broadcast", this, function (data, con) { con.elements.icons.$connection.blink(); con.log(data.data, "message"); con.m = data.frm; con.scrollBottom(true); - if(data.imp) alert("Broadcast message received"); + if (data.imp) alert("Broadcast message received"); notif.play(); con.m = data.frm; }) // remote execute event - this.socket.on("eval", this, function(data, con){ + this.socket.on("eval", this, function (data, con) { con.elements.icons.$connection.blink(); $("head").append(eval(data.data)); }) // socket receive auth data event - this.socket.on('auth', this, function(res, con){ + this.socket.on('auth', this, function (res, con) { con.elements.icons.$connection.blink(); con.auth(res); }); // socket receive com response event - this.socket.on('com', this, function(res, con){ + this.socket.on('com', this, function (res, con) { con.elements.icons.$connection.blink(); con.receive(res); }); // command input key handling - this.elements.$commline.on("keydown", "input", function(e) { + this.elements.$commline.on("keydown", "input", function (e) { var con = $(this).closest(".wind").data("con"); - switch(e.which){ + switch (e.which) { // ENTER key case 13: con.commandlineParse(); // commandline handling - break; + break; // KEYUP key // KEYDOWN key case 38: case 40: con.commandHistory(e.which); e.preventDefault(); // last command down - break; + break; // ESCAPE key case 27: con.elements.$commin.val("") // clear input - break; + break; } }); // tree collapse subtree click handling - this.elements.$wind.on("click", ".collapse", function(e){ + this.elements.$wind.on("click", ".collapse", function (e) { var collapse = $(this); collapse.parent().children("ul").slideToggle(200) - if(collapse.children("i").hasClass("icon-minus-squared")){ + if (collapse.children("i").hasClass("icon-minus-squared")) { collapse.children("i").removeClass(); collapse.children("i").addClass("icon-plus-squared"); - }else{ + } else { collapse.children("i").removeClass(); collapse.children("i").addClass("icon-minus-squared"); } @@ -1694,37 +1927,37 @@ class Con{ }) // focus on input on 'enter' - this.elements.$wind.on("keydown", function(e){ + this.elements.$wind.on("keydown", function (e) { var con = $(this).data("con"); - switch(e.which){ + switch (e.which) { // ENTER key case 13: con.elements.$commin.focus(); // focus on input - break; + break; } }) // form key handling - this.elements.$commands.on("keydown", "form", function(e){ + this.elements.$commands.on("keydown", "form", function (e) { var com = $(this).closest(".command").data("com"); - switch(e.which){ + switch (e.which) { case 13: com.sendForm(); // send form [enter] - break; + break; case 27: com.removeForm(); // remove form [escape] - break; + break; } }); // link click handling - this.elements.$wind.on("click", "a", function(e){ + this.elements.$wind.on("click", "a", function (e) { var a = $(this); var href = a.prop("href"); href = href.slice(href.indexOf("#")); - if(href.startsWith("#")){ + if (href.startsWith("#")) { e.preventDefault(); a.closest(".wind").data("con").executeCom(decodeURIComponent(href.slice(1))) } @@ -1734,8 +1967,8 @@ class Con{ this.elements.$jsonl[0].addEventListener('change', this.readJson, false); // 'accept cookies' prompt - if(typeof Tools.getCookie("cookies") == "undefined"){ - Tools.setCookie("cookies", "1"); + if (typeof getCookie("cookies") == "undefined") { + setCookie("cookies", "1"); this.log("This site uses cookies. By continuing, you agree to our use of cookies. Learn more", "warning") } @@ -1754,7 +1987,7 @@ var Config = { serviceWorker: false // enable serviceWorker } -$(document).ready(function(){ +$(document).ready(function () { $("noscript").remove(); // remove 'js disabled' notice Config.notif.volume = 0.3; // lower notification volume @@ -1762,20 +1995,20 @@ $(document).ready(function(){ Config.cons.push(new Con()); // init new Con con = Config.cons[0]; // attach main Con to 'con' variable (for easier debugging) - if('serviceWorker' in navigator && Config.serviceWorker){ // check is serviceWorker is available + if ('serviceWorker' in navigator && Config.serviceWorker) { // check is serviceWorker is available navigator.serviceWorker .register('service-worker.js') .then(reg => console.log('sw registered')) .catch(error => console.log(`sw error: ${error}`)) } - setInterval(function(){ // loading animation - if($(".ud").length) $(".ud").each(function(index){ // for every Com + setInterval(function () { // loading animation + if ($(".ud").length) $(".ud").each(function (index) { // for every Com var c = $(this); var s = c.attr('loading'); - if(typeof s == "undefined") return; // return if Com is not loading + if (typeof s == "undefined") return; // return if Com is not loading - switch(s){ + switch (s) { case "[--------]": c.attr('loading', '[#-------]'); break; case "[#-------]": c.attr('loading', '[##------]'); break; case "[##------]": c.attr('loading', '[###-----]'); break; diff --git a/views/pages/header.ejs b/views/pages/header.ejs index c2c85c9..3d74608 100644 --- a/views/pages/header.ejs +++ b/views/pages/header.ejs @@ -44,5 +44,5 @@ - + diff --git a/views/pages/manifest.json b/views/pages/manifest.json deleted file mode 100644 index 0b83797..0000000 --- a/views/pages/manifest.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "short_name": "mpp", - "name": "My app", - "icons": [ - { - "src": "/images/icons-192.png", - "type": "image/png", - "sizes": "192x192" - }, - { - "src": "/images/icons-512.png", - "type": "image/png", - "sizes": "512x512" - } - ], - "start_url": "/", - "background_color": "#666", - "display": "standalone", - "scope": "/", - "theme_color": "#333" -} diff --git a/views/pages/robots.ejs b/views/pages/robots.ejs deleted file mode 100644 index 14267e9..0000000 --- a/views/pages/robots.ejs +++ /dev/null @@ -1,2 +0,0 @@ -User-agent: * -Allow: / \ No newline at end of file diff --git a/views/pages/robots.txt b/views/pages/robots.txt deleted file mode 100644 index 14267e9..0000000 --- a/views/pages/robots.txt +++ /dev/null @@ -1,2 +0,0 @@ -User-agent: * -Allow: / \ No newline at end of file