yunkong2.js-controller
Version:
Updated by reinstall.js on 2018-06-11T15:19:56.688Z
943 lines (880 loc) • 154 kB
JavaScript
/**
*
* js-controller Controller start/stop and install script
*
* 7'2014-2018 bluefox <dogafox@gmail.com>
* 2014 hobbyquaker <hq@ccu.io>
*
*/
/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
'use strict';
// TODO need info about progress of stopping
const fs = require('fs');
const tools = require('./tools');
require('events').EventEmitter.prototype._maxListeners = 100;
process.setMaxListeners(0);
let yargs;
function initYargs() {
yargs = require('yargs')
.usage('Commands:\n' +
tools.appName + ' setup [--objects <host>] [--states <host>] [custom]\n' +
tools.appName + ' start\n' +
tools.appName + ' stop\n' +
tools.appName + ' start <adapter>\n' +
tools.appName + ' stop <adapter>\n' +
tools.appName + ' start all\n' +
tools.appName + ' restart\n' +
tools.appName + ' restart <adapter>\n' +
tools.appName + ' info\n' +
tools.appName + ' add <adapter> [desiredNumber] [--enabled] [--host <host>] [--port <port>]\n' +
tools.appName + ' install <adapter>\n' +
tools.appName + ' url <url> [<name>]\n' +
tools.appName + ' del <adapter>\n' +
tools.appName + ' del <adapter>.<instance>\n' +
tools.appName + ' update [repository url] [--updatable/--u] [--installed/--i]\n' +
tools.appName + ' upgrade [repository url]\n' +
tools.appName + ' upgrade self [repository url]\n' +
tools.appName + ' upgrade <adapter> [repository url]\n' +
tools.appName + ' upload <pathToLocalFile> <pathIn' + tools.appName + '>\n' +
tools.appName + ' upload all\n' +
tools.appName + ' upload <adapter>\n' +
tools.appName + ' object get <id>\n' +
tools.appName + ' object del <id>\n' +
tools.appName + ' object chmod <object-mode> [state-mode] <id>\n' +
tools.appName + ' object chown <user> <group> <id>\n' +
tools.appName + ' object list <id>\n' +
tools.appName + ' state get <id> [\n' +
tools.appName + ' state getplain <id> [--pretty]\n' +
tools.appName + ' state getvalue <id>\n' +
tools.appName + ' state set <id> <value> [ack]\n' +
tools.appName + ' state del <id>\n' +
tools.appName + ' message <adapter>[.instanceid] <command> [<message>]\n' +
tools.appName + ' list <type> [filter]\n' +
tools.appName + ' chmod <mode> <file>\n' +
tools.appName + ' chown <user> <group> <file>\n' +
tools.appName + ' touch <file>\n' +
tools.appName + ' rm <file>\n' +
tools.appName + ' file read <' + tools.appName + '-path-to-read> [<filesystem-path-to-write>]\n' +
tools.appName + ' file write <filesystem-path-to-read> <' + tools.appName + '-path-to-read> \n' +
tools.appName + ' user add <user> [--ingroup group] [--password pass]\n' +
tools.appName + ' user del <user>\n' +
tools.appName + ' user passwd <user> [--password pass]\n' +
tools.appName + ' user enable <user>\n' +
tools.appName + ' user disable <user>\n' +
tools.appName + ' user get <user>\n' +
tools.appName + ' user check <user> [--password pass]\n' +
tools.appName + ' group add <group>\n' +
tools.appName + ' group del <group>\n' +
tools.appName + ' group list <group>\n' +
tools.appName + ' group enable <group>\n' +
tools.appName + ' group disable <group>\n' +
tools.appName + ' group get <group>\n' +
tools.appName + ' group adduser <group> <user>\n' +
tools.appName + ' group deluser <group> <user>\n' +
tools.appName + ' host this \n' +
tools.appName + ' set <adapter>.<instance> [--port port] [--ip address] [--ssl true|false]\n' +
tools.appName + ' license <license.file or license.text>\n' +
tools.appName + ' clean\n' +
tools.appName + ' backup\n' +
tools.appName + ' restore <backup name or path>\n' +
tools.appName + ' <command> --timeout 5000\n' +
tools.appName + ' status\n' +
tools.appName + ' repo [name]\n' +
tools.appName + ' repo add <name> <path or url>\n' +
tools.appName + ' repo set <name>\n' +
tools.appName + ' repo del <name>\n' +
tools.appName + ' uuid\n' +
tools.appName + ' unsetup\n' +
tools.appName + ' multihost <enable|disable> [--secure true|false]\n' +
tools.appName + ' multihost browse\n' +
tools.appName + ' multihost connect\n' +
tools.appName + ' version [adapter]\n' +
tools.appName + ' [adapter] -v\n')
//.default('objects', '127.0.0.1')
//.default('states', '127.0.0.1')
//.default('lang', 'en')
.wrap(null)
;
return yargs;
}
function showHelp(_yargs) {
if (_yargs) {
_yargs.showHelp();
} else if (yargs) {
yargs.showHelp();
}
}
let Objects; // constructor
let objects; // instance
let States; // constructor
let states; // instance
// params can have:
// pretty, force, password, ingroup, v, version, timeout,
// enabled, disabled, port, ssl, ip, updatable, host, enabled, port,
// objects, states
function processCommand(command, args, params, callback) {
if (typeof args === 'function') {
callback = args;
args = null;
}
if (typeof params === 'function') {
callback = params;
params = null;
}
if (!params) params = {};
if (!args) args = [];
if (!callback) callback = processExit;
switch (command) {
case 'start':
case 'stop':
(function () {
// Start stop of adapter
if (args[0]) {
Objects = require(__dirname + '/objects');
let adapter = args[0];
// If user accidentally wrote tools.appName.adapter => remove adapter
const regExp = new RegExp('^' + tools.appName + '\\.', 'i');
if (adapter && regExp.test(adapter)) {
adapter = adapter.substring(tools.appName.length + 1);
}
dbConnect(params, () => {
if (adapter === 'all') {
objects.getObjectList({startkey: 'system.adapter.', endkey: 'system.adapter.\u9999'}, (err, objs) => {
let count = 0;
for (let i = 0; i < objs.rows.length; i++) {
if (objs.rows[i].value.type !== 'instance') continue;
let obj = objs.rows[i].value;
if (command === 'start') {
if (!obj.common.enabled) {
obj.common.enabled = true;
count++;
obj.from = 'system.host.' + tools.getHostName() + '.cli';
obj.ts = new Date().getTime();
objects.setObject(obj._id, obj, () => {
console.log('Adapter "' + adapter + '" started.');
if (!--count) callback();
});
}
} else {
if (obj.common.enabled) {
obj.common.enabled = false;
count++;
obj.from = 'system.host.' + tools.getHostName() + '.cli';
obj.ts = new Date().getTime();
objects.setObject(obj._id, obj, () => {
console.log('Adapter "' + adapter + '" stopped.');
if (!--count) callback();
});
}
}
}
if (!count) callback();
});
} else {
if (adapter.indexOf('.') === -1) {
objects.getObjectList({startkey: 'system.adapter.' + adapter + '.', endkey: 'system.adapter.' + adapter + '.\u9999'}, (err, objs) => {
let obj;
if (!err && objs) {
for (let i = 0; i < objs.rows.length; i++) {
if (objs.rows[i].value.type !== 'instance') continue;
if (obj) {
console.log('Please enter instance of adapter, e.g. "' + obj._id.replace('system.adapter.', '') + '"');
callback(1);
}
obj = objs.rows[i].value;
}
}
if (!obj) {
console.log('Cannot find any instances of "' + adapter + '"');
callback(1);
} else {
if (command === 'start') {
if (!obj.common.enabled) {
obj.common.enabled = true;
obj.from = 'system.host.' + tools.getHostName() + '.cli';
obj.ts = new Date().getTime();
objects.setObject(obj._id, obj, () => {
console.log('Adapter "' + obj._id.replace('system.adapter.', '') + '" started.');
callback();
});
} else {
callback();
}
} else {
if (obj.common.enabled) {
obj.common.enabled = false;
obj.from = 'system.host.' + tools.getHostName() + '.cli';
obj.ts = new Date().getTime();
objects.setObject(obj._id, obj, () => {
console.log('Adapter "' + obj._id.replace('system.adapter.', '') + '" stopped.');
callback();
});
} else {
callback();
}
}
}
});
} else {
objects.getObject('system.adapter.' + adapter, (err, obj) => {
if (!err && obj) {
if (command === 'start') {
obj.common.enabled = true;
obj.from = 'system.host.' + tools.getHostName() + '.cli';
obj.ts = new Date().getTime();
objects.setObject('system.adapter.' + adapter, obj, () => {
console.log('Adapter "' + adapter + '" started.');
callback();
});
} else {
obj.common.enabled = false;
obj.from = 'system.host.' + tools.getHostName() + '.cli';
obj.ts = new Date().getTime();
objects.setObject('system.adapter.' + adapter, obj, () => {
console.log('Adapter "' + adapter + '" stopped.');
callback();
});
}
} else {
console.log('Adapter "' + adapter + '" does not exist.');
callback(24);
}
});
}
}
});
} else {
let memoryLimitMB = 0;
try {
let config = require(tools.getConfigFileName());
if (config && config.system && config.system.memoryLimitMB) {
memoryLimitMB = parseInt(config.system.memoryLimitMB, 10);
}
} catch (err) {
console.warn('Cannot read memoryLimitMB');
console.warn('May be config file does not exist.\nPlease call "' + tools.appName + ' setup first" to initialize the settings.')
}
let startObj = {
main: '../controller.js',
name: tools.appName + ' controller',
pidfile: __dirname + '/' + tools.appName + '.pid',
cwd: '../',
stopTimeout: 6000
};
if (memoryLimitMB) startObj.args = '--max-old-space-size=' + memoryLimitMB;
let daemon = require('daemonize2').setup(startObj);
daemon.on('error', error =>console.log('Error: ' + error.message));
daemon.on('stopped', () => {
// start KILLALL script if something still runs
if (command === 'stop' && !require('os').platform().match(/^win/)) {
let data = '';
fs.chmodSync(__dirname + '/../killall.sh', '777');
let child = require('child_process').spawn(__dirname + '/../killall.sh', []);
child.stdout.on('data', _data => data += _data.toString().replace('\n', ''));
child.stderr.on('data', _data => data += _data.toString().replace('\n', ''));
child.on('exit', exitCode => {
console.log('Exit code for "killall.sh": ' + exitCode);
callback();
});
}
});
daemon[command]();
}
})();
break;
case 'status':
case 'isrun':
(() => {
dbConnect(params, (objects, states, isOffline) => {
if (isOffline) {
console.log(tools.appName + ' is not running');
callback(100);
} else {
console.log(tools.appName + ' is running');
callback();
}
});
})();
break;
case 'r':
case 'restart':
(function () {
if (args[0]) {
Objects = require(__dirname + '/objects');
let adapter = args[0];
// If user accidentally wrote tools.appName.adapter => remove adapter
const regExp = new RegExp('^' + tools.appName + '\\.', 'i');
if (adapter && regExp.test(adapter)) {
adapter = adapter.substring(tools.appName.length + 1);
}
dbConnect(params, () => {
if (adapter.indexOf('.') === -1) {
objects.getObjectList({startkey: 'system.adapter.' + adapter + '.', endkey: 'system.adapter.' + adapter + '.\u9999'}, (err, objs) => {
let obj;
if (!err && objs) {
for (let i = 0; i < objs.rows.length; i++) {
if (objs.rows[i].value.type !== 'instance') continue;
if (obj) {
console.log('Please enter instance of adapter, e.g. "' + obj._id.replace('system.adapter.', '') + '"');
callback(1);
}
obj = objs.rows[i].value;
}
}
if (!obj) {
console.log('Cannot find any instances of "' + adapter + '"');
callback(1);
} else {
obj.common.enabled = true;
obj.from = 'system.host.' + tools.getHostName() + '.cli';
obj.ts = new Date().getTime();
objects.setObject(obj._id, obj, err => {
console.log('Adapter "' + obj._id.replace('system.adapter.', '') + '" restarted.');
callback();
});
}
});
} else {
objects.getObject('system.adapter.' + adapter, (err, obj) => {
if (!err && obj) {
obj.common.enabled = true;
obj.from = 'system.host.' + tools.getHostName() + '.cli';
obj.ts = new Date().getTime();
objects.setObject('system.adapter.' + adapter, obj, () => {
console.log('Adapter "' + adapter + '" restarted.');
callback();
});
} else {
console.log('Adapter "' + adapter + '" does not exist.');
callback(24);
}
});
}
});
} else {
let memoryLimitMB = 0;
try {
const config = require(tools.getConfigFileName());
if (config && config.system && config.system.memoryLimitMB) {
memoryLimitMB = parseInt(config.system.memoryLimitMB, 10);
}
} catch (err) {
console.warn('Cannot read memoryLimitMB');
}
const startObj = {
main: '../controller.js',
name: tools.appName + ' controller',
pidfile: __dirname + '/' + tools.appName + '.pid',
cwd: '../',
stopTimeout: 1000
};
if (memoryLimitMB) startObj.args = '--max-old-space-size=' + memoryLimitMB;
const daemon = require('daemonize2').setup(startObj);
daemon
.on('stopped', () => daemon.start())
.on('notrunning', () => daemon.start())
.on('error', error => console.log('Error: ' + error.message));
daemon.stop();
}
})();
break;
case '_restart':
restartController(() => callback());
break;
case 'update':
(function () {
Objects = require(__dirname + '/objects');
const repoUrl = args[0]; // Repo url or name
dbConnect(params, (_objects, _states) => {
const Repo = require(__dirname + '/setup/setupRepo.js');
const repo = new Repo({
objects: _objects,
states: _states
});
repo.showRepo(repoUrl, params, () => {
setTimeout(() => callback(), 2000)
});
});
})();
break;
case 'setup':
(function () {
if (args[0] === 'custom') {
const readline = require('readline');
let config;
// read actual configuration
try {
if (fs.existsSync(tools.getConfigFileName())) {
config = JSON.parse(fs.readFileSync(tools.getConfigFileName(), 'utf8'));
} else {
config = require(__dirname + '/../conf/' + tools.appName + '-dist.json');
}
} catch (e) {
config = require(__dirname + '/../conf/' + tools.appName + '-dist.json');
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Type of objects DB [(f)ile, (c)ouch, (r)edis], default [file]: ', otype => {
if (!otype) {
otype = 'file';
} else {
otype = (otype || '').toLowerCase();
if (otype === 'r') otype = 'redis';
if (otype === 'f') otype = 'file';
if (otype === 'c') otype = 'couch';
if (otype !== 'file' && otype !== 'couch' && otype !== 'redis') {
console.log('Unknown objects type: ' + otype);
callback(23);
}
}
rl.question('Host / Unix Socket of objects DB(' + otype + '), default[127.0.0.1]: ', ohost => {
if (!ohost) {
ohost = '127.0.0.1';
} else {
ohost = (ohost || '').toLowerCase();
}
let op;
if (otype === 'file') {
op = 9001;
} else if (otype === 'redis') {
op = 6379;
} else if (otype === 'couch') {
op = 5984;
}
rl.question('Port of objects DB(' + otype + '), default[' + op + ']: ', oport => {
let ot;
if (!oport) {
if (otype === 'file') {
oport = 9001;
ot = 'file';
} else if (otype === 'redis') {
ot = 'redis';
oport = 6379;
} else if (otype === 'couch') {
ot = 'couch';
oport = 5984;
}
} else {
oport = parseInt(oport, 10);
if (isNaN(oport)) {
console.log('Invalid objects port: ' + oport);
callback(23);
}
}
rl.question('Type of states DB [(f)file, (r)edis], default [' + ot + ']: ', stype => {
if (!stype) {
stype = ot;
} else {
stype = (stype || '').toLowerCase();
if (stype === 'r') stype = 'redis';
if (stype === 'f') stype = 'file';
if (stype !== 'file' && stype !== 'redis') {
console.log('Unknown states type: ' + stype);
callback(23);
}
}
rl.question('Host / Unix Socket of states DB (' + stype + '), default[' + ohost + ']: ', shost => {
if (!shost) {
shost = ohost;
} else {
shost = (shost || '').toLowerCase();
}
let sp;
if (stype === 'file') {
sp = 9000;
} else if (stype === 'redis') {
sp = 6379;
}
rl.question('Port of states DB (' + stype + '), default[' + sp + ']: ', sport => {
if (!sport) {
if (stype === 'file') {
sport = 9000;
} else if (stype === 'redis') {
sport = 6379;
}
} else {
sport = parseInt(sport, 10);
if (isNaN(sport)) {
console.log('Invalid states port: ' + sport);
callback(23);
}
}
if ((stype === 'file' && (shost === 'localhost' || shost === '127.0.0.1')) ||
(otype === 'file' && (ohost === 'localhost' || ohost === '127.0.0.1'))) {
rl.question('Data directory (file), default[../' + tools.getDefaultDataDir() + ']: ', dir => {
if (!dir) dir = tools.getDefaultDataDir();
rl.question('Host name of this machine [' + require('os').hostname() + ']: ', hname => {
if (!hname) {
hname = '';
} else {
hname = (hname || '');
if (hname.match(/\s/)) {
console.log('Invalid host name: ' + hname);
callback(23);
}
}
rl.close();
console.log('creating conf/' + tools.appName + '.json');
config.system = config.system || {};
config.system.hostname = hname;
config.objects.host = ohost;
config.objects.type = otype;
config.objects.port = oport;
if (config.objects.type === 'file') config.objects.dataDir = dir;
config.states.host = shost;
config.states.type = stype;
config.states.port = sport;
if (config.states.type === 'file') config.states.dataDir = dir;
fs.writeFileSync(tools.getConfigFileName(), JSON.stringify(config, null, 2));
});
});
} else {
rl.question('Host name of this machine [' + require('os').hostname() + ']: ', hname => {
if (!hname) {
hname = '';
} else {
hname = (hname || '');
if (hname.match(/\s/)) {
console.log('Invalid host name: ' + hname);
callback(23);
}
}
rl.close();
console.log('creating conf/' + tools.appName + '.json');
config.system = config.system || {};
config.system.hostname = hname;
config.objects.host = ohost;
config.objects.type = otype;
config.objects.port = oport;
config.states.host = shost;
config.states.type = stype;
config.states.port = sport;
config.states.dataDir = undefined;
config.objects.dataDir = undefined;
fs.writeFileSync(tools.getConfigFileName(), JSON.stringify(config, null, 2));
});
}
});
});
});
});
});
});
} else {
const Setup = require(__dirname + '/setup/setupSetup.js');
const setup = new Setup({
dbConnect: dbConnect,
processExit: callback,
params: params
});
let i = 0;
let isFirst;
let isRedis;
while (args[i] !== undefined) {
if (args[i] === 'first' || args[i] === '--first') {
isFirst = true;
} else if (args[i] === 'redis' || args[i] === '--redis') {
isRedis = true;
}
i++;
}
setup.setup((isFirst, isRedis) => {
if (isFirst) {
const Install = require(__dirname + '/setup/setupInstall.js');
const install = new Install({
objects: objects,
states: states,
installNpm: installNpm,
getRepository: getRepository,
processExit: callback,
params: params
});
//install admin adapter
install.createInstance('admin', {enabled: true, ignoreIfExists: true}, () => {
// check if discovery is installed too
try {
const path = require.resolve(tools.appName + '.discovery');
if (path) {
install.createInstance('discovery', {enabled: true, ignoreIfExists: true}, () => callback());
}
} catch (e) {
// no discovery found
callback();
}
});
} else {
callback();
}
}, isFirst, isRedis);
}
})();
break;
case 'url':
(function () {
Objects = require(__dirname + '/objects');
let url = args[0];
let name = args[1];
if (url[0] === '"' && url[url.length - 1] === '"') {
url = url.substring(1, url.length - 1);
}
// try to fix URL
if (url.match(/^https:\/\/github\.com\//)) {
url = url.replace(/\.git$/, '');
if (!url.match(/\.zip$/) && !url.match(/\.gz$/) && !url.match(/\/tarball\/[^\/]+$/)) {
url += '/tarball/master';
}
}
console.log('install ' + url);
dbConnect(params, () => {
const Install = require(__dirname + '/setup/setupInstall.js');
const install = new Install({
objects: objects,
states: states,
installNpm: installNpm,
getRepository: getRepository,
processExit: callback,
params: params
});
install.npmInstall(url, true, false, (_url, installDir) => {
const Upload = require(__dirname + '/setup/setupUpload.js');
const upload = new Upload({
states: states,
objects: objects,
processExit: callback
});
// Try to extract name from URL
if (!name) {
if (url.match(/\.tgz$|\.zip/)) {
const parts = url.split('/');
const last = parts.pop();
const mm = last.match(/\.([-_\w\d]+)\-[.\d]+/);
if (mm) {
name = mm[1];
}
} else {
const reG = new RegExp(tools.appName + '\\.([-_\\w\\d]+)\\/');
let m = reG.exec(url);
if (m) {
name = m[1];
} else {
const reg = new RegExp(tools.appName.toLowerCase() + '\\.([-_\\w\\d]+)\\/');
m = reg.exec(url);
if (m) name = m[1];
}
}
}
if (name) {
upload.uploadAdapter(name, true, true, () => {
upload.uploadAdapter(name, false, true, () => callback());
});
} else {
// Try to find io-package.json with newest date
const dirs = fs.readdirSync(installDir);
let date = null;
let dir = null;
for (let i = 0; i < dirs.length; i++) {
if (fs.existsSync(installDir + '/' + dirs[i] + '/io-package.json')) {
const stat = fs.statSync(installDir + '/' + dirs[i] + '/io-package.json');
if (!date || stat.mtime.getTime() > date.getTime()) {
dir = dirs[i];
date = stat.mtime;
}
}
}
// if modify time is not older than one hour
if (dir && (new Date()).getTime() - date.getTime() < 3600000) {
name = dir.substring(tools.appName.length + 1);
upload.uploadAdapter(name, true, true, () => {
upload.uploadAdapter(name, false, true, () => callback());
});
} else {
callback();
}
}
});
});
})();
break;
case 'info':
(function () {
Objects = require(__dirname + '/objects');
dbConnect(params, objects => {
tools.getHostInfo(objects, (err, data) => {
if (err) {
console.error('Cannot read host info: '+ err);
if (!data) {
return callback(20);
}
}
const formatters = require(__dirname + '/formatters');
const formatInfo = {
'Uptime': formatters.formatSeconds,
'System uptime': formatters.formatSeconds,
'RAM': formatters.formatRam,
'Speed': formatters.formatSpeed,
'Disk size': formatters.formatBytes,
'Disk free': formatters.formatBytes
};
for (const attr in data) {
if (data.hasOwnProperty(attr)) {
console.log(`${attr}${attr.length < 16 ? new Array(16 - attr.length).join(' ') : ''}: ${formatInfo[attr] ? formatInfo[attr](data[attr]) : data[attr] || ''}`);
}
}
callback();
});
});
})();
break;
case 'a':
case 'add':
case 'install':
case 'i':
(function () {
Objects = require(__dirname + '/objects');
let name = args[0];
let instance = args[1];
let repoUrl = args[2];
if (instance === 0) instance = '0';
if (repoUrl === 0) repoUrl = '0';
if (parseInt(instance, 10).toString() !== (instance || '').toString()) {
repoUrl = instance;
instance = null;
}
if (parseInt(repoUrl, 10).toString() === (repoUrl || '').toString()) {
const temp = instance;
instance = repoUrl;
repoUrl = temp;
}
if (parseInt(instance, 10).toString() === (instance || '').toString()) {
instance = parseInt(instance, 10);
params.instance = instance;
}
// If user accidentally wrote tools.appName.adapter => remove adapter
const regExp = new RegExp('^' + tools.appName + '\\.', 'i');
if (name && regExp.test(name)) {
name = name.substring(tools.appName.length + 1);
}
let adapterDir = tools.getAdapterDir(name);
dbConnect(params, () => {
const Install = require(__dirname + '/setup/setupInstall.js');
let install = new Install({
objects: objects,
states: states,
installNpm: installNpm,
getRepository: getRepository,
processExit: callback,
params: params
});
if (!fs.existsSync(adapterDir)) {
install.downloadPacket(repoUrl, name, null, () => {
if (command !== 'install' && command !== 'i') {
install.createInstance(name, params, () => callback());
} else {
const Upload = require(__dirname + '/setup/setupUpload.js');
let upload = new Upload({
states: states,
objects: objects,
processExit: callback
});
// create objects
install.uploadStaticObjects(name, () => {
upload.uploadAdapter(name, true, true, () => {
upload.uploadAdapter(name, false, true, () => callback());
});
});
}
});
} else {
if (command !== 'install' && command !== 'i') {
install.createInstance(name, params, () => callback());
} else {
console.log('adapter "' + name + '" yet installed. Use "upgrade" to install newer version.');
callback(51);
}
}
});
})();
break;
case 'upload':
case 'u':
(function () {
Objects = require(__dirname + '/objects');
const name = args[0];
const subTree = args[1];
if (name) {
dbConnect(params, () => {
const Upload = require(__dirname + '/setup/setupUpload.js');
const upload = new Upload({
states: states,
objects: objects,
processExit: callback
});
if (name === 'all') {
objects.getObjectList({startkey: 'system.adapter.', endkey: 'system.adapter.\u9999'}, (err, objs) => {
const adapters = [];
for (let i = 0; i < objs.rows.length; i++) {
if (objs.rows[i].value.type !== 'adapter') continue;
adapters.push(objs.rows[i].value.common.name);
}
upload.uploadAdapterFull(adapters, () => callback());
});
} else {
// if upload of file
if (name.indexOf('.') !== -1) {
if (!subTree) {
console.log('Please specify target name, like:\n ' + tools.appName + ' upload /file/picture.png /vis.0/main/img/picture.png');
callback(1);
}
upload.uploadFile(name, subTree, (err, newName) => {
if (!err) console.log('File "' + name + '" is successfully saved under ' + newName);
callback(err ? 40 : undefined);
});
} else {
if (subTree) {
upload.uploadAdapter(name, false, true, subTree, () => callback());
} else {
upload.uploadAdapter(name, true, true, () => {
upload.upgradeAdapterObjects(name, () => {
upload.uploadAdapter(name, false, true, () => callback());
});
});
}
}
}
});
} else {
console.log('No adapter name found!');
showHelp();
callback(1);
}
})();
break;
case 'delete':
case 'del':
(function () {
let adpr = args[0];
let instance = args[1];
// If user accidentally wrote tools.appName.adapter => remove adapter
const regExp = new RegExp('^' + tools.appName + '\\.', 'i');
if (adpr && regExp.test(adpr)) {
adpr = adpr.substring(tools.appName.length + 1);
}
if (!adpr) {
showHelp();
callback(2);
}
if (adpr && adpr.indexOf('.') !== -1) {
const parts = adpr.split('.');
adpr = parts[0];
instance = parts[1];
}
if (instance || instance === 0) {
dbConnect(params, () => {
const Install = require(__dirname + '/setup/setupInstall.js');
const install = new Install({
objects: objects,
state