prepare to use ports instead of pipes, if needed

This commit is contained in:
AJ ONeal 2018-06-29 15:18:32 -06:00
parent 8c3a89c25b
commit 59baac2d2e
1 changed files with 46 additions and 5 deletions

View File

@ -4,6 +4,7 @@ var common = module.exports;
var path = require('path');
var url = require('url');
var fs = require('fs');
var mkdirp = require('mkdirp');
var os = require('os');
var homedir = os.homedir();
@ -30,7 +31,50 @@ common.CONFIG_KEYS = [
//, '_otp' // otp should not be saved
//, '_token' // temporary token
common.pipename = function (config, newApi) {
common.getPort = function (config, cb) {
var portfile = path.resolve(config.sock || common.DEFAULT_SOCK_PATH, '..', 'telebit.port');
if (cb) {
return fs.readFile(portfile, 'utf8', function (err, text) {
cb(err, parseInt((text||'').trim(), 10) || null);
});
} else {
try {
return parseInt(fs.readFileSync(portfile, 'utf8').trim(), 10) || null;
} catch(e) {
return null;
}
}
};
common.setPort = function (config, num, cb) {
var portfile = path.resolve(config.sock || common.DEFAULT_SOCK_PATH, '..', 'telebit.port');
var numstr = (num || '').toString();
if (cb) {
return fs.writeFile(portfile, numstr, 'utf8', function (err) {
cb(err);
});
} else {
try {
return fs.writeFileSync(portfile, numstr, 'utf8');
} catch(e) {
return null;
}
}
};
common.removePort = function (config, cb) {
var portfile = path.resolve(config.sock || common.DEFAULT_SOCK_PATH, '..', 'telebit.port');
if (cb) {
return fs.unlink(portfile, function (err, text) {
cb(err, (text||'').trim());
});
} else {
try {
return fs.unlinkSync(portfile);
} catch(e) {
return null;
}
}
};
common.pipename = function (config) {
var _ipc = {
path: (config.sock || common.DEFAULT_SOCK_PATH)
, comment: (/^win/i.test(os.platform()) ? 'windows pipe' : 'unix socket')
@ -39,10 +83,7 @@ common.pipename = function (config, newApi) {
if ('pipe' === _ipc.type) {
_ipc.path = '\\\\?\\pipe' + _ipc.path.replace(/\//, '\\');
}
if (newApi) {
return _ipc;
}
return _ipc.path;
};
common.DEFAULT_SOCK_PATH = path.join(homedir, '.local/share/telebit/var/run', 'telebit.sock');
common.DEFAULT_CONFIG_PATH = path.join(homedir, '.config/telebit', 'telebitd.yml');