2019-03-21 22:00:34 +00:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
import os = require('os');
|
|
|
|
import path = require('path');
|
|
|
|
import fs = require('fs-extra');
|
|
|
|
|
|
|
|
class Settings {
|
|
|
|
private file : string= path.join(os.homedir(), `/.mcopy/settings.json`);
|
2019-04-15 20:13:28 +00:00
|
|
|
private defaultState : any = {
|
2019-03-21 22:00:34 +00:00
|
|
|
server : {
|
|
|
|
port : 1111,
|
|
|
|
enabled : true
|
|
|
|
},
|
|
|
|
devices : [],
|
|
|
|
profile : 'mcopy',
|
|
|
|
camera : {},
|
|
|
|
projector : {},
|
|
|
|
light : {}
|
|
|
|
}
|
2019-04-15 20:13:28 +00:00
|
|
|
public state : any;
|
2019-03-21 22:00:34 +00:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
**/
|
|
|
|
constructor () {
|
2019-04-15 20:13:28 +00:00
|
|
|
this.state = this.freshState();
|
|
|
|
}
|
2019-03-21 22:00:34 +00:00
|
|
|
|
2019-04-15 20:13:28 +00:00
|
|
|
private freshState () {
|
|
|
|
return JSON.parse(JSON.stringify(this.defaultState));
|
2019-03-21 22:00:34 +00:00
|
|
|
}
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
**/
|
|
|
|
private async checkDir () {
|
|
|
|
const dir : string = path.join(os.homedir(), '.mcopy/');
|
|
|
|
const exists : boolean = await fs.exists(dir)
|
|
|
|
if (!exists) {
|
|
|
|
try {
|
|
|
|
await fs.mkdir(dir);
|
|
|
|
} catch (err) {
|
|
|
|
if (err.code === 'EEXIST') return true
|
|
|
|
console.error(err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
**/
|
|
|
|
public async save () {
|
|
|
|
const str = JSON.stringify(this.state, null, '\t');
|
|
|
|
this.checkDir();
|
|
|
|
try {
|
|
|
|
await fs.writeFile(this.file, str, 'utf8');
|
|
|
|
} catch (err) {
|
|
|
|
console.error(err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
**/
|
|
|
|
public update (key : string, val : any) {
|
|
|
|
this.state[key] = val;
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
**/
|
|
|
|
public get (key : string) {
|
|
|
|
return this.state[key];
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
**/
|
|
|
|
public all () {
|
|
|
|
return this.state;
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
**/
|
|
|
|
public async restore () {
|
|
|
|
let exists;
|
|
|
|
let str;
|
|
|
|
|
|
|
|
this.checkDir();
|
|
|
|
exists = await fs.exists(this.file);
|
|
|
|
|
|
|
|
if (exists) {
|
|
|
|
str = await fs.readFile(this.file, 'utf8');
|
|
|
|
this.state = JSON.parse(str);
|
2019-03-24 01:58:22 +00:00
|
|
|
//console.dir(this.state)
|
2019-03-21 22:00:34 +00:00
|
|
|
} else {
|
|
|
|
this.save();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
**/
|
|
|
|
public async reset () {
|
|
|
|
const exists = await fs.exists(this.file);
|
|
|
|
if (exists) {
|
|
|
|
try {
|
|
|
|
await fs.unlink(this.file);
|
|
|
|
} catch (err) {
|
|
|
|
console.error(err);
|
|
|
|
}
|
|
|
|
}
|
2019-04-15 20:13:28 +00:00
|
|
|
this.state = this.freshState();
|
2019-03-21 22:00:34 +00:00
|
|
|
this.restore();
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = new Settings()
|