-
Notifications
You must be signed in to change notification settings - Fork 48
/
chat.js
378 lines (313 loc) · 11.1 KB
/
chat.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
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
var crypto = require('crypto');
var streamlib = require('stream');
var log = require("../lib/util/log")("Chat")
// implements https://github.com/telehash/telehash.org/blob/master/v3/channels/chat.md
exports.name = 'chat';
exports.mesh = function(mesh, cbMesh)
{
var lib = mesh.lib;
var self = {open:{}, chats:{}};
// overwrite-able callback for invites
var cbInvite = false;
mesh.invited = function(handler){ cbInvite = handler; };
// create/join a new chat
mesh.chat = function(args, profile, cbReady)
{
// javascript is lame
if(typeof profile == 'function')
{
cbReady = profile;
profile = false;
}
if(!profile)
{
profile = args;
args = {};
}
function readyUp(err)
{
if(err) log.debug('chat error', err);
if(!cbReady) return;
// I wish node unrolled itself
var cb = cbReady;
cbReady = false;
cb(err, chat);
}
// accept uri arg
if(typeof args == 'string')
{
var leader = mesh.link(args);
if(!leader || !leader.args.query.id) return readyUp('bad uri: '+args);
args = {leader:leader,id:leader.args.query.id};
}
if(typeof args != 'object') return readyUp('bad args');
// generate or load basics for the unique chat id
var chat = {};
chat.secret = args.secret || crypto.randomBytes(8);
chat.depth = args.depth || 1000;
chat.seq = args.seq || chat.depth;
chat.id = args.id || stamp();
self.chats[chat.id] = chat;
chat.leader = args.leader || mesh;
chat.leading = (chat.leader == mesh) ? true : false;
chat.messages = {}; // index of all cached chat messages "id":{...}
chat.log = []; // ordered combined history ["id","id"]
chat.profiles = {}; // profiles by hashname
chat.last = {}; // last message id by hashname
chat.invited = {}; // ACL
chat.inbox = new streamlib.Readable({objectMode:true});
chat.inbox._read = function(){}; // all evented
chat.outbox = new streamlib.Writable({objectMode:true});
chat.streams = {}; // by hashname
// sanitize our profile
if(typeof profile == 'string') profile = {json:{text:profile}}; // convenient
if(!profile.json) profile = {json:profile};
profile.json.type = 'profile';
profile.json.id = (chat.leading) ? chat.id : stamp();
chat.profile = lib.lob.packet(profile.json, profile.body);
// internal fail handler
function fail(err, cbErr)
{
if(!err) return; // only catch errors
log.warn('chat fail',err);
chat.err = err;
// TODO error inbox/outbox
if(typeof cbErr == 'function') cbErr(err);
readyUp(err);
}
// internal message id generator
function stamp()
{
if(!chat.seq) return fail('chat history overflow, please restart');
var id = lib.hashname.siphash(mesh.hashname, chat.secret);
for(var i = 0; i < chat.seq; i++) id = lib.hashname.siphash(id.key,id);
chat.seq--;
return lib.base32.encode(id);
}
// internal to cache and event a message
chat.receive = function(from, msg)
{
msg.from = from;
// massage join's attached profile
if(msg.json.type == 'join')
{
msg.join = lib.lob.decode(msg.body);
msg.json.join = msg.join.json; // convenience
}
// put in our caches/log
if(msg.json.type == 'chat' || msg.json.type == 'join')
{
if(chat.messages[msg.json.id] && chat.messages[msg.json.id].json.text == msg.json.text) return log.debug('ignoring duplicate message');
chat.messages[msg.json.id] = msg;
chat.last[from] = msg.json.id;
// TODO put ordered in chat.log
chat.log.unshift(msg);
}
log.debug('receiving message',msg.from,msg.json);
chat.inbox.push(msg);
}
// internal to add a profile
chat.add = function(from, profile)
{
profile.from = from;
chat.profiles[from] = profile;
if(!chat.last[from]) chat.last[from] = profile.json.id;
chat.messages[profile.json.id] = profile;
log.debug('added profile',profile.json.id,from);
}
// this channel is ready
chat.connect = function(link, channel, last)
{
log.debug('chat connected',link.hashname);
// see if replacing existing stream
if(chat.streams[link.hashname])
{
// TODO BUGGY
// chat.streams[link.hashname].end();
}else{
chat.receive(link.hashname, lib.lob.packet({type:'connect'}));
}
var stream = chat.streams[link.hashname] = mesh.streamize(channel, 'lob');
stream.on('data', function(msg){
// make sure is sequential/valid id
if(!msg.json.id) return log.debug('bad message',msg.json);
var next = lib.base32.encode(lib.hashname.siphash(link.hashname, lib.base32.decode(msg.json.id)));
if(msg.json.id != chat.last[link.hashname] && next != chat.last[link.hashname]) return log.warn('unsequenced message',msg.json,chat.last[link.hashname]);
chat.receive(link.hashname, msg);
});
stream.on('end', function(){
log.debug('chat stream ended',link.hashname);
if(chat.streams[link.hashname] == stream)
{
chat.receive(link.hashname, lib.lob.packet({type:'disconnect'}));
delete chat.streams[link.hashname];
}
});
// send any messages since the last they saw
function sync(id)
{
if(id == last.json.id) return;
// bottoms up, send older first
sync(lib.base32.encode(lib.hashname.siphash(mesh.hashname, lib.base32.decode(id))));
stream.write(chat.messages[id]);
}
sync(chat.last[mesh.hashname]);
// signal good startup
readyUp();
return stream;
}
chat.join = function(link, profile)
{
chat.invited[link.hashname] = true;
// if we don't have their profile yet, send a join
if(!chat.profiles[link.hashname])
{
var open = {json:{type:'profile',chat:chat.id,seq:1}};
if(profile) open.json.profile = profile;
var channel = link.x.channel(open);
channel.send(open);
var stream = mesh.streamize(channel,'lob');
stream.write(chat.profile);
stream.on('error', function(err){
if(link == chat.leader) fail(err);
});
stream.on('finish',function(){
if(chat.profiles[link.hashname]) chat.join(link);
});
stream.end();
return;
}
// already connected
if(chat.streams[link.hashname]) return;
// let's get chatting
var open = {json:{type:'chat',chat:chat.id,seq:1}};
open.json.last = chat.last[link.hashname];
var chan = link.x.channel(open);
chan.receiving = function(err, packet, cbMore) {
if(packet)
{
var last = chat.messages[packet.json.last];
if(!last || last.from != mesh.hashname) return cbMore('unknown last '+packet.json.last);
chat.connect(link, chan, last);
cbMore();
}
}
chan.send(open);
}
// outgoing helper
chat.send = function(msg)
{
if(typeof msg == 'string') msg = {json:{text:msg}}; // convenient
if(!msg.json) msg = {json:msg}; // friendly to make a packet
if(!msg.json.type) msg.json.type = 'chat';
if(!msg.json.id) msg.json.id = stamp();
if(!msg.json.at) msg.json.at = Math.floor(Date.now()/1000);
if(!msg.json.after && chat.log[0]) msg.json.after = chat.log[0].json.id;
msg = lib.lob.packet(msg.json,msg.body); // consistency
// we receive it first
chat.receive(mesh.hashname, msg);
// deliver to anyone connected
Object.keys(chat.streams).forEach(function(to){
log.debug('sending to',to,msg.json.id);
chat.streams[to].write(msg);
});
}
// read messages from stream too
chat.outbox._write = function(data, enc, cbDone){
chat.send(data);
cbDone();
};
// always add ourselves
chat.add(mesh.hashname, chat.profile);
// if not the leader, send our profile to them to start
if(!chat.leading)
{
chat.join(chat.leader);
}else{
// leader auto-joins
chat.send({json:{type:'join',from:mesh.hashname},body:lib.lob.encode(chat.profile)});
readyUp();
}
return chat;
}
self.open.profile = function(args, open, cbOpen){
var link = this;
// ensure valid request
var id = lib.base32.decode(open.json.chat);
if(!id || id.length != 8) return cbOpen('invalid chat id');
// accept and stream until the profile
var chan = link.x.channel(open);
var stream = mesh.streamize(chan, 'lob');
if(!stream) return cbOpen('invalid open');
// wait for the profile message
stream.on('data', function(profile){
if(profile.json.type != 'profile' || !profile.json.id) return cbOpen('bad profile');
log.debug('join request',open.json,profile.json);
stream.end(); // send all done
// process invites for unknown chats
var chat = self.chats[open.json.chat];
if(!chat)
{
if(open.json.chat != profile.json.id) return cbOpen('unknown chat');
if(!cbInvite) return cbOpen('cannot accept invites');
// send the invite request to the app
cbInvite(link, profile);
return;
}
// if they're the leader, accept their profile
if(chat.leader == link)
{
// see if they need our profile yet
if(!open.json.profile) chat.join(link, profile.json.id);
// cache/track the profile
chat.add(link.hashname, profile);
// this will now connect
if(open.json.profile) chat.join(link);
return;
}
// not invited is request to join
if(!chat.invited[link.hashname])
{
// event the profile for the app to decide on
chat.receive(link.hashname, profile);
return;
}
// see if they need our profile yet
if(!open.json.profile) chat.join(link, profile.json.id);
// add new profile, send a join message
if(!chat.profiles[link.hashname])
{
chat.add(link.hashname, profile);
var join = {json:{type:'join',from:link.hashname},body:lib.lob.encode(profile)};
chat.send(join);
}
// if they have ours, this will get connected now
if(open.json.profile) chat.join(link);
});
// process stream start
chan.receive(open);
}
self.open.chat = function(args, open, cbOpen){
var link = this;
log.debug('chat request',open.json);
// ensure valid request
var id = lib.base32.decode(open.json.chat);
if(!id || id.length != 8) return cbOpen('invalid chat id');
var chat = self.chats[open.json.chat];
if(!chat) return cbOpen('unknown chat');
if(!chat.profiles[link.hashname]) return cbOpen('no profile');
var last = chat.messages[open.json.last];
if(!last || last.from != mesh.hashname) return cbOpen('unknown last '+open.json.last);
var chan = link.x.channel(open);
chan.receive(open);
// confirm
chan.send({json:{last:chat.last[link.hashname]}});
chat.connect(link, chan, last);
}
cbMesh(undefined, self);
}
exports.Log = function(args){
Object.keys(args).forEach(function(type){
log[type] = args[type].bind(console)
})
}