/
chat.js
executable file
·577 lines (557 loc) · 22.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
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
var Chat = {
BOSH_SERVICE: 'http://localhost:5280/bosh/',
connection: null,
connected: false,
debuggingMode: false,
connect: function (jid, password, BOSH_SERVICE, debugginMode) {
//alert(password);
Chat.BOSH_SERVICE = (BOSH_SERVICE) ? BOSH_SERVICE : Chat.BOSH_SERVICE;
Chat.debuggingMode = (debugginMode) ? debugginMode : true; //set to false after done testing!!
Chat.connection = new Strophe.Connection(Chat.BOSH_SERVICE);
Chat.connection.connect(jid, password, Chat.onConnect);
},
disconnect: function () {
Chat.connection.flush();
Chat.connection.disconnect();
Chat.connected = false;
},
onConnect: function (status) {
if (status === Strophe.Status.CONNECTING) {
Chat.log('Strophe is connecting.');
}
else if (status === Strophe.Status.CONNFAIL) {
Chat.log('Strophe failed to connect.');
}
else if (status === Strophe.Status.DISCONNECTING) {
Chat.log('Strophe is disconnecting.');
}
else if (status === Strophe.Status.DISCONNECTED) {
Chat.log('Strophe is disconnected.');
}
else if (status === Strophe.Status.CONNECTED) {
Chat.log('Strophe is connected.');
Chat.connected = true;
Chat.sendPresence();
Chat.connection.addHandler(Chat.receiveMessage, null, 'message');
//Add ping handler ~noy working...
//Chat.connection.ping.addPingHandler(Chat.receivePing);
//getRoster from server
var iq = $iq({type: 'get'}).c('query', {xmlns: 'jabber:iq:roster'});
Chat.connection.sendIQ(iq, Chat.rosterReceived);
//GetPubSub Nodes
Chat.discoverNodes();
//getNodes user is subscribed to
Chat.getSubscriptions();
}
},
onRegister: function (status) {
if (status === Strophe.Status.REGISTER) {
Chat.log("Registering");
Chat.connection.register.fields.username = Chat.registerUserInfo.Jid;
Chat.connection.register.fields.password = Chat.registerUserInfo.Password;
Chat.connection.register.submit();
} else if (status === Strophe.Status.REGISTERED) {
Chat.log("Registered!");
Chat.connection.authenticate();
} else if (status === Strophe.Status.CONNECTED) {
Chat.log("logged in!");
} else {
// every other status a connection.connect would receive
}
},
registerUserInfo: {},
registerUser: function (server, Jid, Password, BOSH_SERVICE) {
//XEP-0077 InBand Registration
Chat.registerUserInfo = {'Jid': Jid, 'Password': Password};
//possibly more reg fields later... email,name
Chat.connection = true;
Chat.debuggingMode = true;
Chat.BOSH_SERVICE = (BOSH_SERVICE) ? BOSH_SERVICE : Chat.BOSH_SERVICE;
Chat.connection = new Strophe.Connection(Chat.BOSH_SERVICE);
Chat.connection.register.connect(server, Chat.onRegister);
},
sendPriority: function (priority) {
Chat.connection.send($pres()
.c("priority").t(priority));
Chat.log("Priority of " + priority + " sent to contacts.");
},
sendPresence: function () {
Chat.connection.send($pres());
Chat.log("Presence Sent.");
},
messages: [],
chatStates: {},
receiveMessage: function (msg) {
var to = msg.getAttribute('to');
var from = msg.getAttribute('from');
var type = msg.getAttribute('type');
var elems = $(msg).find('body').text();
Chat.log("message received: ", elems);
$("ol").prepend("<li>" + from + ":-" + elems + "</li>");
//GroupChat message
if (type == 'groupchat') {
Chat.log("Group Chat message");
}
//pubsub message
else if (from === Chat.pubsubJid && msg.getElementsByTagName('summary').length) {
Chat.log("pubsub message", msg.getElementsByTagName('summary')[0]);
var items = msg.getElementsByTagName('items');
var nodeName = items[0].getAttribute('node');
Chat.pubsubMessages.push({
"message": Strophe.getText(msg.getElementsByTagName('summary')[0]),
"type": "received",
"nodeName": nodeName
});
}
else if (msg.getElementsByTagName('paused').length) {
Chat.log("Sender is Paused");
Chat.chatStates[from] = "paused";
}
else if (msg.getElementsByTagName('active').length) {
Chat.log("Sender is Active");
Chat.chatStates[from] = "active";
}
else if (msg.getElementsByTagName('composing').length) {
Chat.log("Sender is composing");
Chat.chatStates[from] = "composing"
}
else if (msg.getElementsByTagName('body').length) {
var body = msg.getElementsByTagName('body')[0];
var messageInfo = {
'to': to,
'from': from,
'type': type,
'message': Strophe.getText(body)
}
Chat.messages.push(messageInfo);
}
// we must return true to keep the handler alive.
// returning false would remove it after it finishes.
return true;
},
sendMessage: function (messgeTo, message, type) {
var messagetype = (type) ? type : 'chat';
var reply;
if (messagetype === 'groupchat') {
reply = $msg({to: messgeTo,
from: Chat.connection.jid,
type: messagetype,
id: Chat.connection.getUniqueId()
}).c("body", {xmlns: Strophe.NS.CLIENT}).t(message);
}
else {
reply = $msg({to: messgeTo,
from: Chat.connection.jid,
type: messagetype
}).c("body").t(message);
}
Chat.connection.send(reply.tree());
Chat.log('I sent ' + messgeTo + ': ' + message, reply.tree());
},
Roster: [],
getRoster: function () {
if (!Chat.Roster) {
Chat.log("Roster Items not yet loaded!/No Contacts");
}
else
return Chat.Roster;
},
rosterReceived: function (iq) {
Chat.log(iq);
$(iq).find("item").each(function () {
Chat.Roster.push({jid: $(this).attr('jid'),
name: $(this).attr('name'),
subscription: $(this).attr('subscription')
});
});
Chat.connection.addHandler(Chat.presenceReceived, null, "presence");
},
//add user to your roster
addUser: function (Jid, name, groups) {
if (!Chat.userExists(Jid)) {
var groups = (groups) ? groups : '';
Chat.connection.roster.add(Jid, name, groups, function (status) {
Chat.Roster.push({'jid': Jid,
'name': name,
subscription: '' //NOTE:MIGHT BE ERROR PRONE TO NOT DECLARE SUBSCRIPTION...
});
Chat.log("User Added to roster: " + name, status, Chat.Roster);
});
Chat.log("Added user: " + Jid);
} else
Chat.log("Error adding new User");
},
//remove user from your roster
removeUser: function (Jid) {
if (Chat.userExists(Jid)) {
//Chat.connection.roster.get();
var iq = $iq({type: 'set'}).c('query', {xmlns: Strophe.NS.ROSTER}).c('item', {jid: Jid,
subscription: "remove"});
Chat.connection.sendIQ(iq, function (status) {
Chat.log("Removed: " + Jid, status);
});
for (var i = Chat.Roster.length - 1; i >= 0; i--) {
if (Chat.Roster[i].jid === Jid) {
Chat.Roster.splice(i, 1);
Chat.log(Chat.Roster);
}
}
} else
Chat.log("Error removing user");
},
authorizeUser: function (Jid, message) {
if (Chat.userExists(Jid)) {
Chat.connection.roster.authorize(Jid, message);
Chat.log("Authorized: " + Jid);
} else
Chat.log("Error Authorizing");
},
unauthorizeUser: function (Jid, message) {
if (Chat.userExists(Jid)) {
Chat.connection.roster.unauthorize(Jid, message);
Chat.log("Unauthorized: " + Jid);
} else
Chat.log("Error Unauthorizing");
},
subscribeUser: function (Jid, message) {
if (Chat.userExists(Jid)) {
Chat.connection.roster.subscribe(Jid, message);
//May not need, but added anyways.
Chat.Roster.push({'jid': Jid,
'name': Jid,
subscription: '' //NOTE:MIGHT BE ERROR PRONE TO NOT DECLARE SUBSCRIPTION...
});
Chat.log("Subscribed: " + Jid);
} else
Chat.log("Error subscribing user");
},
unsubscribeUser: function (Jid, message) {
if (Chat.userExists(Jid)) {
Chat.connection.roster.unsubscribe(Jid, message);
Chat.log("Unsubscribed: " + Jid);
} else
Chat.log("Error unsubscribing");
},
userExists: function (Jid) {
for (var i = Chat.Roster.length - 1; i >= 0; i--) {
if (Chat.Roster[i].jid === Jid) {
return true;
}
}
return false;
},
//A list of all the contacts online
presenceMessage: {},
presenceReceived: function (presence) {
var presence_type = $(presence).attr('type'); // unavailable, subscribed, etc...
var from = $(presence).attr('from'); // the jabber_id of the contact...
if (!Chat.presenceMessage[from])
Chat.log(presence);
if (presence_type != 'error') {
if (presence_type === 'unavailable') {
Chat.log("Contact: ", $(presence).attr('from'), " is offline");
Chat.presenceMessage[from] = "offline";
} else {
var show = $(presence).find("show").text(); // this is what gives away, dnd, etc.
if ((show === 'chat' || show === '') && (!Chat.presenceMessage[from])) {
// Mark contact as online
Chat.log("Contact: ", $(presence).attr('from'), " is online");
Chat.presenceMessage[from] = "online";
Chat.sendPresence();
} else if (show === 'away') {
Chat.log("Contact: ", $(presence).attr('from'), " is offline");
Chat.presenceMessage[from] = "offline";
}
}
}
return true;
},
sendChatState: function (Jid, status, type) {
var chatType = (type) ? type : "chat";
if (Chat.connection && Jid) {
Chat.connection.chatstates.init(Chat.connection);
if (status === "active") {
Chat.connection.chatstates.sendActive(Jid, chatType);
} else if (status === "composing") {
Chat.connection.chatstates.sendComposing(Jid, chatType);
} else if (status === "paused") {
Chat.connection.chatstates.sendPaused(Jid, chatType);
} else
Chat.log("Error, try again");
} else {
Chat.log("Error,sorry not connected")
}
},
discoSuccess: {},
discoInfo: function (Jid) {
Chat.connection.disco.info(Jid, '',
//Success callback
function (status) {
Chat.log("Disc Info Success", status);
Chat.discoSuccess[Jid] = true;
},
//error callback
function (status) {
Chat.log("Disc Info Error", status);
Chat.discoSuccess[Jid] = false;
}
);
},
Pings: {},
ping: function (Jid) {
Chat.connection.ping.ping(Jid,
function (status) {
Chat.log("Ping Success", status);
Chat.Pings[Jid] = true;
},
function (status) {
Chat.log("Ping Error", status);
Chat.Pings[Jid] = false;
}
);
},
discoverNodes: function () {
Chat.connection.pubsub.discoverNodes(
function (iq) {
$(iq).find("item").each(function () {
Chat.pubsubNodes.push($(this).attr('node'));
if (!Chat.pubsubJid) {
Chat.pubsubJid = $(this).attr('jid');
}
});
Chat.log("success retreiving nodes, stored in array Chat.pubsubNodes", iq);
},
function (status) {
Chat.log("error", status)
}
);
},
pubsubNodes: [],
pubsubJid: false,
pubsubMessages: [],
//nodeArray
createNode: function (nodeName, options) {
var options = (options) ? options : {};
Chat.connection.pubsub.createNode(
nodeName,
options,
function (status) {
Chat.log("Node created", status);
Chat.connection.send($pres());
}
);
},
pubsubPublish: function (nodeName, message) {
Chat.connection.pubsub.publish(
nodeName,
message,
Chat.onPublish
);
Chat.pubsubMessages.push({
"message": message,
"type": "sent",
"nodeName": nodeName
});
},
onPublish: function (status) {
Chat.log("Message published", status);
return true;
},
pubsubSubscribe: function (nodeName, options) {
var options = (options) ? options : {};
Chat.connection.pubsub.subscribe(
nodeName,
options,
Chat.messageReceived,
function (status) {
Chat.log("Subscribe node created", status)
},
function (status) {
console.log("error subscribing to node");
},
Chat.connection.jid
);
},
pubsubUnsubscribe: function (nodeName) {
Chat.connection.pubsub.unsubscribe(
nodeName,
Chat.getSubJID(Chat.connection.jid),
'',
function (status) {
Chat.log("Succesfully unsubscribed from node", status);
},
function (status) {
Chat.log("Error unsubscribing from node", status);
}
);
},
subscribedNodes: [],
//get all the nodes an individual is subscribed to.
getSubscriptions: function () {
Chat.connection.pubsub.getSubscriptions(function (status) {
Chat.log("Got Subscriptions, stored in Chat.subscribedNodes");
$(status).find("subscription").each(function () {
Chat.subscribedNodes.push($(this).attr('node'));
});
});
},
getNodeSubscriptions: function (nodeName) {
var subscribers = [];
Chat.connection.pubsub.getNodeSubscriptions(nodeName, function (status) {
Chat.log("Got all subscribers to the node", status);
$(status).find("subscription").each(function () {
subscribers.push($(this).attr('jid'));
});
});
return subscribers;
},
//Experimental Method
mucSendPresence: function (roomName) {
//http://xmpp.org/extensions/xep-0045.html#createroom
var presence = $pres({
to: roomName
}).c('x', {'xmlns': 'http://jabber.org/protocol/muc'});
Chat.log(presence.tree());
Chat.connection.send(presence.tree());
},
//Experimental Method
mucCreateRoom: function (roomName) {
//roomname must be of the format:
//'roomName@conference.localhost/nickName'
Chat.mucSendPresence(roomName);
Chat.connection.muc.createInstantRoom(roomName,
function (status) {
Chat.log("Succesfully created ChatRoom", status);
},
function (status) {
Chat.log("Error creating ChatRoom", status);
}
);
},
mucSessionInfo: {},
mucJoin: function (roomName, nickname, password) {
var nickname = (nickname) ? nickname : Chat.getSubJID(Chat.connection.jid);
Chat.connection.muc.join(roomName, nickname, Chat.messageReceived,
Chat.presenceReceived, Chat.rosterReceived, password);
Chat.mucSessionInfo['roomName'] = roomName;
Chat.mucSessionInfo['nickname'] = nickname;
},
mucLeave: function (exitMessage) {
Chat.connection.muc.leave(
Chat.mucSessionInfo['roomName'],
Chat.mucSessionInfo['nickname'],
Chat.presenceReceived,
exitMessage
);
},
mucListRooms: function () {
Chat.connection.muc.listRooms(
Strophe.getDomainFromJid(Chat.connection.jid),
function (status) {
Chat.log("List of Chat Rooms", status);
},
function (status) {
Chat.log("Error getting Chat Rooms", status);
}
);
},
mucQueryOccupants: function (roomName) {
Chat.connection.muc.queryOccupants(
roomName,
function (status) {
Chat.log("Got Group Chat Members", status);
// $(status).find("item").each(function() {
// //Do something with $(this).attr('node')
// });
// });
},
function (status) {
Chat.log("Error Getting Group Chat Members", status);
}
);
},
//to send a muc message,
//call Chat.sendMessage("chatRoom@conference.server","my message text","groupchat")
log: function () {
//If not connected
if (!Chat.connection) {
console.log("Error, not connected`, please enter credentials:\n " +
"Chat.connect('jid','password')");
}
if (Chat.debuggingMode) {
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
},
getSubJID: function (Jid) {
//for parsing JID: ramon@localhost/1234567
// becomes...
// ramon@localhost
var Jid = (Jid) ? Jid : Chat.connection.Jid;
var subJID = '';
for (i = 0; i < Jid.length; i++) {
if (Jid[i] === '/') {
if (Chat.connected)
Chat.log(Jid + " => " + subJID);
return subJID;
}
subJID += Jid[i];
}
return subJID;
}
}
function connect()
{
var jid = sessionStorage.getItem("jid"), password = sessionStorage.getItem("password");
console.log(jid);
console.log(password);
var BOSH_SERVICE = Chat.BOSH_SERVICE;
var debugginMode = false;
Chat.connect(jid, password, BOSH_SERVICE, debugginMode);
}
function createRoom()
{
var room_name = $('#room').val() + '@localhost/' + sessionStorage.getItem("username");;
Chat.mucCreateRoom(room_name);
}
function getRoomList()
{
Chat.mucListRooms();
}
function joinGroup()
{
var room_name = $('#room').val() + '@localhost';
var nickname = sessionStorage.getItem("user_name");;
var password = sessionStorage.getItem("password");;
Chat.mucJoin(room_name, nickname, password);
}
function sendMsg(JID,MSG)
{
debugger
// var room_name = $('#room').val() + '@localhost';
var msg = $('#msg').val();
Chat.sendMessage('1@localhost', msg, "chat");
}
function sendGroupMsg()
{
var room_name = $('#room').val() + '@localhost';
var msg = $('#msg').val();
Chat.sendMessage(room_name, msg, "groupchat");
}
function login()
{
var jid = $('#user_name').val() + '@localhost', password = $('#password').val();
sessionStorage.setItem("user_name", $('#user_name').val());
sessionStorage.setItem("jid", jid);
sessionStorage.setItem("password", password);
window.location="chat.html";
}
function disconnect()
{
sessionStorage.removeItem('user_name');
sessionStorage.removeItem('jid');
sessionStorage.removeItem('password');
Chat.disconnect();
window.location="index.html";
}