diff --git a/app.js b/app.js index 755ed4a..400d497 100644 --- a/app.js +++ b/app.js @@ -38,7 +38,7 @@ const dependencies = [ ['bodyParser', 'body-parser'], 'path', 'fs', - 'node-cmd', + ['cmd', 'node-cmd'], ['cookieParser', 'cookie-parser'], 'http', 'https', ['socket', 'socket.io'], @@ -54,7 +54,6 @@ for(let dep of dependencies){ Functions.log({ action: 'info', data: `Loading '${name}' module` }) } - // other const app = express(), @@ -67,14 +66,6 @@ const } }) -// // ssl credentials -// if (conf.cert.key && conf.cert.crt && conf.cert.ca && conf.cert.enable) -// credentials = { -// 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) { @@ -686,172 +677,167 @@ class Com { } } -function save(file, data) { // save data to file - fs.writeFile(file, data, function (err) { - if (err) { - console.log(err); - return err; - } else { - return true; - } - }); - return true; -} +// function save(file, data) { // save data to file +// fs.writeFile(file, data, function (err) { +// if (err) { +// console.log(err); +// return err; +// } else { +// return true; +// } +// }); +// return true; +// } -function dataparse(data) { // parse data coming from /data - l = data.length; - try { - obj = JSON.parse(data); - for (let key in obj) { - if (key != "type") db.stats[key] = obj[key] - } +// function dataparse(data) { // parse data coming from /data +// l = data.length; +// try { +// obj = JSON.parse(data); +// for (let key in obj) { +// if (key != "type") db.stats[key] = obj[key] +// } - Functions.log({ - action: "data", - data: "Data recieved succesfully. " + "[Length: " + l + "]" - }); - } catch (e) { - Functions.log({ - action: "err", - data: "Invalid JSON string recieved. " + "[Length: " + l + "]" - }); - } +// Functions.log({ +// action: "data", +// data: "Data recieved succesfully. " + "[Length: " + l + "]" +// }); +// } catch (e) { +// Functions.log({ +// action: "err", +// data: "Invalid JSON string recieved. " + "[Length: " + l + "]" +// }); +// } - var to = 0 - switch (obj.type) { - default: to = 0; break; - case "stats": - case "uptime": to = 9; break; +// var to = 0 +// switch (obj.type) { +// default: to = 0; break; +// case "stats": +// case "uptime": to = 9; break; - case "network": to = 0; break; - } +// case "network": to = 0; break; +// } - // emto(obj, to) - Functions.blink(); -} +// // emto(obj, to) +// Functions.blink(); +// } -function gpath(dir, arg) { // get path +// function gpath(dir, arg) { // get path - var path = []; +// var path = []; - Functions.isDefined(arg, ""); // if no user argument replace with empty +// Functions.isDefined(arg, ""); // if no user argument replace with empty - if (arg.startsWith("\/")) { // if arg is absolute, dont merge - path = arg.slice(1).split("\/"); - } else { // if arg is relative, merge - if (!dir.startsWith("/")) dir = "/" + dir; - path = (dir + "/" + arg).slice(1).split("\/"); - } +// if (arg.startsWith("\/")) { // if arg is absolute, dont merge +// path = arg.slice(1).split("\/"); +// } else { // if arg is relative, merge +// if (!dir.startsWith("/")) dir = "/" + dir; +// path = (dir + "/" + arg).slice(1).split("\/"); +// } - while (path.indexOf("..") != -1) { // remove realtive paths (..) - if (path.indexOf("..") == 0) { // stop on empty - path = [""]; - break; - } - z = path.indexOf(".."); // get index of (..) - b = path.slice(0, z - 1); // get first half of path, without one stepdown - c = path.slice(z + 1); // get second half, without (..) - path = b.concat(c); // concat halves - } +// while (path.indexOf("..") != -1) { // remove realtive paths (..) +// if (path.indexOf("..") == 0) { // stop on empty +// path = [""]; +// break; +// } +// z = path.indexOf(".."); // get index of (..) +// b = path.slice(0, z - 1); // get first half of path, without one stepdown +// c = path.slice(z + 1); // get second half, without (..) +// path = b.concat(c); // concat halves +// } - if (path[path.length - 1] == "") path.splice(-1, 1); //remove empty dir at end - if (path[0] != "") path.unshift(""); // if no root path, add at beginning - if (path.length == 0) path.push(""); // if empty, add root dir +// if (path[path.length - 1] == "") path.splice(-1, 1); //remove empty dir at end +// if (path[0] != "") path.unshift(""); // if no root path, add at beginning +// if (path.length == 0) path.push(""); // if empty, add root dir - return path -} +// return path +// } -function gdir(path) { // get directory - if ((path.length == 0) || (path[0] == "")) { - obj = filess; - } - // else - // if(typeof(filess[path[0]]!="undefined")){ - // obj = filess[path[0]]; - // } +// function gdir(path) { // get directory +// if ((path.length == 0) || (path[0] == "")) { +// obj = filess; +// } +// // else +// // if(typeof(filess[path[0]]!="undefined")){ +// // obj = filess[path[0]]; +// // } - for (i = 1; i < path.length; i++) { - if (obj == null) break; - if (typeof obj[path[i]] != "undefined") { - if (typeof obj[path[i]] != "object") { - obj = null - } else obj = obj[path[i]] - } else obj = null - } - return obj; -} +// for (i = 1; i < path.length; i++) { +// if (obj == null) break; +// if (typeof obj[path[i]] != "undefined") { +// if (typeof obj[path[i]] != "object") { +// obj = null +// } else obj = obj[path[i]] +// } else obj = null +// } +// return obj; +// } -function sfile(path, socket, id) { // get file - obj = gdir(path.slice(0, path.length - 1)); - if (obj == null) { - coms({ - data: "err: invalid directory", - arg: [], - flag: 0, - id: id - }, socket); - return null; - } - if (typeof obj[path[path.length - 1]] == "undefined") { - coms({ - data: "err: file doesn't exist", - arg: [], - flag: 0, - id: id - }, socket); - return null; - } - if ((typeof obj[path[path.length - 1]].data == "undefined") && (typeof obj[path[path.length - 1]].link != "undefined")) { - fs.readFile("files/" + obj[path[path.length - 1]].link, "utf8", function (err, fdata) { - if (err) { - coms({ - data: err, - arg: [], - flag: 0, - id: id - }, socket); - } else { - coms({ - data: fdata, - arg: [], - flag: 0, - id: id - }, socket); - } - }); - } else { - if (typeof obj[path[path.length - 1]].static != "undefined") coms({ - data: "" + obj[path[path.length - 1]].static + "", - arg: [], - flag: 0, - id: id - }, socket); - else coms({ - data: obj[path[path.length - 1]].data, - arg: [], - flag: 0, - id: id - }, socket); - } -} +// function sfile(path, socket, id) { // get file +// obj = gdir(path.slice(0, path.length - 1)); +// if (obj == null) { +// coms({ +// data: "err: invalid directory", +// arg: [], +// flag: 0, +// id: id +// }, socket); +// return null; +// } +// if (typeof obj[path[path.length - 1]] == "undefined") { +// coms({ +// data: "err: file doesn't exist", +// arg: [], +// flag: 0, +// id: id +// }, socket); +// return null; +// } +// if ((typeof obj[path[path.length - 1]].data == "undefined") && (typeof obj[path[path.length - 1]].link != "undefined")) { +// fs.readFile("files/" + obj[path[path.length - 1]].link, "utf8", function (err, fdata) { +// if (err) { +// coms({ +// data: err, +// arg: [], +// flag: 0, +// id: id +// }, socket); +// } else { +// coms({ +// data: fdata, +// arg: [], +// flag: 0, +// id: id +// }, socket); +// } +// }); +// } else { +// if (typeof obj[path[path.length - 1]].static != "undefined") coms({ +// data: "" + obj[path[path.length - 1]].static + "", +// arg: [], +// flag: 0, +// id: id +// }, socket); +// else coms({ +// data: obj[path[path.length - 1]].data, +// arg: [], +// flag: 0, +// id: id +// }, socket); +// } +// } -function fsearch(dir, name) { - var is = false; - for (let key in dir) { - if ((typeof dir[key].data != 'undefined') || (typeof dir[key].link != 'undefined')) { - if (name === key) is = true; - } else { - is = fsearch(dir[key], name); - } - if (is) break; - } - return is -} - -function exit(sig) { - console.log(`\n${sig}`) - process.exit(0) -} +// function fsearch(dir, name) { +// var is = false; +// for (let key in dir) { +// if ((typeof dir[key].data != 'undefined') || (typeof dir[key].link != 'undefined')) { +// if (name === key) is = true; +// } else { +// is = fsearch(dir[key], name); +// } +// if (is) break; +// } +// return is +// } // express setup app @@ -878,15 +864,12 @@ app // server setup const httpServer = http.createServer(app), - io = new socket() - .attach(httpServer) + io = new socket(httpServer) -if (conf.cert.enable) { - const httpsServer = https.createServer(credentials, app) - io.attach(httpsServer) -} - -process.on('SIGINT', exit) +process.on('SIGINT', sig => { + console.log(`\n${sig}`) + process.exit(0) +}) // stdin input listener stdin.addListener("data", function (d) { @@ -999,11 +982,7 @@ app.get('/', function (req, res) { ) { res.redirect('https://' + req.hostname + req.originalUrl); } else { - res.render('pages/index', { - vars: { - hostname: db.config.hostname - } - }); + res.sendFile(path.join(__dirname, 'public/index.html')); } }); diff --git a/nodemon.json b/nodemon.json index 498ce2a..fb44467 100644 --- a/nodemon.json +++ b/nodemon.json @@ -1,4 +1,4 @@ { "verbose": true, - "ignore": ["main.js", "logs", "db.json"] + "ignore": ["main.js", "logs", "db.json", "public/packages/*"] } diff --git a/public/favicon.ico b/public/img/favicon.ico similarity index 100% rename from public/favicon.ico rename to public/img/favicon.ico diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..4546b13 --- /dev/null +++ b/public/index.html @@ -0,0 +1,50 @@ + + + + + + + + + + + smart-home + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/main.js b/public/main.js index fdd6996..f8e953c 100644 --- a/public/main.js +++ b/public/main.js @@ -1,186 +1,3 @@ -class H { - constructor(type) { - if ((typeof type != 'string') && (typeof type != 'object')) { - throw new Error('invalid object type') - } - - if (type instanceof Node) - this.element = [type] - else if (type instanceof NodeList) - this.element = type - else - this.element = [document.createElement(type)] - } - - addClass(...classNames) { - for (let key of classNames) { - for (let e of this.element) { - if (e.classList) - e.classList.add(key); - else - e.className += ' ' + key; - } - - } - return this - } - - 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`), ""); - } - - } - return this - } - - setProp(properties) { - for (let prop in properties) { - for (let e of this.element) { - e.setAttribute(prop, properties[prop]) - } - } - return this - } - - 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) - } - } - continue - } else - throw new Error("Invalid input argument") - } - - for (let e of this.element) { - e.appendChild(content) - } - - } - return this - } - - remove() { - this.element.forEach(e => { - e.parentNode.removeChild(e) - }) - } - - 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)) - } -} - -function getCookie(cname) { - /** - * Get cookie - * @param {string} cname cookie name - * - * @returns {string} cookie content (undefined if doesn't exist) - */ - - 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 @@ -309,6 +126,50 @@ function makeID(n) { return out; } +function date(format) { + /** + * thiserates current date in specified format + * long - DD/MM/YYYY HH:MM:SS + * log - DD/MMM HH:MM:SS + * tiny - MM:SS,SSS + * @param {string} format date format + * + * @returns {string} date in specified format + */ + + var d = new Date, + out = new String, + h = d.getHours() < 10 ? "0" + d.getHours() : d.getHours(), + m = d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes(), + s = d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds(), + ms = (function () { + let ms = d.getMilliseconds() + return ms < 10 ? '00' + ms : (ms < 100 ? '0' + ms : ms) + })() + + switch (format) { + default: + case 'long': + out = d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear() + " " + d.getHours() + ":" + m + ":" + s + break; + case 'log': + let p = new Date().toString().replace(/[A-Z]{3}\+/, '+').split(/ /) + out = p[2] + '/' + p[1] + ' ' + p[4] + break; + case 'tiny': + out = `${h}:${m}:${s}.${ms}` + break; + } + + return out +} + +function timestamp() { + return $('') + .addClass('timestamp') + .append(date('tiny') + ' ') +} + function download(content, filename) { /** * Download variable as file @@ -630,36 +491,13 @@ function setSession(key, value) { return value } -function getCookie(key) { - var name = key + "="; - 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 ""; -} - -function setCookie(key, value, exdays) { - var d = new Date(); - d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); - var expires = "expires=" + d.toUTCString(); - document.cookie = key + "=" + value + ";" + expires + ";path=/"; -} - -function resource(link){ +function resource(link) { fetch(link) .then(data => { console.log(data) data.text() .then(text => { - + }) }) } @@ -1043,17 +881,17 @@ class Elements { .prop("spellcheck", false) .prop("autofocus", true) ) - .append( - $("") - .addClass("icons") - .append( - $("").addClass("icon-volume-up"), - $("").addClass("icon-lock-open"), - $("").addClass("icon-trash"), - $("").addClass("icon-level-down"), - $("").addClass("icon-unlink") - ) - ) + // .append( + // $("") + // .addClass("icons") + // .append( + // $("").addClass("icon-volume-up"), + // $("").addClass("icon-lock-open"), + // $("").addClass("icon-trash"), + // $("").addClass("icon-level-down"), + // $("").addClass("icon-unlink") + // ) + // ) ) $("body").append($wind); } @@ -1066,74 +904,74 @@ 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.focus(); - } - }) + // this.$commin.on("blur", function () { + // if ($(this).closest(".wind").data("con").scroll) { + // this.focus(); + // } + // }) var icons = $wind.children(".commline").children(".icons"); - this.icons = {}; + // this.icons = {}; - this.icons.$trash = icons.children("i.icon-trash"); - this.icons.$trash.on("click", function () { - $(this).closest(".wind").data("con").clear(); - }) + // this.icons.$trash = icons.children("i.icon-trash"); + // 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).closest(".wind").data("con").scrollBottom(true); - }) + // this.icons.$levelDown = icons.children("i.icon-level-down"); + // this.icons.$levelDown.on("click", function () { + // $(this).closest(".wind").data("con").scrollBottom(true); + // }) - this.icons.$volume = icons.children("i.icon-volume-up"); + // this.icons.$volume = icons.children("i.icon-volume-up"); - this.icons.$lock = icons.children("i.icon-lock-open"); - this.icons.$lock.change = function () { - var con = $wind.data("con") - if (!con.scroll) { - this.removeClass(); - this.addClass("icon-lock-open"); - con.scroll = true; - con.elements.$commin.focus(); - } else { - this.removeClass(); - this.addClass("icon-lock"); - con.scroll = false; - } - } - this.icons.$lock.on("click", function () { - $(this).closest(".wind").data("con").elements.icons.$lock.change(); - }); + // this.icons.$lock = icons.children("i.icon-lock-open"); + // this.icons.$lock.change = function () { + // var con = $wind.data("con") + // if (!con.scroll) { + // this.removeClass(); + // this.addClass("icon-lock-open"); + // con.scroll = true; + // con.elements.$commin.focus(); + // } else { + // this.removeClass(); + // this.addClass("icon-lock"); + // con.scroll = false; + // } + // } + // 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.addClass("txgrn glow"); - setTimeout(function (icon) { - icon.removeClass("txgrn glow"); - }, 200, this); - } - this.icons.$connection.on("click", function () { - $(this).closest(".wind").data("con").executeCom("connection"); - }) + // this.icons.$connection = icons.children("i.icon-unlink"); + // this.icons.$connection.blink = function () { + // this.addClass("txgrn glow"); + // setTimeout(function (icon) { + // icon.removeClass("txgrn glow"); + // }, 200, this); + // } + // this.icons.$connection.on("click", function () { + // $(this).closest(".wind").data("con").executeCom("connection"); + // }) - this.icons.$lock.enable = function () { - this.removeClass(); - this.addClass("icon-lock-closed"); - } - this.icons.$lock.disable = function () { - this.removeClass(); - this.addClass("icon-lock"); - } + // this.icons.$lock.enable = function () { + // this.removeClass(); + // this.addClass("icon-lock-closed"); + // } + // this.icons.$lock.disable = function () { + // this.removeClass(); + // this.addClass("icon-lock"); + // } - this.icons.$connection.enable = function () { - this.removeClass(); - this.addClass("icon-link"); - } - this.icons.$connection.disable = function () { - this.removeClass(); - this.addClass("icon-unlink"); - } + // this.icons.$connection.enable = function () { + // this.removeClass(); + // this.addClass("icon-link"); + // } + // this.icons.$connection.disable = function () { + // this.removeClass(); + // this.addClass("icon-unlink"); + // } this.$commline = $wind.children(".commline"); this.$commline.enable = function () { @@ -1163,7 +1001,6 @@ class Request { this.id = com.id; this.con = com.con.id; this.udata = com.con.udata; - } } @@ -1195,16 +1032,16 @@ class Com { this.log = this.con.log // log method this._append() - if(!this._local()) + if (!this._local()) this._send() } - // append Com object to Con.commands _append() { this.$elem = $("
") .prop("id", this.id) .addClass("command") .append( + timestamp(), this.$ud = $("") .addClass("ud") .append( @@ -1242,7 +1079,7 @@ class Com { switch (this.c) { default: - if (this.con.socket.connected != true) { + if (this.con.Socket.socket.connected != true) { this.log("socket disconnected", "error"); this.insertResponse(); return 1; @@ -1344,7 +1181,7 @@ class Com { this._startLoading(); // start loading animation this.req = new Request(this); // create Request object - this.con.socket.emit("com", this.req); // send Request object + this.con.Socket.socket.emit("com", this.req); // send Request object this.timer = setTimeout(function (com) { // set server timeout com.timeout(false); // call server response timeout @@ -1383,7 +1220,7 @@ class Com { this.con.scrollBottom(false); // scroll to end of page (non-force) } - _unpack(res){ + _unpack(res) { switch (res.meta.flag) { default: case 0: // standard response, append data as plaintext @@ -1414,7 +1251,7 @@ class Com { $(this.con.elements.$commpath).html(data.data); // append response to command list break; case 6: // log response - this.log(res.data, res.meta.arg); + this.log(res.data.data, res.meta.arg); break; case 7: @@ -1431,7 +1268,7 @@ class Com { case 11: // toSyntax return toSyntax(res.data); - + 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]`; @@ -1457,7 +1294,6 @@ class Com { } - insertResponse() { this._stopLoading(); // stop loading animation @@ -1469,19 +1305,17 @@ class Com { this.sr = $("
") // create response element .append(this.formatted) .addClass("sr") - .hide() + // .hide() this.$elem // append response data to Com element .append(this.sr) - this.sr.slideDown(200); // animate response div + // this.sr.slideDown(200); // animate response div this.con.scrollBottom(false); // scroll to end of page (non-force) } - - remove() { this.$elem.remove(); } @@ -1545,10 +1379,6 @@ class Com { this.con.elements.$commline.enable(); // enable commline } - - - - } class Con { @@ -1556,7 +1386,6 @@ class Con { constructor($wind) { this.id = makeID(6) // Con ID - this.socket = undefined; // socket connection object this.elements = new Elements($wind); // DOM elements object // commands input history @@ -1607,7 +1436,6 @@ class Con { this.fConnect = false; // first connect event flag // this.fAuth = false; // first auth event flag this.first = false - this.udataExp = false; // auth credentials viability this.verbose = Config.verbose; // log display level // credentials @@ -1620,53 +1448,10 @@ class Con { shortid: undefined } - // trigger ready event after init - $($wind).ready(this.ready()); - - } - - set uAuth(val) { - - if ((val === true) || (val === false)) - this.udataExp = val - - if (!val) this.log("User auth data expired", "warning", 3) - - } - - get uAuth() { - - return this.udataExp - - } - - receive(res) { - - this.getCom(res.res.id).update(res); - - } - - auth(udata) { - - con.log("Auth data received", "ok", 2); - this.udata = udata; - this.uAuth = true; - this.elements.$commuser.change(this.udata.login, this.udata.badge); - // if (!this.fAuth) this.firstAuth() - this.motd() - - } - - tryAuth() { - - if(con.credentials){ - con.socket.emit("auth", con.credentials); - con.log("Requesting authentication", "info", 2); - return true - } else { - con.log("No credentials found", "info", 2); - return false - } + $(this.$wind).ready(()=>{ + this._ready() + }); + // this._ready() } @@ -1740,6 +1525,7 @@ class Con { var out = $("
") .addClass('inline') .append( + timestamp(), $('') .addClass(opt[0]) .append("#".repeat(lvl)) @@ -1852,13 +1638,7 @@ class Con { } 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.focus(); } @@ -1880,108 +1660,77 @@ class Con { } - // firstAuth() { - - // this.log("First auth", "info", 3) + _getPackage(name) { + return new Promise((resolve, reject) => { - // this.fAuth = true; - // } + this.log(`Requesting ${name} module`, 'info') + import(`./packages/${name}.js`) + .then(mod => { + this.log(`Downloaded ${name} module`, 'ok') + console.log(mod) + switch(mod.type){ + case 'sub': + this[name] = new mod.default(this) + break; + case 'class': + this[name] = mod.default + break; + } + resolve() + }) + .catch(err => { + this.log(`Downloading ${name} module failed: ${err}`, 'error') - motd() { - if(this.first) return - this.first = true - this.executeCom("motd"); - if (location.hash != "") { - this.log(`Executing command from URI (${location.hash.slice(1)})`, "info", 3) - this.executeCom(decodeURIComponent(location.hash.slice(1))); - } + reject() + }) + + + // var tag = document.createElement('script') + // tag.src = `packages/${name}.js` + + // Config.packages.update(name, 'downloading') + + + // $(tag).ready(() => { + // Config.packages.update(name, 'downloaded') + // resolve() + // if (eval(`if(typeof ${name} != 'undefined')true;else false`)) { + + // this.log(`${name} package downloaded`, 'ok') + // resolve() + // } else { + // Config.packages.update(name, 'failed') + // this.log(`${name} package download failed`, 'error') + // reject() + // } + // }) + // $('head').append(tag) + }); } - // Con init ready event - ready() { + _requires(name) { + if(!Config.packages[name]) + Config.packages[name] = this._getPackage(name) + return Config.packages[name] + // return new Promise((resolve, reject) => { + // if (Config.packages.check(name) == 'undefined') + // this._getPackage(name) + // else resolve() + + // Config.packages.callback(name) + // .then(() => { + // this[name] = eval(`new ${name}(this)`) + // resolve() + // }) + // }) + } + + + _ready() { $(this.elements.$wind).prop("id", this.id); // attach Con id to DOM $(this.elements.$wind).data("con", this); // attach Con object to DOM - this.socket = io('/'); // new socket connection - - // 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)); - }; - - // socket connecting start event - this.socket.on('connecting', this, function (data, con) { - con.log("Conecting...", "info", 2); - - }); - - // socket disconnected event - this.socket.on("disconnect", this, function (data, con) { - con.log(`Disconnected from server: ${data}`, "warning"); - con.elements.icons.$connection.disable(); - con.uAuth = false - - }) - - // socket connection error event - 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) { - - con.log("Conected to the server", "ok"); - con.elements.icons.$connection.enable(); - if(!con.tryAuth()) con.motd() - else con.log("Credentials detected, waiting for auth before motd", "info", 2) - - }); - - // dynamic (refreshed) data update - this.socket.on("dynamic", this, function (data, con) { - con.elements.icons.$connection.blink(); - console.log(data) - // /ChangeDom.updateInfo(data); - - }) - - // message broadcast (private & public) event - 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"); - notif.play(); - con.m = data.frm; - - }) - - // remote execute event - 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) { - con.elements.icons.$connection.blink(); - con.auth(res); - - }); - - // socket receive com response event - 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) { var con = $(this).closest(".wind").data("con"); @@ -2020,32 +1769,32 @@ class Con { }) this.elements.$wind.on('keydown', e => { - var val = (e.altKey)*1 - + (e.ctrlKey)*2 - + (e.metaKey)*3 - + (e.shiftKey)*4 + var val = (e.altKey) * 1 + + (e.ctrlKey) * 2 + + (e.metaKey) * 3 + + (e.shiftKey) * 4 + e.key, options = { '2l': () => this.clear() } - if(options[val]){ + if (options[val]) { options[val]() e.preventDefault() } }) - // focus on input on 'enter' - this.elements.$wind.on("keydown", function (e) { - var con = $(this).data("con"); + // // focus on input on 'enter' + // this.elements.$wind.on("keydown", function (e) { + // var con = $(this).data("con"); - switch (e.which) { - // ENTER key - case 13: con.elements.$commin.focus(); // focus on input - break; - } + // switch (e.which) { + // // ENTER key + // case 13: con.elements.$commin.focus(); // focus on input + // break; + // } - }) + // }) // form key handling this.elements.$commands.on("keydown", "form", function (e) { @@ -2075,24 +1824,60 @@ class Con { // jsonl file input event listener this.elements.$jsonl[0].addEventListener('change', this.readJson, false); - // 'accept cookies' prompt - 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") - } + // // 'accept cookies' prompt + // 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") + // } // update input width // TODO: get this working in pure css this.updateInputWidth(); + this.log("Console ready", 'ok') + + this._requires("Socket") + } } var Config = { - notif: new Audio('unsure.mp3'), // notification sound object + notif: new Audio('res/unsure.mp3'), // notification sound object treeDepth: 4, // tree visualization Depth socket: undefined, // socket connection object cons: [], // cons list + packages: {}, + // packages: { + // list: {}, + // update(name, state) { + // if (this.list[name]) { + // this.list[name].state = state + // } else { + // this.list[name] = { + // state: state, + // callbacks: [] + // } + // } + + // if (state == 'ready') { + // for (let fs of this.list[name].callbacks) { + // fs[0]() + // } + // } else if (state == 'failed') { + // for (let fs of this.list[name].callbacks) { + // fs[1]() + // } + // } + // }, + // callback(name, f) { + // return new Promise((resolve, reject) => { + // this.list[name].callbacks.push([resolve, reject]) + // }) + // }, + // check(name) { + // return typeof this.list[name] != 'undefined' ? this.list[name].state : 'undefined' + // } + // }, verbose: 2, serviceWorker: false // enable serviceWorker } @@ -2100,9 +1885,9 @@ var Config = { $(document).ready(function () { $("noscript").remove(); // remove 'js disabled' notice - Config.notif.volume = 0.3; // lower notification volume - Config.cons.push(new Con()); // init new Con - con = Config.cons[0]; // attach main Con to 'con' variable (for easier debugging) + Config.notif.volume = 0.3 + Config.cons.push(new Con()) + con = Config.cons[0] if ('serviceWorker' in navigator && Config.serviceWorker) { // check is serviceWorker is available navigator.serviceWorker diff --git a/public/packages/Cookies.js b/public/packages/Cookies.js new file mode 100644 index 0000000..0147c0b --- /dev/null +++ b/public/packages/Cookies.js @@ -0,0 +1,40 @@ +class Cookies { + getCookie(cname) { + /** + * Get cookie + * @param {string} cname cookie name + * + * @returns {string} cookie content (undefined if doesn't exist) + */ + + 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; + } + + 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=/"; + } +} diff --git a/public/packages/Core.js b/public/packages/Core.js new file mode 100644 index 0000000..4b9deca --- /dev/null +++ b/public/packages/Core.js @@ -0,0 +1,5 @@ +class Core{ + constructor(){ + console.log('aaa') + } +} \ No newline at end of file diff --git a/public/packages/Socket.js b/public/packages/Socket.js new file mode 100644 index 0000000..6c04255 --- /dev/null +++ b/public/packages/Socket.js @@ -0,0 +1,99 @@ +export var type = "sub" +export default class Socket { + + constructor(con) { + this.con = 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 = io('/') + + // socket connecting start event + this.socket.on('connecting', (data) => con.log("Conecting...", "info", 2)); + this.socket.on("connect_error", (data) => con.log(data, "error")) + + this.socket.on('auth', (data) => this.auth(data)); + this.socket.on('com', (data) => this.receive(data)); + + // socket disconnected event + this.socket.on("disconnect", (data) => { + con.log(`Disconnected from server: ${data}`, "warning") + con.uAuth(false) + }) + + // socket succesfully connected event + this.socket.on('connect', (data) => { + + con.log("Conected to the server", "ok") + if (!this.tryAuth()) this.motd() + else con.log("Credentials detected, waiting for auth before motd", "info", 2) + + }); + + // // dynamic (refreshed) data update + // this.socket.on("dynamic", (data) => { + // console.log(data) + // // /ChangeDom.updateInfo(data); + // }) + + // message broadcast (private & public) event + // this.socket.on("broadcast", (data) => { + // con.log(data.data, "message"); + // con.m = data.frm; + // con.scrollBottom(true); + // if (data.imp) alert("Broadcast message received"); + // notif.play(); + // con.m = data.frm; + + // }) + + // remote execute event TODO: fix + // this.socket.on("eval", (data) => $("head").append(eval(data.data))) + + + } + + motd() { + if (this.con.first) return + this.con.first = true + this.con.executeCom("motd"); + if (location.hash != "") { + this.con.log(`Executing command from URI (${location.hash.slice(1)})`, "info", 3) + this.con.executeCom(decodeURIComponent(location.hash.slice(1))); + } + } + + receive(res) { + this.con.getCom(res.res.id).update(res); + } + + uAuth(val) { + if (val) this.con.udataExp = val + return this.con.udataExp + } + + auth(udata) { + con.log("Auth data received", "ok", 2); + this.con.udata = udata; + this.con.uAuth(true) + this.con.elements.$commuser.change(this.con.udata.login, this.con.udata.badge); + // if (!this.fAuth) this.firstAuth() + this.con.motd() + } + + tryAuth() { + if (con.credentials) { + con.socket.emit("auth".credentials); + con.log("Requesting authentication", "info", 2); + return true + } else { + con.log("No credentials found", "info", 2); + return false + } + } +} + diff --git a/public/packages/Test.js b/public/packages/Test.js new file mode 100644 index 0000000..7ab93ae --- /dev/null +++ b/public/packages/Test.js @@ -0,0 +1,4 @@ +var what = "aa" +export { + what as test +} \ No newline at end of file diff --git a/public/packages/Tree.js b/public/packages/Tree.js new file mode 100644 index 0000000..b8d3b67 --- /dev/null +++ b/public/packages/Tree.js @@ -0,0 +1,170 @@ +export var type = "class" +export default class Tree { + constructor(data) { + this.data = data + + if (this._typeOf(data) != "array" && this._typeOf(data) != "object") + return $("").append(_contentType(data)).append(": ").append(data + "") + + this.$ = $("") + .addClass("ascii tree") + .append( + $("
  • ") + .append( + this._contentType(data), + this._collapse(false), + this._recur(data, 1) + ) + ) + + } + + get(){ + return this.$ + } + + _typeOf(o) { + var t = typeof o + + if (o instanceof Array) t = "array" + if (o instanceof RegExp) t = "regex" + if (o === null) t = "null" + + return t + } + + _contentType(v, name) { + + var type = this._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 : "?") + } + + } + + _collapse(n) { + if (n) { + return $("") + .addClass("collapse") + .append( + $("") + .addClass('icon-plus-squared') + ) + } else { + return $("") + .addClass("collapse") + .append( + $("") + .addClass('icon-minus-squared') + ) + } + } + + _recur(obj, depth) { + + let m = this.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 = this._typeOf(obj[key]); // content type + + + switch (type) { + case 'object': + case 'array': + if ($.isEmptyObject(content)) { // is content epmty + $list.append( // empty object + $("
  • ") + .append(this._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(this._contentType(content, key)) + .append(": ") + .append(`${isWhat(content)}`) + ) + } else { // max depth not reached + $list.append( // continue recursion + $("
  • ") + .append(this._contentType(content, key)) + .append(": ") + .append( // collapse button + this._collapse(depth >= maxc) + ) + .append(this._recur(content, depth + 1)) + ) + } + } + break; + + case 'function': + $list.append( + $("
  • ") + .append(this._contentType(content, key)) + .append(": ") + .append( + `${isWhat(content)}` + ) + ) + break; + + default: + $list.append( + $("
  • ") + .append(this._contentType(content, key)) + .append(": ") + .append(content) + ) + break; + } + + } + + if (i > maxn) { + + $list.append( + $("
  • ") + .append( + $("") + .append(`... ${i - maxn} more`) + ) + ) + + } + + if (depth > maxc) { + $list.hide() + } + + return $list + + } + +}; \ No newline at end of file diff --git a/public/atom-one-dark.min.css b/public/res/atom-one-dark.min.css similarity index 100% rename from public/atom-one-dark.min.css rename to public/res/atom-one-dark.min.css diff --git a/public/chart.min.js b/public/res/chart.min.js similarity index 100% rename from public/chart.min.js rename to public/res/chart.min.js diff --git a/public/res/fontello.css b/public/res/fontello.css new file mode 100644 index 0000000..f475d4a --- /dev/null +++ b/public/res/fontello.css @@ -0,0 +1,2 @@ +@import url("fontello/css/animation.css"); +@import url("fontello/css/fontello.css"); diff --git a/public/fontello/LICENSE.txt b/public/res/fontello/LICENSE.txt similarity index 100% rename from public/fontello/LICENSE.txt rename to public/res/fontello/LICENSE.txt diff --git a/public/fontello/README.txt b/public/res/fontello/README.txt similarity index 100% rename from public/fontello/README.txt rename to public/res/fontello/README.txt diff --git a/public/fontello/config.json b/public/res/fontello/config.json similarity index 100% rename from public/fontello/config.json rename to public/res/fontello/config.json diff --git a/public/fontello/css/animation.css b/public/res/fontello/css/animation.css similarity index 100% rename from public/fontello/css/animation.css rename to public/res/fontello/css/animation.css diff --git a/public/fontello/css/fontello-codes.css b/public/res/fontello/css/fontello-codes.css similarity index 100% rename from public/fontello/css/fontello-codes.css rename to public/res/fontello/css/fontello-codes.css diff --git a/public/fontello/css/fontello-embedded.css b/public/res/fontello/css/fontello-embedded.css similarity index 100% rename from public/fontello/css/fontello-embedded.css rename to public/res/fontello/css/fontello-embedded.css diff --git a/public/fontello/css/fontello-ie7-codes.css b/public/res/fontello/css/fontello-ie7-codes.css similarity index 100% rename from public/fontello/css/fontello-ie7-codes.css rename to public/res/fontello/css/fontello-ie7-codes.css diff --git a/public/fontello/css/fontello-ie7.css b/public/res/fontello/css/fontello-ie7.css similarity index 100% rename from public/fontello/css/fontello-ie7.css rename to public/res/fontello/css/fontello-ie7.css diff --git a/public/fontello/css/fontello.css b/public/res/fontello/css/fontello.css similarity index 100% rename from public/fontello/css/fontello.css rename to public/res/fontello/css/fontello.css diff --git a/public/fontello/demo.html b/public/res/fontello/demo.html similarity index 100% rename from public/fontello/demo.html rename to public/res/fontello/demo.html diff --git a/public/fontello/font/fontello.eot b/public/res/fontello/font/fontello.eot similarity index 100% rename from public/fontello/font/fontello.eot rename to public/res/fontello/font/fontello.eot diff --git a/public/fontello/font/fontello.svg b/public/res/fontello/font/fontello.svg similarity index 100% rename from public/fontello/font/fontello.svg rename to public/res/fontello/font/fontello.svg diff --git a/public/fontello/font/fontello.ttf b/public/res/fontello/font/fontello.ttf similarity index 100% rename from public/fontello/font/fontello.ttf rename to public/res/fontello/font/fontello.ttf diff --git a/public/fontello/font/fontello.woff b/public/res/fontello/font/fontello.woff similarity index 100% rename from public/fontello/font/fontello.woff rename to public/res/fontello/font/fontello.woff diff --git a/public/fontello/font/fontello.woff2 b/public/res/fontello/font/fontello.woff2 similarity index 100% rename from public/fontello/font/fontello.woff2 rename to public/res/fontello/font/fontello.woff2 diff --git a/public/highlight.min.js b/public/res/highlight.min.js similarity index 100% rename from public/highlight.min.js rename to public/res/highlight.min.js diff --git a/public/hljsct.css b/public/res/hljsct.css similarity index 100% rename from public/hljsct.css rename to public/res/hljsct.css diff --git a/public/jquery-3.3.1.min.js b/public/res/jquery-3.3.1.min.js similarity index 100% rename from public/jquery-3.3.1.min.js rename to public/res/jquery-3.3.1.min.js diff --git a/public/jquery-3.3.1.slim.min.js b/public/res/jquery-3.3.1.slim.min.js similarity index 100% rename from public/jquery-3.3.1.slim.min.js rename to public/res/jquery-3.3.1.slim.min.js diff --git a/public/socket.io.js b/public/res/socket.io.js similarity index 100% rename from public/socket.io.js rename to public/res/socket.io.js diff --git a/public/socket.io.js.map b/public/res/socket.io.js.map similarity index 100% rename from public/socket.io.js.map rename to public/res/socket.io.js.map diff --git a/public/socket.io.slim.js b/public/res/socket.io.slim.js similarity index 100% rename from public/socket.io.slim.js rename to public/res/socket.io.slim.js diff --git a/public/socket.io.slim.js.map b/public/res/socket.io.slim.js.map similarity index 100% rename from public/socket.io.slim.js.map rename to public/res/socket.io.slim.js.map diff --git a/public/ubuntu-mono.woff2 b/public/res/ubuntu-mono.woff2 similarity index 100% rename from public/ubuntu-mono.woff2 rename to public/res/ubuntu-mono.woff2 diff --git a/public/unsure.mp3 b/public/res/unsure.mp3 similarity index 100% rename from public/unsure.mp3 rename to public/res/unsure.mp3 diff --git a/public/style.css b/public/style.css index 1e9eec8..cb21165 100644 --- a/public/style.css +++ b/public/style.css @@ -2,7 +2,7 @@ font-family: 'Ubuntu Mono'; font-style: normal; font-weight: 400; - src: local('Ubuntu Mono'), local('UbuntuMono-Regular'), url(ubuntu-mono.woff2) format('woff2'); + src: local('Ubuntu Mono'), local('UbuntuMono-Regular'), url(res/ubuntu-mono.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } @@ -49,7 +49,7 @@ txprp, .txprp {color: #AE00FF;} padding: 0px 15px; color: white; /* font-family: Ubuntu Mono; */ - overflow-y: hidden; + overflow-y: scroll; overflow-x: hidden; box-sizing: border-box; } @@ -106,14 +106,9 @@ body::-webkit-scrollbar, /* commandline row */ .commline{ - position: absolute; - bottom: 0px; - left: 0px; - right: 0px; z-index: 100; - width: auto; - padding: 10px 15px; - background: rgba(0,0,0,0.6); + width: auto; + padding-bottom: 15px; } label{ @@ -152,16 +147,20 @@ table{ /* command output element */ .commands{ line-height: 1.28; - padding: 25px 0px; - padding-bottom: 40px; - overflow-y: scroll; - max-height: 100%; + padding: 15px 0px; + padding-bottom: 0px; + overflow-y: visible; box-sizing: border-box; } +.timestamp{ + position: absolute; + right: 0px; +} + ::selection, ::-moz-selection{ - + color: initial; } .frosted::before {