summaryrefslogtreecommitdiffstats
path: root/comm/mailnews/addrbook/modules/CardDAVDirectory.jsm
blob: e4361d53bb8a0189ea4f56cee753c2ddbed51666 (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/. */

const EXPORTED_SYMBOLS = ["CardDAVDirectory"];

const { XPCOMUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/XPCOMUtils.sys.mjs"
);

const lazy = {};

const { SQLiteDirectory } = ChromeUtils.import(
  "resource:///modules/SQLiteDirectory.jsm"
);

ChromeUtils.defineESModuleGetters(lazy, {
  clearInterval: "resource://gre/modules/Timer.sys.mjs",
  setInterval: "resource://gre/modules/Timer.sys.mjs",
  setTimeout: "resource://gre/modules/Timer.sys.mjs",
});

XPCOMUtils.defineLazyModuleGetters(lazy, {
  CardDAVUtils: "resource:///modules/CardDAVUtils.jsm",
  NotificationCallbacks: "resource:///modules/CardDAVUtils.jsm",
  OAuth2Module: "resource:///modules/OAuth2Module.jsm",
  OAuth2Providers: "resource:///modules/OAuth2Providers.jsm",
  VCardProperties: "resource:///modules/VCardUtils.jsm",
  VCardUtils: "resource:///modules/VCardUtils.jsm",
});

const PREFIX_BINDINGS = {
  card: "urn:ietf:params:xml:ns:carddav",
  cs: "http://calendarserver.org/ns/",
  d: "DAV:",
};
const NAMESPACE_STRING = Object.entries(PREFIX_BINDINGS)
  .map(([prefix, url]) => `xmlns:${prefix}="${url}"`)
  .join(" ");

const log = console.createInstance({
  prefix: "carddav.sync",
  maxLogLevel: "Warn",
  maxLogLevelPref: "carddav.sync.loglevel",
});

/**
 * Adds CardDAV sync to SQLiteDirectory.
 */
class CardDAVDirectory extends SQLiteDirectory {
  /** nsIAbDirectory */

  init(uri) {
    super.init(uri);

    let serverURL = this._serverURL;
    if (serverURL) {
      // Google's server enforces some vCard 3.0-isms (or just fails badly if
      // you don't provide exactly what it wants) so we use this property to
      // determine when to do things differently. Cards from this directory
      // inherit the same property.
      if (this.getBoolValue("carddav.vcard3")) {
        this._isGoogleCardDAV = true;
      } else {
        this._isGoogleCardDAV = serverURL.startsWith(
          "https://www.googleapis.com/"
        );
        if (this._isGoogleCardDAV) {
          this.setBoolValue("carddav.vcard3", true);
        }
      }

      // If this directory is configured, start sync'ing with the server in 30s.
      // Don't do this immediately, as this code runs at start-up and could
      // impact performance if there are lots of changes to process.
      if (this.getIntValue("carddav.syncinterval", 30) > 0) {
        this._syncTimer = lazy.setTimeout(() => this.syncWithServer(), 30000);
      }
    }

    let uidsToSync = this.getStringValue("carddav.uidsToSync", "");
    if (uidsToSync) {
      this._uidsToSync = new Set(uidsToSync.split(" ").filter(Boolean));
      this.setStringValue("carddav.uidsToSync", "");
      log.debug(`Retrieved list of cards to sync: ${uidsToSync}`);
    } else {
      this._uidsToSync = new Set();
    }

    let hrefsToRemove = this.getStringValue("carddav.hrefsToRemove", "");
    if (hrefsToRemove) {
      this._hrefsToRemove = new Set(hrefsToRemove.split(" ").filter(Boolean));
      this.setStringValue("carddav.hrefsToRemove", "");
      log.debug(`Retrieved list of cards to remove: ${hrefsToRemove}`);
    } else {
      this._hrefsToRemove = new Set();
    }
  }
  async cleanUp() {
    await super.cleanUp();

    if (this._syncTimer) {
      lazy.clearInterval(this._syncTimer);
      this._syncTimer = null;
    }

    if (this._uidsToSync.size) {
      let uidsToSync = [...this._uidsToSync].join(" ");
      this.setStringValue("carddav.uidsToSync", uidsToSync);
      log.debug(`Stored list of cards to sync: ${uidsToSync}`);
    }
    if (this._hrefsToRemove.size) {
      let hrefsToRemove = [...this._hrefsToRemove].join(" ");
      this.setStringValue("carddav.hrefsToRemove", hrefsToRemove);
      log.debug(`Stored list of cards to remove: ${hrefsToRemove}`);
    }
  }

  get propertiesChromeURI() {
    return "chrome://messenger/content/addressbook/abCardDAVProperties.xhtml";
  }
  get dirType() {
    return Ci.nsIAbManager.CARDDAV_DIRECTORY_TYPE;
  }
  get supportsMailingLists() {
    return false;
  }

  modifyCard(card) {
    // Well this is awkward. Because it's defined in nsIAbDirectory,
    // modifyCard must not be async, but we need to do async operations.
    let newCard = super.modifyCard(card);
    this._modifyCard(newCard);
  }
  async _modifyCard(card) {
    try {
      await this._sendCardToServer(card);
    } catch (ex) {
      console.error(ex);
    }
  }
  deleteCards(cards) {
    super.deleteCards(cards);
    this._deleteCards(cards);
  }
  async _deleteCards(cards) {
    for (let card of cards) {
      try {
        await this._deleteCardFromServer(card);
      } catch (ex) {
        console.error(ex);
        break;
      }
    }

    for (let card of cards) {
      this._uidsToSync.delete(card.UID);
    }
  }
  dropCard(card, needToCopyCard) {
    // Ideally, we'd not add the card until it was on the server, but we have
    // to return newCard synchronously.
    let newCard = super.dropCard(card, needToCopyCard);
    this._sendCardToServer(newCard).catch(console.error);
    return newCard;
  }
  addMailList() {
    throw Components.Exception(
      "CardDAVDirectory does not implement addMailList",
      Cr.NS_ERROR_NOT_IMPLEMENTED
    );
  }
  setIntValue(name, value) {
    super.setIntValue(name, value);

    // Capture changes to the sync interval from the UI.
    if (name == "carddav.syncinterval") {
      this._scheduleNextSync();
    }
  }

  /** CardDAV specific */
  _syncInProgress = false;
  _syncTimer = null;

  get _serverURL() {
    return this.getStringValue("carddav.url", "");
  }
  get _syncToken() {
    return this.getStringValue("carddav.token", "");
  }
  set _syncToken(value) {
    this.setStringValue("carddav.token", value);
  }

  /**
   * Wraps CardDAVUtils.makeRequest, resolving path this directory's server
   * URL, and providing a mechanism to give a username and password specific
   * to this directory.
   *
   * @param {string} path - A path relative to the server URL.
   * @param {object} details - See CardDAVUtils.makeRequest.
   * @returns {Promise<object>} - See CardDAVUtils.makeRequest.
   */
  async _makeRequest(path, details = {}) {
    let serverURI = Services.io.newURI(this._serverURL);
    let uri = serverURI.resolve(path);

    if (!("_oAuth" in this)) {
      if (lazy.OAuth2Providers.getHostnameDetails(serverURI.host)) {
        this._oAuth = new lazy.OAuth2Module();
        this._oAuth.initFromABDirectory(this, serverURI.host);
      } else {
        this._oAuth = null;
      }
    }
    details.oAuth = this._oAuth;

    let username = this.getStringValue("carddav.username", "");
    let callbacks = new lazy.NotificationCallbacks(username);
    details.callbacks = callbacks;

    details.userContextId =
      this._userContextId ?? lazy.CardDAVUtils.contextForUsername(username);

    let response;
    try {
      Services.obs.notifyObservers(
        this,
        "addrbook-directory-request-start",
        this.UID
      );
      response = await lazy.CardDAVUtils.makeRequest(uri, details);
    } finally {
      Services.obs.notifyObservers(
        this,
        "addrbook-directory-request-end",
        this.UID
      );
    }
    if (
      details.expectedStatuses &&
      !details.expectedStatuses.includes(response.status)
    ) {
      throw Components.Exception(
        `Incorrect response from server: ${response.status} ${response.statusText}`,
        Cr.NS_ERROR_FAILURE
      );
    }

    if (callbacks.shouldSaveAuth) {
      // The user was prompted for a username and password. Save the response.
      this.setStringValue("carddav.username", callbacks.authInfo?.username);
      callbacks.saveAuth();
    }
    return response;
  }

  /**
   * Gets or creates the path for storing this card on the server. Cards that
   * already exist on the server have this value in the _href property.
   *
   * @param {nsIAbCard} card
   * @returns {string}
   */
  _getCardHref(card) {
    let href = card.getProperty("_href", "");
    if (href) {
      return href;
    }
    href = Services.io.newURI(this._serverURL).resolve(`${card.UID}.vcf`);
    return new URL(href).pathname;
  }

  _multigetRequest(hrefsToFetch) {
    hrefsToFetch = hrefsToFetch.map(
      href => `      <d:href>${xmlEncode(href)}</d:href>`
    );
    let data = `<card:addressbook-multiget ${NAMESPACE_STRING}>
      <d:prop>
        <d:getetag/>
        <card:address-data/>
      </d:prop>
      ${hrefsToFetch.join("\n")}
    </card:addressbook-multiget>`;

    return this._makeRequest("", {
      method: "REPORT",
      body: data,
      headers: {
        Depth: 1,
      },
      expectedStatuses: [207],
    });
  }

  /**
   * Performs a multiget request for the provided hrefs, and adds each response
   * to the directory, adding or modifying as necessary.
   *
   * @param {string[]} hrefsToFetch - The href of each card to be requested.
   */
  async _fetchAndStore(hrefsToFetch) {
    if (hrefsToFetch.length == 0) {
      return;
    }

    let response = await this._multigetRequest(hrefsToFetch);

    // If this directory is set to read-only, the following operations would
    // throw NS_ERROR_FAILURE, but sync operations are allowed on a read-only
    // directory, so set this._overrideReadOnly to avoid the exception.
    //
    // Do not use await while it is set, and use a try/finally block to ensure
    // it is cleared.

    try {
      this._overrideReadOnly = true;
      for (let { href, properties } of this._readResponse(response.dom)) {
        if (!properties) {
          continue;
        }

        let etag = properties.querySelector("getetag")?.textContent;
        let vCard = normalizeLineEndings(
          properties.querySelector("address-data")?.textContent
        );

        let abCard = lazy.VCardUtils.vCardToAbCard(vCard);
        abCard.setProperty("_etag", etag);
        abCard.setProperty("_href", href);

        if (!this.cards.has(abCard.UID)) {
          super.dropCard(abCard, false);
        } else if (this.loadCardProperties(abCard.UID).get("_etag") != etag) {
          super.modifyCard(abCard);
        }
      }
    } finally {
      this._overrideReadOnly = false;
    }
  }

  /**
   * Reads a multistatus response, yielding once for each response element.
   *
   * @param {Document} dom - as returned by CardDAVUtils.makeRequest.
   * @yields {object} - An object representing a single <response> element
   *     from the document:
   *     - href, the href of the object represented
   *     - notFound, if a 404 status applies to this response
   *     - properties, the <prop> element, if any, containing properties
   *         of the object represented
   */
  _readResponse = function* (dom) {
    if (!dom || dom.documentElement.localName != "multistatus") {
      throw Components.Exception(
        `Expected a multistatus response, but didn't get one`,
        Cr.NS_ERROR_FAILURE
      );
    }

    for (let r of dom.querySelectorAll("response")) {
      let response = {
        href: r.querySelector("href")?.textContent,
      };

      let responseStatus = r.querySelector("response > status");
      if (responseStatus?.textContent.startsWith("HTTP/1.1 404")) {
        response.notFound = true;
        yield response;
        continue;
      }

      for (let p of r.querySelectorAll("response > propstat")) {
        let status = p.querySelector("propstat > status").textContent;
        if (status == "HTTP/1.1 200 OK") {
          response.properties = p.querySelector("propstat > prop");
        }
      }

      yield response;
    }
  };

  /**
   * Converts the card to a vCard and performs a PUT request to store it on the
   * server. Then immediately performs a GET request ensuring the local copy
   * matches the server copy. Stores the card in the database on success.
   *
   * @param {nsIAbCard} card
   * @returns {boolean} true if the PUT request succeeded without conflict,
   *     false if there was a conflict.
   * @throws if the server responded with anything other than a success or
   *     conflict status code.
   */
  async _sendCardToServer(card) {
    let href = this._getCardHref(card);
    let requestDetails = {
      method: "PUT",
      contentType: "text/vcard",
    };

    let vCard = card.getProperty("_vCard", "");
    if (this._isGoogleCardDAV) {
      // There must be an `N` property, even if empty.
      let vCardProperties = lazy.VCardProperties.fromVCard(vCard);
      if (!vCardProperties.getFirstEntry("n")) {
        vCardProperties.addValue("n", ["", "", "", "", ""]);
      }
      requestDetails.body = vCardProperties.toVCard();
    } else {
      requestDetails.body = vCard;
    }

    let response;
    try {
      log.debug(`Sending ${href} to server.`);
      response = await this._makeRequest(href, requestDetails);
    } catch (ex) {
      Services.obs.notifyObservers(this, "addrbook-directory-sync-failed");
      this._uidsToSync.add(card.UID);
      throw ex;
    }

    if (response.status >= 400) {
      throw Components.Exception(
        `Sending card to the server failed, response was ${response.status} ${response.statusText}`,
        Cr.NS_ERROR_FAILURE
      );
    }

    // At this point we *should* be able to make a simple GET request and
    // store the response. But Google moves the data (fair enough) without
    // telling us where it went (c'mon, really?). Fortunately a multiget
    // request at the original location works.

    response = await this._multigetRequest([href]);

    for (let { href, properties } of this._readResponse(response.dom)) {
      if (!properties) {
        continue;
      }

      let etag = properties.querySelector("getetag")?.textContent;
      let vCard = normalizeLineEndings(
        properties.querySelector("address-data")?.textContent
      );

      let abCard = lazy.VCardUtils.vCardToAbCard(vCard);
      abCard.setProperty("_etag", etag);
      abCard.setProperty("_href", href);

      if (abCard.UID == card.UID) {
        super.modifyCard(abCard);
      } else {
        // Add a property so the UI can work out if it's still displaying the
        // old card and respond appropriately.
        abCard.setProperty("_originalUID", card.UID);
        super.dropCard(abCard, false);
        super.deleteCards([card]);
      }
    }
  }

  /**
   * Deletes card from the server.
   *
   * @param {nsIAbCard|string} cardOrHRef
   */
  async _deleteCardFromServer(cardOrHRef) {
    let href;
    if (typeof cardOrHRef == "string") {
      href = cardOrHRef;
    } else {
      href = cardOrHRef.getProperty("_href", "");
    }
    if (!href) {
      return;
    }

    try {
      log.debug(`Removing ${href} from server.`);
      await this._makeRequest(href, { method: "DELETE" });
    } catch (ex) {
      Services.obs.notifyObservers(this, "addrbook-directory-sync-failed");
      this._hrefsToRemove.add(href);
      throw ex;
    }
  }

  /**
   * Set up a repeating timer for synchronisation with the server. The timer's
   * interval is defined by pref, set it to 0 to disable sync'ing altogether.
   */
  _scheduleNextSync() {
    if (this._syncTimer) {
      lazy.clearInterval(this._syncTimer);
      this._syncTimer = null;
    }

    let interval = this.getIntValue("carddav.syncinterval", 30);
    if (interval <= 0) {
      return;
    }

    this._syncTimer = lazy.setInterval(
      () => this.syncWithServer(false),
      interval * 60000
    );
  }

  /**
   * Get all cards on the server and add them to this directory.
   *
   * This is usually used for the initial population of a directory, but it
   * can also be used for a complete re-sync.
   */
  async fetchAllFromServer() {
    log.log("Fetching all cards from the server.");
    this._syncInProgress = true;

    let data = `<propfind xmlns="${PREFIX_BINDINGS.d}" ${NAMESPACE_STRING}>
      <prop>
        <resourcetype/>
        <getetag/>
        <cs:getctag/>
      </prop>
    </propfind>`;

    let response = await this._makeRequest("", {
      method: "PROPFIND",
      body: data,
      headers: {
        Depth: 1,
      },
      expectedStatuses: [207],
    });

    // A map of all existing hrefs and etags. If the etag for an href matches
    // what we already have, we won't fetch it.
    let currentHrefs = new Map(
      Array.from(this.cards.values(), c => [c.get("_href"), c.get("_etag")])
    );

    let hrefsToFetch = [];
    for (let { href, properties } of this._readResponse(response.dom)) {
      if (!properties || properties.querySelector("resourcetype collection")) {
        continue;
      }

      let currentEtag = currentHrefs.get(href);
      currentHrefs.delete(href);

      let etag = properties.querySelector("getetag")?.textContent;
      if (etag && currentEtag == etag) {
        continue;
      }

      hrefsToFetch.push(href);
    }

    // Delete any existing cards we didn't see. They're not on the server so
    // they shouldn't be on the client.
    let cardsToDelete = [];
    for (let href of currentHrefs.keys()) {
      cardsToDelete.push(this.getCardFromProperty("_href", href, true));
    }
    if (cardsToDelete.length > 0) {
      super.deleteCards(cardsToDelete);
    }

    // Fetch any cards we don't already have, or that have changed.
    if (hrefsToFetch.length > 0) {
      response = await this._multigetRequest(hrefsToFetch);

      let abCards = [];

      for (let { href, properties } of this._readResponse(response.dom)) {
        if (!properties) {
          continue;
        }

        let etag = properties.querySelector("getetag")?.textContent;
        let vCard = normalizeLineEndings(
          properties.querySelector("address-data")?.textContent
        );

        try {
          let abCard = lazy.VCardUtils.vCardToAbCard(vCard);
          abCard.setProperty("_etag", etag);
          abCard.setProperty("_href", href);
          abCards.push(abCard);
        } catch (ex) {
          log.error(`Error parsing: ${vCard}`);
          console.error(ex);
        }
      }

      await this.bulkAddCards(abCards);
    }

    await this._getSyncToken();

    log.log("Sync with server completed successfully.");
    Services.obs.notifyObservers(this, "addrbook-directory-synced");

    this._scheduleNextSync();
    this._syncInProgress = false;
  }

  /**
   * Begin a sync operation. This function will decide which sync protocol to
   * use based on the directory's configuration. It will also (re)start the
   * timer for the next synchronisation unless told not to.
   *
   * @param {boolean} shouldResetTimer
   */
  async syncWithServer(shouldResetTimer = true) {
    if (this._syncInProgress || !this._serverURL) {
      return;
    }

    log.log("Performing sync with server.");
    this._syncInProgress = true;

    try {
      // First perform all pending removals. We don't want to have deleted cards
      // reappearing when we sync.
      for (let href of this._hrefsToRemove) {
        await this._deleteCardFromServer(href);
      }
      this._hrefsToRemove.clear();

      // Now update any cards that were modified while not connected to the server.
      for (let uid of this._uidsToSync) {
        let card = this.getCard(uid);
        // The card may no longer exist. It shouldn't still be listed to send,
        // but it might be.
        if (card) {
          await this._sendCardToServer(card);
        }
      }
      this._uidsToSync.clear();

      if (this._syncToken) {
        await this.updateAllFromServerV2();
      } else {
        await this.updateAllFromServerV1();
      }
    } catch (ex) {
      log.error("Sync with server failed.");
      throw ex;
    } finally {
      if (shouldResetTimer) {
        this._scheduleNextSync();
      }
      this._syncInProgress = false;
    }
  }

  /**
   * Compares cards in the directory with cards on the server, and updates the
   * directory to match what is on the server.
   */
  async updateAllFromServerV1() {
    let data = `<propfind xmlns="${PREFIX_BINDINGS.d}" ${NAMESPACE_STRING}>
      <prop>
        <resourcetype/>
        <getetag/>
        <cs:getctag/>
      </prop>
    </propfind>`;

    let response = await this._makeRequest("", {
      method: "PROPFIND",
      body: data,
      headers: {
        Depth: 1,
      },
      expectedStatuses: [207],
    });

    let hrefMap = new Map();
    for (let { href, properties } of this._readResponse(response.dom)) {
      if (
        !properties ||
        !properties.querySelector("resourcetype") ||
        properties.querySelector("resourcetype collection")
      ) {
        continue;
      }

      let etag = properties.querySelector("getetag").textContent;
      hrefMap.set(href, etag);
    }

    let cardMap = new Map();
    let hrefsToFetch = [];
    let cardsToDelete = [];
    for (let card of this.childCards) {
      let href = card.getProperty("_href", "");
      let etag = card.getProperty("_etag", "");

      if (!href || !etag) {
        // Not sure how we got here. Ignore it.
        continue;
      }
      cardMap.set(href, card);
      if (hrefMap.has(href)) {
        if (hrefMap.get(href) != etag) {
          // The card was updated on server.
          hrefsToFetch.push(href);
        }
      } else {
        // The card doesn't exist on the server.
        cardsToDelete.push(card);
      }
    }

    for (let href of hrefMap.keys()) {
      if (!cardMap.has(href)) {
        // The card is new on the server.
        hrefsToFetch.push(href);
      }
    }

    // If this directory is set to read-only, the following operations would
    // throw NS_ERROR_FAILURE, but sync operations are allowed on a read-only
    // directory, so set this._overrideReadOnly to avoid the exception.
    //
    // Do not use await while it is set, and use a try/finally block to ensure
    // it is cleared.

    if (cardsToDelete.length > 0) {
      this._overrideReadOnly = true;
      try {
        super.deleteCards(cardsToDelete);
      } finally {
        this._overrideReadOnly = false;
      }
    }

    await this._fetchAndStore(hrefsToFetch);

    log.log("Sync with server completed successfully.");
    Services.obs.notifyObservers(this, "addrbook-directory-synced");
  }

  /**
   * Retrieves the current sync token from the server.
   *
   * @see RFC 6578
   */
  async _getSyncToken() {
    log.log("Fetching new sync token");

    let data = `<propfind xmlns="${PREFIX_BINDINGS.d}" ${NAMESPACE_STRING}>
      <prop>
         <displayname/>
         <cs:getctag/>
         <sync-token/>
      </prop>
    </propfind>`;

    let response = await this._makeRequest("", {
      method: "PROPFIND",
      body: data,
      headers: {
        Depth: 0,
      },
    });

    if (response.status == 207) {
      for (let { properties } of this._readResponse(response.dom)) {
        let token = properties?.querySelector("prop sync-token");
        if (token) {
          this._syncToken = token.textContent;
          return;
        }
      }
    }

    this._syncToken = "";
  }

  /**
   * Gets a list of changes on the server since the last call to getSyncToken
   * or updateAllFromServerV2, and updates the directory to match what is on
   * the server.
   *
   * @see RFC 6578
   */
  async updateAllFromServerV2() {
    let syncToken = this._syncToken;
    if (!syncToken) {
      throw new Components.Exception("No sync token", Cr.NS_ERROR_UNEXPECTED);
    }

    let data = `<sync-collection xmlns="${
      PREFIX_BINDINGS.d
    }" ${NAMESPACE_STRING}>
      <sync-token>${xmlEncode(syncToken)}</sync-token>
      <sync-level>1</sync-level>
      <prop>
        <getetag/>
        <card:address-data/>
      </prop>
    </sync-collection>`;

    let response = await this._makeRequest("", {
      method: "REPORT",
      body: data,
      headers: {
        Depth: 1, // Only Google seems to need this.
      },
      expectedStatuses: [207, 400],
    });

    if (response.status == 400) {
      log.warn(
        `Server responded with: ${response.status} ${response.statusText}`
      );
      await this.fetchAllFromServer();
      return;
    }

    let dom = response.dom;

    // If this directory is set to read-only, the following operations would
    // throw NS_ERROR_FAILURE, but sync operations are allowed on a read-only
    // directory, so set this._overrideReadOnly to avoid the exception.
    //
    // Do not use await while it is set, and use a try/finally block to ensure
    // it is cleared.

    let hrefsToFetch = [];
    try {
      this._overrideReadOnly = true;
      let cardsToDelete = [];
      for (let { href, notFound, properties } of this._readResponse(dom)) {
        let card = this.getCardFromProperty("_href", href, true);
        if (notFound) {
          if (card) {
            cardsToDelete.push(card);
          }
          continue;
        }
        if (!properties) {
          continue;
        }

        let etag = properties.querySelector("getetag")?.textContent;
        if (!etag) {
          continue;
        }
        let vCard = properties.querySelector("address-data")?.textContent;
        if (!vCard) {
          hrefsToFetch.push(href);
          continue;
        }
        vCard = normalizeLineEndings(vCard);

        let abCard = lazy.VCardUtils.vCardToAbCard(vCard);
        abCard.setProperty("_etag", etag);
        abCard.setProperty("_href", href);

        if (card) {
          if (card.getProperty("_etag", "") != etag) {
            super.modifyCard(abCard);
          }
        } else {
          super.dropCard(abCard, false);
        }
      }

      if (cardsToDelete.length > 0) {
        super.deleteCards(cardsToDelete);
      }
    } finally {
      this._overrideReadOnly = false;
    }

    await this._fetchAndStore(hrefsToFetch);

    this._syncToken = dom.querySelector("sync-token").textContent;

    log.log("Sync with server completed successfully.");
    Services.obs.notifyObservers(this, "addrbook-directory-synced");
  }

  static forFile(fileName) {
    let directory = super.forFile(fileName);
    if (directory instanceof CardDAVDirectory) {
      return directory;
    }
    return undefined;
  }
}
CardDAVDirectory.prototype.classID = Components.ID(
  "{1fa9941a-07d5-4a6f-9673-15327fc2b9ab}"
);

/**
 * Ensure that `string` always has Windows line-endings. Some functions,
 * notably DOMParser.parseFromString, strip \r, but we want it because \r\n
 * is a part of the vCard specification.
 */
function normalizeLineEndings(string) {
  if (string.includes("\r\n")) {
    return string;
  }
  return string.replace(/\n/g, "\r\n");
}

/**
 * Encode special characters safely for XML.
 */
function xmlEncode(string) {
  return string
    .replace(/&/g, "&amp;")
    .replace(/"/g, "&quot;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;");
}