summaryrefslogtreecommitdiffstats
path: root/comm/mailnews/import/modules/AddrBookFileImporter.jsm
blob: c9cea94893ca20810ee190ee15845e7fdc70b171 (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
/* 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 = ["AddrBookFileImporter"];

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

const lazy = {};

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

XPCOMUtils.defineLazyModuleGetters(lazy, {
  MailStringUtils: "resource:///modules/MailStringUtils.jsm",
  exportAttributes: "resource:///modules/AddrBookUtils.jsm",
});

XPCOMUtils.defineLazyGetter(lazy, "d3", () => {
  let d3Scope = Cu.Sandbox(null);
  Services.scriptloader.loadSubScript(
    "chrome://global/content/third_party/d3/d3.js",
    d3Scope
  );
  return Cu.waiveXrays(d3Scope.d3);
});

/**
 * A module to import address book files.
 */
class AddrBookFileImporter {
  /**
   * @param {string} type - Source file type, currently supporting "csv",
   *   "ldif", "vcard" and "mab".
   */
  constructor(type) {
    this._type = type;
  }

  /**
   * Callback for progress updates.
   *
   * @param {number} current - Current imported items count.
   * @param {number} total - Total items count.
   */
  onProgress = () => {};

  _logger = console.createInstance({
    prefix: "mail.import",
    maxLogLevel: "Warn",
    maxLogLevelPref: "mail.import.loglevel",
  });

  /**
   * Actually start importing records into a directory.
   *
   * @param {nsIFile} sourceFile - The source file to import from.
   * @param {nsIAbDirectory} targetDirectory - The directory to import into.
   */
  async startImport(sourceFile, targetDirectory) {
    this._logger.debug(
      `Importing ${this._type} file from ${sourceFile.path} into ${targetDirectory.dirName}`
    );
    this._sourceFile = sourceFile;
    this._targetDirectory = targetDirectory;

    switch (this._type) {
      case "csv":
        await this._importCsvFile();
        break;
      case "ldif":
        await this._importLdifFile();
        break;
      case "vcard":
        await this._importVCardFile();
        break;
      case "sqlite":
        await this._importSqliteFile();
        break;
      case "mab":
        await this._importMabFile();
        break;
      default:
        throw Components.Exception(
          `Importing ${this._type} file is not supported`,
          Cr.NS_ERROR_NOT_IMPLEMENTED
        );
    }
  }

  /**
   * Parse a CSV/TSV file to an array of rows, each row is an array of columns.
   * The first row is expected to contain field names. If we recognize all the
   * field names, return an empty array, which means everything is parsed fine.
   * Otherwise, return all the rows.
   *
   * @param {nsIFile} sourceFile - The source file to import from.
   * @returns {string[][]}
   */
  async parseCsvFile(sourceFile) {
    let content = await lazy.MailStringUtils.readEncoded(sourceFile.path);

    let csvRows = lazy.d3.csv.parseRows(content);
    let tsvRows = lazy.d3.tsv.parseRows(content);
    let dsvRows = lazy.d3.dsv(";").parseRows(content);
    if (!csvRows.length && !tsvRows.length && !dsvRows.length) {
      this._csvRows = [];
      return [];
    }
    // If we have more CSV columns, then it's a CSV file, otherwise a TSV file.
    this._csvRows = csvRows[0]?.length > tsvRows[0]?.length ? csvRows : tsvRows;
    // See if it's semicolon separated.
    if (this._csvRows[0]?.length < dsvRows[0]?.length) {
      this._csvRows = dsvRows;
    }

    let bundle = Services.strings.createBundle(
      "chrome://messenger/locale/importMsgs.properties"
    );
    let supportedFieldNames = [];
    this._supportedCsvProperties = [];
    // Collect field names in an exported CSV file, and their corresponding
    // nsIAbCard property names.
    for (let [property, stringId] of lazy.exportAttributes) {
      if (stringId) {
        this._supportedCsvProperties.push(property);
        supportedFieldNames.push(
          bundle.GetStringFromID(stringId).toLowerCase()
        );
      }
    }
    this._csvSkipFirstRow = true;
    this._csvProperties = [];
    // Get the nsIAbCard properties corresponding to the user supplied file.
    for (let field of this._csvRows[0]) {
      if (
        !field &&
        this._csvRows[0].length > 1 &&
        field == this._csvRows[0].at(-1)
      ) {
        // This is the last field and empty, caused by a trailing comma, which
        // is OK.
        return [];
      }
      let index = supportedFieldNames.indexOf(field.toLowerCase());
      if (index == -1) {
        return this._csvRows;
      }
      this._csvProperties.push(this._supportedCsvProperties[index]);
    }
    return [];
  }

  /**
   * Set the address book properties to use when importing.
   *
   * @param {number[]} fieldIndexes - An array of indexes representing the
   *   mapping between the source fields and nsIAbCard fields. For example, [2,
   *   4] means the first field maps to the 2nd property, the second field maps
   *   to the 4th property.
   */
  setCsvFields(fieldIndexes) {
    Services.prefs.setCharPref(
      "mail.import.csv.fields",
      fieldIndexes.join(",")
    );
    this._csvProperties = fieldIndexes.map(
      i => this._supportedCsvProperties[i]
    );
    this._csvSkipFirstRow = Services.prefs.getBoolPref(
      "mail.import.csv.skipfirstrow",
      true
    );
  }

  /**
   * Import the .csv/.tsv source file into the target directory.
   */
  async _importCsvFile() {
    let totalLines = this._csvRows.length - 1;
    let currentLine = 0;

    let startRow = this._csvSkipFirstRow ? 1 : 0;
    for (let row of this._csvRows.slice(startRow)) {
      currentLine++;
      let card = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
        Ci.nsIAbCard
      );
      for (let i = 0; i < row.length; i++) {
        let property = this._csvProperties[i];
        if (!property) {
          continue;
        }
        // Set the field value to the property.
        card.setProperty(property, row[i]);
      }
      this._targetDirectory.addCard(card);
      if (currentLine % 10 == 0) {
        this.onProgress(currentLine, totalLines);
        // Give UI a chance to update the progress bar.
        await new Promise(resolve => lazy.setTimeout(resolve));
      }
    }
    this.onProgress(totalLines, totalLines);
  }

  /**
   * Import the .ldif source file into the target directory.
   */
  async _importLdifFile() {
    this.onProgress(2, 10);
    let ldifService = Cc["@mozilla.org/addressbook/abldifservice;1"].getService(
      Ci.nsIAbLDIFService
    );
    let progress = {};
    ldifService.importLDIFFile(
      this._targetDirectory,
      this._sourceFile,
      false,
      progress
    );
    this.onProgress(10, 10);
  }

  /**
   * Import the .vcf source file into the target directory.
   */
  async _importVCardFile() {
    let vcardService = Cc[
      "@mozilla.org/addressbook/msgvcardservice;1"
    ].getService(Ci.nsIMsgVCardService);

    let content = await IOUtils.readUTF8(this._sourceFile.path);
    // According to rfc6350, \r\n should be used as line break.
    let sep = content.includes("\r\n") ? "\r\n" : "\n";
    let lines = content.trim().split(sep);

    let totalLines = lines.length;
    let currentLine = 0;
    let record = [];

    for (let line of lines) {
      currentLine++;
      if (!line) {
        continue;
      }

      if (line.toLowerCase().trimEnd() == "begin:vcard") {
        if (record.length) {
          throw Components.Exception(
            "Expecting END:VCARD but got BEGIN:VCARD",
            Cr.NS_ERROR_ILLEGAL_VALUE
          );
        }
        record.push(line);
        continue;
      } else if (!record.length) {
        throw Components.Exception(
          `Expecting BEGIN:VCARD but got ${line}`,
          Cr.NS_ERROR_ILLEGAL_VALUE
        );
      }

      record.push(line);

      if (line.toLowerCase().trimEnd() == "end:vcard") {
        this._targetDirectory.addCard(
          vcardService.vCardToAbCard(record.join("\n") + "\n")
        );
        record = [];
        this.onProgress(currentLine, totalLines);
        // Give UI a chance to update the progress bar.
        await new Promise(resolve => lazy.setTimeout(resolve));
      }
    }
    this.onProgress(totalLines, totalLines);
  }

  /**
   * Import the .sqlite source file into the target directory.
   */
  async _importSqliteFile() {
    this.onProgress(2, 10);
    // Create a temporary address book.
    let dirId = MailServices.ab.newAddressBook(
      "tmp",
      "",
      Ci.nsIAbManager.JS_DIRECTORY_TYPE
    );
    let tmpDirectory = MailServices.ab.getDirectoryFromId(dirId);

    try {
      // Close the connection to release the file handler.
      await tmpDirectory.cleanUp();
      // Overwrite the sqlite database file.
      this._sourceFile.copyTo(
        Services.dirsvc.get("ProfD", Ci.nsIFile),
        tmpDirectory.fileName
      );
      // Write-Ahead Logging file contains changes not written to .sqlite file
      // yet.
      let sourceWalFile = this._sourceFile.parent.clone();
      sourceWalFile.append(this._sourceFile.leafName + "-wal");
      if (sourceWalFile.exists()) {
        sourceWalFile.copyTo(
          Services.dirsvc.get("ProfD", Ci.nsIFile),
          tmpDirectory.fileName + "-wal"
        );
      }
      // Open a new connection to use the new database file.
      let uri = tmpDirectory.URI;
      tmpDirectory = Cc[
        "@mozilla.org/addressbook/directory;1?type=jsaddrbook"
      ].createInstance(Ci.nsIAbDirectory);
      tmpDirectory.init(uri);

      for (let card of tmpDirectory.childCards) {
        this._targetDirectory.addCard(card);
      }
      this.onProgress(8, 10);

      for (let sourceList of tmpDirectory.childNodes) {
        let targetList = this._targetDirectory.getMailListFromName(
          sourceList.dirName
        );
        if (!targetList) {
          targetList = this._targetDirectory.addMailList(sourceList);
        }
        for (let card of sourceList.childCards) {
          targetList.addCard(card);
        }
      }
      this.onProgress(10, 10);
    } finally {
      MailServices.ab.deleteAddressBook(tmpDirectory.URI);
    }
  }

  /**
   * Import the .mab source file into the target directory.
   */
  async _importMabFile() {
    this.onProgress(2, 10);
    let importMab = Cc[
      "@mozilla.org/import/import-ab-file;1?type=mab"
    ].createInstance(Ci.nsIImportABFile);
    importMab.readFileToDirectory(this._sourceFile, this._targetDirectory);
    this.onProgress(10, 10);
  }
}