-
Notifications
You must be signed in to change notification settings - Fork 0
/
process.js
116 lines (96 loc) · 2.77 KB
/
process.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
var jsonparse = require('cog/jsonparse');
/**
### process
```
fn(signaller, opts) => fn(message)
```
The core processing logic that is used to respond to incoming signaling
messages.
**/
module.exports = function(signaller, opts) {
var handlers = {
announce: require('./handlers/announce')(signaller, opts)
};
function sendEvent(parts, srcState, data) {
// initialise the event name
var evtName = 'message:' + parts[0].slice(1);
// convert any valid json objects to json
var args = parts.slice(2).map(jsonparse);
signaller.apply(
signaller,
[evtName].concat(args).concat([srcState, data])
);
}
return function(originalData) {
var data = originalData;
var isMatch = true;
var parts;
var handler;
var srcData;
var srcState;
var isDirectMessage = false;
// discard primus messages
if (data && data.slice(0, 6) === 'primus') {
return;
}
// force the id into string format so we can run length and comparison tests on it
var id = signaller.id + '';
// process /to messages
if (data.slice(0, 3) === '/to') {
isMatch = data.slice(4, id.length + 4) === id;
if (isMatch) {
parts = data.slice(5 + id.length).split('|').map(jsonparse);
// get the source data
isDirectMessage = true;
// extract the vector clock and update the parts
parts = parts.map(jsonparse);
}
}
// if this is not a match, then bail
if (! isMatch) {
return;
}
// chop the data into parts
signaller('rawdata', data);
parts = parts || data.split('|').map(jsonparse);
// if we have a specific handler for the action, then invoke
if (typeof parts[0] == 'string') {
// extract the metadata from the input data
srcData = parts[1];
// if we got data from ourself, then this is pretty dumb
// but if we have then throw it away
if (srcData === signaller.id) {
return console.warn('got data from ourself, discarding');
}
// get the source state
srcState = signaller.peers.get(srcData) || srcData;
// handle commands
if (parts[0].charAt(0) === '/') {
// look for a handler for the message type
handler = handlers[parts[0].slice(1)];
if (typeof handler == 'function') {
handler(
parts.slice(2),
parts[0].slice(1),
srcData,
srcState,
isDirectMessage
);
}
else {
sendEvent(parts, srcState, originalData);
}
}
// otherwise, emit data
else {
signaller(
'data',
parts.slice(0, 1).concat(parts.slice(2)),
srcData,
srcState,
isDirectMessage
);
}
}
};
};