mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-27 00:37:14 +09:00
Merge pull request #235 from Hornwitser/config-part-3
Config Rewrite Part 3
This commit is contained in:
14 files changed
+527
-572
No files matched your search
@@ -5,8 +5,6 @@ before_install:
|
|||||||
- curl -o factorio.tar.gz -L https://www.factorio.com/get-download/latest/headless/linux64
|
- curl -o factorio.tar.gz -L https://www.factorio.com/get-download/latest/headless/linux64
|
||||||
- tar -xf factorio.tar.gz
|
- tar -xf factorio.tar.gz
|
||||||
- npm install -g codecov
|
- npm install -g codecov
|
||||||
# Needed for lib/manager/configManager
|
|
||||||
- echo {} > config.json
|
|
||||||
script:
|
script:
|
||||||
- npm run-script ci-cover
|
- npm run-script ci-cover
|
||||||
- codecov -f coverage/lcov.info
|
- codecov -f coverage/lcov.info
|
||||||
@@ -19,6 +19,8 @@ Version 2.0.0
|
|||||||
- The masterIP and masterPort config entries has been merged into masterURL.
|
- The masterIP and masterPort config entries has been merged into masterURL.
|
||||||
Breaks discordChat, playerManager, serverSelect, trainTeleports and
|
Breaks discordChat, playerManager, serverSelect, trainTeleports and
|
||||||
clusterioModel.
|
clusterioModel.
|
||||||
|
- Instance names can no longer be invalid Windows file names.
|
||||||
|
- Removed config management from the command line and the server manager.
|
||||||
|
|
||||||
|
|
||||||
Version 1.2.1
|
Version 1.2.1
|
||||||
|
|||||||
@@ -20,38 +20,96 @@ const crypto = require("crypto");
|
|||||||
const objectOps = require("lib/objectOps.js");
|
const objectOps = require("lib/objectOps.js");
|
||||||
const fileOps = require("lib/fileOps");
|
const fileOps = require("lib/fileOps");
|
||||||
const stringUtils = require("lib/stringUtils.js");
|
const stringUtils = require("lib/stringUtils.js");
|
||||||
const configManager = require("lib/manager/configManager.js");
|
|
||||||
const pluginManager = require("lib/manager/pluginManager");
|
const pluginManager = require("lib/manager/pluginManager");
|
||||||
|
const modManager = require("lib/manager/modManager");
|
||||||
const hashFile = require('lib/hash').hashFile;
|
const hashFile = require('lib/hash').hashFile;
|
||||||
|
|
||||||
|
// Uhm...
|
||||||
// argument parsing
|
|
||||||
const args = require('minimist')(process.argv.slice(2));
|
|
||||||
|
|
||||||
// require config.json
|
|
||||||
var config = require(args.config || './config');
|
|
||||||
var global = {};
|
var global = {};
|
||||||
|
|
||||||
const instance = process.argv[3];
|
/**
|
||||||
const instancedirectory = config.instanceDirectory + '/' + instance;
|
* Keeps track of the runtime parameters of an instance
|
||||||
const command = process.argv[2];
|
*/
|
||||||
|
class Instance {
|
||||||
|
constructor(dir, name) {
|
||||||
|
this._name = name;
|
||||||
|
this._dir = dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Name of the instance
|
||||||
|
*
|
||||||
|
* This should not be used for filesystem paths. See .path() for that.
|
||||||
|
*/
|
||||||
|
get name() {
|
||||||
|
return this._name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return path in instance
|
||||||
|
*
|
||||||
|
* Creates a path using path.join with the given parts that's relative to
|
||||||
|
* the directory of the instance. For example instance.path("mods")
|
||||||
|
* returns a path to the mods directory of the instance. If no parts are
|
||||||
|
* given it returns a path to the directory of the instance.
|
||||||
|
*/
|
||||||
|
path(...parts) {
|
||||||
|
return path.join(this._dir, ...parts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkFilename(name) {
|
||||||
|
// All of these are bad in Windows only, except for /, . and ..
|
||||||
|
// See: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
|
||||||
|
const badChars = /[<>:"\/\\|?*\x00-\x1f]/g;
|
||||||
|
const badEnd = /[. ]$/;
|
||||||
|
|
||||||
|
const oneToNine = [1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||||
|
const badNames = [
|
||||||
|
// Relative path components
|
||||||
|
'.', '..',
|
||||||
|
|
||||||
|
// Reserved filenames in Windows
|
||||||
|
'CON', 'PRN', 'AUX', 'NUL',
|
||||||
|
...oneToNine.map(n => `COM${n}`),
|
||||||
|
...oneToNine.map(n => `LPT${n}`),
|
||||||
|
];
|
||||||
|
|
||||||
|
if (typeof name !== "string") {
|
||||||
|
throw new Error("must be a string");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name === "") {
|
||||||
|
throw new Error("cannot be empty");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (badChars.test(name)) {
|
||||||
|
throw new Error('cannot contain <>:"\\/|=* or control characters');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (badNames.includes(name.toUpperCase())) {
|
||||||
|
throw new Error(
|
||||||
|
"cannot be named any of . .. CON PRN AUX NUL COM1-9 and LPT1-9"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (badEnd.test(name)) {
|
||||||
|
throw new Error("cannot end with . or space");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function needleOptionsWithTokenAuthHeader(config) {
|
||||||
|
return {
|
||||||
|
compressed: true,
|
||||||
|
headers: {
|
||||||
|
'x-access-token': config.masterAuthToken
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const needleOptionsWithTokenAuthHeader = {
|
|
||||||
compressed:true,
|
|
||||||
headers: {
|
|
||||||
'x-access-token': config.masterAuthToken
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
var instanceInfo = {};
|
var instanceInfo = {};
|
||||||
var commandBuffer=[];
|
var commandBuffer=[];
|
||||||
// messageInterface Management
|
|
||||||
setInterval(function(){
|
|
||||||
let command=commandBuffer.shift();
|
|
||||||
if(command){
|
|
||||||
messageInterfaceInternal(command[0], command[1], command[2], command[3]);
|
|
||||||
}
|
|
||||||
},config.msBetweenCommands || 50);
|
|
||||||
|
|
||||||
// function to handle sending commands into the game
|
// function to handle sending commands into the game
|
||||||
async function messageInterfaceInternal(command, callback, resolve, reject) {
|
async function messageInterfaceInternal(command, callback, resolve, reject) {
|
||||||
@@ -156,7 +214,7 @@ function printUsage() {
|
|||||||
console.error("node client.js manage");
|
console.error("node client.js manage");
|
||||||
}
|
}
|
||||||
|
|
||||||
async function listInstances() {
|
async function listInstances(config) {
|
||||||
let instanceNames = fileOps.getDirectoriesSync(config.instanceDirectory);
|
let instanceNames = fileOps.getDirectoriesSync(config.instanceDirectory);
|
||||||
let instances = [];
|
let instances = [];
|
||||||
for (instance of instanceNames) {
|
for (instance of instanceNames) {
|
||||||
@@ -171,37 +229,32 @@ async function listInstances() {
|
|||||||
console.log(asTable(instances));
|
console.log(asTable(instances));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function manage() {
|
async function manage(config, instance) {
|
||||||
// console.log("Launching mod manager");
|
// console.log("Launching mod manager");
|
||||||
//const fullUsage = 'node client.js manage [instance, "shared"] ["mods", "config"] ...';
|
//const fullUsage = 'node client.js manage [instance, "shared"] ["mods", "config"] ...';
|
||||||
function usage(instance, tool, action){
|
function usage(instance, tool, action){
|
||||||
if(tool && tool == "mods"){
|
if(tool && tool == "mods"){
|
||||||
console.log('node client.js manage '+instance+' '+tool+' ["list", "search", "add", "remove"]');
|
console.log('node client.js manage '+instance.name+' '+tool+' ["list", "search", "add", "remove"]');
|
||||||
} else if(tool && tool == "config") {
|
|
||||||
console.log('node client.js manage '+instance+' '+tool+' ["list", "edit"]');
|
|
||||||
} else if(tool && tool == "plugins") {
|
} else if(tool && tool == "plugins") {
|
||||||
console.log(`node client.js manage ${instance} ${tool} ["list", "add", "remove"]`);
|
console.log(`node client.js manage ${instance.name} ${tool} ["list", "add", "remove"]`);
|
||||||
} else {
|
} else {
|
||||||
console.log('node client.js manage '+(instance || '[instance, "shared"]') +' '+ (tool || '["mods", "config", "plugins"]') + ' ...');
|
console.log('node client.js manage '+(instance && instance.name || '[instance, "shared"]') +' '+ (tool || '["mods", "plugins"]') + ' ...');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const tool = process.argv[4] || "";
|
const tool = process.argv[4] || "";
|
||||||
const action = process.argv[5] || "";
|
const action = process.argv[5] || "";
|
||||||
if(instance){
|
if (instance !== undefined) {
|
||||||
if(tool == "mods"){
|
if(tool == "mods"){
|
||||||
(async function(){try{
|
(async function(){try{
|
||||||
// do require down here to reduce master load time
|
|
||||||
const modManager = require("lib/manager/modManager.js")(config);
|
|
||||||
|
|
||||||
// allow managing mods
|
// allow managing mods
|
||||||
if(action == "list"){
|
if(action == "list"){
|
||||||
console.log(await modManager.listMods(instance));
|
console.log(await modManager.listMods(config, instance));
|
||||||
} else if(action == "search"){
|
} else if(action == "search"){
|
||||||
console.log(await modManager.findMods(process.argv[6]));
|
console.log(await modManager.findMods(config, process.argv[6]));
|
||||||
} else if(action == "add" || action == "download"){
|
} else if(action == "add" || action == "download"){
|
||||||
await modManager.addMod(process.argv[6], instance);
|
await modManager.addMod(config, process.argv[6], instance);
|
||||||
} else if(action == "remove" || action == "rm" || action == "delete"){
|
} else if(action == "remove" || action == "rm" || action == "delete"){
|
||||||
await modManager.removeMod(process.argv[6], instance);
|
await modManager.removeMod(config, process.argv[6], instance);
|
||||||
} else {
|
} else {
|
||||||
usage(instance, tool);
|
usage(instance, tool);
|
||||||
}
|
}
|
||||||
@@ -210,23 +263,6 @@ async function manage() {
|
|||||||
console.log("Got error from modManager:")
|
console.log("Got error from modManager:")
|
||||||
console.log(e);
|
console.log(e);
|
||||||
}})();
|
}})();
|
||||||
} else if(tool == "config"){
|
|
||||||
// allow managing the config
|
|
||||||
if(action == "list" || action == "show" || action == "display"){
|
|
||||||
configManager.displayConfig(instance);
|
|
||||||
} else if(action == "edit"){
|
|
||||||
let newConfigValue = "";
|
|
||||||
process.argv.forEach((arg, i)=>{
|
|
||||||
if(i >= 8){
|
|
||||||
newConfigValue += " "+arg;
|
|
||||||
} else if(i >= 7){
|
|
||||||
newConfigValue += arg;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
configManager.editConfig(instance, process.argv[6], newConfigValue);
|
|
||||||
} else {
|
|
||||||
usage(instance, tool);
|
|
||||||
}
|
|
||||||
} else if(tool == "plugins"){
|
} else if(tool == "plugins"){
|
||||||
(async function(){try{
|
(async function(){try{
|
||||||
if(action == "list"){
|
if(action == "list"){
|
||||||
@@ -257,16 +293,16 @@ async function manage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function deleteInstance() {
|
async function deleteInstance(instance) {
|
||||||
if (!process.argv[3]) {
|
if (instance === undefined) {
|
||||||
console.error("Usage: node client.js delete [instance]");
|
console.error("Usage: node client.js delete [instance]");
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
} else if (typeof process.argv[3] == "string" && fs.existsSync(config.instanceDirectory+"/" + process.argv[3]) && process.argv[3] != "/" && process.argv[3] != "") {
|
} else if (fs.existsSync(instance.path())) {
|
||||||
fileOps.deleteFolderRecursiveSync(path.resolve(config.instanceDirectory, process.argv[3])); // TODO: Check if this can cause i-craft users to format their server by using wrong paths
|
fileOps.deleteFolderRecursiveSync(instance.path()); // TODO: Check if this can cause i-craft users to format their server by using wrong paths
|
||||||
console.log("Deleted instance " + process.argv[3]);
|
console.log("Deleted instance " + instance.name);
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
} else {
|
} else {
|
||||||
console.error("Instance not found: " + process.argv[3]);
|
console.error("Instance not found: " + instance.name);
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -290,30 +326,29 @@ async function downloadMod() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createInstance() {
|
async function createInstance(config, args, instance) {
|
||||||
// if instance does not exist, create it
|
// if instance does not exist, create it
|
||||||
console.log("Creating instance...");
|
console.log("Creating instance...");
|
||||||
fs.mkdirSync(instancedirectory);
|
fs.mkdirSync(instance.path());
|
||||||
fs.mkdirSync(instancedirectory + "/script-output/");
|
fs.mkdirSync(instance.path("script-output"));
|
||||||
fs.mkdirSync(instancedirectory + "/saves/");
|
fs.writeFileSync(instance.path("script-output", "output.txt"), "");
|
||||||
fs.writeFileSync(instancedirectory + "/script-output/output.txt", "");
|
fs.writeFileSync(instance.path("script-output", "orders.txt"), "");
|
||||||
fs.writeFileSync(instancedirectory + "/script-output/orders.txt", "");
|
fs.writeFileSync(instance.path("script-output", "txbuffer.txt"), "");
|
||||||
fs.writeFileSync(instancedirectory + "/script-output/txbuffer.txt", "");
|
fs.mkdirSync(instance.path("mods"));
|
||||||
fs.mkdirSync(instancedirectory + "/mods/");
|
fs.mkdirSync(instance.path("instanceMods"));
|
||||||
fs.mkdirSync(instancedirectory + "/instanceMods/");
|
fs.mkdirSync(instance.path("scenarios"));
|
||||||
fs.mkdirSync(instancedirectory + "/scenarios/");
|
ncp("lib/scenarios", instance.path("scenarios"), err => {
|
||||||
ncp("lib/scenarios", path.resolve(instancedirectory, "scenarios"), err => {
|
|
||||||
if (err) console.error(err)
|
if (err) console.error(err)
|
||||||
});
|
});
|
||||||
|
|
||||||
// fs.symlinkSync('../../../sharedMods', instancedirectory + "/mods", 'junction') // This is broken because it can only take a file as first argument, not a folder
|
// fs.symlinkSync('../../../sharedMods', instance.path("mods"), 'junction') // This is broken because it can only take a file as first argument, not a folder
|
||||||
fs.writeFileSync(instancedirectory + `/config.ini`, `[path]\r\n
|
fs.writeFileSync(instance.path("config.ini"), `[path]\r\n
|
||||||
read-data=${ path.resolve(config.factorioDirectory, "data") }\r\n
|
read-data=${ path.resolve(config.factorioDirectory, "data") }\r\n
|
||||||
write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n
|
write-data=${ instance.path() }\r\n
|
||||||
`);
|
`);
|
||||||
|
|
||||||
// this line is probably not needed anymore but Im not gonna remove it
|
// this line is probably not needed anymore but Im not gonna remove it
|
||||||
fs.copySync('sharedMods', path.join(instancedirectory, "mods"));
|
fs.copySync('sharedMods', instance.path("mods"));
|
||||||
let instconf = {
|
let instconf = {
|
||||||
"factorioPort": args.port || process.env.FACTORIOPORT || randomDynamicPort(),
|
"factorioPort": args.port || process.env.FACTORIOPORT || randomDynamicPort(),
|
||||||
"clientPort": args["rcon-port"] || process.env.RCONPORT || randomDynamicPort(),
|
"clientPort": args["rcon-port"] || process.env.RCONPORT || randomDynamicPort(),
|
||||||
@@ -325,11 +360,11 @@ write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n
|
|||||||
console.log(instconf);
|
console.log(instconf);
|
||||||
|
|
||||||
// create instance config
|
// create instance config
|
||||||
fs.writeFileSync(instancedirectory + "/config.json", JSON.stringify(instconf, null, 4));
|
fs.writeFileSync(instance.path("config.json"), JSON.stringify(instconf, null, 4));
|
||||||
|
|
||||||
let name = "Clusterio instance: " + instance;
|
let name = "Clusterio instance: " + instance.name;
|
||||||
if (config.username) {
|
if (config.username) {
|
||||||
name = config.username + "'s clusterio " + instance;
|
name = config.username + "'s clusterio " + instance.name;
|
||||||
}
|
}
|
||||||
let serversettings = {
|
let serversettings = {
|
||||||
"name": name,
|
"name": name,
|
||||||
@@ -348,15 +383,15 @@ write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n
|
|||||||
"afk_autokick_interval": 0,
|
"afk_autokick_interval": 0,
|
||||||
"auto_pause": config.auto_pause,
|
"auto_pause": config.auto_pause,
|
||||||
};
|
};
|
||||||
fs.writeFileSync(instancedirectory + "/server-settings.json", JSON.stringify(serversettings, null, 4));
|
fs.writeFileSync(instance.path("server-settings.json"), JSON.stringify(serversettings, null, 4));
|
||||||
console.log("Server settings: "+JSON.stringify(serversettings, null, 4));
|
console.log("Server settings: "+JSON.stringify(serversettings, null, 4));
|
||||||
console.log("Creating save .....");
|
console.log("Creating save .....");
|
||||||
let factorio = child_process.spawn(
|
let factorio = child_process.spawn(
|
||||||
'./' + config.factorioDirectory + '/bin/x64/factorio', [
|
'./' + config.factorioDirectory + '/bin/x64/factorio', [
|
||||||
'-c', instancedirectory + '/config.ini',
|
'-c', instance.path("config.ini"),
|
||||||
// '--create', instancedirectory + '/saves/save.zip',
|
// '--create', instance.path("saves", "save.zip"),
|
||||||
'--start-server-load-scenario', 'Hotpatch',
|
'--start-server-load-scenario', 'Hotpatch',
|
||||||
'--server-settings', instancedirectory + '/server-settings.json',
|
'--server-settings', instance.path("server-settings.json"),
|
||||||
'--rcon-port', Number(process.env.RCONPORT) || instconf.clientPort,
|
'--rcon-port', Number(process.env.RCONPORT) || instconf.clientPort,
|
||||||
'--rcon-password', instconf.clientPassword,
|
'--rcon-password', instconf.clientPassword,
|
||||||
], {
|
], {
|
||||||
@@ -400,37 +435,32 @@ write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function startInstance() {
|
async function startInstance(config, args, instance) {
|
||||||
// Exit if no instance specified (it should be, just a safeguard);
|
var instanceconfig = JSON.parse(await fs.readFile(instance.path("config.json")));
|
||||||
if(instancedirectory != config.instanceDirectory+"/undefined"){
|
instanceconfig.unique = stringUtils.hashCode(instanceconfig.clientPassword);
|
||||||
var instanceconfig = require(path.resolve(instancedirectory,'config'));
|
if (process.env.FACTORIOPORT) {
|
||||||
instanceconfig.unique = stringUtils.hashCode(instanceconfig.clientPassword);
|
instanceconfig.factorioPort = process.env.FACTORIOPORT;
|
||||||
if(process.env.FACTORIOPORT){
|
}
|
||||||
instanceconfig.factorioPort = process.env.FACTORIOPORT;
|
if (process.env.RCONPORT) {
|
||||||
}
|
instanceconfig.rconPort = process.env.RCONPORT;
|
||||||
if(process.env.RCONPORT){
|
|
||||||
instanceconfig.rconPort = process.env.RCONPORT;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
process.exit(1);
|
|
||||||
}
|
}
|
||||||
console.log("Deleting .tmp.zip files");
|
console.log("Deleting .tmp.zip files");
|
||||||
let savefiles = fs.readdirSync(path.join(instancedirectory,"saves"));
|
let savefiles = fs.readdirSync(instance.path("saves"));
|
||||||
for(i = 0; i < savefiles.length; i++){
|
for(i = 0; i < savefiles.length; i++){
|
||||||
if(savefiles[i].substr(savefiles[i].length - 8, 8) == ".tmp.zip") {
|
if(savefiles[i].substr(savefiles[i].length - 8, 8) == ".tmp.zip") {
|
||||||
fs.unlinkSync(path.resolve(instancedirectory, "saves", savefiles[i]));
|
fs.unlinkSync(instance.path("saves", savefiles[i]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console.log("Clusterio | Rotating old logs...");
|
console.log("Clusterio | Rotating old logs...");
|
||||||
// clean old log file to avoid crash
|
// clean old log file to avoid crash
|
||||||
try{
|
try{
|
||||||
let logPath = path.join(instancedirectory,'factorio-current.log');
|
let logPath = instance.path("factorio-current.log");
|
||||||
let stat = await fs.stat(logPath);
|
let stat = await fs.stat(logPath);
|
||||||
console.log(stat)
|
console.log(stat)
|
||||||
console.log(stat.isFile())
|
console.log(stat.isFile())
|
||||||
if(stat.isFile()){
|
if(stat.isFile()){
|
||||||
let logFilename = `factorio-${Math.floor(Date.parse(stat.mtime)/1000)}.log`;
|
let logFilename = `factorio-${Math.floor(Date.parse(stat.mtime)/1000)}.log`;
|
||||||
await fs.rename(logPath, path.join(instancedirectory, logFilename));
|
await fs.rename(logPath, instance.path(logFilename));
|
||||||
console.log(`Log rotated as ${logFilename}`);
|
console.log(`Log rotated as ${logFilename}`);
|
||||||
}
|
}
|
||||||
}catch(e){}
|
}catch(e){}
|
||||||
@@ -438,26 +468,26 @@ async function startInstance() {
|
|||||||
// (new Date).toGMTString()
|
// (new Date).toGMTString()
|
||||||
|
|
||||||
// move mods from ./sharedMods to the instances mod directory
|
// move mods from ./sharedMods to the instances mod directory
|
||||||
try{fs.mkdirSync(path.join(instancedirectory, "instanceMods"));}catch(e){}
|
try{fs.mkdirSync(instance.path("instanceMods"));}catch(e){}
|
||||||
try{rmdirSync(path.join(instancedirectory, "mods"));}catch(e){}
|
try{rmdirSync(instance.path("mods"));}catch(e){}
|
||||||
try {
|
try {
|
||||||
// mods directory that will be emptied (deleted) when closing the server to facilitate seperation of instanceMods and sharedMods
|
// mods directory that will be emptied (deleted) when closing the server to facilitate seperation of instanceMods and sharedMods
|
||||||
fs.mkdirSync(path.join(instancedirectory, "mods"));
|
fs.mkdirSync(instance.path("mods"));
|
||||||
} catch(e){}
|
} catch(e){}
|
||||||
console.log("Clusterio | Moving shared mods from sharedMods/ to instance/mods...");
|
console.log("Clusterio | Moving shared mods from sharedMods/ to instance/mods...");
|
||||||
fs.copySync('sharedMods', path.join(instancedirectory, "mods"));
|
fs.copySync('sharedMods', instance.path("mods"));
|
||||||
console.log("Clusterio | Moving instance specific mods from instance/instanceMods to instance/mods...");
|
console.log("Clusterio | Moving instance specific mods from instance/instanceMods to instance/mods...");
|
||||||
fs.copySync(path.join(instancedirectory, "instanceMods"), path.join(instancedirectory, "mods"));
|
fs.copySync(instance.path("instanceMods"), instance.path("mods"));
|
||||||
|
|
||||||
// Set paths for factorio so it reads and writes from the correct place even if the instance is imported from somewhere else
|
// Set paths for factorio so it reads and writes from the correct place even if the instance is imported from somewhere else
|
||||||
fs.writeFileSync(instancedirectory + `/config.ini`, `[path]\r\n
|
fs.writeFileSync(instance.path("config.ini"), `[path]\r\n
|
||||||
read-data=${ path.resolve(config.factorioDirectory, "data") }\r\n
|
read-data=${ path.resolve(config.factorioDirectory, "data") }\r\n
|
||||||
write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n
|
write-data=${ instance.path() }\r\n
|
||||||
`);
|
`);
|
||||||
|
|
||||||
// Spawn factorio server
|
// Spawn factorio server
|
||||||
//var serverprocess = child_process.exec(commandline);
|
//var serverprocess = child_process.exec(commandline);
|
||||||
fileOps.getNewestFile(instancedirectory + "/saves/", fs.readdirSync(instancedirectory + "/saves/"),function(err, latestSave) {
|
fileOps.getNewestFile(instance.path("saves"), fs.readdirSync(instance.path("saves")),function(err, latestSave) {
|
||||||
if(err) {
|
if(err) {
|
||||||
console.error("ERROR!");
|
console.error("ERROR!");
|
||||||
console.error("Your savefile seems to be missing. This might because you created an instance without having factorio\
|
console.error("Your savefile seems to be missing. This might because you created an instance without having factorio\
|
||||||
@@ -467,11 +497,11 @@ write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n
|
|||||||
// implicit global
|
// implicit global
|
||||||
serverprocess = child_process.spawn(
|
serverprocess = child_process.spawn(
|
||||||
'./' + config.factorioDirectory + '/bin/x64/factorio', [
|
'./' + config.factorioDirectory + '/bin/x64/factorio', [
|
||||||
'-c', instancedirectory + '/config.ini',
|
'-c', instance.path("config.ini"),
|
||||||
'--start-server', latestSave.file,
|
'--start-server', latestSave.file,
|
||||||
'--rcon-port', args["rcon-port"] || Number(process.env.RCONPORT) || instanceconfig.clientPort,
|
'--rcon-port', args["rcon-port"] || Number(process.env.RCONPORT) || instanceconfig.clientPort,
|
||||||
'--rcon-password', args["rcon-password"] || instanceconfig.clientPassword,
|
'--rcon-password', args["rcon-password"] || instanceconfig.clientPassword,
|
||||||
'--server-settings', instancedirectory + '/server-settings.json',
|
'--server-settings', instance.path("server-settings.json"),
|
||||||
'--port', args.port || Number(process.env.FACTORIOPORT) || instanceconfig.factorioPort
|
'--port', args.port || Number(process.env.FACTORIOPORT) || instanceconfig.factorioPort
|
||||||
], {
|
], {
|
||||||
'stdio': ['pipe', 'pipe', 'pipe']
|
'stdio': ['pipe', 'pipe', 'pipe']
|
||||||
@@ -507,7 +537,7 @@ write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n
|
|||||||
// check the logfile to see if the RCON interface is running as there is no way to continue without it
|
// check the logfile to see if the RCON interface is running as there is no way to continue without it
|
||||||
// we read the log every 2 seconds and stop looping when we start connecting to factorio
|
// we read the log every 2 seconds and stop looping when we start connecting to factorio
|
||||||
function checkRcon() {
|
function checkRcon() {
|
||||||
fs.readFile(instancedirectory+"/factorio-current.log", function (err, data) {
|
fs.readFile(instance.path("factorio-current.log"), function (err, data) {
|
||||||
// if (err) console.error(err);
|
// if (err) console.error(err);
|
||||||
if(data && data.indexOf('Starting RCON interface') > 0){
|
if(data && data.indexOf('Starting RCON interface') > 0){
|
||||||
client.connect({
|
client.connect({
|
||||||
@@ -526,7 +556,7 @@ write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n
|
|||||||
|
|
||||||
client.onDidAuthenticate(() => {
|
client.onDidAuthenticate(() => {
|
||||||
console.log('Clusterio | RCON Authenticated!');
|
console.log('Clusterio | RCON Authenticated!');
|
||||||
instanceManagement(instanceconfig); // start using rcons
|
instanceManagement(config, instance, instanceconfig); // start using rcons
|
||||||
});
|
});
|
||||||
client.onDidConnect(() => {
|
client.onDidConnect(() => {
|
||||||
console.log('Clusterio | RCON Connected!');
|
console.log('Clusterio | RCON Connected!');
|
||||||
@@ -548,7 +578,7 @@ write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n
|
|||||||
});
|
});
|
||||||
} else if(process.platform == "linux"){
|
} else if(process.platform == "linux"){
|
||||||
// don't open an RCON connection and just use stdio instead, does not work on windows.
|
// don't open an RCON connection and just use stdio instead, does not work on windows.
|
||||||
instanceManagement(instanceconfig);
|
instanceManagement(config, instance, instanceconfig);
|
||||||
process.on('SIGINT', function () {
|
process.on('SIGINT', function () {
|
||||||
console.log("Caught interrupt signal, sending ^C");
|
console.log("Caught interrupt signal, sending ^C");
|
||||||
serverprocess.kill("SIGINT");
|
serverprocess.kill("SIGINT");
|
||||||
@@ -562,22 +592,39 @@ write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function startClient() {
|
async function startClient() {
|
||||||
if (!fs.existsSync(config.instanceDirectory)) {
|
// argument parsing
|
||||||
fs.mkdirSync(config.instanceDirectory);
|
const args = require('minimist')(process.argv.slice(2));
|
||||||
}
|
|
||||||
if (!fs.existsSync("./sharedPlugins/")) {
|
const command = process.argv[2];
|
||||||
fs.mkdirSync("sharedPlugins");
|
|
||||||
}
|
// add better stack traces on promise rejection
|
||||||
if (!fs.existsSync("./sharedMods/")) {
|
process.on('unhandledRejection', r => console.log(r));
|
||||||
fs.mkdirSync("sharedMods");
|
|
||||||
|
console.log(`Requiring config from ${args.config || './config'}`);
|
||||||
|
const config = require(args.config || './config');
|
||||||
|
|
||||||
|
await fs.ensureDir(config.instanceDirectory);
|
||||||
|
await fs.ensureDir("sharedPlugins");
|
||||||
|
await fs.ensureDir("sharedMods");
|
||||||
|
|
||||||
|
let instance;
|
||||||
|
if (process.argv[3] !== undefined) {
|
||||||
|
let name = process.argv[3];
|
||||||
|
try {
|
||||||
|
checkFilename(name);
|
||||||
|
} catch (err) {
|
||||||
|
throw new Error(`Instance name ${err.message}`);
|
||||||
|
}
|
||||||
|
let dir = path.join(config.instanceDirectory, name);
|
||||||
|
instance = new Instance(dir, name);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the process title, shows up as the title of the CMD window on windows
|
// Set the process title, shows up as the title of the CMD window on windows
|
||||||
// and as the process name in ps/top on linux.
|
// and as the process name in ps/top on linux.
|
||||||
process.title = "clusterioClient "+instance;
|
if (instance) {
|
||||||
|
process.title = "clusterioClient "+instance.name;
|
||||||
|
}
|
||||||
|
|
||||||
// add better stack traces on promise rejection
|
|
||||||
process.on('unhandledRejection', r => console.log(r));
|
|
||||||
|
|
||||||
// make sure we have the master access token (can't write to master without it since clusterio 2.0)
|
// make sure we have the master access token (can't write to master without it since clusterio 2.0)
|
||||||
if(!config.masterAuthToken || typeof config.masterAuthToken !== "string"){
|
if(!config.masterAuthToken || typeof config.masterAuthToken !== "string"){
|
||||||
@@ -587,29 +634,36 @@ async function startClient() {
|
|||||||
You can retrieve your auth token from the master in secret-api-token.txt after running it once.");
|
You can retrieve your auth token from the master in secret-api-token.txt after running it once.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// messageInterface Management
|
||||||
|
setInterval(function(){
|
||||||
|
let command=commandBuffer.shift();
|
||||||
|
if(command){
|
||||||
|
messageInterfaceInternal(command[0], command[1], command[2], command[3]);
|
||||||
|
}
|
||||||
|
},config.msBetweenCommands || 50);
|
||||||
|
|
||||||
// handle commandline parameters
|
// handle commandline parameters
|
||||||
if (!command || command == "help" || command == "--help") {
|
if (!command || command == "help" || command == "--help") {
|
||||||
printUsage();
|
printUsage();
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
} else if (command == "list") {
|
} else if (command == "list") {
|
||||||
await listInstances();
|
await listInstances(config);
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
} else if (command == "manage"){
|
} else if (command == "manage"){
|
||||||
await manage();
|
await manage(config, instance);
|
||||||
// process.exit(0);
|
// process.exit(0);
|
||||||
} else if (command == "delete") {
|
} else if (command == "delete") {
|
||||||
await deleteInstance();
|
await deleteInstance(instance);
|
||||||
} else if (command == "download") {
|
} else if (command == "download") {
|
||||||
await downloadMod();
|
await downloadMod();
|
||||||
} else if (command == "start" && instance === undefined) {
|
} else if (command == "start" && instance === undefined) {
|
||||||
console.error("ERROR: No instanceName provided!");
|
console.error("ERROR: No instanceName provided!");
|
||||||
console.error("Usage: node client.js start [instanceName]");
|
console.error("Usage: node client.js start [instanceName]");
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
} else if (command == "start" && typeof instance == "string" && instance != "/" && !fs.existsSync(instancedirectory)) {
|
} else if (command == "start" && !fs.existsSync(instance.path())) {
|
||||||
await createInstance();
|
await createInstance(config, args, instance);
|
||||||
} else if (command == "start" && typeof instance == "string" && instance != "/" && fs.existsSync(instancedirectory)) {
|
} else if (command == "start" && fs.existsSync(instance.path())) {
|
||||||
await startInstance();
|
await startInstance(config, args, instance);
|
||||||
} else {
|
} else {
|
||||||
console.error("Invalid arguments, quitting.");
|
console.error("Invalid arguments, quitting.");
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
@@ -618,7 +672,7 @@ async function startClient() {
|
|||||||
|
|
||||||
// ensure instancemanagement only ever runs once
|
// ensure instancemanagement only ever runs once
|
||||||
var _instanceInitialized;
|
var _instanceInitialized;
|
||||||
async function instanceManagement(instanceconfig) {
|
async function instanceManagement(config, instance, instanceconfig) {
|
||||||
if (_instanceInitialized) return;
|
if (_instanceInitialized) return;
|
||||||
_instanceInitialized = true;
|
_instanceInitialized = true;
|
||||||
|
|
||||||
@@ -644,7 +698,7 @@ async function instanceManagement(instanceconfig) {
|
|||||||
for(let i = 0; i < pluginsToLoad.length; i++){
|
for(let i = 0; i < pluginsToLoad.length; i++){
|
||||||
let pluginLoadStarted = Date.now();
|
let pluginLoadStarted = Date.now();
|
||||||
let combinedConfig = deepmerge(instanceconfig,config,{clone:true});
|
let combinedConfig = deepmerge(instanceconfig,config,{clone:true});
|
||||||
combinedConfig.instanceName = instance;
|
combinedConfig.instanceName = instance.name;
|
||||||
let pluginConfig = pluginsToLoad[i];
|
let pluginConfig = pluginsToLoad[i];
|
||||||
|
|
||||||
if(!global.subscribedFiles) {
|
if(!global.subscribedFiles) {
|
||||||
@@ -674,23 +728,27 @@ async function instanceManagement(instanceconfig) {
|
|||||||
throw "FATAL ERROR IN " + pluginConfig.name + " FILE ALREADY SUBSCRIBED " + pluginConfig.scriptOutputFileSubscription;
|
throw "FATAL ERROR IN " + pluginConfig.name + " FILE ALREADY SUBSCRIBED " + pluginConfig.scriptOutputFileSubscription;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!fs.existsSync(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription)) {
|
let outputPath = instance.path(
|
||||||
|
"script-output",
|
||||||
|
pluginConfig.scriptOutputFileSubscription
|
||||||
|
);
|
||||||
|
if (!fs.existsSync(outputPath)) {
|
||||||
// Do something
|
// Do something
|
||||||
fs.writeFileSync(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription, "");
|
fs.writeFileSync(outputPath, "");
|
||||||
}
|
}
|
||||||
global.subscribedFiles[pluginConfig.scriptOutputFileSubscription] = true;
|
global.subscribedFiles[pluginConfig.scriptOutputFileSubscription] = true;
|
||||||
console.log("Clusterio | Registered file subscription on "+instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription);
|
console.log("Clusterio | Registered file subscription on "+outputPath);
|
||||||
|
|
||||||
|
|
||||||
if(!pluginConfig.fileReadDelay || pluginConfig.fileReadDelay == 0) {
|
if(!pluginConfig.fileReadDelay || pluginConfig.fileReadDelay == 0) {
|
||||||
// only wipe the file on restart for now, should most likely be rotated during runtime too
|
// only wipe the file on restart for now, should most likely be rotated during runtime too
|
||||||
fs.writeFileSync(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription, "");
|
fs.writeFileSync(outputPath, "");
|
||||||
let tail = new Tail(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription);
|
let tail = new Tail(outputPath);
|
||||||
tail.on("line", function (data) {
|
tail.on("line", function (data) {
|
||||||
plugins[i].scriptOutput(data);
|
plugins[i].scriptOutput(data);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
fs.watch(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription, fileChangeHandler);
|
fs.watch(outputPath, fileChangeHandler);
|
||||||
// run once in case a plugin wrote out information before the plugin loaded fully
|
// run once in case a plugin wrote out information before the plugin loaded fully
|
||||||
// delay, so the socket got enough time to connect
|
// delay, so the socket got enough time to connect
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
@@ -703,11 +761,11 @@ async function instanceManagement(instanceconfig) {
|
|||||||
setTimeout(
|
setTimeout(
|
||||||
() => {
|
() => {
|
||||||
// get array of lines in file
|
// get array of lines in file
|
||||||
let stuff = fs.readFileSync(instancedirectory + "/script-output/" + filename, "utf8").split("\n");
|
let stuff = fs.readFileSync(instance.path("script-output", filename), "utf8").split("\n");
|
||||||
|
|
||||||
// if you found anything, reset the file
|
// if you found anything, reset the file
|
||||||
if (stuff[0]) {
|
if (stuff[0]) {
|
||||||
fs.writeFileSync(instancedirectory + "/script-output/" + filename, "");
|
fs.writeFileSync(instance.path("script-output", filename), "");
|
||||||
}
|
}
|
||||||
for (let o = 0; o < stuff.length; o++) {
|
for (let o = 0; o < stuff.length; o++) {
|
||||||
if (stuff[o] && !stuff[o].includes('\u0000\u0000')) {
|
if (stuff[o] && !stuff[o].includes('\u0000\u0000')) {
|
||||||
@@ -745,7 +803,7 @@ async function instanceManagement(instanceconfig) {
|
|||||||
unique: instanceconfig.unique,
|
unique: instanceconfig.unique,
|
||||||
publicIP: config.publicIP, // IP of the server should be global for all instances, so we pull that straight from the config
|
publicIP: config.publicIP, // IP of the server should be global for all instances, so we pull that straight from the config
|
||||||
mods:modHashes,
|
mods:modHashes,
|
||||||
instanceName: instance,
|
instanceName: instance.name,
|
||||||
info: instanceconfig.info,
|
info: instanceconfig.info,
|
||||||
};
|
};
|
||||||
if(playerCount){
|
if(playerCount){
|
||||||
@@ -762,7 +820,7 @@ async function instanceManagement(instanceconfig) {
|
|||||||
global.mac = mac;
|
global.mac = mac;
|
||||||
payload.mac = mac;
|
payload.mac = mac;
|
||||||
// console.log("Registered our presence with master "+config.masterURL+" at " + payload.time);
|
// console.log("Registered our presence with master "+config.masterURL+" at " + payload.time);
|
||||||
needle.post(config.masterURL + '/api/getID', payload, needleOptionsWithTokenAuthHeader, function (err, response, body) {
|
needle.post(config.masterURL + '/api/getID', payload, needleOptionsWithTokenAuthHeader(config), function (err, response, body) {
|
||||||
if (err && err.code != "ECONNRESET"){
|
if (err && err.code != "ECONNRESET"){
|
||||||
console.error("We got problems, something went wrong when contacting master "+config.masterURL+" at " + payload.time);
|
console.error("We got problems, something went wrong when contacting master "+config.masterURL+" at " + payload.time);
|
||||||
console.error(err);
|
console.error(err);
|
||||||
@@ -795,7 +853,7 @@ async function instanceManagement(instanceconfig) {
|
|||||||
modName: modHashes[i].modName,
|
modName: modHashes[i].modName,
|
||||||
hash: modHashes[i].hash,
|
hash: modHashes[i].hash,
|
||||||
};
|
};
|
||||||
needle.post(config.masterURL + '/api/checkMod', payload, needleOptionsWithTokenAuthHeader, function (err, response, body) {
|
needle.post(config.masterURL + '/api/checkMod', payload, needleOptionsWithTokenAuthHeader(config), function (err, response, body) {
|
||||||
if(err) console.error("Unable to contact master server /api/checkMod! Please check your config.json.");
|
if(err) console.error("Unable to contact master server /api/checkMod! Please check your config.json.");
|
||||||
if(response && body && body == "found") {
|
if(response && body && body == "found") {
|
||||||
console.log("master has mod "+modHashes[i].modName);
|
console.log("master has mod "+modHashes[i].modName);
|
||||||
@@ -817,7 +875,7 @@ async function instanceManagement(instanceconfig) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
var form = req.form();
|
var form = req.form();
|
||||||
form.append('file', fs.createReadStream(config.instanceDirectory+"/"+instance+"/mods/"+mod));
|
form.append('file', fs.createReadStream(instance.path("mods", mod)));
|
||||||
} else {
|
} else {
|
||||||
console.log("Not sending mod: " + mod + " to master because config.uploadModsToMaster is not enabled")
|
console.log("Not sending mod: " + mod + " to master because config.uploadModsToMaster is not enabled")
|
||||||
}
|
}
|
||||||
@@ -829,24 +887,23 @@ async function instanceManagement(instanceconfig) {
|
|||||||
|
|
||||||
// string, function
|
// string, function
|
||||||
// returns [{modName:string,hash:string}, ... ]
|
// returns [{modName:string,hash:string}, ... ]
|
||||||
function hashMods(instanceName, callback) {
|
function hashMods(instance, callback) {
|
||||||
if(!callback) {
|
if(!callback) {
|
||||||
throw new Error("ERROR in function hashMods NO CALLBACK");
|
throw new Error("ERROR in function hashMods NO CALLBACK");
|
||||||
}
|
}
|
||||||
|
|
||||||
let modsDir = config.instanceDirectory+"/"+instanceName+"/mods/";
|
|
||||||
function hashMod(name) {
|
function hashMod(name) {
|
||||||
if (path.extname(name) != ".zip") {
|
if (path.extname(name) != ".zip") {
|
||||||
// Can't hash unzipped mods, return null that's filtered out later
|
// Can't hash unzipped mods, return null that's filtered out later
|
||||||
return null;
|
return null;
|
||||||
} else {
|
} else {
|
||||||
return hashFile(modsDir+name).then(hash => (
|
return hashFile(instance.path("mods", name)).then(hash => (
|
||||||
{modName: name, hash: hash}
|
{modName: name, hash: hash}
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let promises = fs.readdirSync(modsDir).map(hashMod);
|
let promises = fs.readdirSync(instance.path("mods")).map(hashMod);
|
||||||
Promise.all(promises).then(hashes => {
|
Promise.all(promises).then(hashes => {
|
||||||
// Remove null entries from hashMod
|
// Remove null entries from hashMod
|
||||||
callback(hashes.filter(entry => entry !== null));
|
callback(hashes.filter(entry => entry !== null));
|
||||||
@@ -855,6 +912,8 @@ function hashMods(instanceName, callback) {
|
|||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
// For testing only
|
// For testing only
|
||||||
|
_Instance: Instance,
|
||||||
|
_checkFilename: checkFilename,
|
||||||
_randomDynamicPort: randomDynamicPort,
|
_randomDynamicPort: randomDynamicPort,
|
||||||
_generatePassword: generatePassword,
|
_generatePassword: generatePassword,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
/**
|
|
||||||
Provides tools for managing both masters and slaves config files.
|
|
||||||
@module configManager
|
|
||||||
*/
|
|
||||||
// require modules
|
|
||||||
const asTable = require("as-table").configure({delimiter: ' | '});
|
|
||||||
const fs = require("fs");
|
|
||||||
|
|
||||||
// internal requires
|
|
||||||
var config = require("./../../config");
|
|
||||||
const objectOps = require("./../objectOps.js");
|
|
||||||
/**
|
|
||||||
console.log()s each entry in the config
|
|
||||||
|
|
||||||
@param {string} instance Either undefined, "shared" or the instance to show the config for.
|
|
||||||
*/
|
|
||||||
module.exports.displayConfig = function(instance){
|
|
||||||
console.log(asTable(this.getConfig(instance)));
|
|
||||||
}
|
|
||||||
module.exports.getConfig = async function(instance){
|
|
||||||
if(!instance || instance == "shared"){
|
|
||||||
let configArray = [];
|
|
||||||
Object.keys(config).forEach(key=>{
|
|
||||||
if(key != "__comment"){
|
|
||||||
if(typeof config[key] == "object"){
|
|
||||||
configArray.push({entry: key, value: JSON.stringify(config[key])});
|
|
||||||
} else configArray.push({entry: key, value: config[key]});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return configArray;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
module.exports.editConfig = function(instance, entry, newValue){
|
|
||||||
if(!instance || instance == "shared"){
|
|
||||||
if(config[entry] && newValue){
|
|
||||||
if(objectOps.isJSON(newValue)){
|
|
||||||
config[entry] = JSON.parse(newValue);
|
|
||||||
console.log("Changed config entry "+entry+" from "+JSON.stringify(config[entry])+" to "+JSON.stringify(newValue));
|
|
||||||
// console.log("new config file:");
|
|
||||||
// console.log(JSON.stringify(config, null, " "))
|
|
||||||
fs.writeFileSync("config.json", JSON.stringify(config, null, 4));
|
|
||||||
return {
|
|
||||||
ok:true,
|
|
||||||
msg:`Changed config entry ${entry} from Object to ${JSON.stringify(newValue)}`,
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
config[entry] = newValue;
|
|
||||||
console.log("Changed config entry "+entry+" from "+config[entry]+" to '"+newValue+"'");
|
|
||||||
// console.log("new config file:");
|
|
||||||
// console.log(JSON.stringify(config, null, " "))
|
|
||||||
fs.writeFileSync("config.json", JSON.stringify(config, null, 4));
|
|
||||||
return {
|
|
||||||
ok:true,
|
|
||||||
msg:`Changed config entry ${entry} from ***** to '${newValue}'`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return {
|
|
||||||
ok:false,
|
|
||||||
msg:`No such config parameter`,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return {
|
|
||||||
ok:false,
|
|
||||||
msg:`Editing config for single instances is not yet supported`,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
+236
-229
@@ -11,9 +11,9 @@ const https = require('follow-redirects').https;
|
|||||||
const factorioAPI = require("node-factorio-api");
|
const factorioAPI = require("node-factorio-api");
|
||||||
const sLog = require("single-line-log").stdout;
|
const sLog = require("single-line-log").stdout;
|
||||||
const query = require('cli-interact').getYesNo;
|
const query = require('cli-interact').getYesNo;
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
const fileOps = require("lib/fileOps");
|
const fileOps = require("lib/fileOps");
|
||||||
// const config = require("./../../config");
|
|
||||||
|
|
||||||
|
|
||||||
function ellipse(str, max){
|
function ellipse(str, max){
|
||||||
@@ -23,251 +23,250 @@ function ellipse(str, max){
|
|||||||
function formatBytes(a,b){if(0==a)return"0 Bytes";var c=1024,d=b||2,e=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],f=Math.floor(Math.log(a)/Math.log(c));return parseFloat((a/Math.pow(c,f)).toFixed(d))+" "+e[f]};
|
function formatBytes(a,b){if(0==a)return"0 Bytes";var c=1024,d=b||2,e=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],f=Math.floor(Math.log(a)/Math.log(c));return parseFloat((a/Math.pow(c,f)).toFixed(d))+" "+e[f]};
|
||||||
|
|
||||||
|
|
||||||
module.exports = function(config){
|
/**
|
||||||
if(!config) config = require("./../../config");
|
Lists mods for an instance as a table. Warning, handles printing internally.
|
||||||
const instances = require("./../getInstances.js")(config).sync();
|
@param {Instance} instance - Instance object, see client.js
|
||||||
return {
|
|
||||||
/**
|
|
||||||
Lists mods for an instance as a table. Warning, handles printing internally.
|
|
||||||
@param {string} instance - Name of the instance or "shared"
|
|
||||||
|
|
||||||
@example
|
@example
|
||||||
var modManager = require("modManager")(config);
|
var modManager = require("modManager");
|
||||||
modManager.listMods("testInstance");
|
modManager.listMods(config, instance);
|
||||||
// console.logs table of mods installed on instance
|
// console.logs table of mods installed on instance
|
||||||
modManager.listMods("shared");
|
// if instance.name is shared:
|
||||||
// console.logs mods located in /sharedMods as a nice table
|
// console.logs mods located in /sharedMods as a nice table
|
||||||
*/
|
*/
|
||||||
listMods: function(instance){
|
async function listMods(config, instance) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
if(instance && instances.includes(instance)){
|
const instances = require("./../getInstances.js")(config).sync();
|
||||||
factorioAPI.init(false, config.instanceDirectory+'/'+instance+'/instanceMods', config.instanceDirectory+'/'+instance+'/saves', config.factorio_version);
|
if (instances.includes(instance.name)) {
|
||||||
factorioAPI.authenticate({
|
factorioAPI.init(false, instance.path("instanceMods"), instance.path("saves"), config.factorio_version);
|
||||||
username: config.username,
|
factorioAPI.authenticate({
|
||||||
token: config.token,
|
username: config.username,
|
||||||
require_ownership: false
|
token: config.token,
|
||||||
}).then(token => {
|
require_ownership: false
|
||||||
console.log("* Currently installed:");
|
}).then(token => {
|
||||||
factorioAPI.readModZips().then(list => {
|
console.log("* Currently installed:");
|
||||||
console.log(asTable(list.map(mod => {
|
factorioAPI.readModZips().then(list => {
|
||||||
return {
|
console.log(asTable(list.map(mod => {
|
||||||
name:(mod.title || mod.name),
|
return {
|
||||||
version:mod.version,
|
name:(mod.title || mod.name),
|
||||||
date:mod.date,
|
version:mod.version,
|
||||||
factorio_ver:mod.factorio_version,
|
date:mod.date,
|
||||||
author:mod.author,
|
factorio_ver:mod.factorio_version,
|
||||||
}
|
author:mod.author,
|
||||||
})));
|
}
|
||||||
});
|
})));
|
||||||
// Had issues earlier due to bug in node-factorio-api, see https://github.com/Danacus/node-factorio-api/issues/2
|
});
|
||||||
// bug is resolved, thanks to @Danacus and @brotherpot
|
// Had issues earlier due to bug in node-factorio-api, see https://github.com/Danacus/node-factorio-api/issues/2
|
||||||
factorioAPI.getModsFromSaves().then(list => {
|
// bug is resolved, thanks to @Danacus and @brotherpot
|
||||||
console.log("* Mods used in save:");
|
factorioAPI.getModsFromSaves().then(list => {
|
||||||
console.log(asTable(list[0].mods))
|
console.log("* Mods used in save:");
|
||||||
});
|
console.log(asTable(list[0].mods))
|
||||||
}).catch(reason => {
|
});
|
||||||
console.log("Failed to authenticate to factorio.com! Please check your connection and the username+token used for authentication in config.json");
|
}).catch(reason => {
|
||||||
resolve();
|
console.log("Failed to authenticate to factorio.com! Please check your connection and the username+token used for authentication in config.json");
|
||||||
});
|
resolve();
|
||||||
} else {
|
|
||||||
// list shared mods in /sharedMods/
|
|
||||||
factorioAPI.init(false, 'sharedMods/', '', config.factorio_version);
|
|
||||||
factorioAPI.authenticate({
|
|
||||||
username: config.username,
|
|
||||||
token: config.token,
|
|
||||||
require_ownership: false
|
|
||||||
}).then(() => {
|
|
||||||
console.log("\r\n")
|
|
||||||
console.log("* Mods shared by all instances:")
|
|
||||||
factorioAPI.getInstalledMods().then(mods => {
|
|
||||||
console.log(asTable(mods));
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
}).catch(e => {
|
|
||||||
reject(new Error(e));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// get JSON data about GH releases
|
|
||||||
/*let res = syncRequest('GET', 'https://api.github.com/repos/Danielv123/factorioClusterioMod/releases', {"headers":{"User-Agent":"factorioClusterio"}});
|
|
||||||
let url = JSON.parse(res.getBody())[0].assets[0].browser_download_url;
|
|
||||||
let name = JSON.parse(res.getBody())[0].assets[0].name;
|
|
||||||
console.log(JSON.parse(res.getBody()))
|
|
||||||
*/
|
|
||||||
});
|
});
|
||||||
},
|
} else {
|
||||||
/**
|
// list shared mods in /sharedMods/
|
||||||
Searches mods.factorio.com for mods matching a search term and prints
|
factorioAPI.init(false, 'sharedMods/', '', config.factorio_version);
|
||||||
the results to console as a neat looking table
|
factorioAPI.authenticate({
|
||||||
|
username: config.username,
|
||||||
|
token: config.token,
|
||||||
|
require_ownership: false
|
||||||
|
}).then(() => {
|
||||||
|
console.log("\r\n")
|
||||||
|
console.log("* Mods shared by all instances:")
|
||||||
|
factorioAPI.getInstalledMods().then(mods => {
|
||||||
|
console.log(asTable(mods));
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
}).catch(e => {
|
||||||
|
reject(new Error(e));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@param {string} searchTerm What to search for
|
// get JSON data about GH releases
|
||||||
|
/*let res = syncRequest('GET', 'https://api.github.com/repos/Danielv123/factorioClusterioMod/releases', {"headers":{"User-Agent":"factorioClusterio"}});
|
||||||
|
let url = JSON.parse(res.getBody())[0].assets[0].browser_download_url;
|
||||||
|
let name = JSON.parse(res.getBody())[0].assets[0].name;
|
||||||
|
console.log(JSON.parse(res.getBody()))
|
||||||
*/
|
*/
|
||||||
findMods: function(searchTerm){
|
});
|
||||||
return new Promise((resolve, reject) => {
|
}
|
||||||
factorioAPI.init(false);
|
|
||||||
|
/**
|
||||||
|
Searches mods.factorio.com for mods matching a search term and prints
|
||||||
|
the results to console as a neat looking table
|
||||||
|
|
||||||
|
@param {string} searchTerm What to search for
|
||||||
|
*/
|
||||||
|
async function findMods(config, searchTerm) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
factorioAPI.init(false);
|
||||||
|
factorioAPI.authenticate({
|
||||||
|
username: config.username,
|
||||||
|
token: config.token,
|
||||||
|
require_ownership: false
|
||||||
|
}).then(token => {
|
||||||
|
factorioAPI.searchMods(searchTerm).then(mods => {
|
||||||
|
let result = asTable(mods.reverse().map(mod => {
|
||||||
|
return {
|
||||||
|
title:ellipse(mod.title, 50),
|
||||||
|
name:ellipse(mod.name, 30),
|
||||||
|
downloads:mod.downloads_count,
|
||||||
|
updated: moment(mod.updated_at).format("DD.MM.YY"),
|
||||||
|
latest_version: mod.latest_release.version,
|
||||||
|
owner:mod.owner,
|
||||||
|
//license: mod.license_name,
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
resolve(result);
|
||||||
|
// console.log(result);
|
||||||
|
});
|
||||||
|
}).catch(e => {
|
||||||
|
if (e.contains("Insufficient information")) console.log("We are missing some parameters required for logging in! Make sure your factorio username and token are specified in config.json.");
|
||||||
|
reject(new Error(e));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addMod(config, term, instance) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (instance.name == "shared") {
|
||||||
|
var modDirectory = "sharedMods";
|
||||||
|
} else {
|
||||||
|
var modDirectory = instance.path("instanceMods");
|
||||||
|
}
|
||||||
|
if (term && term.length > 0) {
|
||||||
|
if (term.includes("mods.factorio.com/mods/")) { // https://mods.factorio.com/mods/Danielv123/ChooChoo
|
||||||
|
// treat it as a link download
|
||||||
|
factorioAPI.init(false, modDirectory, "", config.factorio_version);
|
||||||
factorioAPI.authenticate({
|
factorioAPI.authenticate({
|
||||||
username: config.username,
|
username: config.username,
|
||||||
token: config.token,
|
token: config.token,
|
||||||
require_ownership: false
|
require_ownership: false
|
||||||
}).then(token => {
|
}).then(() => {
|
||||||
factorioAPI.searchMods(searchTerm).then(mods => {
|
factorioAPI.searchMods(term.split("/")[term.split("/").length-1]).then(body => {
|
||||||
let result = asTable(mods.reverse().map(mod => {
|
console.log("Im gonna download: "+body[0].name + " in version: " + body[0].latest_release.version);
|
||||||
return {
|
factorioAPI.downloadMod( {name: body[0].name, version: body[0].latest_release.version}).then(()=>{
|
||||||
title:ellipse(mod.title, 50),
|
console.log("Mod downloaded");
|
||||||
name:ellipse(mod.name, 30),
|
resolve();
|
||||||
downloads:mod.downloads_count,
|
});
|
||||||
updated: moment(mod.updated_at).format("DD.MM.YY"),
|
|
||||||
latest_version: mod.latest_release.version,
|
|
||||||
owner:mod.owner,
|
|
||||||
//license: mod.license_name,
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
resolve(result);
|
|
||||||
// console.log(result);
|
|
||||||
});
|
});
|
||||||
}).catch(e => {
|
|
||||||
if(e.contains("Insufficient information")) console.log("We are missing some parameters required for logging in! Make sure your factorio username and token are specified in config.json.");
|
|
||||||
reject(new Error(e));
|
|
||||||
});
|
});
|
||||||
});
|
} else if (term.includes("github.com")) { // https://github.com/Danielv123/factorioClusterioMod
|
||||||
},
|
// treat it as a github releases download
|
||||||
addMod: function(term, instance){
|
let apiURL = "https://api.github.com/repos/" + term.split("/")[3] + "/" + term.split("/")[4] + "/releases"; // https://api.github.com/repos/Danielv123/factorioClusterioMod/releases
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
if(instance == "shared"){ // modDirectory has to end in /
|
let res = syncRequest('GET', apiURL, {"headers":{"User-Agent":"factorioClusterio"}});
|
||||||
var modDirectory = "sharedMods/";
|
let url = JSON.parse(res.getBody())[0].assets[0].browser_download_url;
|
||||||
} else {
|
let name = JSON.parse(res.getBody())[0].assets[0].name;
|
||||||
var modDirectory = config.instanceDirectory+"/"+instance+"/instanceMods/";
|
if (url) {
|
||||||
}
|
console.log("Downloading " + url);
|
||||||
if(term && term.length > 0){
|
let file = fs.createWriteStream(path.join(modDirectory, name));
|
||||||
if(term.includes("mods.factorio.com/mods/")){ // https://mods.factorio.com/mods/Danielv123/ChooChoo
|
let bytesDownloaded = 0;
|
||||||
// treat it as a link download
|
let downloadStartTime = Date.now();
|
||||||
factorioAPI.init(false, modDirectory, "", config.factorio_version);
|
https.get(url, function(response) {
|
||||||
factorioAPI.authenticate({
|
let bytesToDownload = response.headers['content-length'];
|
||||||
username: config.username,
|
response.pipe(file);
|
||||||
token: config.token,
|
response.on("data", chunk => {
|
||||||
require_ownership: false
|
bytesDownloaded += chunk.length;
|
||||||
}).then(() => {
|
let downloadTimeElapsed = Date.now() - downloadStartTime;
|
||||||
factorioAPI.searchMods(term.split("/")[term.split("/").length-1]).then(body => {
|
let bytesPerSecond = bytesDownloaded / (downloadTimeElapsed/1000);
|
||||||
console.log("Im gonna download: "+body[0].name + " in version: " + body[0].latest_release.version);
|
let timeToComplete = Math.floor((bytesToDownload - bytesDownloaded)/bytesPerSecond);
|
||||||
factorioAPI.downloadMod( {name: body[0].name, version: body[0].latest_release.version}).then(()=>{
|
sLog("Downloading "+name+" "+(bytesDownloaded/bytesToDownload*100).toPrecision(3)+"% ("+formatBytes(bytesDownloaded)+" / "+formatBytes(bytesToDownload)+")\r\n"+
|
||||||
console.log("Mod downloaded");
|
"about "+timeToComplete+" seconds remaining ("+formatBytes(bytesPerSecond)+"/s)");
|
||||||
resolve();
|
}).on("end", x => {
|
||||||
});
|
sLog.clear();
|
||||||
});
|
console.log(" Downloaded in "+moment.utc(moment.duration(Date.now()-downloadStartTime).as('milliseconds')).format('mm:ss')); // because sLog.clear() doesn't seem to do the job of ending the line properly
|
||||||
|
resolve();
|
||||||
});
|
});
|
||||||
} else if(term.includes("github.com")){ // https://github.com/Danielv123/factorioClusterioMod
|
});
|
||||||
// treat it as a github releases download
|
}
|
||||||
let apiURL = "https://api.github.com/repos/" + term.split("/")[3] + "/" + term.split("/")[4] + "/releases"; // https://api.github.com/repos/Danielv123/factorioClusterioMod/releases
|
} else {
|
||||||
|
// treat it as a search and download the top result
|
||||||
let res = syncRequest('GET', apiURL, {"headers":{"User-Agent":"factorioClusterio"}});
|
factorioAPI.init(false, modDirectory, "", config.factorio_version);
|
||||||
let url = JSON.parse(res.getBody())[0].assets[0].browser_download_url;
|
factorioAPI.authenticate({
|
||||||
let name = JSON.parse(res.getBody())[0].assets[0].name;
|
username: config.username,
|
||||||
if(url) {
|
token: config.token,
|
||||||
console.log("Downloading " + url);
|
require_ownership: false
|
||||||
let file = fs.createWriteStream(modDirectory + name);
|
}).then(() => {
|
||||||
let bytesDownloaded = 0;
|
factorioAPI.searchMods(term).then(body => {
|
||||||
let downloadStartTime = Date.now();
|
console.log(body)
|
||||||
https.get(url, function(response) {
|
console.log("Im gonna download: "+body[0].name + " in version: " + body[0].latest_release.version);
|
||||||
let bytesToDownload = response.headers['content-length'];
|
factorioAPI.downloadMod( {name: body[0].name, version: body[0].latest_release.version}).then(()=>{
|
||||||
response.pipe(file);
|
console.log("Mod downloaded");
|
||||||
response.on("data", chunk => {
|
resolve();
|
||||||
bytesDownloaded += chunk.length;
|
|
||||||
let downloadTimeElapsed = Date.now() - downloadStartTime;
|
|
||||||
let bytesPerSecond = bytesDownloaded / (downloadTimeElapsed/1000);
|
|
||||||
let timeToComplete = Math.floor((bytesToDownload - bytesDownloaded)/bytesPerSecond);
|
|
||||||
sLog("Downloading "+name+" "+(bytesDownloaded/bytesToDownload*100).toPrecision(3)+"% ("+formatBytes(bytesDownloaded)+" / "+formatBytes(bytesToDownload)+")\r\n"+
|
|
||||||
"about "+timeToComplete+" seconds remaining ("+formatBytes(bytesPerSecond)+"/s)");
|
|
||||||
}).on("end", x => {
|
|
||||||
sLog.clear();
|
|
||||||
console.log(" Downloaded in "+moment.utc(moment.duration(Date.now()-downloadStartTime).as('milliseconds')).format('mm:ss')); // because sLog.clear() doesn't seem to do the job of ending the line properly
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// treat it as a search and download the top result
|
|
||||||
factorioAPI.init(false, modDirectory, "", config.factorio_version);
|
|
||||||
factorioAPI.authenticate({
|
|
||||||
username: config.username,
|
|
||||||
token: config.token,
|
|
||||||
require_ownership: false
|
|
||||||
}).then(() => {
|
|
||||||
factorioAPI.searchMods(term).then(body => {
|
|
||||||
console.log(body)
|
|
||||||
console.log("Im gonna download: "+body[0].name + " in version: " + body[0].latest_release.version);
|
|
||||||
factorioAPI.downloadMod( {name: body[0].name, version: body[0].latest_release.version}).then(()=>{
|
|
||||||
console.log("Mod downloaded");
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
} else {
|
|
||||||
reject(new Error("Invalid search term"));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
},
|
|
||||||
removeMod: function removeMod(term, instance, force = false){
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
if(instance == "shared"){ // modDirectory has to end in /
|
|
||||||
var modDirectory = "sharedMods/";
|
|
||||||
} else {
|
|
||||||
var modDirectory = config.instanceDirectory+"/"+instance+"/instanceMods/";
|
|
||||||
}
|
|
||||||
if(term && typeof term == "string" && term.length > 0){
|
|
||||||
let mods = fs.readdirSync(modDirectory);
|
|
||||||
let modsMatchingFilter = mods.filter(mod => mod.toLowerCase().includes(term.toLowerCase()));
|
|
||||||
if(modsMatchingFilter.length < 1){
|
|
||||||
console.log("No mods found matching search");
|
|
||||||
} else if(modsMatchingFilter.length == 1){
|
|
||||||
console.log("Deleting "+modsMatchingFilter[0]);
|
|
||||||
fs.unlinkSync(modDirectory+modsMatchingFilter[0]);
|
|
||||||
console.log("Deleted.");
|
|
||||||
} else if(modsMatchingFilter.length > 1){
|
|
||||||
console.log("Found multiple mods");
|
|
||||||
modsMatchingFilter.forEach(mod => console.log(mod));
|
|
||||||
if(query("Delete all mods matching filter?")){
|
|
||||||
let modsToDelete = modsMatchingFilter.length;
|
|
||||||
for(let i = 0; i < modsToDelete; i++){
|
|
||||||
fs.unlinkSync(modDirectory+modsMatchingFilter[i]);
|
|
||||||
console.log("Deleted "+modsMatchingFilter[i]);
|
|
||||||
}
|
|
||||||
} else console.log("Did not delete mods.")
|
|
||||||
}
|
|
||||||
resolve();
|
|
||||||
} else {
|
|
||||||
reject(new Error("Invalid search term"));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
// 'https://api.github.com/repos/Danielv123/factorioClusterioMod/releases'
|
|
||||||
/**
|
|
||||||
Download mod from github repo by looking for the first binary download in
|
|
||||||
the latest release, saving it to /sharedMods
|
|
||||||
|
|
||||||
@param {string} url a github repo URL, for example https://api.github.com/repos/Danielv123/factorioClusterioMod/releases. Must link to /releases
|
|
||||||
*/
|
|
||||||
downloadFromGitURL: function(url){
|
|
||||||
console.log("Downloading mod from "+url);
|
|
||||||
// get JSON data about releases
|
|
||||||
let res = syncRequest('GET', url, {"headers":{"User-Agent":"factorioClusterio"}});
|
|
||||||
let downloadUrl = JSON.parse(res.getBody())[0].assets[0].browser_download_url;
|
|
||||||
let name = JSON.parse(res.getBody())[0].assets[0].name;
|
|
||||||
console.log(JSON.parse(res.getBody()))
|
|
||||||
if(downloadUrl) {
|
|
||||||
console.log(downloadUrl);
|
|
||||||
let file = fs.createWriteStream("sharedMods/"+name);
|
|
||||||
https.get(downloadUrl, function(response) {
|
|
||||||
response.pipe(file);
|
|
||||||
console.log("Downloaded "+name);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
},
|
} else {
|
||||||
|
reject(new Error("Invalid search term"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeMod(config, term, instance, force = false) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (instance.name == "shared") {
|
||||||
|
var modDirectory = "sharedMods";
|
||||||
|
} else {
|
||||||
|
var modDirectory = instance.path("instanceMods");
|
||||||
|
}
|
||||||
|
if (term && typeof term == "string" && term.length > 0) {
|
||||||
|
let mods = fs.readdirSync(modDirectory);
|
||||||
|
let modsMatchingFilter = mods.filter(mod => mod.toLowerCase().includes(term.toLowerCase()));
|
||||||
|
if (modsMatchingFilter.length < 1) {
|
||||||
|
console.log("No mods found matching search");
|
||||||
|
} else if (modsMatchingFilter.length == 1) {
|
||||||
|
console.log("Deleting "+modsMatchingFilter[0]);
|
||||||
|
fs.unlinkSync(path.join(modDirectory, modsMatchingFilter[0]));
|
||||||
|
console.log("Deleted.");
|
||||||
|
} else if (modsMatchingFilter.length > 1) {
|
||||||
|
console.log("Found multiple mods");
|
||||||
|
modsMatchingFilter.forEach(mod => console.log(mod));
|
||||||
|
if (query("Delete all mods matching filter?")) {
|
||||||
|
let modsToDelete = modsMatchingFilter.length;
|
||||||
|
for (let i = 0; i < modsToDelete; i++) {
|
||||||
|
fs.unlinkSync(path.join(modDirectory, modsMatchingFilter[i]));
|
||||||
|
console.log("Deleted "+modsMatchingFilter[i]);
|
||||||
|
}
|
||||||
|
} else console.log("Did not delete mods.")
|
||||||
|
}
|
||||||
|
resolve();
|
||||||
|
} else {
|
||||||
|
reject(new Error("Invalid search term"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 'https://api.github.com/repos/Danielv123/factorioClusterioMod/releases'
|
||||||
|
/**
|
||||||
|
Download mod from github repo by looking for the first binary download in
|
||||||
|
the latest release, saving it to /sharedMods
|
||||||
|
|
||||||
|
@param {string} url a github repo URL, for example https://api.github.com/repos/Danielv123/factorioClusterioMod/releases. Must link to /releases
|
||||||
|
*/
|
||||||
|
function downloadFromGitURL(url) {
|
||||||
|
console.log("Downloading mod from "+url);
|
||||||
|
// get JSON data about releases
|
||||||
|
let res = syncRequest('GET', url, {"headers":{"User-Agent":"factorioClusterio"}});
|
||||||
|
let downloadUrl = JSON.parse(res.getBody())[0].assets[0].browser_download_url;
|
||||||
|
let name = JSON.parse(res.getBody())[0].assets[0].name;
|
||||||
|
console.log(JSON.parse(res.getBody()))
|
||||||
|
if (downloadUrl) {
|
||||||
|
console.log(downloadUrl);
|
||||||
|
let file = fs.createWriteStream("sharedMods/"+name);
|
||||||
|
https.get(downloadUrl, function(response) {
|
||||||
|
response.pipe(file);
|
||||||
|
console.log("Downloaded "+name);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
module.exports.findUpdates = function(){
|
function findUpdates() {
|
||||||
console.log("Downloading mods...");
|
console.log("Downloading mods...");
|
||||||
// get JSON data about releases
|
// get JSON data about releases
|
||||||
let res = syncRequest('GET', 'https://api.github.com/repos/Danielv123/factorioClusterioMod/releases', {"headers":{"User-Agent":"factorioClusterio"}});
|
let res = syncRequest('GET', 'https://api.github.com/repos/Danielv123/factorioClusterioMod/releases', {"headers":{"User-Agent":"factorioClusterio"}});
|
||||||
@@ -275,3 +274,11 @@ module.exports.findUpdates = function(){
|
|||||||
let name = JSON.parse(res.getBody())[0].assets[0].name;
|
let name = JSON.parse(res.getBody())[0].assets[0].name;
|
||||||
console.log(JSON.parse(res.getBody()))
|
console.log(JSON.parse(res.getBody()))
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
listMods,
|
||||||
|
findMods,
|
||||||
|
addMod,
|
||||||
|
removeMod,
|
||||||
|
downloadFromGitURL,
|
||||||
|
}
|
||||||
@@ -3,9 +3,6 @@ var http = require('http');
|
|||||||
var https = require('https');
|
var https = require('https');
|
||||||
var fs = require('fs');
|
var fs = require('fs');
|
||||||
|
|
||||||
var modManager = require("./manager/modManager.js");
|
|
||||||
|
|
||||||
// modManager.addMod("clusterio", "shared");
|
|
||||||
|
|
||||||
function makeDirectory(path){
|
function makeDirectory(path){
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
|
|||||||
@@ -248,10 +248,10 @@ app.post("/api/getID", authenticate.middleware, function(req,res) {
|
|||||||
// time us a unix timestamp we can use to check for how long the server has been unresponsive
|
// time us a unix timestamp we can use to check for how long the server has been unresponsive
|
||||||
// we should save that somewhere and give appropriate response
|
// we should save that somewhere and give appropriate response
|
||||||
if(req.body){
|
if(req.body){
|
||||||
if (!db.slaves.has(req.body.unique)) {
|
if (!db.slaves.has(String(req.body.unique))) {
|
||||||
db.slaves.set(req.body.unique, {});
|
db.slaves.set(String(req.body.unique), {});
|
||||||
}
|
}
|
||||||
let slave = db.slaves.get(req.body.unique);
|
let slave = db.slaves.get(String(req.body.unique));
|
||||||
for(let k in req.body){
|
for(let k in req.body){
|
||||||
if(k != "meta" && req.body.hasOwnProperty(k)){
|
if(k != "meta" && req.body.hasOwnProperty(k)){
|
||||||
slave[k] = req.body[k];
|
slave[k] = req.body[k];
|
||||||
@@ -272,8 +272,8 @@ app.post("/api/editSlaveMeta", authenticate.middleware, function(req,res) {
|
|||||||
// {instanceID, pass, meta:{x,y,z}}
|
// {instanceID, pass, meta:{x,y,z}}
|
||||||
|
|
||||||
if(req.body && req.body.instanceID && req.body.meta){
|
if(req.body && req.body.instanceID && req.body.meta){
|
||||||
if (db.slaves.has(req.body.instanceID)) {
|
if (db.slaves.has(String(req.body.instanceID))) {
|
||||||
let slave = db.slaves.get(req.body.instanceID);
|
let slave = db.slaves.get(String(req.body.instanceID));
|
||||||
if(!slave.meta) {
|
if(!slave.meta) {
|
||||||
slave.meta = {};
|
slave.meta = {};
|
||||||
}
|
}
|
||||||
@@ -300,8 +300,8 @@ app.post("/api/getSlaveMeta", function (req, res) {
|
|||||||
endpointHitCounter.labels(req.route.path).inc();
|
endpointHitCounter.labels(req.route.path).inc();
|
||||||
console.log("body", req.body);
|
console.log("body", req.body);
|
||||||
if(req.body && req.body.instanceID){
|
if(req.body && req.body.instanceID){
|
||||||
if (db.slaves.has(req.body.instanceID)) {
|
if (db.slaves.has(String(req.body.instanceID))) {
|
||||||
let slave = db.slaves.get(req.body.instanceID);
|
let slave = db.slaves.get(String(req.body.instanceID));
|
||||||
console.log("returning meta for ", req.body.instanceID);
|
console.log("returning meta for ", req.body.instanceID);
|
||||||
if(!slave.meta) {
|
if(!slave.meta) {
|
||||||
slave.meta = {};
|
slave.meta = {};
|
||||||
@@ -508,8 +508,8 @@ app.post("/api/remove", authenticate.middleware, function(req, res) {
|
|||||||
if(!object.instanceName) {
|
if(!object.instanceName) {
|
||||||
object.instanceName = "unknown";
|
object.instanceName = "unknown";
|
||||||
}
|
}
|
||||||
if (db.slaves.has(object.instanceID)) {
|
if (db.slaves.has(String(object.instanceID))) {
|
||||||
object.instanceName = db.slaves.get(object.instanceID).instanceName;
|
object.instanceName = db.slaves.get(String(object.instanceID)).instanceName;
|
||||||
}
|
}
|
||||||
let itemCount = db.items.getItemCount(object.name);
|
let itemCount = db.items.getItemCount(object.name);
|
||||||
if (
|
if (
|
||||||
|
|||||||
@@ -10,8 +10,7 @@ module.exports = class remoteCommands {
|
|||||||
this.config = mergedConfig;
|
this.config = mergedConfig;
|
||||||
this.socket = extras.socket;
|
this.socket = extras.socket;
|
||||||
const pluginManager = require("lib/manager/pluginManager.js");
|
const pluginManager = require("lib/manager/pluginManager.js");
|
||||||
const configManager = require("lib/manager/configManager.js");
|
// const modManager = require("lib/manager/modManager");
|
||||||
// const modManager = require("lib/manager/modManager.js")(this.config);
|
|
||||||
this.socket.on("hello", () => {
|
this.socket.on("hello", () => {
|
||||||
this.socket.emit("registerServerManager");
|
this.socket.emit("registerServerManager");
|
||||||
});
|
});
|
||||||
@@ -20,16 +19,9 @@ module.exports = class remoteCommands {
|
|||||||
});
|
});
|
||||||
this.socket.on("serverManagerGetMods", async (data, callback) => {
|
this.socket.on("serverManagerGetMods", async (data, callback) => {
|
||||||
// TODO: Implement this function separately from listMods (which console.logs it)
|
// TODO: Implement this function separately from listMods (which console.logs it)
|
||||||
// let mods = modManager.getMods()
|
// let mods = modManager.getMods(this.config)
|
||||||
// callback(mods);
|
// callback(mods);
|
||||||
});
|
});
|
||||||
this.socket.on("serverManagerGetConfig", async (data, callback) => {
|
|
||||||
let config = await configManager.getConfig(data.instance);
|
|
||||||
callback(config);
|
|
||||||
});
|
|
||||||
this.socket.on("serverManagerEditConfig", async (data, callback) => {
|
|
||||||
callback(configManager.editConfig(data.instance, data.entry, data.value));
|
|
||||||
});
|
|
||||||
this.socket.on("serverManagerGetPlugins", async (data, callback) => {
|
this.socket.on("serverManagerGetPlugins", async (data, callback) => {
|
||||||
callback(await pluginManager.getPlugins());
|
callback(await pluginManager.getPlugins());
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -77,48 +77,9 @@ module.exports = that => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
that.app.post("/api/serverManager/editConfig", async (req,res) => {
|
|
||||||
if((req.body.token || req.cookies.token)
|
|
||||||
&& req.body.instanceID
|
|
||||||
&& typeof req.body.instanceID == "string"
|
|
||||||
&& req.body.entry
|
|
||||||
&& typeof req.body.entry == "string"
|
|
||||||
&& req.body.value !== undefined
|
|
||||||
&& that.playerManager){
|
|
||||||
let perms = await that.playerManager.main.getPermissions((req.body.token || req.cookies.token));
|
|
||||||
if(perms.cluster.includes("writeConfig")
|
|
||||||
|| (perms.instance[req.body.instanceID]
|
|
||||||
&& perms.instance[req.body.instanceID].includes("writeConfig"))){
|
|
||||||
that.serverSockets[req.body.instanceID].socket.emit("serverManagerEditConfig", {
|
|
||||||
entry: req.body.entry,
|
|
||||||
value: req.body.value,
|
|
||||||
}, async resp => {
|
|
||||||
if(resp.ok){
|
|
||||||
// Retrieve the latest config from the server and store it
|
|
||||||
await updateData("config", req.body.instanceID);
|
|
||||||
}
|
|
||||||
res.send(resp);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
res.send({
|
|
||||||
ok:false,
|
|
||||||
msg:"Insufficient permissions",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
res.send({
|
|
||||||
ok:false,
|
|
||||||
msg:"Invalid request body",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
async function updateData(type, instanceID){
|
async function updateData(type, instanceID){
|
||||||
// Retrieve the latest ${type} from the server and store it
|
// Retrieve the latest ${type} from the server and store it
|
||||||
if(type == "config"){
|
if(type == "plugins"){
|
||||||
that.serverSockets[instanceID].socket.emit("serverManagerGetConfig", {}, data => {
|
|
||||||
that.serverSockets[instanceID].config = data;
|
|
||||||
});
|
|
||||||
} else if(type == "plugins"){
|
|
||||||
that.serverSockets[instanceID].socket.emit("serverManagerGetPlugins", {}, data => {
|
that.serverSockets[instanceID].socket.emit("serverManagerGetPlugins", {}, data => {
|
||||||
that.serverSockets[instanceID].plugins = data;
|
that.serverSockets[instanceID].plugins = data;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -63,9 +63,6 @@ class masterPlugin {
|
|||||||
server.socket.emit("serverManagerGetPlugins", {}, data => {
|
server.socket.emit("serverManagerGetPlugins", {}, data => {
|
||||||
server.plugins = data;
|
server.plugins = data;
|
||||||
});
|
});
|
||||||
server.socket.emit("serverManagerGetConfig", {}, data => {
|
|
||||||
server.config = data;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// I can't seem to get express static pages + ejs rendering to work properly, so I write my own thing.
|
// I can't seem to get express static pages + ejs rendering to work properly, so I write my own thing.
|
||||||
|
|||||||
@@ -26,23 +26,7 @@
|
|||||||
if(server.plugins) server.plugins.forEach(plugin => {
|
if(server.plugins) server.plugins.forEach(plugin => {
|
||||||
html += `<li><div class="pluginStatus" style="background-color: ${plugin.enabled ? 'green' : 'red'}"></div><div style="width: calc( 100% - 50px )"><h3>${plugin.name}</h3><p>${plugin.description}</p></div></li>`
|
html += `<li><div class="pluginStatus" style="background-color: ${plugin.enabled ? 'green' : 'red'}"></div><div style="width: calc( 100% - 50px )"><h3>${plugin.name}</h3><p>${plugin.description}</p></div></li>`
|
||||||
});
|
});
|
||||||
html += `</ul></div><div id="config">`
|
html += `</ul></div>`
|
||||||
if(permissions && permissions.cluster && permissions.cluster.includes("readConfig")){
|
|
||||||
if(server.config){
|
|
||||||
html += `<ul>`;
|
|
||||||
server.config.forEach(setting => {
|
|
||||||
if(setting.entry[1] !== "_" && setting.entry !== "masterAuthSecret"){
|
|
||||||
html += `<li class="settingInput">
|
|
||||||
<p style="width: 50%; display:inline-block;">${setting.entry}</p>
|
|
||||||
<input style="color:black; width: calc(50% - 4px); box-sizing: border-box;" value='${setting.value}'>
|
|
||||||
</li>`
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
html += `</ul>
|
|
||||||
<input id="submitSettings" type="button" value="Save changes" style="color:black"/>
|
|
||||||
</div>`
|
|
||||||
}
|
}
|
||||||
%>
|
%>
|
||||||
<%- html %>
|
<%- html %>
|
||||||
|
|||||||
@@ -1,40 +1,3 @@
|
|||||||
// Handle config editing
|
|
||||||
originalSettings = {};
|
|
||||||
let settings = document.querySelectorAll(".settingInput");
|
|
||||||
settings.forEach(setting => {
|
|
||||||
let entry = setting.children[0].innerText
|
|
||||||
originalSettings[setting.children[0].innerText] = {
|
|
||||||
entry: setting.children[0].innerText,
|
|
||||||
value: setting.children[1].value,
|
|
||||||
}
|
|
||||||
setting.children[1].addEventListener("input", ()=>{
|
|
||||||
let newValue = setting.children[1].value;
|
|
||||||
if(newValue != originalSettings[entry].value){
|
|
||||||
setting.children[1].style.backgroundColor = "lightgreen";
|
|
||||||
} else {
|
|
||||||
setting.children[1].style.backgroundColor = "";
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
let submitSettings = document.querySelector("#submitSettings");
|
|
||||||
submitSettings.addEventListener("click", async ()=>{
|
|
||||||
let settings = document.querySelectorAll(".settingInput");
|
|
||||||
for(let i = 0; i < settings.length; i++){
|
|
||||||
let setting = settings[i];
|
|
||||||
let entry = setting.children[0].innerText
|
|
||||||
if(setting.children[1].value != originalSettings[entry].value){
|
|
||||||
// upload new changes, display results somehow
|
|
||||||
let status = await postJSON("/api/serverManager/editConfig", {
|
|
||||||
entry,
|
|
||||||
value: setting.children[1].value,
|
|
||||||
instanceID: getParameterByName("instanceID"),
|
|
||||||
});
|
|
||||||
if(status.ok){
|
|
||||||
setting.children[1].style.backgroundColor = "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
// Handle plugin management
|
// Handle plugin management
|
||||||
let pluginStatuses = document.querySelectorAll(".pluginStatus");
|
let pluginStatuses = document.querySelectorAll(".pluginStatus");
|
||||||
pluginStatuses.forEach(pluginStatus => {
|
pluginStatuses.forEach(pluginStatus => {
|
||||||
|
|||||||
@@ -6,10 +6,6 @@
|
|||||||
width:calc((( 100% ) - (( 100% ) / 4))/2);
|
width:calc((( 100% ) - (( 100% ) / 4))/2);
|
||||||
float:left;
|
float:left;
|
||||||
}
|
}
|
||||||
#config {
|
|
||||||
width:calc((( 100% ) - (( 100% ) / 4))/2);
|
|
||||||
float:left;
|
|
||||||
}
|
|
||||||
ul {
|
ul {
|
||||||
list-style: none;
|
list-style: none;
|
||||||
padding:0px;
|
padding:0px;
|
||||||
|
|||||||
@@ -1,8 +1,76 @@
|
|||||||
const assert = require('assert').strict;
|
const assert = require('assert').strict;
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
const client = require("../client");
|
const client = require("../client");
|
||||||
|
|
||||||
describe("Client testing", function() {
|
describe("Client testing", function() {
|
||||||
|
describe("class Instance", function() {
|
||||||
|
let instance = new client._Instance("dir", "foo")
|
||||||
|
it("should give the name on .name", function() {
|
||||||
|
assert.equal(instance.name, "foo");
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should give the path to it on .path()", function() {
|
||||||
|
assert.equal(instance.path(), "dir");
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should join path on .path(...parts)", function() {
|
||||||
|
assert.equal(instance.path("bar"), path.join("dir", "bar"));
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("checkFilename()", function() {
|
||||||
|
it("should allow a basic name", function() {
|
||||||
|
client._checkFilename("file");
|
||||||
|
});
|
||||||
|
|
||||||
|
function check(item, msg) {
|
||||||
|
assert.throws(() => client._checkFilename(item), new Error(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
it("should throw on non-string", function() {
|
||||||
|
check(undefined, "must be a string");
|
||||||
|
check(null, "must be a string");
|
||||||
|
check({}, "must be a string");
|
||||||
|
check([], "must be a string");
|
||||||
|
check(0, "must be a string");
|
||||||
|
check(false, "must be a string");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should throw on empty name", function() {
|
||||||
|
check("", "cannot be empty");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should throw on <>:\"\\/|?* \\x00\\r\\n\\t", function() {
|
||||||
|
for (let char of '<>:"\\/|?*\x00\r\n\t') {
|
||||||
|
check(char, 'cannot contain <>:"\\/|=* or control characters');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should throw on CON, PRN, AUX, NUL, COM1, LPT1", function() {
|
||||||
|
for (let bad of ['CON', 'PRN', 'AUX', 'NUL', 'COM1', 'LPT1']) {
|
||||||
|
check(
|
||||||
|
bad, 'cannot be named any of . ..'
|
||||||
|
+' CON PRN AUX NUL COM1-9 and LPT1-9'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should throw on . and ..", function() {
|
||||||
|
for (let bad of ['.', '..']) {
|
||||||
|
check(
|
||||||
|
bad, 'cannot be named any of . ..'
|
||||||
|
+' CON PRN AUX NUL COM1-9 and LPT1-9'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should throw on names ending with . or space", function() {
|
||||||
|
check("a ", "cannot end with . or space");
|
||||||
|
check("a.", "cannot end with . or space");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("randomDynamicPort()", function() {
|
describe("randomDynamicPort()", function() {
|
||||||
it("should return a port number", function() {
|
it("should return a port number", function() {
|
||||||
let port = client._randomDynamicPort()
|
let port = client._randomDynamicPort()
|
||||||
|
|||||||
Reference in new issue
Block a user