├── .gitignore ├── bin └── webrcon ├── example.js ├── package.json ├── README.md ├── cli └── index.js ├── LICENSE └── webrcon.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | raw/ 3 | .vscode/ 4 | -------------------------------------------------------------------------------- /bin/webrcon: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | require('../cli/index.js').main(Array.prototype.slice.call(process.argv, 2)) 3 | -------------------------------------------------------------------------------- /example.js: -------------------------------------------------------------------------------- 1 | var WebRcon = require('.') 2 | 3 | // Create a new client: 4 | var rcon = new WebRcon('127.0.0.1', 28025) 5 | 6 | // Handle events: 7 | rcon.on('connect', function() { 8 | console.log('CONNECTED') 9 | 10 | // Run a command once connected: 11 | rcon.run('echo hello world!', 0) 12 | }) 13 | rcon.on('disconnect', function() { 14 | console.log('DISCONNECTED') 15 | }) 16 | rcon.on('message', function(msg) { 17 | console.log('MESSAGE:', msg) 18 | }) 19 | rcon.on('error', function(err) { 20 | console.log('ERROR:', err) 21 | }) 22 | 23 | // Connect by providing the server's rcon.password: 24 | rcon.connect('1234') 25 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "webrconjs", 3 | "description": "RCON over WebSocket client library and command line interface.", 4 | "author": "Daniel Wirtz ", 5 | "version": "1.0.0", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/dcodeIO/WebRcon.git" 9 | }, 10 | "bugs": { 11 | "url": "https://github.com/dcodeIO/WebRcon/issues" 12 | }, 13 | "homepage": "https://github.com/dcodeIO/WebRcon", 14 | "keywords": [ 15 | "webrcon", 16 | "rcon", 17 | "gameserver", 18 | "websocket", 19 | "rust" 20 | ], 21 | "browser": { 22 | "ws": false 23 | }, 24 | "license": "Apache-2.0", 25 | "main": "webrcon.js", 26 | "bin": { 27 | "webrcon": "./bin/webrcon" 28 | }, 29 | "dependencies": { 30 | "chalk": "^1.1.1", 31 | "ws": "^1.0.1", 32 | "yargs": "^4.2.0" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | WebRcon 2 | ============ 3 | RCON over WebSocket client library and command line interface. 4 | 5 | * Supported games: [Rust](http://playrust.com) 6 | * Supported platforms: node.js and any modern browser (CommonJS, AMD, shim) 7 | 8 | Usage 9 | ----- 10 | ```js 11 | var WebRcon = require('webrconjs') // node.js only 12 | 13 | // Create a new client: 14 | var rcon = new WebRcon('127.0.0.1', 28025) 15 | 16 | // Handle events: 17 | rcon.on('connect', function() { 18 | console.log('CONNECTED') 19 | 20 | // Run a command once connected: 21 | rcon.run('echo hello world!', 0) 22 | }) 23 | rcon.on('disconnect', function() { 24 | console.log('DISCONNECTED') 25 | }) 26 | rcon.on('message', function(msg) { 27 | console.log('MESSAGE:', msg) 28 | }) 29 | rcon.on('error', function(err) { 30 | console.log('ERROR:', err) 31 | }) 32 | 33 | // Connect by providing the server's rcon.password: 34 | rcon.connect('1234') 35 | ``` 36 | 37 | Browser usage 38 | ------------- 39 | ```html 40 | 41 | 46 | ``` 47 | 48 | Also works as an AMD module. 49 | 50 | Command line usage 51 | ------------------ 52 | `npm -g install webrconjs` 53 | 54 | ``` 55 | Usage: webrcon [port] [password] 56 | 57 | Examples: 58 | webrcon 127.0.0.1 27015 p4ssw0rd Connects to the local machine 59 | ``` 60 | 61 | **License:** [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html) 62 | -------------------------------------------------------------------------------- /cli/index.js: -------------------------------------------------------------------------------- 1 | var readline = require('readline'), 2 | util = require('util'), 3 | yargs = require('yargs'), 4 | chalk = require('chalk'), 5 | WebRcon = require('../') 6 | 7 | exports.main = function(argv) { 8 | argv = yargs(argv) 9 | .usage('Usage: webrcon [port] [password]') 10 | .demand(1) 11 | .example('webrcon 127.0.0.1 27015 p4ssw0rd', 'Connects to the local machine') 12 | .argv 13 | 14 | var ip = argv._[0], 15 | port = argv._[1] || 27015, 16 | pass = argv._[2] || '', 17 | rcon = null 18 | 19 | process.stdout.write("\x1Bc"); 20 | 21 | var rl = readline.createInterface({ 22 | input: process.stdin, 23 | output: process.stdout 24 | }) 25 | rl.on('line', function(line) { 26 | process.stdout.write('\n') 27 | rl.prompt() 28 | if (rcon) 29 | rcon.run(line) 30 | }) 31 | rl.on('close', function() { 32 | return process.exit(1) 33 | }) 34 | var exitOnSigint = false 35 | rl.on('SIGINT', function() { 36 | if (exitOnSigint) 37 | return exit() 38 | exitOnSigint = true 39 | rl.clearLine() 40 | rl.question('Do you really want to exit? [y] ', function(answer) { 41 | exitOnSigint = false 42 | if (answer === '' || answer.match(/^y(es)?$/i)) 43 | exit() 44 | else 45 | rl.output.write(chalk.cyan('> ')) 46 | }) 47 | }) 48 | 49 | function print(type, args) { 50 | var t = Math.ceil((rl.line.length + 3) / process.stdout.columns); 51 | var text = util.format.apply(console, args); 52 | rl.output.write("\n\x1B[" + t + "A\x1B[0J"); 53 | rl.output.write(text + "\n"); 54 | rl.output.write(Array(t).join("\n\x1B[E")); 55 | rl._refreshLine(); 56 | }; 57 | 58 | console.log = function() { 59 | print("log", arguments); 60 | }; 61 | console.warn = function() { 62 | print("warn", arguments); 63 | }; 64 | console.info = function() { 65 | print("info", arguments); 66 | }; 67 | console.error = function() { 68 | print("error", arguments); 69 | }; 70 | 71 | function connect() { 72 | console.log(chalk.cyan('connecting to ' + ip + ':' + port + ' ...')) 73 | rcon = new WebRcon(ip, port) 74 | rcon.on('connect', function() { 75 | console.log(chalk.cyan("connected")) 76 | rl.setPrompt(chalk.cyan('> '), 2) 77 | rl.resume() 78 | rl.prompt() 79 | }) 80 | rcon.on('disconnect', function() { 81 | console.log(chalk.cyan('disconnected')) 82 | rcon = null 83 | }) 84 | rcon.on('message', function(message) { 85 | console.log(message.message) 86 | }) 87 | rcon.on('error', function(err) { 88 | console.error(chalk.red('error:'), err) 89 | rcon = null 90 | }) 91 | rcon.connect(pass) 92 | } 93 | 94 | function exit() { 95 | rl.pause() 96 | if (rcon) 97 | rcon.disconnect() 98 | rcon = null 99 | rl.close() // exits 100 | } 101 | 102 | if (!pass) { 103 | exitOnSigint = true 104 | rl.question('rcon.password: ', function(answer) { 105 | exitOnSigint = false 106 | pass = answer 107 | rl.pause() 108 | connect() 109 | }) 110 | } else { 111 | rl.pause() 112 | connect() 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /webrcon.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license Rust-WebRcon (c) 2016 Daniel Wirtz 3 | * Released under the Apache License, Version 2.0 4 | * see: https://github.com/dcodeIO/rust-webrcon for details 5 | */ 6 | (function(global, factory) { 7 | 8 | /* AMD */ if (typeof define === 'function' && define["amd"]) 9 | define(factory) 10 | /* CommonJS */ else if (typeof require === "function" && typeof module === "object" && module && module["exports"]) 11 | module["exports"] = factory() 12 | /* Global */ else 13 | (global["dcodeIO"] = global["dcodeIO"] || {})["WebRcon"] = factory() 14 | 15 | })(this, function(isNode) { 16 | "use strict" 17 | 18 | /** 19 | * Actual WebSocket implementation used. 20 | * @type {function(string, new:WebSocket)} 21 | * @inner 22 | */ 23 | var WebSocketImpl = typeof WebSocket !== 'undefined' ? WebSocket : require('ws') 24 | 25 | /** 26 | * WebRcon interface. 27 | * @exports WebRcon 28 | * @constructor 29 | * @param {string} ip Server IP 30 | * @param {number} port Server port 31 | */ 32 | function WebRcon(ip, port) { 33 | 34 | /** 35 | * Server IP. 36 | * @type {string} 37 | */ 38 | this.ip = ip 39 | 40 | /** 41 | * Server port. 42 | * @type {number} 43 | */ 44 | this.port = port 45 | 46 | /** 47 | * WebSocket. 48 | * @type {?WebSocket} 49 | */ 50 | this.socket = null 51 | 52 | /** 53 | * Event listeners. 54 | * @type {!Object.>} 55 | * @private 56 | */ 57 | this._listeners = {} 58 | } 59 | 60 | /** 61 | * Connecting socket state. 62 | * @type {number} 63 | * @const 64 | */ 65 | WebRcon.STATE_CONNECTING = 0 66 | 67 | /** 68 | * Connected socket state. 69 | * @type {number} 70 | * @const 71 | */ 72 | WebRcon.STATE_CONNECTED = 1 73 | 74 | /** 75 | * Closing socket state. 76 | * @type {number} 77 | * @const 78 | */ 79 | WebRcon.STATE_CLOSING = 2 80 | 81 | /** 82 | * Closed socket state. 83 | * @type {number} 84 | * @const 85 | */ 86 | WebRcon.STATE_CLOSED = 3 87 | 88 | /** 89 | * Error message type. 90 | * @type {number} 91 | * @const 92 | */ 93 | WebRcon.TYPE_ERROR = 0 94 | 95 | /** 96 | * Assert message type. 97 | * @type {number} 98 | * @const 99 | */ 100 | WebRcon.TYPE_ASSERT = 0 101 | 102 | /** 103 | * Warning message type. 104 | * @type {number} 105 | * @const 106 | */ 107 | WebRcon.TYPE_WARNING = 2 108 | 109 | /** 110 | * Log message type. 111 | * @type {number} 112 | * @const 113 | */ 114 | WebRcon.TYPE_LOG = 3 115 | 116 | /** 117 | * Exception message type. 118 | * @type {number} 119 | * @const 120 | */ 121 | WebRcon.TYPE_EXCEPTION = 4 122 | 123 | /** 124 | * @name WebRconconnecting 125 | * @type {boolean} 126 | * @readonly 127 | */ 128 | Object.defineProperty(WebRcon.prototype, 'connecting', { 129 | get: function get_connecting() { 130 | return (this.socket && this.socket.readyState === WebRcon.STATE_CONNECTING) === true 131 | } 132 | }) 133 | 134 | /** 135 | * @name WebRcon#connected 136 | * @type {boolean} 137 | * @readonly 138 | */ 139 | Object.defineProperty(WebRcon.prototype, 'connected', { 140 | get: function get_connected() { 141 | return (this.socket && this.socket.readyState === WebRcon.STATE_CONNECTED) === true 142 | } 143 | }) 144 | 145 | /** 146 | * @name WebRconN#closing 147 | * @type {boolean} 148 | * @readonly 149 | */ 150 | Object.defineProperty(WebRcon.prototype, 'closing', { 151 | get: function get_closing() { 152 | return (this.socket && this.socket.readyState === WebRcon.STATE_CLOSING) === true 153 | } 154 | }) 155 | 156 | /** 157 | * @name WebRcon#closed 158 | * @type {boolean} 159 | * @readonly 160 | */ 161 | Object.defineProperty(WebRcon.prototype, 'closed', { 162 | get: function get_closed() { 163 | return (this.socket === null || this.socket.readyState === WebRcon.STATE_CLOSED) === true 164 | } 165 | }) 166 | 167 | /** 168 | * @name WebRcon#status 169 | * @type {string} 170 | * @readonly 171 | */ 172 | Object.defineProperty(WebRcon.prototype, 'status', { 173 | get: function get_status() { 174 | if (!this.socket) 175 | return 'CLOSED' 176 | switch (this.socket.readyState) { 177 | case WebRcon.STATE_CONNECTING: 178 | return 'CONNECTING' 179 | case WebRcon.STATE_CONNECTED: 180 | return 'CONNECTED' 181 | case WebRcon.STATE_CLOSING: 182 | return 'CLOSING' 183 | case WebRcon.STATE_CLOSED: 184 | return 'CLOSED' 185 | default: 186 | return 'UNKNOWN' 187 | } 188 | } 189 | }) 190 | 191 | function onopen(e) { 192 | this.emit('connect', e) 193 | } 194 | 195 | function onmessage(e) { 196 | try { 197 | this.emit('message', ServerMessage.fromPayload(e.data)) 198 | } catch (err) { 199 | this.emit('error', err) 200 | } 201 | } 202 | 203 | function onerror(e) { 204 | this.emit('error', e) 205 | } 206 | 207 | function onclose(e) { 208 | this.emit('disconnect', e) 209 | this.socket = null 210 | } 211 | 212 | /** 213 | * Connects to the specified endpoint. 214 | * @param {string} endpoint Endpoint address 215 | * @private 216 | */ 217 | WebRcon.prototype._connect = function(endpoint) { 218 | if (!this.closed) 219 | throw Error('already connected') 220 | this.socket = new WebSocketImpl(endpoint) 221 | this.socket.addEventListener('open', onopen.bind(this)) 222 | this.socket.addEventListener('message', onmessage.bind(this)) 223 | this.socket.addEventListener('error', onerror.bind(this)) 224 | this.socket.addEventListener('close', onclose.bind(this)) 225 | } 226 | 227 | /** 228 | * Asynchronously connects to the RCON interface. 229 | * @param {string} password The RCON password 230 | * @throws {Error} If the RCON interface is already connecting, connected or still closing 231 | */ 232 | WebRcon.prototype.connect = function connect(password) { 233 | this._connect('ws://' + this.ip + ':' + this.port + '/' + password) 234 | } 235 | 236 | /** 237 | * Disconnects from the RCON interface. 238 | * @returns {boolean} `true` if now closing, `false` if not connected 239 | */ 240 | WebRcon.prototype.disconnect = function disconnect() { 241 | if (!this.connected) 242 | return false 243 | this.socket.close() 244 | this.socket = null 245 | return true 246 | } 247 | 248 | /** 249 | * Runs an RCON command. 250 | * @param {string} command Command to run 251 | * @param {number=} identity Server identity, defaults to -1 252 | */ 253 | WebRcon.prototype.run = function run(command, identity) { 254 | this.socket.send(JSON.stringify({ 255 | Identifier: identity === void 0 ? -1 : identity, 256 | Message: command, 257 | Name: 'WebRcon' 258 | })) 259 | } 260 | 261 | // Minimal EventEmitter 262 | 263 | /** 264 | * Adds an event listener for the specified event. 265 | * @param {string} event Event name 266 | * @param {function(...*)} callback Callback 267 | */ 268 | WebRcon.prototype.addListener = function addListener(event, callback) { 269 | if (!this._listeners.hasOwnProperty(event)) { 270 | this._listeners[event] = [ callback ] 271 | return 272 | } 273 | var listeners = this._listeners[event] 274 | if (listeners.indexOf(callback) < 0) 275 | listeners.push(callback) 276 | } 277 | 278 | /** 279 | * Adds an event listener for the specified event. 280 | * @function 281 | * @param {string} event Event name 282 | * @param {function(...*)} callback Callback 283 | */ 284 | WebRcon.prototype.on = WebRcon.prototype.addListener 285 | 286 | /** 287 | * Adds an event listener for the specified event that is executed only once. 288 | * @function 289 | * @param {string} event Event name 290 | * @param {function(...*)} callback Callback 291 | */ 292 | WebRcon.prototype.once = function once(event, callback) { 293 | var self = this 294 | var onceCallback = function onceCallback(a1, a2, a3) { 295 | self.removeListener(event, onceCallback) 296 | callback(a1, a2, a3) 297 | } 298 | this.addListener(event, onceCallback) 299 | } 300 | 301 | /** 302 | * Removes an event listener. 303 | * @param {string} event Event name 304 | * @param {function()} callback Callback 305 | */ 306 | WebRcon.prototype.removeListener = function removeListener(event, callback) { 307 | if (!this._listeners.hasOwnProperty(event)) 308 | return 309 | var listeners = this._listeners[event], 310 | index = listeners.indexOf(callback) 311 | if (index < 0) 312 | return 313 | if (listeners.length === 1) 314 | delete this._listeners[event] 315 | else 316 | listeners.splice(index, 1) 317 | } 318 | 319 | /** 320 | * Removes all listeners. 321 | * @param {string=} event If specified, removes all listeners for this event only 322 | */ 323 | WebRcon.prototype.removeAllListeners = function(event) { 324 | if (event === void 0) { 325 | this._listeners = {} 326 | return 327 | } 328 | if (this._listeners.hasOwnProperty(event)) 329 | this._listeners[event] = [] 330 | } 331 | 332 | /** 333 | * Emits an event by calling all associated listeners. 334 | * @param {string} event Event name 335 | * @param {...*} var_args Arguments 336 | */ 337 | WebRcon.prototype.emit = function emit(event, a1, a2, a3) { 338 | var listeners = this._listeners[event], 339 | k 340 | if (!(listeners && (k = listeners.length))) 341 | return 342 | for (var i = 0; i < k; ++i) 343 | listeners[i](a1, a2, a3) 344 | } 345 | 346 | /** 347 | * A message sent by the server. 348 | * @constructor 349 | */ 350 | function ServerMessage(message, type, stacktrace, identity) { 351 | 352 | /** 353 | * Message string. 354 | * @type {string} 355 | */ 356 | this.message = message 357 | 358 | /** 359 | * Message type. 360 | * @type {number} 361 | * @see {@link WebRcon#TYPE_ERROR} 362 | * @see {@link WebRcon#TYPE_ASSERT} 363 | * @see {@link WebRcon#TYPE_WARNING} 364 | * @see {@link WebRcon#TYPE_LOG} 365 | * @see {@link WebRcon#TYPE_EXCEPTION} 366 | */ 367 | this.type = type 368 | 369 | /** 370 | * Stacktrace, if any. 371 | * @type {?string} 372 | */ 373 | this.stacktrace = stacktrace || null 374 | 375 | /** 376 | * Server identity. 377 | * @type {number} 378 | */ 379 | this.identity = identity 380 | 381 | /** 382 | * Message time. 383 | * @type {number} 384 | */ 385 | this.time = Date.now() 386 | } 387 | 388 | /** 389 | * Constructs a ServerMessage from the specified payload. 390 | * @param {string} Payload JSON 391 | * @returns {!ServerMessage} 392 | */ 393 | ServerMessage.fromPayload = function fromPayload(payload) { 394 | var data = JSON.parse(payload) 395 | return new ServerMessage(data.Message, data.Type, data.Stacktrace, data.Identifier) 396 | } 397 | 398 | /** 399 | * @name ServerMessage#isError 400 | * @type {boolean} 401 | * @readonly 402 | */ 403 | Object.defineProperty(ServerMessage.prototype, 'isError', { 404 | get: function get_isError() { 405 | return this.type === WebRcon.TYPE_ERROR 406 | } 407 | }) 408 | 409 | /** 410 | * @name ServerMessage#isAssert 411 | * @type {boolean} 412 | * @readonly 413 | */ 414 | Object.defineProperty(ServerMessage.prototype, 'isAssert', { 415 | get: function get_isAssert() { 416 | return this.type === WebRcon.TYPE_ASSERT 417 | } 418 | }) 419 | 420 | /** 421 | * @name ServerMessage#isWarning 422 | * @type {boolean} 423 | * @readonly 424 | */ 425 | Object.defineProperty(ServerMessage.prototype, 'isWarning', { 426 | get: function get_isWarning() { 427 | return this.type === WebRcon.TYPE_WARNING 428 | } 429 | }) 430 | 431 | /** 432 | * @name ServerMessage#isLog 433 | * @type {boolean} 434 | * @readonly 435 | */ 436 | Object.defineProperty(ServerMessage.prototype, 'isLog', { 437 | get: function get_isLog() { 438 | return this.type === WebRcon.TYPE_LOG 439 | } 440 | }) 441 | 442 | /** 443 | * @name ServerMessage#isException 444 | * @type {boolean} 445 | * @readonly 446 | */ 447 | Object.defineProperty(ServerMessage.prototype, 'isException', { 448 | get: function get_isException() { 449 | return this.type === WebRcon.TYPE_EXCEPTION 450 | } 451 | }) 452 | 453 | /** 454 | * @name ServerMessage#hasStacktrace 455 | * @type {boolean} 456 | * @readonly 457 | */ 458 | Object.defineProperty(ServerMessage.prototype, 'hasStacktrace', { 459 | get: function get_hasStacktrace() { 460 | return this.stacktrace !== null 461 | } 462 | }) 463 | 464 | /** 465 | * @alias ServerMessage 466 | */ 467 | WebRcon.ServerMessage = ServerMessage 468 | 469 | return WebRcon 470 | }) 471 | --------------------------------------------------------------------------------