Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
version: '3.2'

services:
dcm:
build:
context: .
dockerfile: ./etc/dev/node/Dockerfile
command:
- "npm"
- "start"
ports:
- "9991:9991"

mysql:
image: mysql:8
command: --default-authentication-plugin=mysql_native_password
ports:
- "3306:3306"
environment:
- MYSQL_ROOT_PASSWORD=pass123!
- MYSQL_DATABASE=dcm
volumes:
- db_data:/var/lib/mysql

volumes:
db_data:
5 changes: 5 additions & 0 deletions etc/dev/node/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
FROM node:12.16.2-alpine

WORKDIR /app

CMD ["npm", "start"]
64 changes: 64 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"author": "versx",
"license": "ISC",
"dependencies": {
"atob": "^2.1.2",
"express": "^4.17.1",
"express-session": "^1.17.1",
"i18n": "^0.9.0",
Expand Down
33 changes: 25 additions & 8 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
'use strict';

const path = require('path');
//const csrf = require('csurf');
//const cookieParser = require('cookie-parser');
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
Expand All @@ -21,10 +23,7 @@ const timezones = require('../static/data/timezones.json');

// TODO: Create route classes
// TODO: Fix devices scroll with DataTables
// TODO: Delete all logs button
// TODO: Secure /api/config endpoint with token
// TODO: Accomodate for # in uuid name
// TODO: Fix schedule end time
// TODO: Center align data in table columns
// TODO: Change require to import

Expand Down Expand Up @@ -60,11 +59,10 @@ app.use(express.static(path.resolve(__dirname, '../static')));
//app.use('/logs', express.static(path.resolve(__dirname, '../logs')));
app.use('/screenshots', express.static(path.resolve(__dirname, '../screenshots')));

//app.use(express.cookieParser());
app.use(i18n.init);

// register helper as a locals function wrapped as mustache expects
app.use(function (req, res, next) {
app.use(function(req, res, next) {
// mustache helper
res.locals.__ = function() {
/* eslint-disable no-unused-vars */
Expand All @@ -90,6 +88,21 @@ app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false, limit: '50mb' })); // for parsing application/x-www-form-urlencoded
//app.use(bodyParser.raw({ type: 'application/x-www-form-urlencoded' }));

/*
app.use(cookieParser());
app.use(csrf({ cookie: true }));
app.use(function(req, res, next) {
var csrf = req.csrfToken();
defaultData.csrf = csrf;
//defaultData.csrf = request.session?.data["csrf"];
console.log("CSRF Token:", csrf);
res.cookie('x-csrf-token', csrf);
res.cookie('TOKEN', csrf);
res.locals.csrftoken = csrf;
next();
});
*/

// Sessions middleware
app.use(session({
secret: config.secret, // REVIEW: Randomize?
Expand All @@ -110,6 +123,10 @@ app.use(function(req, res, next) {
next();
return;
}
//if (defaultData.csrf !== req.csrfToken()) {
// console.log("TOKEN GOOD");
// //return next();
//}
res.redirect('/login');
});

Expand All @@ -121,7 +138,7 @@ app.get(['/', '/index'], async function(req, res) {
var configs = await Config.getAll();
var schedules = ScheduleManager.getAll();
var metadata = await Migrator.getEntries();
var logsSize = Log.getTotalSize();
var logsSize = await Log.getTotalSize();
var data = defaultData;
data.metadata = metadata;
data.devices = devices.length;
Expand Down Expand Up @@ -333,13 +350,13 @@ app.get('/settings', function(req, res) {
});
data.languages = [
{ 'name': 'en' },
{ 'name': 'es' }
{ 'name': 'es' },
{ 'name': 'de' }
];
data.languages.forEach(function(locale) {
locale.selected = locale.name === config.locale;
});
data.logging = config.logging.enabled ? 'checked' : '';
data.max_size = config.logging.max_size;
console.log('Settings:', data);
res.render('settings', data);
});
4 changes: 2 additions & 2 deletions src/migrator.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,15 @@ class Migrator {
var migrateSQL;
try {
var sqlFile = `${migrationsDir}${path.sep}${fromVersion + 1}.sql`;
migrateSQL = utils.readFile(sqlFile);
migrateSQL = await utils.readFile(sqlFile);
migrateSQL.replace('\r', '').replace('\n', '');
} catch (err) {
console.error('[DBController] Migration failed:', err);
process.exit(-1);
}
var sqlSplit = migrateSQL.split(';');
sqlSplit.forEach(async sql => {
let msql = sql.replace('&semi', ';').trim();
var msql = sql.replace('&semi', ';').trim();
if (msql !== '') {
console.log('[DBController] Executing:', msql);
var result = await query(msql)
Expand Down
73 changes: 43 additions & 30 deletions src/models/log.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,34 +16,39 @@ class Log {
this.timestamp = timestamp;
this.message = message;
}
static getByDevice(uuid) {
static async getByDevice(uuid) {
var name = uuid + '.log';
var logFile = path.resolve(logsDir, name);
if (!fs.existsSync(logFile)) {
var exists = await utils.fileExists(logFile);
if (!exists) {
return null;
}
var data = utils.readFile(logFile).split('\r\n');
var logs = [];
data.forEach(function(log) {
if (log) {
var l = JSON.parse(log);
logs.push({
message: l.message,
date: utils.getDateTime(l.timestamp),
uuid: l.uuid
});
}
});
var data = await utils.readFile(logFile);
var split = data.split('\r\n');
if (split) {
split.forEach(function(log) {
if (log) {
var l = JSON.parse(log);
logs.push({
message: l.message,
date: utils.getDateTime(l.timestamp),
uuid: l.uuid
});
}
});
}
return logs;
}
static create(uuid, message) {
static async create(uuid, message) {
var name = uuid + '.log';
var logFile = path.resolve(logsDir, name);
if (fs.existsSync(logFile)) {
var size = fs.statSync(logFile).size || 0;
var exists = await utils.fileExists(logFile);
if (exists) {
var size = await utils.fileSize(logFile) || 0;
var maxSize = (config.logging.max_size || 5) * 1024 * 1024;
if (size >= maxSize) {
this.delete(uuid);
await this.delete(uuid);
}
}
var msg = {
Expand All @@ -55,10 +60,11 @@ class Log {
if (err) throw err;
});
}
static delete(uuid) {
static async delete(uuid) {
var name = uuid + '.log';
var logFile = path.resolve(logsDir, name);
if (fs.existsSync(logFile)) {
var exists = await utils.fileExists(logFile);
if (exists) {
fs.unlinkSync(logFile);
return true;
}
Expand All @@ -75,18 +81,25 @@ class Log {
});
});
}
static getTotalSize() {
var total = 0;
if (!fs.existsSync(logsDir)) {
return total;
}
var logs = fs.readdirSync(logsDir);
logs.forEach(function(log) {
var logFile = path.join(logsDir, log);
var stats = fs.statSync(logFile);
total += stats.size;
static async getTotalSize() {
var exists = await utils.fileExists(logsDir);
return new Promise((resolve, reject) => {
if (!exists) {
return reject(total);
}
var total = 0;
var files = fs.readdirSync(logsDir);
if (files) {
files.forEach(function(file) {
var logFile = path.resolve(logsDir, file);
var stats = fs.statSync(logFile);
total += stats.size;
});
} else {
return reject();
}
resolve(total);
});
return total;
}
}

Expand Down
5 changes: 2 additions & 3 deletions src/models/schedule-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,8 @@ class ScheduleManager {
await ScheduleManager.triggerSchedule(schedule, schedule.config);
} else if (startTimeSeconds !== 0 &&
endTimeSeconds !== 0 &&
now < startTimeSeconds &&
now > endTimeSeconds &&
lastUpdate < endTimeSeconds) {
!(now > startTimeSeconds && now < endTimeSeconds) &&
lastUpdate > endTimeSeconds) {
await ScheduleManager.triggerSchedule(schedule, schedule.next_config);
}
}
Expand Down
Loading