aboutsummaryrefslogtreecommitdiffstats
path: root/server/managers/config.js
blob: 2865d006ec42dacd6dfa50e3c01b35ce465619a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/**
  * Server configuration manager, handling loading, creation, parsing and saving
  * of the main config.json file
  *
  * Version: v2.0.0
  * Developer: Marzavec ( https://github.com/marzavec )
  * License: WTFPL ( http://www.wtfpl.net/txt/copying/ )
  *
  */

const stripIndents = require('common-tags').stripIndents;
const dateFormat = require('dateformat');
const chalk = require('chalk');
const fse = require('fs-extra');
const prompt = require('prompt');
const path = require('path');
const deSync = require('deasync');

class ConfigManager {
  /**
    * Create a `ConfigManager` instance for (re)loading classes and config
    *
    * @param {Object} core reference to the global core object
    * @param {String} base executing directory name; __dirname
    * @param {Object} dynamicImports dynamic import engine reference
    */
  constructor (core, base, dynamicImports) {
    this._core = core;
    this._base = base;

    this._configPath = path.resolve(base, 'config/config.json');

    this._dynamicImports = dynamicImports;
  }

  /**
    * Pulls both core config questions along with any optional config questions,
    * used in building the initial config.json or re-building it.
    *
    * @param {Object} currentConfig an object containing current server settings, if any
    * @param {Object} optionalConfigs optional (non-core) module config
    */
  getQuestions (currentConfig, optionalConfigs) {
    // core server setup questions
    const questions = {
      properties: {
        adminName: {
          pattern: /^"?[a-zA-Z0-9_]+"?$/,
          type: 'string',
          message: 'Nicks can only contain letters, numbers and underscores',
          required: !currentConfig.adminName,
          default: currentConfig.adminName,
          before: value => value.replace(/"/g, '')
        },
        adminPass: {
          type: 'string',
          required: !currentConfig.adminPass,
          default: currentConfig.adminPass,
          hidden: true,
          replace: '*',
        },
        websocketPort: {
          type: 'number',
          required: !currentConfig.websocketPort,
          default: currentConfig.websocketPort || 6060
        },
        tripSalt: {
          type: 'string',
          required: !currentConfig.tripSalt,
          default: currentConfig.tripSalt,
          hidden: true,
          replace: '*',
        }
      }
    };

    // non-core server setup questions, for future plugin support
    Object.keys(optionalConfigs).forEach(configName => {
      const config = optionalConfigs[configName];
      const question = config.getQuestion(currentConfig, configName);

      if (!question) {
        return;
      }

      question.description = (question.description || configName) + ' (Optional)';
      questions.properties[configName] = question;
    });

    return questions;
  }

  /**
    * `load` function overload, only blocking
    *
    */
  loadSync () {
    let conf = {};
    conf = this.load();

    // trip salt is the last core config question, wait until it's been populated
    // TODO: update this to work with new plugin support
    while(conf === null || typeof conf.tripSalt === 'undefined') {
      deSync.sleep(100);
    }

    return conf;
  }

  /**
    * (Re)builds the config.json (main server config), or loads the config into mem
    * if rebuilding, process will exit- this is to allow a process manager to take over
    *
    * @param {Boolean} reconfiguring set to true by `scripts/configure.js`, will exit if true
    */
  load (reconfiguring = false) {
    if (reconfiguring || !fse.existsSync(this._configPath)) {
      // gotta have that sexy console
      console.log(stripIndents`
        ${chalk.magenta('°º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸°º¤ø,¸¸,ø¤º°`°º¤ø')}
        ${chalk.gray('--------------(') + chalk.white(' HackChat Setup Wizard v1.0 ') + chalk.gray(')--------------')}
        ${chalk.magenta('°º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸°º¤ø,¸¸,ø¤º°`°º¤ø')}

        For advanced setup, see the HackChat wiki at:
        ${chalk.green('https://github.com/')}

        ${chalk.white('Note:')} ${chalk.green('npm/yarn run config')} will re-run this utility.

        You will now be asked for the following:
        -     ${chalk.magenta('Admin Name')}, the initial admin username
        -     ${chalk.magenta('Admin Pass')}, the initial admin password
        -     ${chalk.magenta('      Port')}, the port for the websocket
        -     ${chalk.magenta('      Salt')}, the salt for username trip
        \u200b
      `);

      let currentConfig = this._config || {};
      if (reconfiguring && fse.existsSync(this._configPath)) {
        this._backup();
        currentConfig = fse.readJSONSync(this._configPath);
      }

      prompt.get(this.getQuestions(currentConfig, this._dynamicImports.optionalConfigs), (err, res) => {
        if (typeof res.mods === 'undefined') {
          res.mods = [];
        }

        if (err) {
          console.error(err);
          process.exit(666); // SPOOKY!
        }

        try {
          fse.outputJsonSync(this._configPath, res);
        } catch (e) {
          console.error(`Couldn't write config to ${this._configPath}\n${e.stack}`);
          if (!reconfiguring) {
            process.exit(666); // SPOOKY!
          }
        }

        console.log('Config generated! You may now start the server normally.')

        process.exit(reconfiguring ? 0 : 42);
      });

      return null;
    }

    this._config = fse.readJSONSync(this._configPath);

    return this._config;
  }

  /**
    * Creates backup of current config into _configPath
    *
    */
  _backup () {
    const backupPath = `${this._configPath}.${dateFormat('dd-mm-yy-HH-MM-ss')}.bak`;
    fse.copySync(this._configPath, backupPath);

    return backupPath;
  }

  /**
    * First makes a backup of the current `config.json`, then writes current config
    * to disk
    *
    */
  save () {
    const backupPath = this._backup();

    if (!fse.existsSync(this._configPath)){
      fse.mkdirSync(this._configPath);
    }

    try {
      fse.writeJSONSync(this._configPath, this._config);
      fse.removeSync(backupPath);

      return true;
    } catch (err) {
      console.log(`Failed to save config file: ${err}`);

      return false;
    }
  }

  /**
    * Updates current config[`key`] with `value` then writes changes to disk
    *
    * @param {*} key arbitrary configuration key
    * @param {*} value new value to change `key` to
    */
  set (key, value) {
    const realKey = `${key}`;
    this._config[realKey] = value;

    this.save();
  }
}

module.exports = ConfigManager;