delivery_receipts.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. messages.fetchSentAt(receipt.get('timestamp')).then(function() {
  43. if (messages.length === 0) { return; }
  44. var message = messages.find(function(message) {
  45. return (!message.isIncoming() && receipt.get('source') === message.get('conversationId'));
  46. });
  47. if (message) { return message; }
  48. var groups = new GroupCollection();
  49. return groups.fetchGroups(receipt.get('source')).then(function() {
  50. var ids = groups.pluck('id');
  51. ids.push(receipt.get('source'));
  52. return messages.find(function(message) {
  53. return (!message.isIncoming() &&
  54. _.contains(ids, message.get('conversationId')));
  55. });
  56. });
  57. }).then(function(message) {
  58. if (message) {
  59. this.remove(receipt);
  60. var deliveries = message.get('delivered') || 0;
  61. message.save({
  62. delivered: deliveries + 1
  63. }).then(function() {
  64. // notify frontend listeners
  65. var conversation = ConversationController.get(
  66. message.get('conversationId')
  67. );
  68. if (conversation) {
  69. conversation.trigger('delivered', message);
  70. }
  71. });
  72. // TODO: consider keeping a list of numbers we've
  73. // successfully delivered to?
  74. }
  75. }.bind(this));
  76. }
  77. }))();
  78. })();