forked from candy-chat/candy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
candy.bundle.js
5325 lines (5280 loc) · 212 KB
/
candy.bundle.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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** File: candy.js
* Candy - Chats are not dead yet.
*
* Authors:
* - Patrick Stadler <[email protected]>
* - Michael Weibel <[email protected]>
*
* Copyright:
* (c) 2011 Amiado Group AG. All rights reserved.
* (c) 2012-2014 Patrick Stadler & Michael Weibel. All rights reserved.
*/
"use strict";
/* global jQuery */
/** Class: Candy
* Candy base class for initalizing the view and the core
*
* Parameters:
* (Candy) self - itself
* (jQuery) $ - jQuery
*/
var Candy = function(self, $) {
/** Object: about
* About candy
*
* Contains:
* (String) name - Candy
* (Float) version - Candy version
*/
self.about = {
name: "Candy",
version: "1.6.0"
};
/** Function: init
* Init view & core
*
* Parameters:
* (String) service - URL to the BOSH interface
* (Object) options - Options for candy
*
* Options:
* (Boolean) debug - Debug (Default: false)
* (Array|Boolean) autojoin - Autojoin these channels. When boolean true, do not autojoin, wait if the server sends something.
*/
self.init = function(service, options) {
if (!options.viewClass) {
options.viewClass = self.View;
}
options.viewClass.init($("#candy"), options.view);
self.Core.init(service, options.core);
};
return self;
}(Candy || {}, jQuery);
/** File: core.js
* Candy - Chats are not dead yet.
*
* Authors:
* - Patrick Stadler <[email protected]>
* - Michael Weibel <[email protected]>
*
* Copyright:
* (c) 2011 Amiado Group AG. All rights reserved.
* (c) 2012-2014 Patrick Stadler & Michael Weibel. All rights reserved.
*/
"use strict";
/* global Candy, window, Strophe, jQuery */
/** Class: Candy.Core
* Candy Chat Core
*
* Parameters:
* (Candy.Core) self - itself
* (Strophe) Strophe - Strophe JS
* (jQuery) $ - jQuery
*/
Candy.Core = function(self, Strophe, $) {
/** PrivateVariable: _connection
* Strophe connection
*/
var _connection = null, /** PrivateVariable: _service
* URL of BOSH service
*/
_service = null, /** PrivateVariable: _user
* Current user (me)
*/
_user = null, /** PrivateVariable: _rooms
* Opened rooms, containing instances of Candy.Core.ChatRooms
*/
_rooms = {}, /** PrivateVariable: _anonymousConnection
* Set in <Candy.Core.connect> when jidOrHost doesn't contain a @-char.
*/
_anonymousConnection = false, /** PrivateVariable: _status
* Current Strophe connection state
*/
_status, /** PrivateVariable: _options
* Options:
* (Boolean) debug - Debug (Default: false)
* (Array|Boolean) autojoin - Autojoin these channels. When boolean true, do not autojoin, wait if the server sends something.
*/
_options = {
/** Boolean: autojoin
* If set to `true` try to get the bookmarks and autojoin the rooms (supported by Openfire).
* You may want to define an array of rooms to autojoin: `['[email protected]', 'room2...]` (ejabberd, Openfire, ...)
*/
autojoin: undefined,
debug: false,
disableWindowUnload: false,
/** Integer: presencePriority
* Default priority for presence messages in order to receive messages across different resources
*/
presencePriority: 1,
/** String: resource
* JID resource to use when connecting to the server.
* Specify `''` (an empty string) to request a random resource.
*/
resource: Candy.about.name
}, /** PrivateFunction: _addNamespace
* Adds a namespace.
*
* Parameters:
* (String) name - namespace name (will become a constant living in Strophe.NS.*)
* (String) value - XML Namespace
*/
_addNamespace = function(name, value) {
Strophe.addNamespace(name, value);
}, /** PrivateFunction: _addNamespaces
* Adds namespaces needed by Candy.
*/
_addNamespaces = function() {
_addNamespace("PRIVATE", "jabber:iq:private");
_addNamespace("BOOKMARKS", "storage:bookmarks");
_addNamespace("PRIVACY", "jabber:iq:privacy");
_addNamespace("DELAY", "jabber:x:delay");
}, _getEscapedJidFromJid = function(jid) {
var node = Strophe.getNodeFromJid(jid), domain = Strophe.getDomainFromJid(jid);
return node ? Strophe.escapeNode(node) + "@" + domain : domain;
};
/** Function: init
* Initialize Core.
*
* Parameters:
* (String) service - URL of BOSH/Websocket service
* (Object) options - Options for candy
*/
self.init = function(service, options) {
_service = service;
// Apply options
$.extend(true, _options, options);
// Enable debug logging
if (_options.debug) {
if (typeof window.console !== undefined && typeof window.console.log !== undefined) {
if (Function.prototype.bind) {
self.log = Function.prototype.bind.call(console.log, console);
} else {
self.log = function() {
Function.prototype.apply.call(console.log, console, arguments);
};
}
}
self.log("[Init] Debugging enabled");
}
_addNamespaces();
// Connect to BOSH/Websocket service
_connection = new Strophe.Connection(_service);
_connection.rawInput = self.rawInput.bind(self);
_connection.rawOutput = self.rawOutput.bind(self);
// set caps node
_connection.caps.node = "https://candy-chat.github.io/candy/";
// Window unload handler... works on all browsers but Opera. There is NO workaround.
// Opera clients getting disconnected 1-2 minutes delayed.
if (!_options.disableWindowUnload) {
window.onbeforeunload = self.onWindowUnload;
}
};
/** Function: registerEventHandlers
* Adds listening handlers to the connection.
*
* Use with caution from outside of Candy.
*/
self.registerEventHandlers = function() {
self.addHandler(self.Event.Jabber.Version, Strophe.NS.VERSION, "iq");
self.addHandler(self.Event.Jabber.Presence, null, "presence");
self.addHandler(self.Event.Jabber.Message, null, "message");
self.addHandler(self.Event.Jabber.Bookmarks, Strophe.NS.PRIVATE, "iq");
self.addHandler(self.Event.Jabber.Room.Disco, Strophe.NS.DISCO_INFO, "iq", "result");
self.addHandler(_connection.disco._onDiscoInfo.bind(_connection.disco), Strophe.NS.DISCO_INFO, "iq", "get");
self.addHandler(_connection.disco._onDiscoItems.bind(_connection.disco), Strophe.NS.DISCO_ITEMS, "iq", "get");
self.addHandler(_connection.caps._delegateCapabilities.bind(_connection.caps), Strophe.NS.CAPS);
};
/** Function: connect
* Connect to the jabber host.
*
* There are four different procedures to login:
* connect('JID', 'password') - Connect a registered user
* connect('domain') - Connect anonymously to the domain. The user should receive a random JID.
* connect('domain', null, 'nick') - Connect anonymously to the domain. The user should receive a random JID but with a nick set.
* connect('JID') - Show login form and prompt for password. JID input is hidden.
* connect() - Show login form and prompt for JID and password.
*
* See:
* <Candy.Core.attach()> for attaching an already established session.
*
* Parameters:
* (String) jidOrHost - JID or Host
* (String) password - Password of the user
* (String) nick - Nick of the user. Set one if you want to anonymously connect but preset a nick. If jidOrHost is a domain
* and this param is not set, Candy will prompt for a nick.
*/
self.connect = function(jidOrHost, password, nick) {
// Reset before every connection attempt to make sure reconnections work after authfail, alltabsclosed, ...
_connection.reset();
self.registerEventHandlers();
/** Event: candy:core.before-connect
* Triggered before a connection attempt is made.
*
* Plugins should register their stanza handlers using this event
* to ensure that they are set.
*
* See also <#84 at https://github.com/candy-chat/candy/issues/84>.
*
* Parameters:
* (Strophe.Connection) conncetion - Strophe connection
*/
$(Candy).triggerHandler("candy:core.before-connect", {
connection: _connection
});
_anonymousConnection = !_anonymousConnection ? jidOrHost && jidOrHost.indexOf("@") < 0 : true;
if (jidOrHost && password) {
// authentication
_connection.connect(_getEscapedJidFromJid(jidOrHost) + "/" + _options.resource, password, Candy.Core.Event.Strophe.Connect);
if (nick) {
_user = new self.ChatUser(jidOrHost, nick);
} else {
_user = new self.ChatUser(jidOrHost, Strophe.getNodeFromJid(jidOrHost));
}
} else if (jidOrHost && nick) {
// anonymous connect
_connection.connect(_getEscapedJidFromJid(jidOrHost) + "/" + _options.resource, null, Candy.Core.Event.Strophe.Connect);
_user = new self.ChatUser(null, nick);
} else if (jidOrHost) {
Candy.Core.Event.Login(jidOrHost);
} else {
// display login modal
Candy.Core.Event.Login();
}
};
/** Function: attach
* Attach an already binded & connected session to the server
*
* _See_ Strophe.Connection.attach
*
* Parameters:
* (String) jid - Jabber ID
* (Integer) sid - Session ID
* (Integer) rid - rid
*/
self.attach = function(jid, sid, rid) {
_user = new self.ChatUser(jid, Strophe.getNodeFromJid(jid));
self.registerEventHandlers();
_connection.attach(jid, sid, rid, Candy.Core.Event.Strophe.Connect);
};
/** Function: disconnect
* Leave all rooms and disconnect
*/
self.disconnect = function() {
if (_connection.connected) {
$.each(self.getRooms(), function() {
Candy.Core.Action.Jabber.Room.Leave(this.getJid());
});
_connection.disconnect();
}
};
/** Function: addHandler
* Wrapper for Strophe.Connection.addHandler() to add a stanza handler for the connection.
*
* Parameters:
* (Function) handler - The user callback.
* (String) ns - The namespace to match.
* (String) name - The stanza name to match.
* (String) type - The stanza type attribute to match.
* (String) id - The stanza id attribute to match.
* (String) from - The stanza from attribute to match.
* (String) options - The handler options
*
* Returns:
* A reference to the handler that can be used to remove it.
*/
self.addHandler = function(handler, ns, name, type, id, from, options) {
return _connection.addHandler(handler, ns, name, type, id, from, options);
};
/** Function: getUser
* Gets current user
*
* Returns:
* Instance of Candy.Core.ChatUser
*/
self.getUser = function() {
return _user;
};
/** Function: setUser
* Set current user. Needed when anonymous login is used, as jid gets retrieved later.
*
* Parameters:
* (Candy.Core.ChatUser) user - User instance
*/
self.setUser = function(user) {
_user = user;
};
/** Function: getConnection
* Gets Strophe connection
*
* Returns:
* Instance of Strophe.Connection
*/
self.getConnection = function() {
return _connection;
};
/** Function: removeRoom
* Removes a room from the rooms list
*
* Parameters:
* (String) roomJid - roomJid
*/
self.removeRoom = function(roomJid) {
delete _rooms[roomJid];
};
/** Function: getRooms
* Gets all joined rooms
*
* Returns:
* Object containing instances of Candy.Core.ChatRoom
*/
self.getRooms = function() {
return _rooms;
};
/** Function: getStropheStatus
* Get the status set by Strophe.
*
* Returns:
* (Strophe.Status.*) - one of Strophe's statuses
*/
self.getStropheStatus = function() {
return _status;
};
/** Function: setStropheStatus
* Set the strophe status
*
* Called by:
* Candy.Core.Event.Strophe.Connect
*
* Parameters:
* (Strophe.Status.*) status - Strophe's status
*/
self.setStropheStatus = function(status) {
_status = status;
};
/** Function: isAnonymousConnection
* Returns true if <Candy.Core.connect> was first called with a domain instead of a jid as the first param.
*
* Returns:
* (Boolean)
*/
self.isAnonymousConnection = function() {
return _anonymousConnection;
};
/** Function: getOptions
* Gets options
*
* Returns:
* Object
*/
self.getOptions = function() {
return _options;
};
/** Function: getRoom
* Gets a specific room
*
* Parameters:
* (String) roomJid - JID of the room
*
* Returns:
* If the room is joined, instance of Candy.Core.ChatRoom, otherwise null.
*/
self.getRoom = function(roomJid) {
if (_rooms[roomJid]) {
return _rooms[roomJid];
}
return null;
};
/** Function: onWindowUnload
* window.onbeforeunload event which disconnects the client from the Jabber server.
*/
self.onWindowUnload = function() {
// Enable synchronous requests because Safari doesn't send asynchronous requests within unbeforeunload events.
// Only works properly when following patch is applied to strophejs: https://github.com/metajack/strophejs/issues/16/#issuecomment-600266
_connection.options.sync = true;
self.disconnect();
_connection.flush();
};
/** Function: rawInput
* (Overridden from Strophe.Connection.rawInput)
*
* Logs all raw input if debug is set to true.
*/
self.rawInput = function(data) {
this.log("RECV: " + data);
};
/** Function rawOutput
* (Overridden from Strophe.Connection.rawOutput)
*
* Logs all raw output if debug is set to true.
*/
self.rawOutput = function(data) {
this.log("SENT: " + data);
};
/** Function: log
* Overridden to do something useful if debug is set to true.
*
* See: Candy.Core#init
*/
self.log = function() {};
return self;
}(Candy.Core || {}, Strophe, jQuery);
/** File: view.js
* Candy - Chats are not dead yet.
*
* Authors:
* - Patrick Stadler <[email protected]>
* - Michael Weibel <[email protected]>
*
* Copyright:
* (c) 2011 Amiado Group AG. All rights reserved.
* (c) 2012-2014 Patrick Stadler & Michael Weibel. All rights reserved.
*/
"use strict";
/* global jQuery, Candy, window, Mustache, document */
/** Class: Candy.View
* The Candy View Class
*
* Parameters:
* (Candy.View) self - itself
* (jQuery) $ - jQuery
*/
Candy.View = function(self, $) {
/** PrivateObject: _current
* Object containing current container & roomJid which the client sees.
*/
var _current = {
container: null,
roomJid: null
}, /** PrivateObject: _options
*
* Options:
* (String) language - language to use
* (String) resources - path to resources directory (with trailing slash)
* (Object) messages - limit: clean up message pane when n is reached / remove: remove n messages after limit has been reached
* (Object) crop - crop if longer than defined: message.nickname=15, message.body=1000, roster.nickname=15
*/
_options = {
language: "en",
resources: "res/",
messages: {
limit: 2e3,
remove: 500
},
crop: {
message: {
nickname: 15,
body: 1e3
},
roster: {
nickname: 15
}
}
}, /** PrivateFunction: _setupTranslation
* Set dictionary using jQuery.i18n plugin.
*
* See: view/translation.js
* See: libs/jquery-i18n/jquery.i18n.js
*
* Parameters:
* (String) language - Language identifier
*/
_setupTranslation = function(language) {
$.i18n.load(self.Translation[language]);
}, /** PrivateFunction: _registerObservers
* Register observers. Candy core will now notify the View on changes.
*/
_registerObservers = function() {
$(Candy).on("candy:core.chat.connection", self.Observer.Chat.Connection);
$(Candy).on("candy:core.chat.message", self.Observer.Chat.Message);
$(Candy).on("candy:core.login", self.Observer.Login);
$(Candy).on("candy:core.autojoin-missing", self.Observer.AutojoinMissing);
$(Candy).on("candy:core.presence", self.Observer.Presence.update);
$(Candy).on("candy:core.presence.leave", self.Observer.Presence.update);
$(Candy).on("candy:core.presence.room", self.Observer.Presence.update);
$(Candy).on("candy:core.presence.error", self.Observer.PresenceError);
$(Candy).on("candy:core.message", self.Observer.Message);
}, /** PrivateFunction: _registerWindowHandlers
* Register window focus / blur / resize handlers.
*
* jQuery.focus()/.blur() <= 1.5.1 do not work for IE < 9. Fortunately onfocusin/onfocusout will work for them.
*/
_registerWindowHandlers = function() {
if (Candy.Util.getIeVersion() < 9) {
$(document).focusin(Candy.View.Pane.Window.onFocus).focusout(Candy.View.Pane.Window.onBlur);
} else {
$(window).focus(Candy.View.Pane.Window.onFocus).blur(Candy.View.Pane.Window.onBlur);
}
$(window).resize(Candy.View.Pane.Chat.fitTabs);
}, /** PrivateFunction: _initToolbar
* Initialize toolbar.
*/
_initToolbar = function() {
self.Pane.Chat.Toolbar.init();
}, /** PrivateFunction: _delegateTooltips
* Delegate mouseenter on tooltipified element to <Candy.View.Pane.Chat.Tooltip.show>.
*/
_delegateTooltips = function() {
$("body").delegate("li[data-tooltip]", "mouseenter", Candy.View.Pane.Chat.Tooltip.show);
};
/** Function: init
* Initialize chat view (setup DOM, register handlers & observers)
*
* Parameters:
* (jQuery.element) container - Container element of the whole chat view
* (Object) options - Options: see _options field (value passed here gets extended by the default value in _options field)
*/
self.init = function(container, options) {
$.extend(true, _options, options);
_setupTranslation(_options.language);
// Set path to emoticons
Candy.Util.Parser.setEmoticonPath(this.getOptions().resources + "img/emoticons/");
// Start DOMination...
_current.container = container;
_current.container.html(Mustache.to_html(Candy.View.Template.Chat.pane, {
tooltipEmoticons: $.i18n._("tooltipEmoticons"),
tooltipSound: $.i18n._("tooltipSound"),
tooltipAutoscroll: $.i18n._("tooltipAutoscroll"),
tooltipStatusmessage: $.i18n._("tooltipStatusmessage"),
tooltipAdministration: $.i18n._("tooltipAdministration"),
tooltipUsercount: $.i18n._("tooltipUsercount"),
resourcesPath: this.getOptions().resources
}, {
tabs: Candy.View.Template.Chat.tabs,
rooms: Candy.View.Template.Chat.rooms,
modal: Candy.View.Template.Chat.modal,
toolbar: Candy.View.Template.Chat.toolbar,
soundcontrol: Candy.View.Template.Chat.soundcontrol
}));
// ... and let the elements dance.
_registerWindowHandlers();
_initToolbar();
_registerObservers();
_delegateTooltips();
};
/** Function: getCurrent
* Get current container & roomJid in an object.
*
* Returns:
* Object containing container & roomJid
*/
self.getCurrent = function() {
return _current;
};
/** Function: getOptions
* Gets options
*
* Returns:
* Object
*/
self.getOptions = function() {
return _options;
};
return self;
}(Candy.View || {}, jQuery);
/** File: util.js
* Candy - Chats are not dead yet.
*
* Authors:
* - Patrick Stadler <[email protected]>
* - Michael Weibel <[email protected]>
*
* Copyright:
* (c) 2011 Amiado Group AG. All rights reserved.
* (c) 2012-2014 Patrick Stadler & Michael Weibel. All rights reserved.
*/
"use strict";
/* global Candy, MD5, Strophe, document, escape, jQuery */
/** Class: Candy.Util
* Candy utils
*
* Parameters:
* (Candy.Util) self - itself
* (jQuery) $ - jQuery
*/
Candy.Util = function(self, $) {
/** Function: jidToId
* Translates a jid to a MD5-Id
*
* Parameters:
* (String) jid - Jid
*
* Returns:
* MD5-ified jid
*/
self.jidToId = function(jid) {
return MD5.hexdigest(jid);
};
/** Function: escapeJid
* Escapes a jid (node & resource get escaped)
*
* See:
* XEP-0106
*
* Parameters:
* (String) jid - Jid
*
* Returns:
* (String) - escaped jid
*/
self.escapeJid = function(jid) {
var node = Strophe.escapeNode(Strophe.getNodeFromJid(jid)), domain = Strophe.getDomainFromJid(jid), resource = Strophe.getResourceFromJid(jid);
jid = node + "@" + domain;
if (resource) {
jid += "/" + resource;
}
return jid;
};
/** Function: unescapeJid
* Unescapes a jid (node & resource get unescaped)
*
* See:
* XEP-0106
*
* Parameters:
* (String) jid - Jid
*
* Returns:
* (String) - unescaped Jid
*/
self.unescapeJid = function(jid) {
var node = Strophe.unescapeNode(Strophe.getNodeFromJid(jid)), domain = Strophe.getDomainFromJid(jid), resource = Strophe.getResourceFromJid(jid);
jid = node + "@" + domain;
if (resource) {
jid += "/" + resource;
}
return jid;
};
/** Function: crop
* Crop a string with the specified length
*
* Parameters:
* (String) str - String to crop
* (Integer) len - Max length
*/
self.crop = function(str, len) {
if (str.length > len) {
str = str.substr(0, len - 3) + "...";
}
return str;
};
/** Function: setCookie
* Sets a new cookie
*
* Parameters:
* (String) name - cookie name
* (String) value - Value
* (Integer) lifetime_days - Lifetime in days
*/
self.setCookie = function(name, value, lifetime_days) {
var exp = new Date();
exp.setDate(new Date().getDate() + lifetime_days);
document.cookie = name + "=" + value + ";expires=" + exp.toUTCString() + ";path=/";
};
/** Function: cookieExists
* Tests if a cookie with the given name exists
*
* Parameters:
* (String) name - Cookie name
*
* Returns:
* (Boolean) - true/false
*/
self.cookieExists = function(name) {
return document.cookie.indexOf(name) > -1;
};
/** Function: getCookie
* Returns the cookie value if there's one with this name, otherwise returns undefined
*
* Parameters:
* (String) name - Cookie name
*
* Returns:
* Cookie value or undefined
*/
self.getCookie = function(name) {
if (document.cookie) {
var regex = new RegExp(escape(name) + "=([^;]*)", "gm"), matches = regex.exec(document.cookie);
if (matches) {
return matches[1];
}
}
};
/** Function: deleteCookie
* Deletes a cookie with the given name
*
* Parameters:
* (String) name - cookie name
*/
self.deleteCookie = function(name) {
document.cookie = name + "=;expires=Thu, 01-Jan-70 00:00:01 GMT;path=/";
};
/** Function: getPosLeftAccordingToWindowBounds
* Fetches the window width and element width
* and checks if specified position + element width is bigger
* than the window width.
*
* If this evaluates to true, the position gets substracted by the element width.
*
* Parameters:
* (jQuery.Element) elem - Element to position
* (Integer) pos - Position left
*
* Returns:
* Object containing `px` (calculated position in pixel) and `alignment` (alignment of the element in relation to pos, either 'left' or 'right')
*/
self.getPosLeftAccordingToWindowBounds = function(elem, pos) {
var windowWidth = $(document).width(), elemWidth = elem.outerWidth(), marginDiff = elemWidth - elem.outerWidth(true), backgroundPositionAlignment = "left";
if (pos + elemWidth >= windowWidth) {
pos -= elemWidth - marginDiff;
backgroundPositionAlignment = "right";
}
return {
px: pos,
backgroundPositionAlignment: backgroundPositionAlignment
};
};
/** Function: getPosTopAccordingToWindowBounds
* Fetches the window height and element height
* and checks if specified position + element height is bigger
* than the window height.
*
* If this evaluates to true, the position gets substracted by the element height.
*
* Parameters:
* (jQuery.Element) elem - Element to position
* (Integer) pos - Position top
*
* Returns:
* Object containing `px` (calculated position in pixel) and `alignment` (alignment of the element in relation to pos, either 'top' or 'bottom')
*/
self.getPosTopAccordingToWindowBounds = function(elem, pos) {
var windowHeight = $(document).height(), elemHeight = elem.outerHeight(), marginDiff = elemHeight - elem.outerHeight(true), backgroundPositionAlignment = "top";
if (pos + elemHeight >= windowHeight) {
pos -= elemHeight - marginDiff;
backgroundPositionAlignment = "bottom";
}
return {
px: pos,
backgroundPositionAlignment: backgroundPositionAlignment
};
};
/** Function: localizedTime
* Localizes ISO-8610 Date with the time/dateformat specified in the translation.
*
* See: libs/dateformat/dateFormat.js
* See: src/view/translation.js
* See: jquery-i18n/jquery.i18n.js
*
* Parameters:
* (String) dateTime - ISO-8610 Datetime
*
* Returns:
* If current date is equal to the date supplied, format with timeFormat, otherwise with dateFormat
*/
self.localizedTime = function(dateTime) {
if (dateTime === undefined) {
return undefined;
}
var date = self.iso8601toDate(dateTime);
if (date.toDateString() === new Date().toDateString()) {
return date.format($.i18n._("timeFormat"));
} else {
return date.format($.i18n._("dateFormat"));
}
};
/** Function: iso8610toDate
* Parses a ISO-8610 Date to a Date-Object.
*
* Uses a fallback if the client's browser doesn't support it.
*
* Quote:
* ECMAScript revision 5 adds native support for ISO-8601 dates in the Date.parse method,
* but many browsers currently on the market (Safari 4, Chrome 4, IE 6-8) do not support it.
*
* Credits:
* <Colin Snover at http://zetafleet.com/blog/javascript-dateparse-for-iso-8601>
*
* Parameters:
* (String) date - ISO-8610 Date
*
* Returns:
* Date-Object
*/
self.iso8601toDate = function(date) {
var timestamp = Date.parse(date);
if (isNaN(timestamp)) {
var struct = /^(\d{4}|[+\-]\d{6})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?))?/.exec(date);
if (struct) {
var minutesOffset = 0;
if (struct[8] !== "Z") {
minutesOffset = +struct[10] * 60 + +struct[11];
if (struct[9] === "+") {
minutesOffset = -minutesOffset;
}
}
minutesOffset -= new Date().getTimezoneOffset();
return new Date(+struct[1], +struct[2] - 1, +struct[3], +struct[4], +struct[5] + minutesOffset, +struct[6], struct[7] ? +struct[7].substr(0, 3) : 0);
} else {
// XEP-0091 date
timestamp = Date.parse(date.replace(/^(\d{4})(\d{2})(\d{2})/, "$1-$2-$3") + "Z");
}
}
return new Date(timestamp);
};
/** Function: isEmptyObject
* IE7 doesn't work with jQuery.isEmptyObject (<=1.5.1), workaround.
*
* Parameters:
* (Object) obj - the object to test for
*
* Returns:
* Boolean true or false.
*/
self.isEmptyObject = function(obj) {
var prop;
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
};
/** Function: forceRedraw
* Fix IE7 not redrawing under some circumstances.
*
* Parameters:
* (jQuery.element) elem - jQuery element to redraw
*/
self.forceRedraw = function(elem) {
elem.css({
display: "none"
});
setTimeout(function() {
this.css({
display: "block"
});
}.bind(elem), 1);
};
/** PrivateVariable: ie
* Checks for IE version
*
* From: http://stackoverflow.com/a/5574871/315242
*/
var ie = function() {
var undef, v = 3, div = document.createElement("div"), all = div.getElementsByTagName("i");
while (// adds innerhtml and continues as long as all[0] is truthy
div.innerHTML = "<!--[if gt IE " + ++v + "]><i></i><![endif]-->", all[0]) {}
return v > 4 ? v : undef;
}();
/** Function: getIeVersion
* Returns local variable `ie` which you can use to detect which IE version
* is available.
*
* Use e.g. like this: if(Candy.Util.getIeVersion() < 9) alert('kaboom');
*/
self.getIeVersion = function() {
return ie;
};
/** Class: Candy.Util.Parser
* Parser for emoticons, links and also supports escaping.
*/
self.Parser = {
/** PrivateVariable: _emoticonPath
* Path to emoticons.
*
* Use setEmoticonPath() to change it
*/
_emoticonPath: "",
/** Function: setEmoticonPath
* Set emoticons location.
*
* Parameters:
* (String) path - location of emoticons with trailing slash
*/
setEmoticonPath: function(path) {
this._emoticonPath = path;
},
/** Array: emoticons
* Array containing emoticons to be replaced by their images.
*
* Can be overridden/extended.
*/
emoticons: [ {
plain: ":)",
regex: /((\s):-?\)|:-?\)(\s|$))/gm,
image: "Smiling.png"
}, {
plain: ";)",
regex: /((\s);-?\)|;-?\)(\s|$))/gm,
image: "Winking.png"
}, {
plain: ":D",
regex: /((\s):-?D|:-?D(\s|$))/gm,
image: "Grinning.png"
}, {
plain: ";D",
regex: /((\s);-?D|;-?D(\s|$))/gm,
image: "Grinning_Winking.png"
}, {
plain: ":(",
regex: /((\s):-?\(|:-?\((\s|$))/gm,
image: "Unhappy.png"
}, {
plain: "^^",
regex: /((\s)\^\^|\^\^(\s|$))/gm,
image: "Happy_3.png"
}, {
plain: ":P",
regex: /((\s):-?P|:-?P(\s|$))/gim,
image: "Tongue_Out.png"
}, {
plain: ";P",
regex: /((\s);-?P|;-?P(\s|$))/gim,
image: "Tongue_Out_Winking.png"
}, {
plain: ":S",
regex: /((\s):-?S|:-?S(\s|$))/gim,
image: "Confused.png"
}, {
plain: ":/",
regex: /((\s):-?\/|:-?\/(\s|$))/gm,
image: "Uncertain.png"
}, {
plain: "8)",
regex: /((\s)8-?\)|8-?\)(\s|$))/gm,
image: "Sunglasses.png"
}, {
plain: "$)",
regex: /((\s)\$-?\)|\$-?\)(\s|$))/gm,
image: "Greedy.png"
}, {
plain: "oO",
regex: /((\s)oO|oO(\s|$))/gm,
image: "Huh.png"
}, {
plain: ":x",
regex: /((\s):x|:x(\s|$))/gm,
image: "Lips_Sealed.png"
}, {
plain: ":666:",
regex: /((\s):666:|:666:(\s|$))/gm,
image: "Devil.png"
}, {
plain: "<3",
regex: /((\s)<3|<3(\s|$))/gm,
image: "Heart.png"
} ],
/** Function: emotify
* Replaces text-emoticons with their image equivalent.
*
* Parameters:
* (String) text - Text to emotify
*
* Returns:
* Emotified text
*/
emotify: function(text) {
var i;
for (i = this.emoticons.length - 1; i >= 0; i--) {
text = text.replace(this.emoticons[i].regex, '$2<img class="emoticon" alt="$1" src="' + this._emoticonPath + this.emoticons[i].image + '" />$3');
}
return text;
},
/** Function: linkify
* Replaces URLs with a HTML-link.
*
* Parameters:
* (String) text - Text to linkify
*
* Returns:
* Linkified text
*/
linkify: function(text) {