-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathfirechat.js
645 lines (538 loc) · 20.3 KB
/
firechat.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// Firechat is a simple, easily-extensible data layer for multi-user,
// multi-room chat, built entirely on [Firebase](https://firebase.google.com).
//
// The Firechat object is the primary conduit for all underlying data events.
// It exposes a number of methods for binding event listeners, creating,
// entering, or leaving chat rooms, initiating chats, sending messages,
// and moderator actions such as warning, kicking, or suspending users.
//
// firechat.js 0.0.0
// https://firebase.google.com
// (c) 2016 Firebase
// License: MIT
// Setup
// --------------
(function() {
// Establish a reference to the `window` object, and save the previous value
// of the `Firechat` variable.
var root = this,
previousFirechat = root.Firechat;
function Firechat(firebaseRef, options) {
// Cache the provided Database reference and the firebase.App instance
this._firechatRef = firebaseRef;
this._firebaseApp = firebaseRef.database.app;
// User-specific instance variables.
this._user = null;
this._userId = null;
this._userName = null;
this._isModerator = false;
// A unique id generated for each session.
this._sessionId = null;
// A mapping of event IDs to an array of callbacks.
this._events = {};
// A mapping of room IDs to a boolean indicating presence.
this._rooms = {};
// A mapping of operations to re-queue on disconnect.
this._presenceBits = {};
// Commonly-used Firebase references.
this._userRef = null;
this._messageRef = this._firechatRef.child('room-messages');
this._roomRef = this._firechatRef.child('room-metadata');
this._privateRoomRef = this._firechatRef.child('room-private-metadata');
this._moderatorsRef = this._firechatRef.child('moderators');
this._suspensionsRef = this._firechatRef.child('suspensions');
this._usersOnlineRef = this._firechatRef.child('user-names-online');
// Setup and establish default options.
this._options = options || {};
// The number of historical messages to load per room.
this._options.numMaxMessages = this._options.numMaxMessages || 50;
}
// Run Firechat in *noConflict* mode, returning the `Firechat` variable to
// its previous owner, and returning a reference to the Firechat object.
Firechat.noConflict = function noConflict() {
root.Firechat = previousFirechat;
return Firechat;
};
// Export the Firechat object as a global.
root.Firechat = Firechat;
// Firechat Internal Methods
// --------------
Firechat.prototype = {
// Load the initial metadata for the user's account and set initial state.
_loadUserMetadata: function(onComplete) {
var self = this;
// Update the user record with a default name on user's first visit.
this._userRef.transaction(function(current) {
if (!current || !current.id || !current.name) {
return {
id: self._userId,
name: self._userName
};
}
}, function(error, committed, snapshot) {
self._user = snapshot.val();
self._moderatorsRef.child(self._userId).once('value', function(snapshot) {
self._isModerator = !!snapshot.val();
root.setTimeout(onComplete, 0);
});
});
},
// Initialize Firebase listeners and callbacks for the supported bindings.
_setupDataEvents: function() {
// Monitor connection state so we can requeue disconnect operations if need be.
var connectedRef = this._firechatRef.root.child('.info/connected');
connectedRef.on('value', function(snapshot) {
if (snapshot.val() === true) {
// We're connected (or reconnected)! Set up our presence state.
for (var path in this._presenceBits) {
var op = this._presenceBits[path],
ref = op.ref;
ref.onDisconnect().set(op.offlineValue);
ref.set(op.onlineValue);
}
}
}, this);
// Queue up a presence operation to remove the session when presence is lost
this._queuePresenceOperation(this._sessionRef, true, null);
// Register our username in the public user listing.
var usernameRef = this._usersOnlineRef.child(this._userName.toLowerCase());
var usernameSessionRef = usernameRef.child(this._sessionId);
this._queuePresenceOperation(usernameSessionRef, {
id: this._userId,
name: this._userName
}, null);
// Listen for state changes for the given user.
this._userRef.on('value', this._onUpdateUser, this);
// Listen for chat invitations from other users.
this._userRef.child('invites').on('child_added', this._onFirechatInvite, this);
// Listen for messages from moderators and adminstrators.
this._userRef.child('notifications').on('child_added', this._onNotification, this);
},
// Append the new callback to our list of event handlers.
_addEventCallback: function(eventId, callback) {
this._events[eventId] = this._events[eventId] || [];
this._events[eventId].push(callback);
},
// Retrieve the list of event handlers for a given event id.
_getEventCallbacks: function(eventId) {
if (this._events.hasOwnProperty(eventId)) {
return this._events[eventId];
}
return [];
},
// Invoke each of the event handlers for a given event id with specified data.
_invokeEventCallbacks: function(eventId) {
var args = [],
callbacks = this._getEventCallbacks(eventId);
Array.prototype.push.apply(args, arguments);
args = args.slice(1);
for (var i = 0; i < callbacks.length; i += 1) {
callbacks[i].apply(null, args);
}
},
// Keep track of on-disconnect events so they can be requeued if we disconnect the reconnect.
_queuePresenceOperation: function(ref, onlineValue, offlineValue) {
ref.onDisconnect().set(offlineValue);
ref.set(onlineValue);
this._presenceBits[ref.toString()] = {
ref: ref,
onlineValue: onlineValue,
offlineValue: offlineValue
};
},
// Remove an on-disconnect event from firing upon future disconnect and reconnect.
_removePresenceOperation: function(ref, value) {
var path = ref.toString();
ref.onDisconnect().cancel();
ref.set(value);
delete this._presenceBits[path];
},
// Event to monitor current user state.
_onUpdateUser: function(snapshot) {
this._user = snapshot.val();
this._userName = this._user.name;
this._invokeEventCallbacks('user-update', this._user);
},
// Event to monitor current auth + user state.
_onAuthRequired: function() {
this._invokeEventCallbacks('auth-required');
},
// Events to monitor room entry / exit and messages additional / removal.
_onEnterRoom: function(room) {
this._invokeEventCallbacks('room-enter', room);
},
_onNewMessage: function(roomId, snapshot) {
var message = snapshot.val();
message.id = snapshot.key;
this._invokeEventCallbacks('message-add', roomId, message);
},
_onRemoveMessage: function(roomId, snapshot) {
var messageId = snapshot.key;
this._invokeEventCallbacks('message-remove', roomId, messageId);
},
_onLeaveRoom: function(roomId) {
this._invokeEventCallbacks('room-exit', roomId);
},
// Event to listen for notifications from administrators and moderators.
_onNotification: function(snapshot) {
var notification = snapshot.val();
if (!notification.read) {
if (notification.notificationType !== 'suspension' || notification.data.suspendedUntil < new Date().getTime()) {
snapshot.ref.child('read').set(true);
}
this._invokeEventCallbacks('notification', notification);
}
},
// Events to monitor chat invitations and invitation replies.
_onFirechatInvite: function(snapshot) {
var self = this,
invite = snapshot.val();
// Skip invites we've already responded to.
if (invite.status) {
return;
}
invite.id = invite.id || snapshot.key;
self.getRoom(invite.roomId, function(room) {
invite.toRoomName = room.name;
self._invokeEventCallbacks('room-invite', invite);
});
},
_onFirechatInviteResponse: function(snapshot) {
var self = this,
invite = snapshot.val();
invite.id = invite.id || snapshot.key;
this._invokeEventCallbacks('room-invite-response', invite);
}
};
// Firechat External Methods
// --------------
// Initialize the library and setup data listeners.
Firechat.prototype.setUser = function(userId, userName, callback) {
var self = this;
self._firebaseApp.auth().onAuthStateChanged(function(user) {
if (user) {
self._userId = userId.toString();
self._userName = userName.toString();
self._userRef = self._firechatRef.child('users').child(self._userId);
self._sessionRef = self._userRef.child('sessions').push();
self._sessionId = self._sessionRef.key;
self._loadUserMetadata(function() {
root.setTimeout(function() {
callback(self._user);
self._setupDataEvents();
}, 0);
});
} else {
self.warn('Firechat requires an authenticated Firebase reference. Pass an authenticated reference before loading.');
}
});
};
// Resumes the previous session by automatically entering rooms.
Firechat.prototype.resumeSession = function() {
this._userRef.child('rooms').once('value', function(snapshot) {
var rooms = snapshot.val();
for (var roomId in rooms) {
this.enterRoom(rooms[roomId].id);
}
}, /* onError */ function(){}, /* context */ this);
};
// Callback registration. Supports each of the following events:
Firechat.prototype.on = function(eventType, cb) {
this._addEventCallback(eventType, cb);
};
// Create and automatically enter a new chat room.
Firechat.prototype.createRoom = function(roomName, roomType, callback) {
var self = this,
newRoomRef = this._roomRef.push();
var newRoom = {
id: newRoomRef.key,
name: roomName,
type: roomType || 'public',
createdByUserId: this._userId,
createdAt: firebase.database.ServerValue.TIMESTAMP
};
if (roomType === 'private') {
newRoom.authorizedUsers = {};
newRoom.authorizedUsers[this._userId] = true;
}
newRoomRef.set(newRoom, function(error) {
if (!error) {
self.enterRoom(newRoomRef.key);
}
if (callback) {
callback(newRoomRef.key);
}
});
};
// Enter a chat room.
Firechat.prototype.enterRoom = function(roomId) {
var self = this;
self.getRoom(roomId, function(room) {
var roomName = room.name;
if (!roomId || !roomName) return;
// Skip if we're already in this room.
if (self._rooms[roomId]) {
return;
}
self._rooms[roomId] = true;
if (self._user) {
// Save entering this room to resume the session again later.
self._userRef.child('rooms').child(roomId).set({
id: roomId,
name: roomName,
active: true
});
// Set presence bit for the room and queue it for removal on disconnect.
var presenceRef = self._firechatRef.child('room-users').child(roomId).child(self._userId).child(self._sessionId);
self._queuePresenceOperation(presenceRef, {
id: self._userId,
name: self._userName
}, null);
}
// Invoke our callbacks before we start listening for new messages.
self._onEnterRoom({ id: roomId, name: roomName });
// Setup message listeners
self._roomRef.child(roomId).once('value', function(snapshot) {
self._messageRef.child(roomId).limitToLast(self._options.numMaxMessages).on('child_added', function(snapshot) {
self._onNewMessage(roomId, snapshot);
}, /* onCancel */ function() {
// Turns out we don't have permission to access these messages.
self.leaveRoom(roomId);
}, /* context */ self);
self._messageRef.child(roomId).limitToLast(self._options.numMaxMessages).on('child_removed', function(snapshot) {
self._onRemoveMessage(roomId, snapshot);
}, /* onCancel */ function(){}, /* context */ self);
}, /* onFailure */ function(){}, self);
});
};
// Leave a chat room.
Firechat.prototype.leaveRoom = function(roomId) {
var self = this,
userRoomRef = self._firechatRef.child('room-users').child(roomId);
// Remove listener for new messages to this room.
self._messageRef.child(roomId).off();
if (self._user) {
var presenceRef = userRoomRef.child(self._userId).child(self._sessionId);
// Remove presence bit for the room and cancel on-disconnect removal.
self._removePresenceOperation(presenceRef, null);
// Remove session bit for the room.
self._userRef.child('rooms').child(roomId).remove();
}
delete self._rooms[roomId];
// Invoke event callbacks for the room-exit event.
self._onLeaveRoom(roomId);
};
Firechat.prototype.sendMessage = function(roomId, messageContent, messageType, cb) {
var self = this,
message = {
userId: self._userId,
name: self._userName,
timestamp: firebase.database.ServerValue.TIMESTAMP,
message: messageContent,
type: messageType || 'default'
},
newMessageRef;
if (!self._user) {
self._onAuthRequired();
if (cb) {
cb(new Error('Not authenticated or user not set!'));
}
return;
}
newMessageRef = self._messageRef.child(roomId).push();
newMessageRef.setWithPriority(message, firebase.database.ServerValue.TIMESTAMP, cb);
};
Firechat.prototype.deleteMessage = function(roomId, messageId, cb) {
var self = this;
self._messageRef.child(roomId).child(messageId).remove(cb);
};
// Mute or unmute a given user by id. This list will be stored internally and
// all messages from the muted clients will be filtered client-side after
// receipt of each new message.
Firechat.prototype.toggleUserMute = function(userId, cb) {
var self = this;
if (!self._user) {
self._onAuthRequired();
if (cb) {
cb(new Error('Not authenticated or user not set!'));
}
return;
}
self._userRef.child('muted').child(userId).transaction(function(isMuted) {
return (isMuted) ? null : true;
}, cb);
};
// Send a moderator notification to a specific user.
Firechat.prototype.sendSuperuserNotification = function(userId, notificationType, data, cb) {
var self = this,
userNotificationsRef = self._firechatRef.child('users').child(userId).child('notifications');
userNotificationsRef.push({
fromUserId: self._userId,
timestamp: firebase.database.ServerValue.TIMESTAMP,
notificationType: notificationType,
data: data || {}
}, cb);
};
// Warn a user for violating the terms of service or being abusive.
Firechat.prototype.warnUser = function(userId) {
var self = this;
self.sendSuperuserNotification(userId, 'warning');
};
// Suspend a user by putting the user into read-only mode for a period.
Firechat.prototype.suspendUser = function(userId, timeLengthSeconds, cb) {
var self = this,
suspendedUntil = new Date().getTime() + 1000*timeLengthSeconds;
self._suspensionsRef.child(userId).set(suspendedUntil, function(error) {
if (error && cb) {
return cb(error);
} else {
self.sendSuperuserNotification(userId, 'suspension', {
suspendedUntil: suspendedUntil
});
return cb(null);
}
});
};
// Invite a user to a specific chat room.
Firechat.prototype.inviteUser = function(userId, roomId) {
var self = this,
sendInvite = function() {
var inviteRef = self._firechatRef.child('users').child(userId).child('invites').push();
inviteRef.set({
id: inviteRef.key,
fromUserId: self._userId,
fromUserName: self._userName,
roomId: roomId
});
// Handle listen unauth / failure in case we're kicked.
inviteRef.on('value', self._onFirechatInviteResponse, function(){}, self);
};
if (!self._user) {
self._onAuthRequired();
return;
}
self.getRoom(roomId, function(room) {
if (room.type === 'private') {
var authorizedUserRef = self._roomRef.child(roomId).child('authorizedUsers');
authorizedUserRef.child(userId).set(true, function(error) {
if (!error) {
sendInvite();
}
});
} else {
sendInvite();
}
});
};
Firechat.prototype.acceptInvite = function(inviteId, cb) {
var self = this;
self._userRef.child('invites').child(inviteId).once('value', function(snapshot) {
var invite = snapshot.val();
if (invite === null && cb) {
return cb(new Error('acceptInvite(' + inviteId + '): invalid invite id'));
} else {
self.enterRoom(invite.roomId);
self._userRef.child('invites').child(inviteId).update({
'status': 'accepted',
'toUserName': self._userName
}, cb);
}
}, self);
};
Firechat.prototype.declineInvite = function(inviteId, cb) {
var self = this,
updates = {
'status': 'declined',
'toUserName': self._userName
};
self._userRef.child('invites').child(inviteId).update(updates, cb);
};
Firechat.prototype.getRoomList = function(cb) {
var self = this;
self._roomRef.once('value', function(snapshot) {
cb(snapshot.val());
});
};
Firechat.prototype.getUsersByRoom = function() {
var self = this,
roomId = arguments[0],
query = self._firechatRef.child('room-users').child(roomId),
cb = arguments[arguments.length - 1],
limit = null;
if (arguments.length > 2) {
limit = arguments[1];
}
query = (limit) ? query.limitToLast(limit) : query;
query.once('value', function(snapshot) {
var usernames = snapshot.val() || {},
usernamesUnique = {};
for (var username in usernames) {
for (var session in usernames[username]) {
// Skip all other sessions for this user as we only need one.
usernamesUnique[username] = usernames[username][session];
break;
}
}
root.setTimeout(function() {
cb(usernamesUnique);
}, 0);
});
};
Firechat.prototype.getUsersByPrefix = function(prefix, startAt, endAt, limit, cb) {
var self = this,
query = this._usersOnlineRef,
prefixLower = prefix.toLowerCase();
if (startAt) {
query = query.startAt(null, startAt);
} else if (endAt) {
query = query.endAt(null, endAt);
} else {
query = (prefixLower) ? query.startAt(null, prefixLower) : query.startAt();
}
query = (limit) ? query.limitToLast(limit) : query;
query.once('value', function(snapshot) {
var usernames = snapshot.val() || {},
usernamesFiltered = {};
for (var userNameKey in usernames) {
var sessions = usernames[userNameKey],
userName, userId, usernameClean;
// Grab the user data from the first registered active session.
for (var sessionId in sessions) {
userName = sessions[sessionId].name;
userId = sessions[sessionId].id;
// Skip all other sessions for this user as we only need one.
break;
}
// Filter out any usernames that don't match our prefix and break.
if ((prefix.length > 0) && (userName.toLowerCase().indexOf(prefixLower) !== 0))
continue;
usernamesFiltered[userName] = {
name: userName,
id: userId
};
}
root.setTimeout(function() {
cb(usernamesFiltered);
}, 0);
});
};
// Miscellaneous helper methods.
Firechat.prototype.getRoom = function(roomId, callback) {
this._roomRef.child(roomId).once('value', function(snapshot) {
callback(snapshot.val());
});
};
Firechat.prototype.userIsModerator = function() {
return this._isModerator;
};
Firechat.prototype.warn = function(msg) {
if (console) {
msg = 'Firechat Warning: ' + msg;
if (typeof console.warn === 'function') {
console.warn(msg);
} else if (typeof console.log === 'function') {
console.log(msg);
}
}
};
})();