signal-desktop/js/delivery_receipts.js

101 lines
3 KiB
JavaScript
Raw Normal View History

/* global Backbone: false */
/* global Whisper: false */
/* global ConversationController: false */
/* global _: false */
/* eslint-disable more/no-then */
// eslint-disable-next-line func-names
2018-04-27 21:25:04 +00:00
(function() {
'use strict';
2018-04-27 21:25:04 +00:00
window.Whisper = window.Whisper || {};
2018-04-27 21:25:04 +00:00
Whisper.DeliveryReceipts = new (Backbone.Collection.extend({
forMessage(conversation, message) {
let recipients;
2018-04-27 21:25:04 +00:00
if (conversation.isPrivate()) {
recipients = [conversation.id];
} else {
recipients = conversation.get('members') || [];
}
const receipts = this.filter(
receipt =>
2018-04-27 21:25:04 +00:00
receipt.get('timestamp') === message.get('sent_at') &&
recipients.indexOf(receipt.get('source')) > -1
);
2018-04-27 21:25:04 +00:00
this.remove(receipts);
return receipts;
},
onReceipt(receipt) {
const messages = new Whisper.MessageCollection();
2018-04-27 21:25:04 +00:00
return messages
.fetchSentAt(receipt.get('timestamp'))
.then(() => {
2018-04-27 21:25:04 +00:00
if (messages.length === 0) {
return null;
2018-04-27 21:25:04 +00:00
}
const message = messages.find(
item =>
!item.isIncoming() &&
receipt.get('source') === item.get('conversationId')
);
2018-04-27 21:25:04 +00:00
if (message) {
return message;
}
const groups = new Whisper.GroupCollection();
return groups.fetchGroups(receipt.get('source')).then(() => {
const ids = groups.pluck('id');
2018-04-27 21:25:04 +00:00
ids.push(receipt.get('source'));
return messages.find(
item =>
!item.isIncoming() &&
_.contains(ids, item.get('conversationId'))
);
2018-04-27 21:25:04 +00:00
});
})
.then(message => {
if (message) {
const deliveries = message.get('delivered') || 0;
const deliveredTo = message.get('delivered_to') || [];
return new Promise((resolve, reject) => {
message
.save({
delivered_to: _.union(deliveredTo, [receipt.get('source')]),
delivered: deliveries + 1,
})
.then(() => {
// notify frontend listeners
const conversation = ConversationController.get(
message.get('conversationId')
);
if (conversation) {
conversation.trigger('delivered', message);
}
2018-04-27 21:25:04 +00:00
this.remove(receipt);
resolve();
}, reject);
});
// TODO: consider keeping a list of numbers we've
// successfully delivered to?
}
console.log(
'No message for delivery receipt',
receipt.get('source'),
receipt.get('timestamp')
);
return null;
})
.catch(error => {
2018-04-27 21:25:04 +00:00
console.log(
'DeliveryReceipts.onReceipt error:',
error && error.stack ? error.stack : error
);
});
},
}))();
})();