summaryrefslogtreecommitdiffstats
path: root/comm/mailnews/addrbook/prefs/content/pref-directory-add.js
blob: 23bee12a0ef640140c0f653c33f70533a645f96b (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
/* -*- Mode: JavaScript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */

var { MailServices } = ChromeUtils.import(
  "resource:///modules/MailServices.jsm"
);
var { isLegalHostNameOrIP, cleanUpHostName } = ChromeUtils.import(
  "resource:///modules/hostnameUtils.jsm"
);

var gCurrentDirectory = null;
var gReplicationBundle = null;
var gReplicationService = Cc[
  "@mozilla.org/addressbook/ldap-replication-service;1"
].getService(Ci.nsIAbLDAPReplicationService);
var gReplicationCancelled = false;
var gProgressText;
var gProgressMeter;
var gDownloadInProgress = false;

var kDefaultLDAPPort = 389;
var kDefaultSecureLDAPPort = 636;

window.addEventListener("DOMContentLoaded", Startup);
window.addEventListener("unload", onUnload);
document.addEventListener("dialogaccept", onAccept);
document.addEventListener("dialogcancel", onCancel);

var ldapOfflineObserver = {
  observe(subject, topic, state) {
    // sanity checks
    if (topic != "network:offline-status-changed") {
      return;
    }
    setDownloadOfflineOnlineState(state == "offline");
  },
};

function Startup() {
  gReplicationBundle = document.getElementById("bundle_replication");

  document.getElementById("download").label =
    gReplicationBundle.getString("downloadButton");
  document.getElementById("download").accessKey = gReplicationBundle.getString(
    "downloadButton.accesskey"
  );

  if (
    "arguments" in window &&
    window.arguments[0] &&
    window.arguments[0].selectedDirectory
  ) {
    gCurrentDirectory = window.arguments[0].selectedDirectory;
    try {
      fillSettings();
    } catch (ex) {
      dump(
        "pref-directory-add.js:Startup(): fillSettings() exception: " +
          ex +
          "\n"
      );
    }

    let oldListName = gCurrentDirectory.dirName;
    document.title = gReplicationBundle.getFormattedString(
      "directoryTitleEdit",
      [oldListName]
    );

    // Only set up the download button for online/offline status toggling
    // if the pref isn't locked to disable the button.
    if (
      !Services.prefs.prefIsLocked(
        gCurrentDirectory.dirPrefId + ".disable_button_download"
      )
    ) {
      // Now connect to the offline/online observer
      Services.obs.addObserver(
        ldapOfflineObserver,
        "network:offline-status-changed"
      );

      // Now set the initial offline/online state and update the state
      setDownloadOfflineOnlineState(Services.io.offline);
    }
  } else {
    document.title = gReplicationBundle.getString("directoryTitleNew");
    fillDefaultSettings();
    // Don't add observer here as it doesn't make any sense.
  }
}

function onUnload() {
  if (
    "arguments" in window &&
    window.arguments[0] &&
    window.arguments[0].selectedDirectory &&
    !Services.prefs.prefIsLocked(
      gCurrentDirectory.dirPrefId + ".disable_button_download"
    )
  ) {
    // Remove the observer that we put in on dialog startup
    Services.obs.removeObserver(
      ldapOfflineObserver,
      "network:offline-status-changed"
    );
  }
}

var progressListener = {
  onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) {
    if (aStateFlags & Ci.nsIWebProgressListener.STATE_START) {
      // start the spinning
      gProgressMeter.removeAttribute("value");
      gProgressText.value = gReplicationBundle.getString(
        aStatus ? "replicationStarted" : "changesStarted"
      );
      gDownloadInProgress = true;
      document.getElementById("download").label = gReplicationBundle.getString(
        "cancelDownloadButton"
      );
      document.getElementById("download").accessKey =
        gReplicationBundle.getString("cancelDownloadButton.accesskey");
    }

    if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) {
      EndDownload(aStatus);
    }
  },
  onProgressChange(
    aWebProgress,
    aRequest,
    aCurSelfProgress,
    aMaxSelfProgress,
    aCurTotalProgress,
    aMaxTotalProgress
  ) {
    gProgressText.value = gReplicationBundle.getFormattedString(
      "currentCount",
      [aCurSelfProgress]
    );
  },
  onLocationChange(aWebProgress, aRequest, aLocation, aFlags) {},
  onStatusChange(aWebProgress, aRequest, aStatus, aMessage) {},
  onSecurityChange(aWebProgress, aRequest, state) {},
  onContentBlockingEvent(aWebProgress, aRequest, aEvent) {},
  QueryInterface: ChromeUtils.generateQI([
    "nsIWebProgressListener",
    "nsISupportsWeakReference",
  ]),
};

