diff --git a/.travis.yml b/.travis.yml index f7059a13..31d07777 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,8 +5,6 @@ before_install: - curl -o factorio.tar.gz -L https://www.factorio.com/get-download/latest/headless/linux64 - tar -xf factorio.tar.gz - npm install -g codecov - # Needed for lib/manager/configManager - - echo {} > config.json script: - npm run-script ci-cover - codecov -f coverage/lcov.info diff --git a/CHANGELOG.md b/CHANGELOG.md index bc90041f..bccfa8b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ Version 2.0.0 - The masterIP and masterPort config entries has been merged into masterURL. Breaks discordChat, playerManager, serverSelect, trainTeleports and 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 diff --git a/client.js b/client.js index 5a9b5799..4de02024 100644 --- a/client.js +++ b/client.js @@ -20,38 +20,96 @@ const crypto = require("crypto"); const objectOps = require("lib/objectOps.js"); const fileOps = require("lib/fileOps"); const stringUtils = require("lib/stringUtils.js"); -const configManager = require("lib/manager/configManager.js"); const pluginManager = require("lib/manager/pluginManager"); +const modManager = require("lib/manager/modManager"); const hashFile = require('lib/hash').hashFile; - -// argument parsing -const args = require('minimist')(process.argv.slice(2)); - -// require config.json -var config = require(args.config || './config'); +// Uhm... var global = {}; -const instance = process.argv[3]; -const instancedirectory = config.instanceDirectory + '/' + instance; -const command = process.argv[2]; +/** + * Keeps track of the runtime parameters of an instance + */ +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 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 async function messageInterfaceInternal(command, callback, resolve, reject) { @@ -156,7 +214,7 @@ function printUsage() { console.error("node client.js manage"); } -async function listInstances() { +async function listInstances(config) { let instanceNames = fileOps.getDirectoriesSync(config.instanceDirectory); let instances = []; for (instance of instanceNames) { @@ -171,37 +229,32 @@ async function listInstances() { console.log(asTable(instances)); } -async function manage() { +async function manage(config, instance) { // console.log("Launching mod manager"); //const fullUsage = 'node client.js manage [instance, "shared"] ["mods", "config"] ...'; function usage(instance, tool, action){ if(tool && tool == "mods"){ - console.log('node client.js manage '+instance+' '+tool+' ["list", "search", "add", "remove"]'); - } else if(tool && tool == "config") { - console.log('node client.js manage '+instance+' '+tool+' ["list", "edit"]'); + console.log('node client.js manage '+instance.name+' '+tool+' ["list", "search", "add", "remove"]'); } 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 { - 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 action = process.argv[5] || ""; - if(instance){ + if (instance !== undefined) { if(tool == "mods"){ (async function(){try{ - // do require down here to reduce master load time - const modManager = require("lib/manager/modManager.js")(config); - // allow managing mods if(action == "list"){ - console.log(await modManager.listMods(instance)); + console.log(await modManager.listMods(config, instance)); } 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"){ - await modManager.addMod(process.argv[6], instance); + await modManager.addMod(config, process.argv[6], instance); } else if(action == "remove" || action == "rm" || action == "delete"){ - await modManager.removeMod(process.argv[6], instance); + await modManager.removeMod(config, process.argv[6], instance); } else { usage(instance, tool); } @@ -210,23 +263,6 @@ async function manage() { console.log("Got error from modManager:") 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"){ (async function(){try{ if(action == "list"){ @@ -257,16 +293,16 @@ async function manage() { } } -async function deleteInstance() { - if (!process.argv[3]) { +async function deleteInstance(instance) { + if (instance === undefined) { console.error("Usage: node client.js delete [instance]"); process.exit(1); - } else if (typeof process.argv[3] == "string" && fs.existsSync(config.instanceDirectory+"/" + process.argv[3]) && process.argv[3] != "/" && process.argv[3] != "") { - 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 - console.log("Deleted instance " + process.argv[3]); + } else if (fs.existsSync(instance.path())) { + 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 " + instance.name); process.exit(0); } else { - console.error("Instance not found: " + process.argv[3]); + console.error("Instance not found: " + instance.name); 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 console.log("Creating instance..."); - fs.mkdirSync(instancedirectory); - fs.mkdirSync(instancedirectory + "/script-output/"); - fs.mkdirSync(instancedirectory + "/saves/"); - fs.writeFileSync(instancedirectory + "/script-output/output.txt", ""); - fs.writeFileSync(instancedirectory + "/script-output/orders.txt", ""); - fs.writeFileSync(instancedirectory + "/script-output/txbuffer.txt", ""); - fs.mkdirSync(instancedirectory + "/mods/"); - fs.mkdirSync(instancedirectory + "/instanceMods/"); - fs.mkdirSync(instancedirectory + "/scenarios/"); - ncp("lib/scenarios", path.resolve(instancedirectory, "scenarios"), err => { + fs.mkdirSync(instance.path()); + fs.mkdirSync(instance.path("script-output")); + fs.writeFileSync(instance.path("script-output", "output.txt"), ""); + fs.writeFileSync(instance.path("script-output", "orders.txt"), ""); + fs.writeFileSync(instance.path("script-output", "txbuffer.txt"), ""); + fs.mkdirSync(instance.path("mods")); + fs.mkdirSync(instance.path("instanceMods")); + fs.mkdirSync(instance.path("scenarios")); + ncp("lib/scenarios", instance.path("scenarios"), 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.writeFileSync(instancedirectory + `/config.ini`, `[path]\r\n + // 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(instance.path("config.ini"), `[path]\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 - fs.copySync('sharedMods', path.join(instancedirectory, "mods")); + fs.copySync('sharedMods', instance.path("mods")); let instconf = { "factorioPort": args.port || process.env.FACTORIOPORT || 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); // 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) { - name = config.username + "'s clusterio " + instance; + name = config.username + "'s clusterio " + instance.name; } let serversettings = { "name": name, @@ -348,15 +383,15 @@ write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n "afk_autokick_interval": 0, "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("Creating save ....."); let factorio = child_process.spawn( './' + config.factorioDirectory + '/bin/x64/factorio', [ - '-c', instancedirectory + '/config.ini', - // '--create', instancedirectory + '/saves/save.zip', + '-c', instance.path("config.ini"), + // '--create', instance.path("saves", "save.zip"), '--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-password', instconf.clientPassword, ], { @@ -400,37 +435,32 @@ write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n }); } -async function startInstance() { - // Exit if no instance specified (it should be, just a safeguard); - if(instancedirectory != config.instanceDirectory+"/undefined"){ - var instanceconfig = require(path.resolve(instancedirectory,'config')); - instanceconfig.unique = stringUtils.hashCode(instanceconfig.clientPassword); - if(process.env.FACTORIOPORT){ - instanceconfig.factorioPort = process.env.FACTORIOPORT; - } - if(process.env.RCONPORT){ - instanceconfig.rconPort = process.env.RCONPORT; - } - } else { - process.exit(1); +async function startInstance(config, args, instance) { + var instanceconfig = JSON.parse(await fs.readFile(instance.path("config.json"))); + instanceconfig.unique = stringUtils.hashCode(instanceconfig.clientPassword); + if (process.env.FACTORIOPORT) { + instanceconfig.factorioPort = process.env.FACTORIOPORT; + } + if (process.env.RCONPORT) { + instanceconfig.rconPort = process.env.RCONPORT; } 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++){ 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..."); // clean old log file to avoid crash try{ - let logPath = path.join(instancedirectory,'factorio-current.log'); + let logPath = instance.path("factorio-current.log"); let stat = await fs.stat(logPath); console.log(stat) console.log(stat.isFile()) if(stat.isFile()){ 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}`); } }catch(e){} @@ -438,26 +468,26 @@ async function startInstance() { // (new Date).toGMTString() // move mods from ./sharedMods to the instances mod directory - try{fs.mkdirSync(path.join(instancedirectory, "instanceMods"));}catch(e){} - try{rmdirSync(path.join(instancedirectory, "mods"));}catch(e){} + try{fs.mkdirSync(instance.path("instanceMods"));}catch(e){} + try{rmdirSync(instance.path("mods"));}catch(e){} try { // 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){} 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..."); - 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 - 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 -write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n +write-data=${ instance.path() }\r\n `); // Spawn factorio server //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) { console.error("ERROR!"); 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 serverprocess = child_process.spawn( './' + config.factorioDirectory + '/bin/x64/factorio', [ - '-c', instancedirectory + '/config.ini', + '-c', instance.path("config.ini"), '--start-server', latestSave.file, '--rcon-port', args["rcon-port"] || Number(process.env.RCONPORT) || instanceconfig.clientPort, '--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 ], { '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 // we read the log every 2 seconds and stop looping when we start connecting to factorio 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(data && data.indexOf('Starting RCON interface') > 0){ client.connect({ @@ -526,7 +556,7 @@ write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n client.onDidAuthenticate(() => { console.log('Clusterio | RCON Authenticated!'); - instanceManagement(instanceconfig); // start using rcons + instanceManagement(config, instance, instanceconfig); // start using rcons }); client.onDidConnect(() => { console.log('Clusterio | RCON Connected!'); @@ -548,7 +578,7 @@ write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n }); } else if(process.platform == "linux"){ // 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 () { console.log("Caught interrupt signal, sending ^C"); serverprocess.kill("SIGINT"); @@ -562,22 +592,39 @@ write-data=${ path.resolve(config.instanceDirectory, instance) }\r\n } async function startClient() { - if (!fs.existsSync(config.instanceDirectory)) { - fs.mkdirSync(config.instanceDirectory); - } - if (!fs.existsSync("./sharedPlugins/")) { - fs.mkdirSync("sharedPlugins"); - } - if (!fs.existsSync("./sharedMods/")) { - fs.mkdirSync("sharedMods"); + // argument parsing + const args = require('minimist')(process.argv.slice(2)); + + const command = process.argv[2]; + + // add better stack traces on promise rejection + process.on('unhandledRejection', r => console.log(r)); + + 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 // 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) 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."); } + // 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 if (!command || command == "help" || command == "--help") { printUsage(); process.exit(1); } else if (command == "list") { - await listInstances(); + await listInstances(config); process.exit(0); } else if (command == "manage"){ - await manage(); + await manage(config, instance); // process.exit(0); } else if (command == "delete") { - await deleteInstance(); + await deleteInstance(instance); } else if (command == "download") { await downloadMod(); } else if (command == "start" && instance === undefined) { console.error("ERROR: No instanceName provided!"); console.error("Usage: node client.js start [instanceName]"); process.exit(0); - } else if (command == "start" && typeof instance == "string" && instance != "/" && !fs.existsSync(instancedirectory)) { - await createInstance(); - } else if (command == "start" && typeof instance == "string" && instance != "/" && fs.existsSync(instancedirectory)) { - await startInstance(); + } else if (command == "start" && !fs.existsSync(instance.path())) { + await createInstance(config, args, instance); + } else if (command == "start" && fs.existsSync(instance.path())) { + await startInstance(config, args, instance); } else { console.error("Invalid arguments, quitting."); process.exit(1); @@ -618,7 +672,7 @@ async function startClient() { // ensure instancemanagement only ever runs once var _instanceInitialized; -async function instanceManagement(instanceconfig) { +async function instanceManagement(config, instance, instanceconfig) { if (_instanceInitialized) return; _instanceInitialized = true; @@ -644,7 +698,7 @@ async function instanceManagement(instanceconfig) { for(let i = 0; i < pluginsToLoad.length; i++){ let pluginLoadStarted = Date.now(); let combinedConfig = deepmerge(instanceconfig,config,{clone:true}); - combinedConfig.instanceName = instance; + combinedConfig.instanceName = instance.name; let pluginConfig = pluginsToLoad[i]; if(!global.subscribedFiles) { @@ -674,23 +728,27 @@ async function instanceManagement(instanceconfig) { 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 - fs.writeFileSync(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription, ""); + fs.writeFileSync(outputPath, ""); } 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) { // only wipe the file on restart for now, should most likely be rotated during runtime too - fs.writeFileSync(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription, ""); - let tail = new Tail(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription); + fs.writeFileSync(outputPath, ""); + let tail = new Tail(outputPath); tail.on("line", function (data) { plugins[i].scriptOutput(data); }); } 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 // delay, so the socket got enough time to connect setTimeout(() => { @@ -703,11 +761,11 @@ async function instanceManagement(instanceconfig) { setTimeout( () => { // 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 (stuff[0]) { - fs.writeFileSync(instancedirectory + "/script-output/" + filename, ""); + fs.writeFileSync(instance.path("script-output", filename), ""); } for (let o = 0; o < stuff.length; o++) { if (stuff[o] && !stuff[o].includes('\u0000\u0000')) { @@ -745,7 +803,7 @@ async function instanceManagement(instanceconfig) { unique: instanceconfig.unique, publicIP: config.publicIP, // IP of the server should be global for all instances, so we pull that straight from the config mods:modHashes, - instanceName: instance, + instanceName: instance.name, info: instanceconfig.info, }; if(playerCount){ @@ -762,7 +820,7 @@ async function instanceManagement(instanceconfig) { global.mac = mac; payload.mac = mac; // 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"){ console.error("We got problems, something went wrong when contacting master "+config.masterURL+" at " + payload.time); console.error(err); @@ -795,7 +853,7 @@ async function instanceManagement(instanceconfig) { modName: modHashes[i].modName, 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(response && body && body == "found") { console.log("master has mod "+modHashes[i].modName); @@ -817,7 +875,7 @@ async function instanceManagement(instanceconfig) { } }); var form = req.form(); - form.append('file', fs.createReadStream(config.instanceDirectory+"/"+instance+"/mods/"+mod)); + form.append('file', fs.createReadStream(instance.path("mods", mod))); } else { console.log("Not sending mod: " + mod + " to master because config.uploadModsToMaster is not enabled") } @@ -829,24 +887,23 @@ async function instanceManagement(instanceconfig) { // string, function // returns [{modName:string,hash:string}, ... ] -function hashMods(instanceName, callback) { +function hashMods(instance, callback) { if(!callback) { throw new Error("ERROR in function hashMods NO CALLBACK"); } - let modsDir = config.instanceDirectory+"/"+instanceName+"/mods/"; function hashMod(name) { if (path.extname(name) != ".zip") { // Can't hash unzipped mods, return null that's filtered out later return null; } else { - return hashFile(modsDir+name).then(hash => ( + return hashFile(instance.path("mods", name)).then(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 => { // Remove null entries from hashMod callback(hashes.filter(entry => entry !== null)); @@ -855,6 +912,8 @@ function hashMods(instanceName, callback) { module.exports = { // For testing only + _Instance: Instance, + _checkFilename: checkFilename, _randomDynamicPort: randomDynamicPort, _generatePassword: generatePassword, }; diff --git a/lib/manager/configManager.js b/lib/manager/configManager.js deleted file mode 100644 index ab6034e2..00000000 --- a/lib/manager/configManager.js +++ /dev/null @@ -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`, - } - } -}; diff --git a/lib/manager/modManager.js b/lib/manager/modManager.js index b975db96..606cef05 100644 --- a/lib/manager/modManager.js +++ b/lib/manager/modManager.js @@ -11,9 +11,9 @@ const https = require('follow-redirects').https; const factorioAPI = require("node-factorio-api"); const sLog = require("single-line-log").stdout; const query = require('cli-interact').getYesNo; +const path = require("path"); const fileOps = require("lib/fileOps"); -// const config = require("./../../config"); function ellipse(str, max){ @@ -23,255 +23,262 @@ 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]}; -module.exports = function(config){ - if(!config) config = require("./../../config"); - const instances = require("./../getInstances.js")(config).sync(); - return { - /** - Lists mods for an instance as a table. Warning, handles printing internally. - @param {string} instance - Name of the instance or "shared" +/** +Lists mods for an instance as a table. Warning, handles printing internally. +@param {Instance} instance - Instance object, see client.js - @example - var modManager = require("modManager")(config); - modManager.listMods("testInstance"); - // console.logs table of mods installed on instance - modManager.listMods("shared"); - // console.logs mods located in /sharedMods as a nice table - */ - listMods: function(instance){ - return new Promise((resolve, reject) => { - if(instance && instances.includes(instance)){ - factorioAPI.init(false, config.instanceDirectory+'/'+instance+'/instanceMods', config.instanceDirectory+'/'+instance+'/saves', config.factorio_version); - factorioAPI.authenticate({ - username: config.username, - token: config.token, - require_ownership: false - }).then(token => { - console.log("* Currently installed:"); - factorioAPI.readModZips().then(list => { - console.log(asTable(list.map(mod => { - return { - name:(mod.title || mod.name), - version:mod.version, - date:mod.date, - 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 - factorioAPI.getModsFromSaves().then(list => { - 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"); - 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())) - */ +@example +var modManager = require("modManager"); +modManager.listMods(config, instance); +// console.logs table of mods installed on instance +// if instance.name is shared: +// console.logs mods located in /sharedMods as a nice table +*/ +async function listMods(config, instance) { + return new Promise((resolve, reject) => { + const instances = require("./../getInstances.js")(config).sync(); + if (instances.includes(instance.name)) { + factorioAPI.init(false, instance.path("instanceMods"), instance.path("saves"), config.factorio_version); + factorioAPI.authenticate({ + username: config.username, + token: config.token, + require_ownership: false + }).then(token => { + console.log("* Currently installed:"); + factorioAPI.readModZips().then(list => { + console.log(asTable(list.map(mod => { + return { + name:(mod.title || mod.name), + version:mod.version, + date:mod.date, + 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 + factorioAPI.getModsFromSaves().then(list => { + 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"); + resolve(); }); - }, - /** - Searches mods.factorio.com for mods matching a search term and prints - the results to console as a neat looking table + } 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)); + }); + } - @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({ 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); + }).then(() => { + factorioAPI.searchMods(term.split("/")[term.split("/").length-1]).then(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(); + }); }); - }).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)); }); - }); - }, - addMod: function(term, instance){ - 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 && 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({ - username: config.username, - token: config.token, - require_ownership: false - }).then(() => { - factorioAPI.searchMods(term.split("/")[term.split("/").length-1]).then(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 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 - - let res = syncRequest('GET', apiURL, {"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; - if(url) { - console.log("Downloading " + url); - let file = fs.createWriteStream(modDirectory + name); - let bytesDownloaded = 0; - let downloadStartTime = Date.now(); - https.get(url, function(response) { - let bytesToDownload = response.headers['content-length']; - response.pipe(file); - response.on("data", chunk => { - 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")); - } - }); - }, + } 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 - // '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); + let res = syncRequest('GET', apiURL, {"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; + if (url) { + console.log("Downloading " + url); + let file = fs.createWriteStream(path.join(modDirectory, name)); + let bytesDownloaded = 0; + let downloadStartTime = Date.now(); + https.get(url, function(response) { + let bytesToDownload = response.headers['content-length']; + response.pipe(file); + response.on("data", chunk => { + 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")); + } + }); +} + +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..."); // get JSON data about 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())) -}*/ \ No newline at end of file +}*/ + +module.exports = { + listMods, + findMods, + addMod, + removeMod, + downloadFromGitURL, +} diff --git a/lib/npmPostinstall.js b/lib/npmPostinstall.js index 04300505..7e2e3c5e 100644 --- a/lib/npmPostinstall.js +++ b/lib/npmPostinstall.js @@ -3,9 +3,6 @@ var http = require('http'); var https = require('https'); var fs = require('fs'); -var modManager = require("./manager/modManager.js"); - -// modManager.addMod("clusterio", "shared"); function makeDirectory(path){ return new Promise((resolve, reject) => { diff --git a/master.js b/master.js index 17842674..6f407ed7 100644 --- a/master.js +++ b/master.js @@ -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 // we should save that somewhere and give appropriate response if(req.body){ - if (!db.slaves.has(req.body.unique)) { - db.slaves.set(req.body.unique, {}); + if (!db.slaves.has(String(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){ if(k != "meta" && req.body.hasOwnProperty(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}} if(req.body && req.body.instanceID && req.body.meta){ - if (db.slaves.has(req.body.instanceID)) { - let slave = db.slaves.get(req.body.instanceID); + if (db.slaves.has(String(req.body.instanceID))) { + let slave = db.slaves.get(String(req.body.instanceID)); if(!slave.meta) { slave.meta = {}; } @@ -300,8 +300,8 @@ app.post("/api/getSlaveMeta", function (req, res) { endpointHitCounter.labels(req.route.path).inc(); console.log("body", req.body); if(req.body && req.body.instanceID){ - if (db.slaves.has(req.body.instanceID)) { - let slave = db.slaves.get(req.body.instanceID); + if (db.slaves.has(String(req.body.instanceID))) { + let slave = db.slaves.get(String(req.body.instanceID)); console.log("returning meta for ", req.body.instanceID); if(!slave.meta) { slave.meta = {}; @@ -508,8 +508,8 @@ app.post("/api/remove", authenticate.middleware, function(req, res) { if(!object.instanceName) { object.instanceName = "unknown"; } - if (db.slaves.has(object.instanceID)) { - object.instanceName = db.slaves.get(object.instanceID).instanceName; + if (db.slaves.has(String(object.instanceID))) { + object.instanceName = db.slaves.get(String(object.instanceID)).instanceName; } let itemCount = db.items.getItemCount(object.name); if ( diff --git a/sharedPlugins/serverManager/index.js b/sharedPlugins/serverManager/index.js index 82202ceb..a175630f 100644 --- a/sharedPlugins/serverManager/index.js +++ b/sharedPlugins/serverManager/index.js @@ -10,8 +10,7 @@ module.exports = class remoteCommands { this.config = mergedConfig; this.socket = extras.socket; const pluginManager = require("lib/manager/pluginManager.js"); - const configManager = require("lib/manager/configManager.js"); - // const modManager = require("lib/manager/modManager.js")(this.config); + // const modManager = require("lib/manager/modManager"); this.socket.on("hello", () => { this.socket.emit("registerServerManager"); }); @@ -20,16 +19,9 @@ module.exports = class remoteCommands { }); this.socket.on("serverManagerGetMods", async (data, callback) => { // TODO: Implement this function separately from listMods (which console.logs it) - // let mods = modManager.getMods() + // let mods = modManager.getMods(this.config) // 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) => { callback(await pluginManager.getPlugins()); }); diff --git a/sharedPlugins/serverManager/js/api-endpoints.js b/sharedPlugins/serverManager/js/api-endpoints.js index 6c3301ef..40cd7c7e 100644 --- a/sharedPlugins/serverManager/js/api-endpoints.js +++ b/sharedPlugins/serverManager/js/api-endpoints.js @@ -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){ // Retrieve the latest ${type} from the server and store it - if(type == "config"){ - that.serverSockets[instanceID].socket.emit("serverManagerGetConfig", {}, data => { - that.serverSockets[instanceID].config = data; - }); - } else if(type == "plugins"){ + if(type == "plugins"){ that.serverSockets[instanceID].socket.emit("serverManagerGetPlugins", {}, data => { that.serverSockets[instanceID].plugins = data; }); diff --git a/sharedPlugins/serverManager/masterPlugin.js b/sharedPlugins/serverManager/masterPlugin.js index cfe7e2a3..e972283d 100644 --- a/sharedPlugins/serverManager/masterPlugin.js +++ b/sharedPlugins/serverManager/masterPlugin.js @@ -63,9 +63,6 @@ class masterPlugin { server.socket.emit("serverManagerGetPlugins", {}, 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. diff --git a/sharedPlugins/serverManager/static/index.html b/sharedPlugins/serverManager/static/index.html index 5af40484..0dd92458 100644 --- a/sharedPlugins/serverManager/static/index.html +++ b/sharedPlugins/serverManager/static/index.html @@ -26,23 +26,7 @@ if(server.plugins) server.plugins.forEach(plugin => { html += `
  • ${plugin.name}

    ${plugin.description}

  • ` }); - html += `
    ` - if(permissions && permissions.cluster && permissions.cluster.includes("readConfig")){ - if(server.config){ - html += ` - -
    ` + html += `` } %> <%- html %> diff --git a/sharedPlugins/serverManager/static/index.js b/sharedPlugins/serverManager/static/index.js index 8c893dbf..478ccfcc 100644 --- a/sharedPlugins/serverManager/static/index.js +++ b/sharedPlugins/serverManager/static/index.js @@ -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 let pluginStatuses = document.querySelectorAll(".pluginStatus"); pluginStatuses.forEach(pluginStatus => { diff --git a/sharedPlugins/serverManager/static/serverManager.css b/sharedPlugins/serverManager/static/serverManager.css index 7a610d99..99b0142b 100644 --- a/sharedPlugins/serverManager/static/serverManager.css +++ b/sharedPlugins/serverManager/static/serverManager.css @@ -6,10 +6,6 @@ width:calc((( 100% ) - (( 100% ) / 4))/2); float:left; } -#config { - width:calc((( 100% ) - (( 100% ) / 4))/2); - float:left; -} ul { list-style: none; padding:0px; diff --git a/test/client.js b/test/client.js index ae5dce13..0260174d 100644 --- a/test/client.js +++ b/test/client.js @@ -1,8 +1,76 @@ const assert = require('assert').strict; +const path = require('path'); const client = require("../client"); 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() { it("should return a port number", function() { let port = client._randomDynamicPort()