mirrored from git://git.moodle.org/moodle.git
/
message_drawer_view_conversation.js
1583 lines (1464 loc) · 62.9 KB
/
message_drawer_view_conversation.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
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Controls the conversation page in the message drawer.
*
* This function handles all of the user actions that the user can take
* when interacting with the conversation page.
*
* It maintains a view state which is a data representation of the view
* and only operates on that data.
*
* The view state is immutable and should never be modified directly. Instead
* all changes to the view state should be done using the StateManager which
* will generate a new version of the view state with the requested changes.
*
* After any changes to the view state the module will call the render function
* to ask the renderer to update the UI.
*
* General rules for this module:
* 1.) Never modify viewState directly. All changes should be via the StateManager.
* 2.) Call render() with the new state when you want to update the UI
* 3.) Never modify the UI directly in this module. This module is only concerned
* with the data in the view state.
*
* The general flow for a user interaction will be something like:
* User interaction: User clicks "confirm block" button to block the other user
* 1.) This module is hears the click
* 2.) This module sends a request to the server to block the user
* 3.) The server responds with the new user profile
* 4.) This module generates a new state using the StateManager with the updated
* user profile.
* 5.) This module asks the Patcher to generate a patch from the current state and
* the newly generated state. This patch tells the renderer what has changed
* between the states.
* 6.) This module gives the Renderer the generated patch. The renderer updates
* the UI with changes according to the patch.
*
* @module core_message/message_drawer_view_conversation
* @copyright 2018 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define(
[
'jquery',
'core/auto_rows',
'core/backoff_timer',
'core/custom_interaction_events',
'core/notification',
'core/pubsub',
'core/str',
'core_message/message_repository',
'core_message/message_drawer_events',
'core_message/message_drawer_view_conversation_constants',
'core_message/message_drawer_view_conversation_patcher',
'core_message/message_drawer_view_conversation_renderer',
'core_message/message_drawer_view_conversation_state_manager',
'core_message/message_drawer_router',
'core_message/message_drawer_routes',
],
function(
$,
AutoRows,
BackOffTimer,
CustomEvents,
Notification,
PubSub,
Str,
Repository,
MessageDrawerEvents,
Constants,
Patcher,
Renderer,
StateManager,
MessageDrawerRouter,
MessageDrawerRoutes
) {
// Contains a cache of all view states that have been loaded so far
// which saves us having to reload stuff with network requests when
// switching between conversations.
var stateCache = {};
// The current data representation of the view.
var viewState = null;
var loadedAllMessages = false;
var messagesOffset = 0;
var newMessagesPollTimer = null;
// This is the render function which will be generated when this module is
// first called. See generateRenderFunction for details.
var render = null;
var NEWEST_FIRST = Constants.NEWEST_MESSAGES_FIRST;
var LOAD_MESSAGE_LIMIT = Constants.LOAD_MESSAGE_LIMIT;
var INITIAL_NEW_MESSAGE_POLL_TIMEOUT = Constants.INITIAL_NEW_MESSAGE_POLL_TIMEOUT;
var SELECTORS = Constants.SELECTORS;
var CONVERSATION_TYPES = Constants.CONVERSATION_TYPES;
/**
* Get the other user userid.
*
* @return {Number} Userid.
*/
var getOtherUserId = function() {
if (!viewState || viewState.type != CONVERSATION_TYPES.PRIVATE) {
return null;
}
var loggedInUserId = viewState.loggedInUserId;
var otherUserIds = Object.keys(viewState.members).filter(function(userId) {
return loggedInUserId != userId;
});
return otherUserIds.length ? otherUserIds[0] : null;
};
/**
* Search the cache to see if we've already loaded a private conversation
* with the given user id.
*
* @param {Number} userId The id of the other user.
* @return {Number|null} Conversation id.
*/
var getCachedPrivateConversationIdFromUserId = function(userId) {
return Object.keys(stateCache).reduce(function(carry, id) {
if (!carry) {
var state = stateCache[id].state;
if (state.type == CONVERSATION_TYPES.PRIVATE) {
if (userId in state.members) {
// We've found a cached conversation for this user!
carry = state.id;
}
}
}
return carry;
}, null);
};
/**
* Get profile info for logged in user.
*
* @param {Object} body Conversation body container element.
* @return {Object}
*/
var getLoggedInUserProfile = function(body) {
return {
id: parseInt(body.attr('data-user-id'), 10),
contactrequests: []
};
};
/**
* Get the messages offset value to load more messages.
*
* @return {Number}
*/
var getMessagesOffset = function() {
return messagesOffset;
};
/**
* Set the messages offset value for loading more messages.
*
* @param {Number} value The offset value
*/
var setMessagesOffset = function(value) {
messagesOffset = value;
stateCache[viewState.id].messagesOffset = value;
};
/**
* Check if all messages have been loaded.
*
* @return {Bool}
*/
var hasLoadedAllMessages = function() {
return loadedAllMessages;
};
/**
* Set whether all messages have been loaded or not.
*
* @param {Bool} value If all messages have been loaded.
*/
var setLoadedAllMessages = function(value) {
loadedAllMessages = value;
stateCache[viewState.id].loadedAllMessages = value;
};
/**
* Get the messages container element.
*
* @param {Object} body Conversation body container element.
* @return {Object} The messages container element.
*/
var getMessagesContainer = function(body) {
return body.find(SELECTORS.MESSAGES_CONTAINER);
};
/**
* Reformat the conversation for an event payload.
*
* @param {Object} state The view state.
* @return {Object} New formatted conversation.
*/
var formatConversationForEvent = function(state) {
return {
id: state.id,
name: state.name,
subname: state.subname,
imageUrl: state.imageUrl,
isFavourite: state.isFavourite,
type: state.type,
totalMemberCount: state.totalMemberCount,
loggedInUserId: state.loggedInUserId,
messages: state.messages.map(function(message) {
return $.extend({}, message);
}),
members: Object.keys(state.members).reduce(function(carry, id) {
carry[id] = $.extend({}, state.members[id]);
carry[id].contactrequests = state.members[id].contactrequests.map(function(request) {
return $.extend({}, request);
});
return carry;
}, {})
};
};
/**
* Load up an empty private conversation between the logged in user and the
* other user. Sets all of the conversation details based on the other user.
*
* A conversation isn't created until the user sends the first message.
*
* @param {Object} loggedInUserProfile The logged in user profile.
* @param {Number} otherUserId The other user id.
* @return {Object} Profile returned from repository.
*/
var loadEmptyPrivateConversation = function(loggedInUserProfile, otherUserId) {
var loggedInUserId = loggedInUserProfile.id;
var newState = StateManager.setLoadingMembers(viewState, true);
newState = StateManager.setLoadingMessages(newState, true);
return render(newState)
.then(function() {
return Repository.getMemberInfo(loggedInUserId, [otherUserId], true, true);
})
.then(function(profiles) {
if (profiles.length) {
return profiles[0];
} else {
throw new Error('Unable to load other user profile');
}
})
.then(function(profile) {
var newState = StateManager.addMembers(viewState, [profile, loggedInUserProfile]);
newState = StateManager.setLoadingMembers(newState, false);
newState = StateManager.setLoadingMessages(newState, false);
newState = StateManager.setName(newState, profile.fullname);
newState = StateManager.setType(newState, 1);
newState = StateManager.setImageUrl(newState, profile.profileimageurl);
newState = StateManager.setTotalMemberCount(newState, 2);
return render(newState)
.then(function() {
return profile;
});
})
.catch(function(error) {
var newState = StateManager.setLoadingMembers(viewState, false);
render(newState);
Notification.exception(error);
});
};
/**
* Create a new state from a conversation object.
*
* @param {Object} conversation The conversation object.
* @param {Number} loggedInUserId The logged in user id.
* @return {Object} new state.
*/
var updateStateFromConversation = function(conversation, loggedInUserId) {
var otherUsers = conversation.members.filter(function(member) {
return member.id != loggedInUserId;
});
var otherUser = otherUsers.length ? otherUsers[0] : null;
var name = conversation.name;
var imageUrl = conversation.imageurl;
if (conversation.type == CONVERSATION_TYPES.PRIVATE) {
name = name || otherUser ? otherUser.fullname : '';
imageUrl = imageUrl || otherUser ? otherUser.profileimageurl : '';
}
var newState = StateManager.addMembers(viewState, conversation.members);
newState = StateManager.setName(newState, name);
newState = StateManager.setSubname(newState, conversation.subname);
newState = StateManager.setType(newState, conversation.type);
newState = StateManager.setImageUrl(newState, imageUrl);
newState = StateManager.setTotalMemberCount(newState, conversation.membercount);
newState = StateManager.setIsFavourite(newState, conversation.isfavourite);
newState = StateManager.addMessages(newState, conversation.messages);
return newState;
};
/**
* Get the details for a conversation from the conversation id.
*
* @param {Number} conversationId The conversation id.
* @param {Object} loggedInUserProfile The logged in user profile.
* @param {Number} messageLimit The number of messages to include.
* @param {Number} messageOffset The number of messages to skip.
* @param {Bool} newestFirst Order messages newest first.
* @return {Object} Promise resolved when loaded.
*/
var loadNewConversation = function(
conversationId,
loggedInUserProfile,
messageLimit,
messageOffset,
newestFirst
) {
var loggedInUserId = loggedInUserProfile.id;
var newState = StateManager.setLoadingMembers(viewState, true);
newState = StateManager.setLoadingMessages(newState, true);
return render(newState)
.then(function() {
return Repository.getConversation(
loggedInUserId,
conversationId,
true,
true,
0,
0,
messageLimit + 1,
messageOffset,
newestFirst
);
})
.then(function(conversation) {
if (conversation.messages.length > messageLimit) {
conversation.messages = conversation.messages.slice(1);
} else {
setLoadedAllMessages(true);
}
setMessagesOffset(messageOffset + messageLimit);
return conversation;
})
.then(function(conversation) {
var hasLoggedInUser = conversation.members.filter(function(member) {
return member.id == loggedInUserProfile.id;
});
if (hasLoggedInUser.length < 1) {
conversation.members = conversation.members.concat([loggedInUserProfile]);
}
var newState = updateStateFromConversation(conversation, loggedInUserProfile.id);
newState = StateManager.setLoadingMembers(newState, false);
newState = StateManager.setLoadingMessages(newState, false);
return render(newState)
.then(function() {
return conversation;
});
})
.then(function() {
return markConversationAsRead(conversationId);
})
.catch(function(error) {
var newState = StateManager.setLoadingMembers(viewState, false);
newState = StateManager.setLoadingMessages(newState, false);
render(newState);
Notification.exception(error);
});
};
/**
* Get the details for a conversation from and existing conversation object.
*
* @param {Object} conversation The conversation object.
* @param {Object} loggedInUserProfile The logged in user profile.
* @param {Number} messageLimit The number of messages to include.
* @param {Bool} newestFirst Order messages newest first.
* @return {Object} Promise resolved when loaded.
*/
var loadExistingConversation = function(
conversation,
loggedInUserProfile,
messageLimit,
newestFirst
) {
var hasLoggedInUser = conversation.members.filter(function(member) {
return member.id == loggedInUserProfile.id;
});
if (hasLoggedInUser.length < 1) {
conversation.members = conversation.members.concat([loggedInUserProfile]);
}
var newState = updateStateFromConversation(conversation, loggedInUserProfile.id);
newState = StateManager.setLoadingMembers(newState, false);
newState = StateManager.setLoadingMessages(newState, true);
var messageCount = conversation.messages.length;
return render(newState)
.then(function() {
if (messageCount < messageLimit) {
// We haven't got enough messages so let's load some more.
return loadMessages(conversation.id, messageLimit, messageCount, newestFirst, []);
} else {
// We've got enough messages. No need to load any more for now.
var newState = StateManager.setLoadingMessages(newState, false);
return render(newState);
}
})
.then(function(messages) {
setMessagesOffset(messageCount + messageLimit);
return messages;
})
.then(function() {
return markConversationAsRead(conversation.id);
})
.catch(Notification.exception);
};
/**
* Load messages for this conversation and pass them to the renderer.
*
* @param {Number} conversationId Conversation id.
* @param {Number} limit Number of messages to load.
* @param {Number} offset Get messages from offset.
* @param {Bool} newestFirst Get newest messages first.
* @param {Array} ignoreList Ignore any messages with ids in this list.
* @param {Number|null} timeFrom Only get messages from this time onwards.
* @return {Promise} renderer promise.
*/
var loadMessages = function(conversationId, limit, offset, newestFirst, ignoreList, timeFrom) {
return Repository.getMessages(
viewState.loggedInUserId,
conversationId,
limit ? limit + 1 : limit,
offset,
newestFirst,
timeFrom
)
.then(function(result) {
if (result.messages.length && ignoreList.length) {
result.messages = result.messages.filter(function(message) {
// Skip any messages in our ignore list.
return ignoreList.indexOf(parseInt(message.id, 10)) < 0;
});
}
return result;
})
.then(function(result) {
if (!limit) {
return result;
} else if (result.messages.length > limit) {
result.messages = result.messages.slice(1);
} else {
setLoadedAllMessages(true);
}
return result;
})
.then(function(result) {
var membersToAdd = result.members.filter(function(member) {
return !(member.id in viewState.members);
});
var newState = StateManager.addMembers(viewState, membersToAdd);
newState = StateManager.addMessages(newState, result.messages);
newState = StateManager.setLoadingMessages(newState, false);
return render(newState)
.then(function() {
return result;
});
})
.catch(function(error) {
var newState = StateManager.setLoadingMessages(viewState, false);
render(newState);
// Re-throw the error for other error handlers.
throw error;
});
};
/**
* Create a callback function for getting new messages for this conversation.
*
* @param {Number} conversationId Conversation id.
* @param {Bool} newestFirst Show newest messages first
* @return {Function} Callback function that returns a renderer promise.
*/
var getLoadNewMessagesCallback = function(conversationId, newestFirst) {
return function() {
var messages = viewState.messages;
var mostRecentMessage = messages.length ? messages[messages.length - 1] : null;
if (mostRecentMessage) {
// There may be multiple messages with the same time created value since
// the accuracy is only down to the second. The server will include these
// messages in the result (since it does a >= comparison on time from) so
// we need to filter them back out of the result so that we're left only
// with the new messages.
var ignoreMessageIds = [];
for (var i = messages.length - 1; i >= 0; i--) {
var message = messages[i];
if (message.timeCreated === mostRecentMessage.timeCreated) {
ignoreMessageIds.push(message.id);
} else {
// Since the messages are ordered in ascending order of time created
// we can break as soon as we hit a message with a different time created
// because we know all other messages will have lower values.
break;
}
}
return loadMessages(
conversationId,
0,
0,
newestFirst,
ignoreMessageIds,
mostRecentMessage.timeCreated
)
.then(function(result) {
if (result.messages.length) {
// If we found some results then restart the polling timer
// because the other user might be sending messages.
newMessagesPollTimer.restart();
return markConversationAsRead(conversationId);
} else {
return result;
}
});
}
};
};
/**
* Mark a conversation as read.
*
* @param {Number} conversationId The conversation id.
* @return {Promise} The renderer promise.
*/
var markConversationAsRead = function(conversationId) {
var loggedInUserId = viewState.loggedInUserId;
return Repository.markAllConversationMessagesAsRead(loggedInUserId, conversationId)
.then(function() {
var newState = StateManager.markMessagesAsRead(viewState, viewState.messages);
PubSub.publish(MessageDrawerEvents.CONVERSATION_READ, conversationId);
return render(newState);
});
};
/**
* Tell the statemanager there is request to block a user and run the renderer
* to show the block user dialogue.
*
* @param {Number} userId User id.
* @return {Promise} Renderer promise.
*/
var requestBlockUser = function(userId) {
return cancelRequest(userId).then(function() {
var newState = StateManager.addPendingBlockUsersById(viewState, [userId]);
return render(newState);
});
};
/**
* Send the repository a request to block a user, update the statemanager and publish
* a contact has been blocked.
*
* @param {Number} userId User id of user to block.
* @return {Promise} Renderer promise.
*/
var blockUser = function(userId) {
var newState = StateManager.setLoadingConfirmAction(viewState, true);
return render(newState)
.then(function() {
return Repository.blockUser(viewState.loggedInUserId, userId);
})
.then(function(profile) {
var newState = StateManager.addMembers(viewState, [profile]);
newState = StateManager.removePendingBlockUsersById(newState, [userId]);
newState = StateManager.setLoadingConfirmAction(newState, false);
PubSub.publish(MessageDrawerEvents.CONTACT_BLOCKED, newState.id);
return render(newState);
});
};
/**
* Tell the statemanager there is a request to unblock a user and run the renderer
* to show the unblock user dialogue.
*
* @param {Number} userId User id of user to unblock.
* @return {Promise} Renderer promise.
*/
var requestUnblockUser = function(userId) {
return cancelRequest(userId).then(function() {
var newState = StateManager.addPendingUnblockUsersById(viewState, [userId]);
return render(newState);
});
};
/**
* Send the repository a request to unblock a user, update the statemanager and publish
* a contact has been unblocked.
*
* @param {Number} userId User id of user to unblock.
* @return {Promise} Renderer promise.
*/
var unblockUser = function(userId) {
var newState = StateManager.setLoadingConfirmAction(viewState, true);
return render(newState)
.then(function() {
return Repository.unblockUser(viewState.loggedInUserId, userId);
})
.then(function(profile) {
var newState = StateManager.addMembers(viewState, [profile]);
newState = StateManager.removePendingUnblockUsersById(newState, [userId]);
newState = StateManager.setLoadingConfirmAction(newState, false);
PubSub.publish(MessageDrawerEvents.CONTACT_UNBLOCKED, newState.id);
return render(newState);
});
};
/**
* Tell the statemanager there is a request to remove a user from the contact list
* and run the renderer to show the remove user from contacts dialogue.
*
* @param {Number} userId User id of user to remove from contacts.
* @return {Promise} Renderer promise.
*/
var requestRemoveContact = function(userId) {
return cancelRequest(userId).then(function() {
var newState = StateManager.addPendingRemoveContactsById(viewState, [userId]);
return render(newState);
});
};
/**
* Send the repository a request to remove a user from the contacts list. update the statemanager
* and publish a contact has been removed.
*
* @param {Number} userId User id of user to remove from contacts.
* @return {Promise} Renderer promise.
*/
var removeContact = function(userId) {
var newState = StateManager.setLoadingConfirmAction(viewState, true);
return render(newState)
.then(function() {
return Repository.deleteContacts(viewState.loggedInUserId, [userId]);
})
.then(function(profiles) {
var newState = StateManager.addMembers(viewState, profiles);
newState = StateManager.removePendingRemoveContactsById(newState, [userId]);
newState = StateManager.setLoadingConfirmAction(newState, false);
PubSub.publish(MessageDrawerEvents.CONTACT_REMOVED, userId);
return render(newState);
});
};
/**
* Tell the statemanager there is a request to add a user to the contact list
* and run the renderer to show the add user to contacts dialogue.
*
* @param {Number} userId User id of user to add to contacts.
* @return {Promise} Renderer promise.
*/
var requestAddContact = function(userId) {
return cancelRequest(userId).then(function() {
var newState = StateManager.addPendingAddContactsById(viewState, [userId]);
return render(newState);
});
};
/**
* Send the repository a request to add a user to the contacts list. update the statemanager
* and publish a contact has been added.
*
* @param {Number} userId User id of user to add to contacts.
* @return {Promise} Renderer promise.
*/
var addContact = function(userId) {
var newState = StateManager.setLoadingConfirmAction(viewState, true);
return render(newState)
.then(function() {
return Repository.createContactRequest(viewState.loggedInUserId, userId);
})
.then(function(response) {
if (!response.request) {
throw new Error(response.warnings[0].message);
}
return response.request;
})
.then(function(request) {
var newState = StateManager.removePendingAddContactsById(viewState, [userId]);
newState = StateManager.addContactRequests(newState, [request]);
newState = StateManager.setLoadingConfirmAction(newState, false);
return render(newState);
});
};
/**
* Set the current conversation as a favourite conversation.
*
* @return {Promise} Renderer promise.
*/
var setFavourite = function() {
var userId = viewState.loggedInUserId;
var conversationId = viewState.id;
return Repository.setFavouriteConversations(userId, [conversationId])
.then(function() {
var newState = StateManager.setIsFavourite(viewState, true);
return render(newState);
})
.then(function() {
return PubSub.publish(
MessageDrawerEvents.CONVERSATION_SET_FAVOURITE,
formatConversationForEvent(viewState)
);
});
};
/**
* Unset the current conversation as a favourite conversation.
*
* @return {Promise} Renderer promise.
*/
var unsetFavourite = function() {
var userId = viewState.loggedInUserId;
var conversationId = viewState.id;
return Repository.unsetFavouriteConversations(userId, [conversationId])
.then(function() {
var newState = StateManager.setIsFavourite(viewState, false);
return render(newState);
})
.then(function() {
return PubSub.publish(
MessageDrawerEvents.CONVERSATION_UNSET_FAVOURITE,
formatConversationForEvent(viewState)
);
});
};
/**
* Tell the statemanager there is a request to delete the selected messages
* and run the renderer to show confirm delete messages dialogue.
*
* @param {Number} userId User id.
* @return {Promise} Renderer promise.
*/
var requestDeleteSelectedMessages = function(userId) {
var selectedMessageIds = viewState.selectedMessageIds;
return cancelRequest(userId).then(function() {
var newState = StateManager.addPendingDeleteMessagesById(viewState, selectedMessageIds);
return render(newState);
});
};
/**
* Send the repository a request to delete the messages pending deletion. Update the statemanager
* and publish a message deletion event.
*
* @return {Promise} Renderer promise.
*/
var deleteSelectedMessages = function() {
var messageIds = viewState.pendingDeleteMessageIds;
var newState = StateManager.setLoadingConfirmAction(viewState, true);
return render(newState)
.then(function() {
return Repository.deleteMessages(viewState.loggedInUserId, messageIds);
})
.then(function() {
var newState = StateManager.removeMessagesById(viewState, messageIds);
newState = StateManager.removePendingDeleteMessagesById(newState, messageIds);
newState = StateManager.removeSelectedMessagesById(newState, messageIds);
newState = StateManager.setLoadingConfirmAction(newState, false);
var prevLastMessage = viewState.messages[viewState.messages.length - 1];
var newLastMessage = newState.messages.length ? newState.messages[newState.messages.length - 1] : null;
if (newLastMessage && newLastMessage.id != prevLastMessage.id) {
var conversation = formatConversationForEvent(newState);
PubSub.publish(MessageDrawerEvents.CONVERSATION_NEW_LAST_MESSAGE, conversation);
} else if (!newState.messages.length) {
PubSub.publish(MessageDrawerEvents.CONVERSATION_DELETED, newState.id);
}
return render(newState);
});
};
/**
* Tell the statemanager there is a request to delete a conversation
* and run the renderer to show confirm delete conversation dialogue.
*
* @param {Number} userId User id of other user.
* @return {Promise} Renderer promise.
*/
var requestDeleteConversation = function(userId) {
return cancelRequest(userId).then(function() {
var newState = StateManager.setPendingDeleteConversation(viewState, true);
return render(newState);
});
};
/**
* Send the repository a request to delete a conversation. Update the statemanager
* and publish a conversation deleted event.
*
* @return {Promise} Renderer promise.
*/
var deleteConversation = function() {
var newState = StateManager.setLoadingConfirmAction(viewState, true);
return render(newState)
.then(function() {
return Repository.deleteCoversation(viewState.loggedInUserId, getOtherUserId());
})
.then(function() {
var newState = StateManager.removeMessages(viewState, viewState.messages);
newState = StateManager.removeSelectedMessagesById(newState, viewState.selectedMessageIds);
newState = StateManager.setPendingDeleteConversation(newState, false);
newState = StateManager.setLoadingConfirmAction(newState, false);
PubSub.publish(MessageDrawerEvents.CONVERSATION_DELETED, newState.id);
return render(newState);
});
};
/**
* Tell the statemanager to cancel all pending actions.
*
* @param {Number} userId User id.
* @return {Promise} Renderer promise.
*/
var cancelRequest = function(userId) {
var pendingDeleteMessageIds = viewState.pendingDeleteMessageIds;
var newState = StateManager.removePendingAddContactsById(viewState, [userId]);
newState = StateManager.removePendingRemoveContactsById(newState, [userId]);
newState = StateManager.removePendingUnblockUsersById(newState, [userId]);
newState = StateManager.removePendingBlockUsersById(newState, [userId]);
newState = StateManager.removePendingDeleteMessagesById(newState, pendingDeleteMessageIds);
newState = StateManager.setPendingDeleteConversation(newState, false);
return render(newState);
};
/**
* Accept the contact request from the given user.
*
* @param {Number} userId User id of other user.
* @return {Promise} Renderer promise.
*/
var acceptContactRequest = function(userId) {
// Search the list of the logged in user's contact requests to find the
// one from this user.
var loggedInUserId = viewState.loggedInUserId;
var requests = viewState.members[userId].contactrequests.filter(function(request) {
return request.requesteduserid == loggedInUserId;
});
var request = requests[0];
var newState = StateManager.setLoadingConfirmAction(viewState, true);
return render(newState)
.then(function() {
return Repository.acceptContactRequest(userId, loggedInUserId);
})
.then(function(profile) {
var newState = StateManager.removeContactRequests(viewState, [request]);
newState = StateManager.addMembers(viewState, [profile]);
newState = StateManager.setLoadingConfirmAction(newState, false);
return render(newState);
})
.then(function() {
PubSub.publish(MessageDrawerEvents.CONTACT_ADDED, viewState.members[userId]);
PubSub.publish(MessageDrawerEvents.CONTACT_REQUEST_ACCEPTED, request);
return;
});
};
/**
* Decline the contact request from the given user.
*
* @param {Number} userId User id of other user.
* @return {Promise} Renderer promise.
*/
var declineContactRequest = function(userId) {
// Search the list of the logged in user's contact requests to find the
// one from this user.
var loggedInUserId = viewState.loggedInUserId;
var requests = viewState.members[loggedInUserId].contactrequests.filter(function(request) {
return request.userid == userId;
});
var request = requests[0];
var newState = StateManager.setLoadingConfirmAction(viewState, true);
return render(newState)
.then(function() {
return Repository.declineContactRequest(userId, loggedInUserId);
})
.then(function(profile) {
var newState = StateManager.removeContactRequests(viewState, [request]);
newState = StateManager.addMembers(viewState, [profile]);
newState = StateManager.setLoadingConfirmAction(newState, false);
return render(newState);
})
.then(function() {
PubSub.publish(MessageDrawerEvents.CONTACT_REQUEST_DECLINED, request);
return;
});
};
/**
* Send a message to the repository, update the statemanager publish a message send event
* and call the renderer.
*
* @param {Number} conversationId The conversation to send to.
* @param {String} text Text to send.
* @return {Promise} Renderer promise.
*/
var sendMessage = function(conversationId, text) {
var newState = StateManager.setSendingMessage(viewState, true);
var newConversationId = null;
return render(newState)
.then(function() {
if (!conversationId && viewState.type == CONVERSATION_TYPES.PRIVATE) {
// If it's a new private conversation then we need to use the old
// web service function to create the conversation.
var otherUserId = getOtherUserId();
return Repository.sendMessageToUser(otherUserId, text)
.then(function(message) {
newConversationId = parseInt(message.conversationid, 10);
return message;
});
} else {
return Repository.sendMessageToConversation(conversationId, text);
}
})
.then(function(message) {
var newState = StateManager.addMessages(viewState, [message]);
newState = StateManager.setSendingMessage(newState, false);
var conversation = formatConversationForEvent(newState);
if (!newState.id) {
// If this message created the conversation then save the conversation
// id.
newState = StateManager.setId(newState, newConversationId);
conversation.id = newConversationId;
resetMessagePollTimer(newConversationId);
PubSub.publish(MessageDrawerEvents.CONVERSATION_CREATED, conversation);
}
return render(newState)
.then(function() {
PubSub.publish(MessageDrawerEvents.CONVERSATION_NEW_LAST_MESSAGE, conversation);
return;
});
})
.catch(function(error) {
var newState = StateManager.setSendingMessage(viewState, false);
render(newState);
Notification.exception(error);
});
};
/**
* Toggle the selected messages update the statemanager and render the result.
*
* @param {Number} messageId The id of the message to be toggled
* @return {Promise} Renderer promise.
*/
var toggleSelectMessage = function(messageId) {
var newState = viewState;
if (viewState.selectedMessageIds.indexOf(messageId) > -1) {
newState = StateManager.removeSelectedMessagesById(viewState, [messageId]);
} else {
newState = StateManager.addSelectedMessagesById(viewState, [messageId]);
}
return render(newState);
};
/**
* Cancel edit mode (selecting the messages).