delivery_receipts.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * vim: ts=4:sw=4:expandtab
  3. */
  4. ;(function() {
  5. 'use strict';
  6. window.Whisper = window.Whisper || {};
  7. var GroupCollection = Backbone.Collection.extend({
  8. database: Whisper.Database,
  9. storeName: 'conversations',
  10. model: Backbone.Model,
  11. fetchGroups: function(number) {
  12. return new Promise(function(resolve) {
  13. this.fetch({
  14. index: {
  15. name: 'group',
  16. only: number
  17. }
  18. }).always(resolve);
  19. }.bind(this));
  20. }
  21. });
  22. Whisper.DeliveryReceipts = new (Backbone.Collection.extend({
  23. initialize: function() {
  24. this.on('add', this.onReceipt);
  25. },
  26. forMessage: function(conversation, message) {
  27. var recipients;
  28. if (conversation.isPrivate()) {
  29. recipients = [ conversation.id ];
  30. } else {
  31. recipients = conversation.get('members') || [];
  32. }
  33. var receipts = this.filter(function(receipt) {
  34. return (receipt.get('timestamp') === message.get('sent_at')) &&
  35. (recipients.indexOf(receipt.get('source')) > -1);
  36. });
  37. this.remove(receipts);
  38. return receipts;
  39. },
  40. onReceipt: function(receipt) {
  41. var messages = new Whisper.MessageCollection();
  42. var groups = new GroupCollection();
  43. Promise.all([
  44. groups.fetchGroups(receipt.get('source')),
  45. messages.fetchSentAt(receipt.get('timestamp'))
  46. ]).then(function() {
  47. var ids = groups.pluck('id');
  48. ids.push(receipt.get('source'));
  49. var message = messages.find(function(message) {
  50. return (!message.isIncoming() &&
  51. _.contains(ids, message.get('conversationId')));
  52. });
  53. if (message) {
  54. this.remove(receipt);
  55. var deliveries = message.get('delivered') || 0;
  56. message.save({
  57. delivered: deliveries + 1
  58. }).then(function() {
  59. // notify frontend listeners
  60. var conversation = ConversationController.get(
  61. message.get('conversationId')
  62. );
  63. if (conversation) {
  64. conversation.trigger('newmessage', message);
  65. }
  66. });
  67. // TODO: consider keeping a list of numbers we've
  68. // successfully delivered to?
  69. }
  70. }.bind(this));
  71. }
  72. }))();
  73. })();