sync_request.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * vim: ts=4:sw=4:expandtab
  3. */
  4. ;(function () {
  5. 'use strict';
  6. window.textsecure = window.textsecure || {};
  7. function SyncRequest(sender, receiver) {
  8. if (!(sender instanceof textsecure.MessageSender) || !(receiver instanceof textsecure.MessageReceiver)) {
  9. throw new Error('Tried to construct a SyncRequest without MessageSender and MessageReceiver');
  10. }
  11. this.receiver = receiver;
  12. this.oncontact = this.onContactSyncComplete.bind(this);
  13. receiver.addEventListener('contactsync', this.oncontact);
  14. this.ongroup = this.onGroupSyncComplete.bind(this);
  15. receiver.addEventListener('groupsync', this.ongroup);
  16. sender.sendRequestContactSyncMessage().then(function() {
  17. sender.sendRequestGroupSyncMessage();
  18. });
  19. this.timeout = setTimeout(this.onTimeout.bind(this), 60000);
  20. }
  21. SyncRequest.prototype = new textsecure.EventTarget();
  22. SyncRequest.prototype.extend({
  23. constructor: SyncRequest,
  24. onContactSyncComplete: function() {
  25. this.contactSync = true;
  26. this.update();
  27. },
  28. onGroupSyncComplete: function() {
  29. this.groupSync = true;
  30. this.update();
  31. },
  32. update: function() {
  33. if (this.contactSync && this.groupSync) {
  34. this.dispatchEvent(new Event('success'));
  35. this.cleanup();
  36. }
  37. },
  38. onTimeout: function() {
  39. if (this.contactSync || this.groupSync) {
  40. this.dispatchEvent(new Event('success'));
  41. } else {
  42. this.dispatchEvent(new Event('timeout'));
  43. }
  44. this.cleanup();
  45. },
  46. cleanup: function() {
  47. clearTimeout(this.timeout);
  48. this.receiver.removeEventListener('contactsync', this.oncontact);
  49. this.receiver.removeEventListener('groupSync', this.ongroup);
  50. delete this.listeners;
  51. }
  52. });
  53. textsecure.SyncRequest = function(sender, receiver) {
  54. var syncRequest = new SyncRequest(sender, receiver);
  55. this.addEventListener = syncRequest.addEventListener.bind(syncRequest);
  56. this.removeEventListener = syncRequest.removeEventListener.bind(syncRequest);
  57. };
  58. textsecure.SyncRequest.prototype = {
  59. constructor: textsecure.SyncRequest
  60. };
  61. }());