| 5 | |
| 6 | |
| 7 | function setup(options, imports, register) { |
| 8 | // Import |
| 9 | var logger = imports.logger.namespace("shells.stream"); |
| 10 | var shells = imports.shells; |
| 11 | var io = imports.socket_io.io; |
| 12 | var events = imports.events; |
| 13 | var shells_rpc = imports.shells_rpc; |
| 14 | |
| 15 | var getShell = function(data) { |
| 16 | if(shells.shells[data.shellId]) { |
| 17 | return Q(shells.attach(data.shellId)); |
| 18 | } |
| 19 | return shells.createShell(data.shellId, data.opts) |
| 20 | }; |
| 21 | |
| 22 | events.on('shell.spawn', function(data) { |
| 23 | return shells.shells[data.shellId].ps.pause(); |
| 24 | }); |
| 25 | |
| 26 | events.on('shell.open', function(data) { |
| 27 | shells.shells[data.shellId].ps.resume(); |
| 28 | }); |
| 29 | |
| 30 | // Construct |
| 31 | io.of('/shells').on('connection', function(socket) { |
| 32 | var shell = null; |
| 33 | var shellOptions = null; |
| 34 | |
| 35 | logger.log("new socket connected"); |
| 36 | |
| 37 | |
| 38 | var handleShellOutput = function(data) { |
| 39 | socket.emit("shell.output", utils.btoa(data.toString("utf8"))); |
| 40 | }; |
| 41 | |
| 42 | |
| 43 | // Open the shell |
| 44 | socket.on('shell.open', function(data) { |
| 45 | shellOptions = data; |
| 46 | logger.log("open shell ", shellOptions); |
| 47 | |
| 48 | // Default options |
| 49 | shellOptions.opts = _.defaults(shellOptions.opts, { |
| 50 | 'arguments': [] |
| 51 | }); |
| 52 | |
| 53 | return getShell(shellOptions) |
| 54 | .then(function(_shell) { |
| 55 | // Increment number of socket connected to this shell |
| 56 | shells.shells[data.shellId].nSockets = (shells.shells[data.shellId].nSockets || 0) + 1; |
| 57 | |
| 58 | shell = _shell; |
| 59 | |
| 60 | // Bind events |
| 61 | shell.on('data', handleShellOutput); |
| 62 | shell.once('end', function() { |
| 63 | socket.disconnect(); |
| 64 | }); |