forked from unconed/TermKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
102 lines (85 loc) · 2.28 KB
/
router.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
var shell = require("shell/shell");
var returnMeta = require('misc').returnMeta;
var protocol = require('protocol');
/**
* Processes incoming messages on a connection, routes them to active sessions.
*/
exports.router = function (connection) {
var that = this;
this.protocol = new protocol.protocol(connection, this, true);
this.sessions = {};
this.counter = 1;
};
exports.router.prototype = {
dispatch: function (message) {
// Look up session.
var that = this,
session = message.session && this.getSession(message.session);
returned = false,
// Define convenient answer callback.
exit = function (success, object, meta) {
if (!returned) {
meta = meta || {};
meta.session = message.session;
meta.success = success;
that.protocol.answer(message.query, object, meta);
returned = true;
}
};
// Find handler.
var handler = exports.handlers[message.method];
if (handler) {
handler.call(this, session, message.query, message.args || {}, exit);
return;
}
// Else forward to session.
session.dispatch(message.query, message.method, message.args || {}, exit);
},
forward: function (message) {
this.protocol.notify(null, null, message);
},
disconnect: function () {
for (i in this.sessions) {
this.sessions[i].close();
}
this.sessions = {};
this.protocol = null;
},
getSession: function (id) {
for (i in this.sessions) {
if (i == id) return this.sessions[id];
}
},
addSession: function (session) {
var id = session.id = this.counter++;
this.sessions[id] = session;
},
removeSession: function (session) {
delete this.sessions[session.id];
},
};
/**
* Method handlers.
*/
exports.handlers = {
'session.open.shell': function (session, query, args, exit) {
try {
var session = new shell.shell(args, this);
this.addSession(session);
exit(true, { session: session.id });
}
catch (e) {
exit(false);
}
},
'session.close': function (session, query, args, exit) {
if (session) {
session.close();
this.removeSession(session);
exit(true);
}
else {
exit(false);
}
},
};