mcopy/app/lib/settings/index.js

83 lines
1.5 KiB
JavaScript
Raw Normal View History

'use strict'
const os = require('os');
const path = require('path');
2018-09-02 18:26:12 +00:00
const fs = require('fs-extra');
const settings = {};
settings.file = path.join(os.homedir(), `/.mcopy/settings.json`);
settings.state = {
server : {
port : 1111,
enabled : true
},
2018-01-21 23:53:15 +00:00
devices : [],
2018-01-30 14:33:34 +00:00
profile : 'mcopy',
camera : {},
projector : {},
light : {}
}
2018-09-02 18:26:12 +00:00
settings.checkDir = async function () {
2018-01-21 23:53:15 +00:00
const dir = path.join(os.homedir(), '.mcopy/');
2018-09-02 18:26:12 +00:00
const exists = await fs.exists(dir)
if (!exists) {
try {
await fs.mkdir(dir);
} catch (err) {
if (err.code === 'EEXIST') return true
console.error(err);
}
}
2018-09-02 18:26:12 +00:00
return true
}
2018-09-02 18:26:12 +00:00
settings.save = async function () {
const str = JSON.stringify(settings.state, null, '\t');
2018-01-21 23:53:15 +00:00
settings.checkDir();
2018-09-02 18:26:12 +00:00
try {
await fs.writeFile(settings.file, str, 'utf8');
} catch (err) {
console.error(err);
}
}
settings.update = function (key, val) {
2018-01-21 23:53:15 +00:00
settings.state[key] = val;
}
settings.get = function (key) {
2018-01-21 23:53:15 +00:00
return settings.state[key];
}
settings.all = function () {
2018-01-21 23:53:15 +00:00
return settings.state;
}
2018-09-02 18:26:12 +00:00
settings.restore = async function () {
let exists;
2018-01-21 23:53:15 +00:00
let str;
2018-09-02 18:26:12 +00:00
2018-01-21 23:53:15 +00:00
settings.checkDir();
2018-09-02 18:26:12 +00:00
exists = await fs.exists(settings.file);
if (exists) {
str = await fs.readFile(settings.file, 'utf8');
2018-01-21 23:53:15 +00:00
settings.state = JSON.parse(str);
} else {
2018-01-21 23:53:15 +00:00
settings.save();
}
}
2018-09-02 18:26:12 +00:00
settings.reset = async function () {
const exists = await fs.exists(settings.file);
if (exists) {
try {
await fs.unlink(settings.file);
} catch (err) {
console.error(err);
}
2018-01-21 23:53:15 +00:00
}
settings.restore();
};
2018-09-02 18:26:12 +00:00
module.exports = settings;