-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathangular-chat.js
135 lines (91 loc) · 2.63 KB
/
angular-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
'use strict';
angular.module('chat', []);
// Common JS
if (typeof(exports) !== 'undefined') exports.chat = angular.module('chat');
// define Angular Message module
angular.module('chat').service( 'Messages', [ 'ChatCore', function(ChatCore) {
var self = this;
// Send Messages
self.send = function(message) {
if (!message.data) return;
ChatCore.publish({
to: message.to || 'global',
message: message.data,
user: ChatCore.user()
});
};
// Receive Messages
self.receive = function(fn) {
self.subscription = ChatCore.subscribe(fn);
};
// Set/Get User
self.user = function(data) {
return ChatCore.user(data);
};
return self;
}]);
// AngularJS Chat Core Service
angular.module('chat').service('ChatCore',
['$rootScope', '$http', 'config',
function($rootScope, $http, config) {
var user = {
id: uuid(),
name: 'Anonymous'
};
var self = this;
self.rltm = rltm(config.rltm);
// the global room everyone is in
self.roomGlobal;
// my own private rooms
self.roomPrivate;
// everyone elses private rooms
self.rooms = {};
// Set User Data
self.user = function(data) {
if (data) {
angular.extend(user, data);
}
return user;
};
// Publish over network
self.publish = function(setup) {
var user = setup.user || self.user();
var data = setup.data;
if(setup.to) {
if(!self.rooms[setup.to]) {
self.rooms[setup.to] = self.rltm.join(setup.to);
}
return self.rooms[setup.to].publish({
data: setup.message,
user: user
});
} else {
return self.roomGlobal.publish({
data: setup.message,
user: user
});
}
};
// Subscribe to new messages
self.subscribe = function(fn) {
self.roomGlobal = self.rltm.join('global');
self.roomPrivate = self.rltm.join(self.user().id);
self.roomGlobal.on('message', function(uuid, data) {
fn(data, false);
$rootScope.$apply();
});
self.roomPrivate.on('message', function(uuid, data) {
fn(data, true);
$rootScope.$apply();
});
return self.room;
};
}]);
// UUID utility
function uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}