Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/**
17
 * Controls a section of the overview page in the message drawer.
18
 *
19
 * @module     core_message/message_drawer_view_overview_section
20
 * @copyright  2018 Ryan Wyllie <ryan@moodle.com>
21
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 */
23
define(
24
[
25
    'jquery',
26
    'core/custom_interaction_events',
27
    'core/notification',
28
    'core/pubsub',
29
    'core/str',
30
    'core/pending',
31
    'core/templates',
32
    'core/user_date',
33
    'core_message/message_repository',
34
    'core_message/message_drawer_events',
35
    'core_message/message_drawer_router',
36
    'core_message/message_drawer_routes',
37
    'core_message/message_drawer_lazy_load_list',
38
    'core_message/message_drawer_view_conversation_constants'
39
],
40
function(
41
    $,
42
    CustomEvents,
43
    Notification,
44
    PubSub,
45
    Str,
46
    Pending,
47
    Templates,
48
    UserDate,
49
    MessageRepository,
50
    MessageDrawerEvents,
51
    MessageDrawerRouter,
52
    MessageDrawerRoutes,
53
    LazyLoadList,
54
    MessageDrawerViewConversationContants
55
) {
56
 
57
    var SELECTORS = {
58
        TOGGLE: '[data-region="toggle"]',
59
        CONVERSATION: '[data-conversation-id]',
60
        BLOCKED_ICON_CONTAINER: '[data-region="contact-icon-blocked"]',
61
        LAST_MESSAGE: '[data-region="last-message"]',
62
        LAST_MESSAGE_DATE: '[data-region="last-message-date"]',
63
        MUTED_ICON_CONTAINER: '[data-region="muted-icon-container"]',
64
        UNREAD_COUNT: '[data-region="unread-count"]',
65
        SECTION_TOTAL_COUNT: '[data-region="section-total-count"]',
66
        SECTION_TOTAL_COUNT_CONTAINER: '[data-region="section-total-count-container"]',
67
        SECTION_UNREAD_COUNT: '[data-region="section-unread-count"]',
68
        SECTION_UNREAD_COUNT_CONTAINER: '[data-region="section-unread-count-container"]',
69
        PLACEHOLDER_CONTAINER: '[data-region="placeholder-container"]'
70
    };
71
 
72
    var TEMPLATES = {
73
        CONVERSATIONS_LIST: 'core_message/message_drawer_conversations_list',
74
        CONVERSATIONS_LIST_ITEMS_PLACEHOLDER: 'core_message/message_drawer_conversations_list_items_placeholder'
75
    };
76
 
77
    var LOAD_LIMIT = 50;
78
    var loadedConversationsById = {};
79
    var deletedConversationsById = {};
80
    var loadedTotalCounts = false;
81
    var loadedUnreadCounts = false;
82
 
83
    /**
84
     * Get the section visibility status.
85
     *
86
     * @param  {Object} root The section container element.
87
     * @return {Bool} Is section visible.
88
     */
89
    var isVisible = function(root) {
90
        return LazyLoadList.getRoot(root).hasClass('show');
91
    };
92
 
93
    /**
94
     * Set this section as expanded.
95
     *
96
     * @param  {Object} root The section container element.
97
     */
98
    var setExpanded = function(root) {
99
        root.addClass('expanded');
100
    };
101
 
102
    /**
103
     * Set this section as collapsed.
104
     *
105
     * @param  {Object} root The section container element.
106
     */
107
    var setCollapsed = function(root) {
108
        root.removeClass('expanded');
109
    };
110
 
111
    /**
112
     * Render the total count value and show it for the user. Also update the placeholder
113
     * HTML for better visuals.
114
     *
115
     * @param {Object} root The section container element.
116
     * @param {Number} count The total count
117
     */
118
    var renderTotalCount = function(root, count) {
119
        var container = root.find(SELECTORS.SECTION_TOTAL_COUNT_CONTAINER);
120
        var countElement = container.find(SELECTORS.SECTION_TOTAL_COUNT);
121
        countElement.text(count);
122
        container.removeClass('hidden');
123
        Str.get_string('totalconversations', 'core_message', count).done(function(string) {
124
            $('#' + container.attr('aria-labelledby')).text(string);
125
        });
126
 
127
        var numPlaceholders = count > 20 ? 20 : count;
128
        // Array of "true" up to the number of placeholders we want.
129
        var placeholders = Array.apply(null, Array(numPlaceholders)).map(function() {
130
            return true;
131
        });
132
 
133
        // Replace the current placeholder (loading spinner) with some nicer placeholders that
134
        // better represent the content.
135
        Templates.render(TEMPLATES.CONVERSATIONS_LIST_ITEMS_PLACEHOLDER, {placeholders: placeholders})
136
            .then(function(html) {
137
                var placeholderContainer = root.find(SELECTORS.PLACEHOLDER_CONTAINER);
138
                placeholderContainer.html(html);
139
                return;
140
            })
141
            .catch(function() {
142
                // Silently ignore. Doesn't matter if we can't render the placeholders.
143
            });
144
    };
145
 
146
    /**
147
     * Render the unread count value and show it for the user if it's higher than zero.
148
     *
149
     * @param {Object} root The section container element.
150
     * @param {Number} count The unread count
151
     */
152
    var renderUnreadCount = function(root, count) {
153
        var container = root.find(SELECTORS.SECTION_UNREAD_COUNT_CONTAINER);
154
        var countElement = container.find(SELECTORS.SECTION_UNREAD_COUNT);
155
        countElement.text(count);
156
 
157
        Str.get_string('unreadconversations', 'core_message', count).done(function(string) {
158
            $('#' + container.attr('aria-labelledby')).text(string);
159
        });
160
 
161
        if (count > 0) {
162
            container.removeClass('hidden');
1441 ariadna 163
        } else {
164
            container.addClass('hidden');
1 efrain 165
        }
166
    };
167
 
168
    /**
169
     * Create a formatted conversation object from the the one we get from events. The new object
170
     * will be in a format that matches what we receive from the server.
171
     *
172
     * @param {Object} conversation
173
     * @return {Object} formatted conversation.
174
     */
175
    var formatConversationFromEvent = function(conversation) {
176
        // Recursively lowercase all of the keys for an object.
177
        var recursivelyLowercaseKeys = function(object) {
178
            return Object.keys(object).reduce(function(carry, key) {
179
                if ($.isArray(object[key])) {
180
                    carry[key.toLowerCase()] = object[key].map(recursivelyLowercaseKeys);
181
                } else {
182
                    carry[key.toLowerCase()] = object[key];
183
                }
184
 
185
                return carry;
186
            }, {});
187
        };
188
 
189
        // Recursively lowercase all of the keys for the conversation.
190
        var formatted = recursivelyLowercaseKeys(conversation);
191
 
192
        // Make sure all messages have the useridfrom property set.
193
        formatted.messages = formatted.messages.map(function(message) {
194
            message.useridfrom = message.userfrom.id;
195
            return message;
196
        });
197
 
198
        return formatted;
199
    };
200
 
201
    /**
202
     * Render the messages in the overview page.
203
     *
204
     * @param {Array} conversations List of conversations to render.
205
     * @param {Number} userId Logged in user id.
206
     * @return {Object} jQuery promise.
207
     */
208
    var render = function(conversations, userId) {
209
 
210
        // Helper to format the last message for rendering.
211
        // Returns a promise which resolves to either a string, or null
212
        // (such as in the event of an empty personal space).
213
        var pending = new Pending();
214
 
215
        var formatMessagePreview = async function(lastMessage) {
216
            if (!lastMessage) {
217
                return null;
218
            }
219
            // Check the message html for a src attribute, indicative of media.
220
            // Replace <img with <noimg to stop browsers pre-fetching the image as part of tmp element creation.
221
            var tmpElement = document.createElement("element");
222
            tmpElement.innerHTML = lastMessage.text.replace(/<img /g, '<noimg ');
223
            var isMedia = tmpElement.querySelector("[src]") || false;
224
 
225
            if (!isMedia) {
226
                // Try to get the text value of the content.
227
                // If that's not possible, we'll report it under the catch-all 'other media'.
228
                var messagePreview = $(lastMessage.text).text();
229
                if (messagePreview) {
230
                    // The text value of the message must have no html/script tags.
231
                    if (messagePreview.indexOf('<') == -1) {
232
                        return messagePreview;
233
                    }
234
                }
235
            }
236
 
237
            // As a fallback, report unknowns as 'other media' type content.
238
            var pix = 'i/messagecontentmultimediageneral';
239
            var label = 'messagecontentmultimediageneral';
240
 
241
            if (lastMessage.text.includes('<img')) {
242
                pix = 'i/messagecontentimage';
243
                label = 'messagecontentimage';
244
            } else if (lastMessage.text.includes('<video')) {
245
                pix = 'i/messagecontentvideo';
246
                label = 'messagecontentvideo';
247
            } else if (lastMessage.text.includes('<audio')) {
248
                pix = 'i/messagecontentaudio';
249
                label = 'messagecontentaudio';
250
            }
251
 
252
            try {
253
                var labelString = await Str.get_string(label, 'core_message');
254
                var icon = await Templates.renderPix(pix, 'core', labelString);
255
                return icon + ' ' + labelString;
256
            } catch (error) {
257
                Notification.exception(error);
258
                return null;
259
            }
260
        };
261
 
262
        var mapPromises = conversations.map(function(conversation) {
263
 
264
            var lastMessage = conversation.messages.length ? conversation.messages[conversation.messages.length - 1] : null;
265
 
266
            return formatMessagePreview(lastMessage)
267
                .then(function(messagePreview) {
268
                    var formattedConversation = {
269
                        id: conversation.id,
270
                        imageurl: conversation.imageurl,
271
                        name: conversation.name,
272
                        subname: conversation.subname,
273
                        unreadcount: conversation.unreadcount,
274
                        ismuted: conversation.ismuted,
275
                        lastmessagedate: lastMessage ? lastMessage.timecreated : null,
276
                        sentfromcurrentuser: lastMessage ? lastMessage.useridfrom == userId : null,
277
                        lastmessage: messagePreview
278
                    };
279
 
280
                    var otherUser = null;
281
                    if (conversation.type == MessageDrawerViewConversationContants.CONVERSATION_TYPES.SELF) {
282
                        // Self-conversations have only one member.
283
                        otherUser = conversation.members[0];
284
                    } else if (conversation.type == MessageDrawerViewConversationContants.CONVERSATION_TYPES.PRIVATE) {
285
                        // For private conversations, remove the current userId from the members to get the other user.
286
                        otherUser = conversation.members.reduce(function(carry, member) {
287
                            if (!carry && member.id != userId) {
288
                                carry = member;
289
                            }
290
                            return carry;
291
                        }, null);
292
                    }
293
 
294
                    if (otherUser !== null) {
295
                        formattedConversation.userid = otherUser.id;
296
                        formattedConversation.showonlinestatus = otherUser.showonlinestatus;
297
                        formattedConversation.isonline = otherUser.isonline;
298
                        formattedConversation.isblocked = otherUser.isblocked;
299
                    }
300
 
301
                    if (conversation.type == MessageDrawerViewConversationContants.CONVERSATION_TYPES.PUBLIC) {
302
                        formattedConversation.lastsendername = conversation.members.reduce(function(carry, member) {
303
                            if (!carry && lastMessage && member.id == lastMessage.useridfrom) {
304
                                carry = member.fullname;
305
                            }
306
                            return carry;
307
                        }, null);
308
                    }
309
 
310
                    return formattedConversation;
311
                }).catch(Notification.exception);
312
        });
313
 
314
        return Promise.all(mapPromises)
315
            .then(function(formattedConversations) {
316
                formattedConversations.forEach(function(conversation) {
317
                    if (new Date().toDateString() == new Date(conversation.lastmessagedate * 1000).toDateString()) {
318
                        conversation.istoday = true;
319
                    }
320
                });
321
 
322
                return Templates.render(TEMPLATES.CONVERSATIONS_LIST, {conversations: formattedConversations});
323
            }).then(function(html, js) {
324
                pending.resolve();
325
                return $.Deferred().resolve(html, js);
326
            }).catch(function(error) {
327
                pending.resolve();
328
                Notification.exception(error);
329
            });
330
    };
331
 
332
    /**
333
     * Build the callback to load conversations.
334
     *
335
     * @param  {Array|null} types The conversation types for this section.
336
     * @param  {bool} includeFavourites Include/exclude favourites.
337
     * @param  {Number} offset Result offset
338
     * @return {Function}
339
     */
340
    var getLoadCallback = function(types, includeFavourites, offset) {
341
        // Note: This function is a bit messy because we've added the concept of loading
342
        // multiple conversations types (e.g. private + self) at once but haven't properly
343
        // updated the web service to accept an array of types. Instead we've added a new
344
        // parameter for the self type which means we can only ever load self + other type.
345
        // This should be improved to make it more extensible in the future. Adding new params
346
        // for each type isn't very scalable.
347
        var type = null;
348
        // Include self conversations in the results by default.
349
        var includeSelfConversations = true;
350
        if (types && types.length) {
351
            // Just get the conversation types that aren't "self" for now.
352
            var nonSelfConversationTypes = types.filter(function(candidate) {
353
                return candidate != MessageDrawerViewConversationContants.CONVERSATION_TYPES.SELF;
354
            });
355
            // If we're specifically asking for a list of types that doesn't include the self
356
            // conversations then we don't need to include them.
357
            includeSelfConversations = types.length != nonSelfConversationTypes.length;
358
            // As mentioned above the webservice is currently limited to loading one type at a
359
            // time (plus self conversations) so let's hope we never change this.
360
            type = nonSelfConversationTypes[0];
361
        }
362
 
363
        return function(root, userId) {
364
            return MessageRepository.getConversations(
365
                    userId,
366
                    type,
367
                    LOAD_LIMIT + 1,
368
                    offset,
369
                    includeFavourites,
370
                    includeSelfConversations
371
                )
372
                .then(function(response) {
373
                    var conversations = response.conversations;
374
 
375
                    if (conversations.length > LOAD_LIMIT) {
376
                        conversations = conversations.slice(0, -1);
377
                    } else {
378
                        LazyLoadList.setLoadedAll(root, true);
379
                    }
380
 
381
                    offset = offset + LOAD_LIMIT;
382
 
383
                    conversations.forEach(function(conversation) {
384
                        loadedConversationsById[conversation.id] = conversation;
385
                    });
386
 
387
                    return conversations;
388
                })
389
                .catch(Notification.exception);
390
        };
391
    };
392
 
393
    /**
394
     * Get the total count container element.
395
     *
396
     * @param  {Object} root Overview messages container element.
397
     * @return {Object} Total count container element.
398
     */
399
    var getTotalConversationCountElement = function(root) {
400
        return root.find(SELECTORS.SECTION_TOTAL_COUNT);
401
    };
402
 
403
    /**
404
     * Get the unread conversations count container element.
405
     *
406
     * @param  {Object} root Overview messages container element.
407
     * @return {Object} Unread conversations count container element.
408
     */
409
    var getTotalUnreadConversationCountElement = function(root) {
410
        return root.find(SELECTORS.SECTION_UNREAD_COUNT);
411
    };
412
 
413
    /**
414
     * Increment the total conversations count.
415
     *
416
     * @param  {Object} root Overview messages container element.
417
     */
418
    var incrementTotalConversationCount = function(root) {
419
        if (loadedTotalCounts) {
420
            var element = getTotalConversationCountElement(root);
421
            var count = parseInt(element.text());
422
            count = count + 1;
423
            element.text(count);
424
        }
425
    };
426
 
427
    /**
428
     * Decrement the total conversations count.
429
     *
430
     * @param  {Object} root Overview messages container element.
431
     */
432
    var decrementTotalConversationCount = function(root) {
433
        if (loadedTotalCounts) {
434
            var element = getTotalConversationCountElement(root);
435
            var count = parseInt(element.text());
436
            count = count - 1;
437
            element.text(count);
438
        }
439
    };
440
 
441
    /**
442
     * Decrement the total unread conversations count.
443
     *
444
     * @param  {Object} root Overview messages container element.
445
     */
446
    var decrementTotalUnreadConversationCount = function(root) {
447
        if (loadedUnreadCounts) {
448
            var element = getTotalUnreadConversationCountElement(root);
449
            var count = parseInt(element.text());
450
            count = count - 1;
1441 ariadna 451
            // Re-render the unread count.
452
            renderUnreadCount(root, count);
1 efrain 453
        }
454
    };
455
 
456
    /**
457
     * Get a contact / conversation element.
458
     *
459
     * @param  {Object} root Overview messages container element.
460
     * @param  {Number} conversationId The conversation id.
461
     * @return {Object} Conversation element.
462
     */
463
    var getConversationElement = function(root, conversationId) {
464
        return root.find('[data-conversation-id="' + conversationId + '"]');
465
    };
466
 
467
    /**
468
     * Get a contact / conversation element from a user id.
469
     *
470
     * @param  {Object} root Overview messages container element.
471
     * @param  {Number} userId The user id.
472
     * @return {Object} Conversation element.
473
     */
474
    var getConversationElementFromUserId = function(root, userId) {
475
        return root.find('[data-user-id="' + userId + '"]');
476
    };
477
 
478
    /**
479
     * Show the conversation is muted icon.
480
     *
481
     * @param  {Object} conversationElement The conversation element.
482
     */
483
    var muteConversation = function(conversationElement) {
484
        conversationElement.find(SELECTORS.MUTED_ICON_CONTAINER).removeClass('hidden');
485
    };
486
 
487
    /**
488
     * Hide the conversation is muted icon.
489
     *
490
     * @param  {Object} conversationElement The conversation element.
491
     */
492
    var unmuteConversation = function(conversationElement) {
493
        conversationElement.find(SELECTORS.MUTED_ICON_CONTAINER).addClass('hidden');
494
    };
495
 
496
    /**
497
     * Show the contact is blocked icon.
498
     *
499
     * @param  {Object} conversationElement The conversation element.
500
     */
501
    var blockContact = function(conversationElement) {
502
        conversationElement.find(SELECTORS.BLOCKED_ICON_CONTAINER).removeClass('hidden');
503
    };
504
 
505
    /**
506
     * Hide the contact is blocked icon.
507
     *
508
     * @param  {Object} conversationElement The conversation element.
509
     */
510
    var unblockContact = function(conversationElement) {
511
        conversationElement.find(SELECTORS.BLOCKED_ICON_CONTAINER).addClass('hidden');
512
    };
513
 
514
    /**
515
     * Create an render new conversation element in the list of conversations.
516
     *
517
     * @param  {Object} root Overview messages container element.
518
     * @param  {Object} conversation The conversation.
519
     * @param  {Number} userId The logged in user id.
520
     * @return {Object} jQuery promise
521
     */
522
    var createNewConversationFromEvent = function(root, conversation, userId) {
523
        var existingConversations = root.find(SELECTORS.CONVERSATION);
524
 
525
        if (!existingConversations.length) {
526
            // If we didn't have any conversations then we need to show
527
            // the content of the list and hide the empty message.
528
            var listRoot = LazyLoadList.getRoot(root);
529
            LazyLoadList.showContent(listRoot);
530
            LazyLoadList.hideEmptyMessage(listRoot);
531
        }
532
 
533
        // Cache the conversation.
534
        loadedConversationsById[conversation.id] = conversation;
535
 
536
        return render([conversation], userId)
537
            .then(function(html) {
538
                var contentContainer = LazyLoadList.getContentContainer(root);
539
                return contentContainer.prepend(html);
540
            })
541
            .then(function() {
542
                return incrementTotalConversationCount(root);
543
            })
544
            .catch(Notification.exception);
545
    };
546
 
547
    /**
548
     * Delete a conversation from the list of conversations.
549
     *
550
     * @param  {Object} root Overview messages container element.
551
     * @param  {Object} conversationElement The conversation element.
552
     */
553
    var deleteConversation = function(root, conversationElement) {
554
        conversationElement.remove();
555
        decrementTotalConversationCount(root);
556
 
557
        var conversations = root.find(SELECTORS.CONVERSATION);
558
        if (!conversations.length) {
559
            // If we don't have any conversations then we need to hide
560
            // the content of the list and show the empty message.
561
            var listRoot = LazyLoadList.getRoot(root);
562
            LazyLoadList.hideContent(listRoot);
563
            LazyLoadList.showEmptyMessage(listRoot);
564
        }
565
    };
566
 
567
    /**
568
     * Mark a conversation as read.
569
     *
570
     * @param  {Object} root Overview messages container element.
571
     * @param  {Object} conversationElement The conversation element.
572
     */
573
    var markConversationAsRead = function(root, conversationElement) {
574
        var unreadCount = conversationElement.find(SELECTORS.UNREAD_COUNT);
575
        unreadCount.text('0');
576
        unreadCount.addClass('hidden');
577
        decrementTotalUnreadConversationCount(root);
578
    };
579
 
580
    /**
581
     * Listen to, and handle events in this section.
582
     *
583
     * @param {String} namespace Unique identifier for the Routes
584
     * @param {Object} root The section container element.
585
     * @param {Function} loadCallback The callback to load items.
586
     * @param {Array|null} types The conversation types for this section
587
     * @param {bool} includeFavourites If this section includes favourites
588
     * @param {String} fromPanel Routing argument to send if the section is loaded in message index left panel.
589
     */
590
    var registerEventListeners = function(namespace, root, loadCallback, types, includeFavourites, fromPanel) {
591
        var listRoot = LazyLoadList.getRoot(root);
592
        var conversationBelongsToThisSection = function(conversation) {
593
            // Make sure the type is an int so that the index of check matches correctly.
594
            var conversationType = parseInt(conversation.type, 10);
595
            if (
596
                // If the conversation type isn't one this section cares about then we can ignore it.
597
                (types && types.indexOf(conversationType) < 0) ||
598
                // If this is the favourites section and the conversation isn't a favourite then ignore it.
599
                (includeFavourites && !conversation.isFavourite) ||
600
                // If this section doesn't include favourites and the conversation is a favourite then ignore it.
601
                (!includeFavourites && conversation.isFavourite)
602
            ) {
603
                return false;
604
            }
605
 
606
            return true;
607
        };
608
 
609
 
1441 ariadna 610
        root[0].addEventListener('show.bs.collapse', function() {
1 efrain 611
            setExpanded(root);
612
            LazyLoadList.show(listRoot, loadCallback, function(contentContainer, conversations, userId) {
613
                return render(conversations, userId)
614
                    .then(function(html) {
615
                        contentContainer.append(html);
616
                        return html;
617
                    })
618
                    .catch(Notification.exception);
619
            });
620
        });
621
 
1441 ariadna 622
        root[0].addEventListener('hidden.bs.collapse', function() {
1 efrain 623
            setCollapsed(root);
624
        });
625
 
626
        PubSub.subscribe(MessageDrawerEvents.CONTACT_BLOCKED, function(userId) {
627
            var conversationElement = getConversationElementFromUserId(root, userId);
628
            if (conversationElement.length) {
629
                blockContact(conversationElement);
630
            }
631
        });
632
 
633
        PubSub.subscribe(MessageDrawerEvents.CONTACT_UNBLOCKED, function(userId) {
634
            var conversationElement = getConversationElementFromUserId(root, userId);
635
 
636
            if (conversationElement.length) {
637
                unblockContact(conversationElement);
638
            }
639
        });
640
 
641
        PubSub.subscribe(MessageDrawerEvents.CONVERSATION_SET_MUTED, function(conversation) {
642
            var conversationId = conversation.id;
643
            var conversationElement = getConversationElement(root, conversationId);
644
            if (conversationElement.length) {
645
                muteConversation(conversationElement);
646
            }
647
        });
648
 
649
        PubSub.subscribe(MessageDrawerEvents.CONVERSATION_UNSET_MUTED, function(conversation) {
650
            var conversationId = conversation.id;
651
            var conversationElement = getConversationElement(root, conversationId);
652
            if (conversationElement.length) {
653
                unmuteConversation(conversationElement);
654
            }
655
        });
656
 
657
        PubSub.subscribe(MessageDrawerEvents.CONVERSATION_NEW_LAST_MESSAGE, function(conversation) {
658
            if (!conversationBelongsToThisSection(conversation)) {
659
                return;
660
            }
661
 
662
            var pendingPromise = new Pending('core_message/message_drawer_view_overview_section:new');
663
            var loggedInUserId = conversation.loggedInUserId;
664
            var conversationId = conversation.id;
665
            var element = getConversationElement(root, conversationId);
666
            conversation = formatConversationFromEvent(conversation);
667
            if (element.length) {
668
                var contentContainer = LazyLoadList.getContentContainer(root);
669
                render([conversation], loggedInUserId)
670
                    .then(function(html) {
671
                        if (deletedConversationsById[conversationId]) {
672
                            // This conversation was deleted at some point since the messaging drawer was created.
673
                            if (conversation.messages[0].timeadded < deletedConversationsById[conversationId]) {
674
                                // The 'new' message was added before the conversation was deleted.
675
                                // This is probably stale data.
676
                                return;
677
                            }
678
                        }
679
                        contentContainer.prepend(html);
680
                        element.remove();
681
 
682
                        return;
683
                    })
684
                    .then(pendingPromise.resolve)
685
                    .catch(Notification.exception);
686
            } else if (conversation.messages.length) {
687
                createNewConversationFromEvent(root, conversation, loggedInUserId)
688
                .then(pendingPromise.resolve)
689
                .catch();
690
            } else {
691
                pendingPromise.resolve();
692
            }
693
        });
694
 
695
        PubSub.subscribe(MessageDrawerEvents.CONVERSATION_DELETED, function(conversationId) {
696
            var conversationElement = getConversationElement(root, conversationId);
697
            delete loadedConversationsById[conversationId];
698
            deletedConversationsById[conversationId] = new Date();
699
            if (conversationElement.length) {
700
                deleteConversation(root, conversationElement);
701
            }
702
        });
703
 
704
        PubSub.subscribe(MessageDrawerEvents.CONVERSATION_READ, function(conversationId) {
705
            var conversationElement = getConversationElement(root, conversationId);
706
            if (conversationElement.length) {
707
                markConversationAsRead(root, conversationElement);
708
            }
709
        });
710
 
711
        PubSub.subscribe(MessageDrawerEvents.CONVERSATION_SET_FAVOURITE, function(conversation) {
712
            var conversationElement = null;
713
            if (conversationBelongsToThisSection(conversation)) {
714
                conversationElement = getConversationElement(root, conversation.id);
715
                if (!conversationElement.length) {
716
                    createNewConversationFromEvent(
717
                        root,
718
                        formatConversationFromEvent(conversation),
719
                        conversation.loggedInUserId
720
                    );
721
                }
722
            } else {
723
                conversationElement = getConversationElement(root, conversation.id);
724
                if (conversationElement.length) {
725
                    deleteConversation(root, conversationElement);
726
                }
727
            }
728
        });
729
 
730
        PubSub.subscribe(MessageDrawerEvents.CONVERSATION_UNSET_FAVOURITE, function(conversation) {
731
            var conversationElement = null;
732
            if (conversationBelongsToThisSection(conversation)) {
733
                conversationElement = getConversationElement(root, conversation.id);
734
                if (!conversationElement.length) {
735
                    createNewConversationFromEvent(
736
                        root,
737
                        formatConversationFromEvent(conversation),
738
                        conversation.loggedInUserId
739
                    );
740
                }
741
            } else {
742
                conversationElement = getConversationElement(root, conversation.id);
743
                if (conversationElement.length) {
744
                    deleteConversation(root, conversationElement);
745
                }
746
            }
747
        });
748
 
749
        CustomEvents.define(root, [CustomEvents.events.activate]);
750
        root.on(CustomEvents.events.activate, SELECTORS.CONVERSATION, function(e, data) {
751
            var conversationElement = $(e.target).closest(SELECTORS.CONVERSATION);
752
            var conversationId = conversationElement.attr('data-conversation-id');
753
            var conversation = loadedConversationsById[conversationId];
754
            MessageDrawerRouter.go(namespace, MessageDrawerRoutes.VIEW_CONVERSATION, conversation, fromPanel);
755
 
756
            data.originalEvent.preventDefault();
757
        });
758
    };
759
 
760
    /**
761
     * Setup the section.
762
     *
763
     * @param {String} namespace Unique identifier for the Routes
764
     * @param {Object} header The header container element.
765
     * @param {Object} body The section container element.
766
     * @param {Object} footer The footer container element.
767
     * @param {Array} types The conversation types that show in this section
768
     * @param {bool} includeFavourites If this section includes favourites
769
     * @param {Object} totalCountPromise Resolves wth the total conversations count
770
     * @param {Object} unreadCountPromise Resolves wth the unread conversations count
771
     * @param {bool} fromPanel shown in message app panel.
772
     */
773
    var show = function(namespace, header, body, footer, types, includeFavourites, totalCountPromise, unreadCountPromise,
774
        fromPanel) {
775
        var root = $(body);
776
 
777
        if (!root.attr('data-init')) {
778
            var loadCallback = getLoadCallback(types, includeFavourites, 0);
779
            registerEventListeners(namespace, root, loadCallback, types, includeFavourites, fromPanel);
780
 
781
            if (isVisible(root)) {
782
                setExpanded(root);
783
                var listRoot = LazyLoadList.getRoot(root);
784
                LazyLoadList.show(listRoot, loadCallback, function(contentContainer, conversations, userId) {
785
                    return render(conversations, userId)
786
                        .then(function(html) {
787
                            contentContainer.append(html);
788
                            return html;
789
                        })
790
                        .catch(Notification.exception);
791
                });
792
            }
793
 
794
            // This is given to us by the calling code because the total counts for all sections
795
            // are loaded in a single ajax request rather than one request per section.
796
            totalCountPromise.then(function(count) {
797
                renderTotalCount(root, count);
798
                loadedTotalCounts = true;
799
                return;
800
            })
801
            .catch(function() {
802
                // Silently ignore if we can't updated the counts. No need to bother the user.
803
            });
804
 
805
            // This is given to us by the calling code because the unread counts for all sections
806
            // are loaded in a single ajax request rather than one request per section.
807
            unreadCountPromise.then(function(count) {
808
                renderUnreadCount(root, count);
809
                loadedUnreadCounts = true;
810
                return;
811
            })
812
            .catch(function() {
813
                // Silently ignore if we can't updated the counts. No need to bother the user.
814
            });
815
 
816
            root.attr('data-init', true);
817
        }
818
    };
819
 
820
    return {
821
        show: show,
822
        isVisible: isVisible
823
    };
824
});