function DownloadNow() {
  if (!gDownloadInProgress) {
    gProgressText = document.getElementById("replicationProgressText");
    gProgressMeter = document.getElementById("replicationProgressMeter");

    gProgressText.hidden = false;
    gProgressMeter.hidden = false;
    gReplicationCancelled = false;

    try {
      if (gCurrentDirectory instanceof Ci.nsIAbLDAPDirectory) {
        gReplicationService.startReplication(
          gCurrentDirectory,
          progressListener
        );
      } else {
        EndDownload(Cr.NS_ERROR_FAILURE);
      }
    } catch (ex) {
      EndDownload(Cr.NS_ERROR_FAILURE);
    }
  } else {
    gReplicationCancelled = true;
    try {
      gReplicationService.cancelReplication(gCurrentDirectory);
    } catch (ex) {
      // XXX todo
      // perhaps replication hasn't started yet?  This can happen if you hit cancel after attempting to replication when offline
      dump("unexpected failure while cancelling.  ex=" + ex + "\n");
    }
  }
}

function EndDownload(aStatus) {
  document.getElementById("download").label =
    gReplicationBundle.getString("downloadButton");
  document.getElementById("download").accessKey = gReplicationBundle.getString(
    "downloadButton.accesskey"
  );

  // stop the spinning
  gProgressMeter.value = 100;
  gProgressMeter.hidden = true;

  gDownloadInProgress = false;
  if (Components.isSuccessCode(aStatus)) {
    gProgressText.value = gReplicationBundle.getString("replicationSucceeded");
  } else if (gReplicationCancelled) {
    gProgressText.value = gReplicationBundle.getString("replicationCancelled");
  } else {
    gProgressText.value = gReplicationBundle.getString("replicationFailed");
  }
}

// fill the settings panel with the data from the preferences.
//
function fillSettings() {
  document.getElementById("description").value = gCurrentDirectory.dirName;

  if (gCurrentDirectory instanceof Ci.nsIAbLDAPDirectory) {
    var ldapUrl = gCurrentDirectory.lDAPURL;

    document.getElementById("results").value = gCurrentDirectory.maxHits;
    document.getElementById("login").value = gCurrentDirectory.authDn;
    document.getElementById("hostname").value = ldapUrl.host;
    document.getElementById("basedn").value = ldapUrl.dn;
    document.getElementById("search").value = ldapUrl.filter;

    var sub = document.getElementById("sub");
    switch (ldapUrl.scope) {
      case Ci.nsILDAPURL.SCOPE_ONELEVEL:
        sub.radioGroup.selectedItem = document.getElementById("one");
        break;
      default:
        sub.radioGroup.selectedItem = sub;
        break;
    }

    var sasl = document.getElementById("saslMechanism");
    switch (gCurrentDirectory.saslMechanism) {
      case "GSSAPI":
        sasl.selectedItem = document.getElementById("GSSAPI");
        break;
      default:
        sasl.selectedItem = document.getElementById("Simple");
        break;
    }

    var secure = ldapUrl.options & ldapUrl.OPT_SECURE;
    if (secure) {
      document.getElementById("secure").setAttribute("checked", "true");
    }

    if (ldapUrl.port == -1) {
      document.getElementById("port").value = secure
        ? kDefaultSecureLDAPPort
        : kDefaultLDAPPort;
    } else {
      document.getElementById("port").value = ldapUrl.port;
    }
  }

  // check if any of the preferences for this server are locked.
  // If they are locked disable them
  DisableUriFields(gCurrentDirectory.dirPrefId + ".uri");
  DisableElementIfPrefIsLocked(
    gCurrentDirectory.dirPrefId + ".description",
    "description"
  );
  DisableElementIfPrefIsLocked(
    gCurrentDirectory.dirPrefId + ".disable_button_download",
    "download"
  );
  DisableElementIfPrefIsLocked(
    gCurrentDirectory.dirPrefId + ".maxHits",
    "results"
  );
  DisableElementIfPrefIsLocked(
    gCurrentDirectory.dirPrefId + ".auth.dn",
    "login"
  );
}

function DisableElementIfPrefIsLocked(aPrefName, aElementId) {
  if (Services.prefs.prefIsLocked(aPrefName)) {
    document.getElementById(aElementId).setAttribute("disabled", true);
  }
}

// disables all the text fields corresponding to the .uri pref.
function DisableUriFields(aPrefName) {
  if (Services.prefs.prefIsLocked(aPrefName)) {
    let lockedElements = document.querySelectorAll('[disableiflocked="true"]');
    for (let i = 0; i < lockedElements.length; i++) {
      lockedElements[i].setAttribute("disabled", "true");
    }
  }
}

function onSecure() {
  document.getElementById("port").value = document.getElementById("secure")
    .checked
    ? kDefaultSecureLDAPPort
    : kDefaultLDAPPort;
}

function fillDefaultSettings() {
  document.getElementById("port").value = kDefaultLDAPPort;
  var sub = document.getElementById("sub");
  sub.radioGroup.selectedItem = sub;

  // Disable the download button and add some text indicating why.
  document.getElementById("download").disabled = true;
  document.getElementById("downloadWarningMsg").hidden = false;
  document.getElementById("downloadWarningMsg").textContent = document
    .getElementById("bundle_addressBook")
    .getString("abReplicationSaveSettings");
}

