-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProtocolHandler.js
More file actions
306 lines (288 loc) · 10.5 KB
/
ProtocolHandler.js
File metadata and controls
306 lines (288 loc) · 10.5 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
const PeerInfo = require('peer-info')
const pull = require('pull-stream');
const lp = require('pull-length-prefixed')
const each = require('async/each')
const CmdSignal = require('./types/CmdSignal')
const Network = require('./Network')
/**
* Standard issue ProtocolHandler, redirects data to CommandHandler.
* This class does stream handling, serialization and response handling.
* This ProtocolHandler is designed to use Command Signal serialization/protocol.
* Register commands with this class...
*/
class ProtocolHandler {
/**
*
* @param {ProtocolName} ProtocolName
* @param {Network} Network
*/
constructor(ProtocolName, Network) {
this.protocolName = ProtocolName;
this.Network = Network;
this.commandHandlers = {};
this.callBacks = {};
}
get availableCommands() {
return Object.keys(this.commandHandlers)
}
/**
*
* @param {String} cmdName
* @param {function} handler
*/
registerCommand(cmdName, handler) {
this.commandHandlers[cmdName] = handler;
}
registerCommandList(Map) {
var Keys = Object.keys(this.protocolHandlers)
for (var CmdName in Keys) {
var Command = Map[protocol];
this.commandHandlers[CmdName] = Command;
}
}
/**
*
* @param {String} cmdName
*/
unregisterCommand(cmdName) {
delete this.commandHandlers[cmdName];
}
/**
*
* @param {String[]} List
*/
unregisterCommandList(List) {
for(var cmdName in List) {
delete this.commandHandlers[cmdName];
}
}
start() {
this._running = true;
this._onPeerConnected = this._onPeerConnected.bind(this);
this._onPeerDisconnected = this._onPeerDisconnected.bind(this);
this._onConnection = this._onConnection.bind(this);
this.Network.registerProtocol(this.protocolName, this)
}
stop() {
if (this._running = false)
this.Network.unregisterProtocol(this.protocolName)
delete this.commandHandlers;
}
/**
* Simple way to send command and receive response.
* @param {PeerInfo} cmd
* @param {String} cmd
* @param {Object} args //Anything you want it to be... Should pass this to command handler.
* @param {Number} type //1 is request, 2 is response. handle accordingly.
* @param {String} tid
*/
sendCommand(peerId, cmd, args, type, tid) {
return new Promise((resolve, reject) => {
var Signal = new CmdSignal();
let rtid;
if (type === 1 || type === undefined || type === null) {
rtid = Signal.addCommand(cmd, args);
} else {
rtid = Signal.addResponse(cmd, args, tid);
}
if (type === 1 || type === undefined || type === null) {
this.callBacks[rtid] = (err, response) => {
if (err) reject(err);
resolve(response); //Response *should* be a fragment object
};
} else {
resolve()
}
this.Network.sendMessage(peerId, Signal, this.protocolName);
});
}
/**
* Simple way to send command and receive response.
* This is meant to dial custom protocols.
* @param {String} protoName
* @param {PeerInfo} cmd
* @param {String} cmd
* @param {Object} args //Anything you want it to be... Should pass this to command handler.
* @param {Number} type //1 is request, 2 is response. handle accordingly.
* @param {String} tid
*/
sendCommandProtocol(protoName, peerId, cmd, args, type, tid) {
return new Promise((resolve, reject) => {
var Signal = new CmdSignal();
let rtid;
if (type === 1 || type === undefined || type === null) {
rtid = Signal.addCommand(cmd, args);
} else {
rtid = Signal.addResponse(cmd, args, tid);
}
if (type === 1 || type === undefined || type === null) {
this.callBacks[rtid] = (err, response) => {
if (err) reject(err);
resolve(response); //Response *should* be a fragment object
};
} else {
resolve()
}
this.Network.sendMessage(peerId, Signal, protoName);
});
}
/**
* Meant to send multiple commands.. This function is experimental
* @param {PeerInfo} peerId
* @param {CmdSignal} cmd
* @returns {Promise[]}
*/
sendCommandObj(peerId, cmd) {
var out = []
const fragments = Array.from(cmd.fragments.values())
each(fragments, (fragment) => {
var promise = new Promise((resolve, reject) => {
if (fragment.type === 1) {
this.callBacks[fragment.tid] = (err, response) => {
if (err) reject(err);
resolve(response); //Response *should* be a fragment object
};
} else {
resolve()
}
});
out.push(promise);
})
this.Network.sendMessage(peerId, cmd, this.protocolName);
return out;
}
/* ######## only for internal use ######## */
_processCommand(peerId, fragment) {
(async () => {
let msg = new CmdSignal({})
var cmdName = fragment.cmd.toString()
switch (cmdName) {
case 'test':
console.log('sending ok #', fragment.tid.toString())
msg.addResponse(cmdName, 'OK', fragment.tid.toString())
break
case 'example':
var ret = await this._exampleCommand(peerId, fragment.cmd, fragment.args, fragment.tid);
msg.addResponse(cmdName, ret + " Success! this example works", fragment.tid);
break;
case 'commands':
//Give a updated list of commands.
var cmds = [];
cmds.push("commands");
cmds.push.apply(cmds, this.availableCommands);
msg.addResponse(cmdName, JSON.stringify(cmds), fragment.tid);
break;
default:
if (this.commandHandlers[cmdName]) {
//console.log("command '" + cmdName + "' exists");
/**
* @type {Promise}
*/
var result = await this.commandHandlers[cmdName](peerId, fragment.cmd, fragment.args, fragment.tid);
msg.addResponse(cmdName, JSON.stringify(result), fragment.tid);
} else {
//Command does not exist.
msg.addResponse(cmdName, "501", fragment.tid);
}
//console.log('received command, args: ' + JSON.stringify(command))
//this.notifications.receivedCommand(peerId, command)
// throw new Error('unknown command')
}
this.sendCommandObj(peerId, msg)
})();
}
_processResponse(peerId, response) {
//this.callBacks
console.log("tid is " + response.tid)
if (this.callBacks[response.tid]) {
this.callBacks[response.tid](null, response);
delete this.callBacks[response.tid]; //Clean up old callbacks.
}
}
// handle errors on the receiving channel
_receiveError(err) {
console.error('ReceiveError: %s', err.message)
}
// handle new peers
_onPeerConnected(peerInfo) {
//console.log('_onPeerConnected ' + peerId.id.toB58String())
}
// handle peers being disconnected
_onPeerDisconnected(peerInfo) {
// this.engine.peerDisconnected(peerId)
//console.log('_onPeerDisconnected ', peerId.id.toB58String())
}
_receiveMessage(peerId, incoming) {
return new Promise((resolve, reject) => {
//console.log(`received MSG from ${PeerId.toB58String()}`)
if (incoming.fragments.size === 0) {
return reject();
}
const fragments = Array.from(incoming.fragments.values())
each(fragments, (fragment) => {
//console.log("fragments: " + fragment)
// TODO process commands here.
switch (fragment.type) {
case 1:
// command
console.log(`received Command : ${fragment.cmd.toString()}`)
this._processCommand(peerId, fragment)
break
case 2:
// response
console.log(`received response ${fragment.tid.toString()} : ${fragment.cmd.toString()}`)
this._processResponse(peerId, fragment)
break
default:
reject(new Error('unknown fragment type'))
}
})
});
}
/**
* @param {String} protocol
* @param {*} conn
*/
_onConnection(protocol, conn) {
if (!this._running) { return; }
//console.log("Incoming message")
pull(
conn,
lp.decode(),
pull.asyncMap((data, cb) => CmdSignal.deserializeCallback(data, cb)), //Convert logic to promise
pull.asyncMap((msg, cb) => {
conn.getPeerInfo((err, peerInfo) => {
if (err) { return cb(err); }
//console.log("getting message")
this._receiveMessage(peerInfo.id, msg);
});
}),
pull.onEnd((err) => {
console.log('ending connection');
if (err) {
this._receiveError(err);
}
})
);
}
/**
* Copy this function to create your own command.
* Type = 1 is request; Type = 2 is response.
* Use promise to respond to any requests.
* If response, return no value on promise
*
* @param {PeerId} PeerId
* @param {String} cmd
* @param {Object} args
* @param {String} tid
* @returns {Promise}
*/
_exampleCommand(PeerId, cmd, args, tid) {
console.log(cmd)
return new Promise((resolve, reject) => {
//Do something here!
resolve("This is example command.")
});
}
}
exports = module.exports = ProtocolHandler;