Welcome to mirror list, hosted at ThFree Co, Russian Federation.

roster.js « pane « view « src - github.com/candy-chat/candy.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 344f0d1c75f3e47284eed62d4e83ffb65420eaf6 (plain)
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
/** File: roster.js
 * Candy - Chats are not dead yet.
 *
 * Authors:
 *   - Patrick Stadler <patrick.stadler@gmail.com>
 *   - Michael Weibel <michael.weibel@gmail.com>
 *
 * Copyright:
 *   (c) 2011 Amiado Group AG. All rights reserved.
 *   (c) 2012-2014 Patrick Stadler & Michael Weibel. All rights reserved.
 *   (c) 2015 Adhearsion Foundation Inc <info@adhearsion.com>. All rights reserved.
 */
'use strict';

/* global Candy, Mustache, Strophe, jQuery */

/** Class: Candy.View.Pane
 * Candy view pane handles everything regarding DOM updates etc.
 *
 * Parameters:
 *   (Candy.View.Pane) self - itself
 *   (jQuery) $ - jQuery
 */
Candy.View.Pane = (function(self, $) {

  /** Class Candy.View.Pane.Roster
   * Handles everyhing regarding roster updates.
   */
  self.Roster = {
    /** Function: update
     * Called by <Candy.View.Observer.Presence.update> to update the roster if needed.
     * Adds/removes users from the roster list or updates informations on their items (roles, affiliations etc.)
     *
     * TODO: Refactoring, this method has too much LOC.
     *
     * Parameters:
     *   (String) roomJid - Room JID in which the update happens
     *   (Candy.Core.ChatUser) user - User on which the update happens
     *   (String) action - one of "join", "leave", "kick" and "ban"
     *   (Candy.Core.ChatUser) currentUser - Current user
     *
     * Triggers:
     *   candy:view.roster.before-update using {roomJid, user, action, element}
     *   candy:view.roster.after-update using {roomJid, user, action, element}
     */
    update: function(roomJid, user, action, currentUser) {
      Candy.Core.log('[View:Pane:Roster] ' + action);
      var roomId = self.Chat.rooms[roomJid].id,
        userId = Candy.Util.jidToId(user.getJid()),
        usercountDiff = -1,
        userElem = $('#user-' + roomId + '-' + userId),
        evtData = {
          'roomJid' : roomJid,
          'user' : user,
          'action': action,
          'element': userElem
        };

      /** Event: candy:view.roster.before-update
       * Before updating the roster of a room
       *
       * Parameters:
       *   (String) roomJid - Room JID
       *   (Candy.Core.ChatUser) user - User
       *   (String) action - [join, leave, kick, ban]
       *   (jQuery.Element) element - User element
       */
      $(Candy).triggerHandler('candy:view.roster.before-update', evtData);

      // a user joined the room
      if(action === 'join') {
        usercountDiff = 1;

        if(userElem.length < 1) {
          self.Roster._insertUser(roomJid, roomId, user, userId, currentUser);
          self.Roster.showJoinAnimation(user, userId, roomId, roomJid, currentUser);
        // user is in room but maybe the affiliation/role has changed
        } else {
          usercountDiff = 0;
          userElem.remove();
          self.Roster._insertUser(roomJid, roomId, user, userId, currentUser);
          // it's me, update the toolbar
          if(currentUser !== undefined && user.getNick() === currentUser.getNick() && self.Room.getUser(roomJid)) {
            self.Chat.Toolbar.update(roomJid);
          }
        }

        // Presence of client
        if (currentUser !== undefined && currentUser.getNick() === user.getNick()) {
          self.Room.setUser(roomJid, user);
        // add click handler for private chat
        } else {
          $('#user-' + roomId + '-' + userId).click(self.Roster.userClick);
        }

        $('#user-' + roomId + '-' + userId + ' .context').click(function(e) {
          self.Chat.Context.show(e.currentTarget, roomJid, user);
          e.stopPropagation();
        });

        // check if current user is ignoring the user who has joined.
        if (currentUser !== undefined && currentUser.isInPrivacyList('ignore', user.getJid())) {
          Candy.View.Pane.Room.addIgnoreIcon(roomJid, user.getJid());
        }
      // a user left the room
      } else if(action === 'leave') {
        self.Roster.leaveAnimation('user-' + roomId + '-' + userId);
        // always show leave message in private room, even if status messages have been disabled
        if (self.Chat.rooms[roomJid].type === 'chat') {
          self.Chat.onInfoMessage(roomJid, null, $.i18n._('userLeftRoom', [user.getNick()]));
        } else {
          self.Chat.infoMessage(roomJid, null, $.i18n._('userLeftRoom', [user.getNick()]), '');
        }

      } else if(action === 'nickchange') {
        usercountDiff = 0;
        self.Roster.changeNick(roomId, user);
        self.Room.changeDataUserJidIfUserIsMe(roomId, user);
        self.PrivateRoom.changeNick(roomJid, user);
        var infoMessage = $.i18n._('userChangedNick', [user.getPreviousNick(), user.getNick()]);
        self.Chat.infoMessage(roomJid, null, infoMessage);
      // user has been kicked
      } else if(action === 'kick') {
        self.Roster.leaveAnimation('user-' + roomId + '-' + userId);
        self.Chat.onInfoMessage(roomJid, null, $.i18n._('userHasBeenKickedFromRoom', [user.getNick()]));
      // user has been banned
      } else if(action === 'ban') {
        self.Roster.leaveAnimation('user-' + roomId + '-' + userId);
        self.Chat.onInfoMessage(roomJid, null, $.i18n._('userHasBeenBannedFromRoom', [user.getNick()]));
      }

      // Update user count
      Candy.View.Pane.Chat.rooms[roomJid].usercount += usercountDiff;

      if(roomJid === Candy.View.getCurrent().roomJid) {
        Candy.View.Pane.Chat.Toolbar.updateUsercount(Candy.View.Pane.Chat.rooms[roomJid].usercount);
      }


      // in case there's been a join, the element is now there (previously not)
      evtData.element = $('#user-' + roomId + '-' + userId);
      /** Event: candy:view.roster.after-update
       * After updating a room's roster
       *
       * Parameters:
       *   (String) roomJid - Room JID
       *   (Candy.Core.ChatUser) user - User
       *   (String) action - [join, leave, kick, ban]
       *   (jQuery.Element) element - User element
       */
      $(Candy).triggerHandler('candy:view.roster.after-update', evtData);
    },

    _insertUser: function(roomJid, roomId, user, userId, currentUser) {
      var contact = user.getContact();
      var html = Mustache.to_html(Candy.View.Template.Roster.user, {
          roomId: roomId,
          userId : userId,
          userJid: user.getJid(),
          realJid: user.getRealJid(),
          status: user.getStatus(),
          contact_status: contact ? contact.getStatus() : 'unavailable',
          nick: user.getNick(),
          displayNick: Candy.Util.crop(user.getNick(), Candy.View.getOptions().crop.roster.nickname),
          role: user.getRole(),
          affiliation: user.getAffiliation(),
          me: currentUser !== undefined && user.getNick() === currentUser.getNick(),
          tooltipRole: $.i18n._('tooltipRole'),
          tooltipIgnored: $.i18n._('tooltipIgnored')
        });

      var userInserted = false,
        rosterPane = self.Room.getPane(roomJid, '.roster-pane');

      // there are already users in the roster
      if(rosterPane.children().length > 0) {
        // insert alphabetically, sorted by status
        var userSortCompare = self.Roster._userSortCompare(user.getNick(), user.getStatus());
        rosterPane.children().each(function() {
          var elem = $(this);
          if(self.Roster._userSortCompare(elem.attr('data-nick'), elem.attr('data-status')) > userSortCompare) {
            elem.before(html);
            userInserted = true;
            return false;
          }
          return true;
        });
      }
      // first user in roster
      if(!userInserted) {
        rosterPane.append(html);
      }
    },

    _userSortCompare: function(nick, status) {
      var statusWeight;
      switch (status) {
        case 'available':
          statusWeight = 1;
          break;
        case 'unavailable':
          statusWeight = 9;
          break;
        default:
          statusWeight = 8;
      }
      return statusWeight + nick.toUpperCase();
    },

    /** Function: userClick
     * Click handler for opening a private room
     */
    userClick: function() {
      var elem = $(this),
        realJid = elem.attr('data-real-jid'),
        useRealJid = Candy.Core.getOptions().useParticipantRealJid && (realJid !== undefined && realJid !== null && realJid !== ''),
        targetJid = useRealJid && realJid ? Strophe.getBareJidFromJid(realJid) : elem.attr('data-jid');
      self.PrivateRoom.open(targetJid, elem.attr('data-nick'), true, useRealJid);
    },

    /** Function: showJoinAnimation
     * Shows join animation if needed
     *
     * FIXME: Refactor. Part of this will be done by the big room improvements
     */
    showJoinAnimation: function(user, userId, roomId, roomJid, currentUser) {
      // don't show if the user has recently changed the nickname.
      var rosterUserId = 'user-' + roomId + '-' + userId,
        $rosterUserElem = $('#' + rosterUserId);
      if (!user.getPreviousNick() || !$rosterUserElem || $rosterUserElem.is(':visible') === false) {
        self.Roster.joinAnimation(rosterUserId);
        // only show other users joining & don't show if there's no message in the room.
        if(currentUser !== undefined && user.getNick() !== currentUser.getNick() && self.Room.getUser(roomJid)) {
          // always show join message in private room, even if status messages have been disabled
          if (self.Chat.rooms[roomJid].type === 'chat') {
            self.Chat.onInfoMessage(roomJid, null, $.i18n._('userJoinedRoom', [user.getNick()]));
          } else {
            self.Chat.infoMessage(roomJid, null, $.i18n._('userJoinedRoom', [user.getNick()]));
          }
        }
      }
    },

    /** Function: joinAnimation
     * Animates specified elementId on join
     *
     * Parameters:
     *   (String) elementId - Specific element to do the animation on
     */
    joinAnimation: function(elementId) {
      $('#' + elementId).stop(true).slideDown('normal', function() {
        $(this).animate({opacity: 1});
      });
    },

    /** Function: leaveAnimation
     * Leave animation for specified element id and removes the DOM element on completion.
     *
     * Parameters:
     *   (String) elementId - Specific element to do the animation on
     */
    leaveAnimation: function(elementId) {
      $('#' + elementId).stop(true).attr('id', '#' + elementId + '-leaving').animate({opacity: 0}, {
        complete: function() {
          $(this).slideUp('normal', function() {
            $(this).remove();
          });
        }
      });
    },

    /** Function: changeNick
     * Change nick of an existing user in the roster
     *
     * UserId has to be recalculated from the user because at the time of this call,
     * the user is already set with the new jid & nick.
     *
     * Parameters:
     *   (String) roomId - Id of the room
     *   (Candy.Core.ChatUser) user - User object
     */
    changeNick: function(roomId, user) {
      Candy.Core.log('[View:Pane:Roster] changeNick');
      var previousUserJid = Strophe.getBareJidFromJid(user.getJid()) + '/' + user.getPreviousNick(),
        elementId = 'user-' + roomId + '-' + Candy.Util.jidToId(previousUserJid),
        el = $('#' + elementId);

      el.attr('data-nick', user.getNick());
      el.attr('data-jid', user.getJid());
      el.children('div.label').text(user.getNick());
      el.attr('id', 'user-' + roomId + '-' + Candy.Util.jidToId(user.getJid()));
    }
  };

  return self;
}(Candy.View.Pane || {}, jQuery));