function hasCharacters(number) {
  var re = /[0-9]/g;
  var num = number.match(re);
  if (num && num.length == number.length) {
    return false;
  }
  return true;
}

function onAccept(event) {
  try {
    let description = document.getElementById("description").value.trim();
    let hostname = cleanUpHostName(document.getElementById("hostname").value);
    let port = document.getElementById("port").value;
    let secure = document.getElementById("secure");
    let results = document.getElementById("results").value;
    let errorValue = null;
    let errorArg = null;
    let saslMechanism = "";

    let findDupeName = function (newName) {
      // Do not allow an already existing name.
      for (let ab of MailServices.ab.directories) {
        if (
          ab.dirName.toLowerCase() == newName.toLowerCase() &&
          (!gCurrentDirectory || ab.URI != gCurrentDirectory.URI)
        ) {
          return ab.dirName;
        }
      }
      return null;
    };

    if (!description) {
      errorValue = "invalidName";
    } else if ((errorArg = findDupeName(description))) {
      errorValue = "duplicateNameText";
    } else if (!isLegalHostNameOrIP(hostname)) {
      errorValue = "invalidHostname";
    } else if (port && hasCharacters(port)) {
      // XXX write isValidDn and call it on the dn string here?
      errorValue = "invalidPortNumber";
    } else if (results && hasCharacters(results)) {
      errorValue = "invalidResults";
    }

    if (!errorValue) {
      if (!port) {
        port = secure.checked ? kDefaultSecureLDAPPort : kDefaultLDAPPort;
      }
      if (hostname.includes(":")) {
        // Wrap IPv6 address in [].
        hostname = `[${hostname}]`;
      }
      let ldapUrl = Services.io
        .newURI(`${secure.checked ? "ldaps" : "ldap"}://${hostname}:${port}`)
        .QueryInterface(Ci.nsILDAPURL);

      ldapUrl.dn = document.getElementById("basedn").value;
      ldapUrl.scope = document.getElementById("one").selected
        ? Ci.nsILDAPURL.SCOPE_ONELEVEL
        : Ci.nsILDAPURL.SCOPE_SUBTREE;

      ldapUrl.filter = document.getElementById("search").value;
      if (document.getElementById("GSSAPI").selected) {
        saslMechanism = "GSSAPI";
      }

      // check if we are modifying an existing directory or adding a new directory
      if (gCurrentDirectory) {
        gCurrentDirectory.dirName = description;
        gCurrentDirectory.lDAPURL = ldapUrl;
        window.opener.gNewServerString = gCurrentDirectory.dirPrefId;
      } else {
        // adding a new directory
        window.opener.gNewServerString = MailServices.ab.newAddressBook(
          description,
          ldapUrl.spec,
          Ci.nsIAbManager.LDAP_DIRECTORY_TYPE
        );
      }

      // XXX This is really annoying - both new/modify Address Book don't
      // give us back the new directory we just created - so go find it from
      // rdf so we can set a few final things up on it.
      var targetURI = "moz-abldapdirectory://" + window.opener.gNewServerString;
      var theDirectory = MailServices.ab
        .getDirectory(targetURI)
        .QueryInterface(Ci.nsIAbLDAPDirectory);

      theDirectory.maxHits = results;
      theDirectory.authDn = document.getElementById("login").value;
      theDirectory.saslMechanism = saslMechanism;

      window.opener.gNewServer = description;
      // set window.opener.gUpdate to true so that LDAP Directory Servers
      // dialog gets updated
      window.opener.gUpdate = true;
      window.arguments[0].newDirectoryUID = theDirectory.UID;
      if ("onNewDirectory" in window.arguments[0]) {
        window.arguments[0].onNewDirectory(theDirectory);
      }
    } else {
      let addressBookBundle = document.getElementById("bundle_addressBook");

      let errorText;
      if (errorArg) {
        errorText = addressBookBundle.getFormattedString(errorValue, [
          errorArg,
        ]);
      } else {
        errorText = addressBookBundle.getString(errorValue);
      }

      Services.prompt.alert(window, document.title, errorText);
      event.preventDefault();
      return;
    }
  } catch (outer) {
    console.error(
      "Internal error in pref-directory-add.js:onAccept() " + outer
    );
  }
}

function onCancel() {
  window.opener.gUpdate = false;
}

// Sets the download button state for offline or online.
// This function should only be called for ldap edit dialogs.
function setDownloadOfflineOnlineState(isOffline) {
  if (isOffline) {
    // Disable the download button and add some text indicating why.
    document.getElementById("downloadWarningMsg").textContent = document
      .getElementById("bundle_addressBook")
      .getString("abReplicationOfflineWarning");
  }
  document.getElementById("downloadWarningMsg").hidden = !isOffline;
  document.getElementById("download").disabled = isOffline;
}