This is just some static backup of the original site, don't expect every link to work!

source: modules/vI_account.js @ 509348

ng_0.9
Last change on this file since 509348 was 509348, checked in by rene <rene@…>, 8 years ago

code formatting (no code changes)

  • Property mode set to 100644
File size: 21.3 KB
Line 
1/* ***** BEGIN LICENSE BLOCK *****
2    This program is free software; you can redistribute it and/or modify
3    it under the terms of the GNU General Public License as published by
4    the Free Software Foundation; either version 2 of the License, or
5    (at your option) any later version.
6
7    This program is distributed in the hope that it will be useful,
8    but WITHOUT ANY WARRANTY; without even the implied warranty of
9    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10    GNU General Public License for more details.
11
12    You should have received a copy of the GNU General Public License
13    along with this program; if not, write to the Free Software
14    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
15
16    The Original Code is the Virtual Identity Extension.
17
18    The Initial Developer of the Original Code is Rene Ejury.
19    Portions created by the Initial Developer are Copyright (C) 2007
20    the Initial Developer. All Rights Reserved.
21
22    Contributor(s):
23 * ***** END LICENSE BLOCK ***** */
24
25var EXPORTED_SYMBOLS = ["vIaccount_cleanupSystem", "get_vIaccount",
26  "vIaccount_prepareSendMsg", "vIaccount_finalCheck",
27  "vIaccount_createAccount", "vIaccount_removeUsedVIAccount"
28]
29
30const {
31  classes: Cc,
32  interfaces: Ci,
33  utils: Cu,
34  results: Cr
35} = Components;
36
37Cu.import("resource://gre/modules/Services.jsm");
38Cu.import("resource://v_identity/vI_log.js");
39Cu.import("resource://v_identity/vI_identityData.js");
40Cu.import("resource://v_identity/vI_rdfDatasource.js");
41Cu.import("resource://v_identity/vI_prefs.js");
42Cu.import("resource://v_identity/vI_accountUtils.js");
43
44let Log = setupLogging("virtualIdentity.account");
45
46function vIaccount_prepareSendMsg(vid, msgType, identityData, baseIdentity, recipients, currentWindow) {
47  var stringBundle = Services.strings.createBundle("chrome://v_identity/locale/v_identity.properties");
48
49  var promptService = Cc["@mozilla.org/embedcomp/prompt-service;1"]
50    .getService(Ci.nsIPromptService);
51
52  var AccountManager = Cc["@mozilla.org/messenger/account-manager;1"]
53    .getService(Ci.nsIMsgAccountManager);
54
55  Log.debug("prepareSendMsg " + msgType + " " + Ci.nsIMsgCompDeliverMode.Now);
56
57  returnValue = {};
58
59  if (msgType == Ci.nsIMsgCompDeliverMode.Now) {
60    if ((vid && vIprefs.get("warn_virtual") &&
61        !(promptService.confirm(currentWindow, "Warning",
62          stringBundle.GetStringFromName("vident.sendVirtual.warning")))) ||
63      (!vid && vIprefs.get("warn_nonvirtual") &&
64        !(promptService.confirm(currentWindow, "Warning",
65          stringBundle.GetStringFromName("vident.sendNonvirtual.warning"))))) {
66      return {
67        update: "abort",
68        storedIdentity: null
69      }; // completely abort sending
70    }
71    if (vIprefs.get("storage") && vIprefs.get("storage_store")) {
72      var localeDatasourceAccess = new rdfDatasourceAccess();
73      var returnValue = localeDatasourceAccess.storeVIdentityToAllRecipients(identityData, recipients, currentWindow)
74      if (returnValue.update == "abort" || returnValue.update == "takeover") {
75        Log.debug("prepareSendMsg: sending aborted");
76        return returnValue;
77      }
78    } else Log.debug("prepareSendMsg: storage deactivated");
79  }
80  if (vid) {
81    account.removeUsedVIAccount();
82    account.createAccount(identityData, baseIdentity);
83  }
84  return {
85    update: "accept",
86    storedIdentity: null
87  };
88};
89
90function vIaccount_finalCheck(virtualIdentityData, currentIdentity) {
91  var stringBundle = Services.strings.createBundle("chrome://v_identity/locale/v_identity.properties");
92
93  // identityData(email, fullName, id, smtp, extras, sideDescription, existingID)
94  var currentIdentityData = new identityData(currentIdentity.email, currentIdentity.fullName, null, currentIdentity.smtpServerKey, null, null, null);
95
96  Log.debug("SendMessage Final Check");
97  Log.debug("currentIdentity: fullName='" + currentIdentityData.fullName + "' email='" + currentIdentityData.email + "' smtp='" + currentIdentityData.smtp.key + "'");
98  Log.debug("virtualIdentityData: fullName='" + virtualIdentityData.fullName + "' email='" + virtualIdentityData.email + "' smtp='" + virtualIdentityData.smtp.key + "'");
99
100  if (currentIdentityData.fullName.toLowerCase() == virtualIdentityData.fullName.toLowerCase() &&
101    currentIdentityData.email.toLowerCase() == virtualIdentityData.email.toLowerCase() &&
102    virtualIdentityData.smtp.equal(currentIdentityData.smtp)) {
103    return true
104  } else {
105    if (!(currentIdentityData.fullName.toLowerCase() == virtualIdentityData.fullName.toLowerCase()))
106      Log.error("failed check for fullName.");
107    if (!(currentIdentityData.email.toLowerCase() == virtualIdentityData.email.toLowerCase()))
108      Log.error("failed check for email.");
109    if (!(virtualIdentityData.smtp.equal(currentIdentityData.smtp)))
110      Log.error("failed check for SMTP.");
111    alert(stringBundle.GetStringFromName("vident.genericSendMessage.error"));
112    return false
113  }
114};
115
116var account = {
117  _account: null,
118
119  _baseIdentity: null,
120
121  _AccountManager: Cc["@mozilla.org/messenger/account-manager;1"]
122    .getService(Ci.nsIMsgAccountManager),
123
124  _unicodeConverter: Cc["@mozilla.org/intl/scriptableunicodeconverter"]
125    .createInstance(Ci.nsIScriptableUnicodeConverter),
126
127  _copyBoolAttribute: function (name) {
128    account._account.defaultIdentity.setBoolAttribute(name,
129      account._baseIdentity.getBoolAttribute(name));
130  },
131
132  _copyIntAttribute: function (name) {
133    account._account.defaultIdentity.setIntAttribute(name,
134      account._baseIdentity.getIntAttribute(name));
135  },
136
137  _copyCharAttribute: function (name) {
138    account._account.defaultIdentity.setCharAttribute(name,
139      account._baseIdentity.getCharAttribute(name));
140  },
141
142  _copyUnicharAttribute: function (name) {
143    account._account.defaultIdentity.setUnicharAttribute(name,
144      account._baseIdentity.getUnicharAttribute(name));
145  },
146
147  _copyPreferences: function () {
148    if (vIprefs.get("copySMIMESettings")) {
149      // SMIME settings
150      Log.debug("copy S/MIME settings")
151      account._copyUnicharAttribute("signing_cert_name");
152      account._copyUnicharAttribute("encryption_cert_name");
153      account._copyIntAttribute("encryptionpolicy");
154    }
155    /*      seems not required, encryption happens before Virtual Identity account is created
156            if (vIprefs.get("copyEnigmailSettings")) {
157                // pgp/enigmail settings
158                Log.debug("copy PGP settings")
159                account._copyBoolAttribute("pgpSignEncrypted");
160                account._copyBoolAttribute("pgpSignPlain");
161                account._copyBoolAttribute("enablePgp");
162                account._copyIntAttribute("pgpKeyMode");
163                account._copyCharAttribute("pgpkeyId");
164                account._copyIntAttribute("openPgpHeaderMode");
165                account._copyCharAttribute("openPgpUrlName");
166           
167                account._copyIntAttribute("defaultEncryptionPolicy");
168            }   */
169    if (vIprefs.get("copyAttachVCardSettings")) {
170      // attach vcard
171      Log.debug("copy VCard settings")
172      account._copyBoolAttribute("attachVCard");
173      account._copyCharAttribute("escapedVCard");
174    }
175  },
176
177  // checks if directory is empty, not really used
178  // ignores files ending with *.msf, else reports if a non-zero file is found.
179  __dirEmpty: function (directory) {
180    var dirEnumerator = directory.directoryEntries;
181    while (dirEnumerator.hasMoreElements()) {
182      var maildir = dirEnumerator.getNext();
183      maildir.QueryInterface(Ci.nsIFile);
184      // recurse into all subdirectories
185      if (maildir.isDirectory() &&
186        !account.__dirEmpty(maildir)) return false;
187      // ignore files with ending "*.msf"
188      if (!maildir.path.match(new RegExp(".*\.msf$", "i")) &&
189        maildir.fileSize != 0) return false;
190    }
191    return true;
192  },
193
194  __cleanupDirectories: function () {
195    Log.debug("checking for leftover VirtualIdentity directories ...")
196
197    var file = Cc["@mozilla.org/file/directory_service;1"]
198      .getService(Ci.nsIProperties)
199      .get("ProfD", Ci.nsIFile);
200
201    var fileEnumerator = file.directoryEntries
202    while (fileEnumerator.hasMoreElements()) {
203      var dir = fileEnumerator.getNext()
204      dir.QueryInterface(Ci.nsIFile);
205      if (dir.path.match(new RegExp("[/\\\\]Mail$", "i"))) { // match Windows and Linux/Mac separators
206        var dirEnumerator = dir.directoryEntries
207        while (dirEnumerator.hasMoreElements()) {
208          var maildir = dirEnumerator.getNext()
209          maildir.QueryInterface(Ci.nsIFile);
210          // match Windows and Linux/Mac separators
211          if (maildir.path.match(new RegExp("[/\\\\]virtualIdentity.*$", "i"))) {
212            // should be empty, VirtualIdentity never uses those directories
213            if (account.__dirEmpty(maildir)) {
214              try {
215                maildir.remove(true)
216              } catch (e) {}
217            }
218          }
219        }
220      }
221    }
222    Log.debug("done.")
223  },
224
225  cleanupSystem: function () {
226    Log.debug("checking for leftover VirtualIdentity accounts ...")
227    var accounts = getAccountsArray();
228
229    for (let acc = 0; acc < accounts.length; acc++) {
230      let checkAccount = accounts[acc];
231      if (account.__isVIdentityAccount(checkAccount)) {
232        account.__removeAccount(checkAccount);
233      }
234      // replace account with key, required for next check
235      accounts[acc] = accounts[acc].key;
236    }
237
238    //      account-prefs are not removed, grrrr --> https://bugzilla.mozilla.org/show_bug.cgi?id=875675
239    //  compare against all accounts, getAccountsArray() does not include 'smart mailboxes' == 'unified folders'
240    var all_accounts = prefroot.getCharPref("mail.accountmanager.accounts").split(",");
241    try {
242      var lastAccountKey = prefroot.getIntPref("mail.account.lastKey");
243      for (let key = 0; key <= lastAccountKey; key++) {
244        if (all_accounts.indexOf("account" + key) > -1) continue;
245        account.__removeAccountPrefs("account" + key);
246      }
247    } catch (e) {};
248    Log.debug("done.")
249    account.__cleanupDirectories();
250  },
251
252  __isVIdentityAccount: function (checkAccount) {
253    // check for new (post0.5.0) accounts,
254    try {
255      prefroot.getBoolPref("mail.account." + checkAccount.key + ".vIdentity");
256      return true;
257    } catch (e) {};
258    // check for old (pre 0.5.0) accounts
259    if (checkAccount.incomingServer && checkAccount.incomingServer.hostName == "virtualIdentity") return true;
260    return false;
261  },
262
263  __removeAccountPrefs: function (key) {
264    // remove the additional tagging-pref
265    try {
266      prefroot.clearUserPref("mail.account." + key + ".vIdentity");
267    } catch (e) {};
268    try {
269      // account-prefs are not removed, grrrr --> https://bugzilla.mozilla.org/show_bug.cgi?id=875675
270      prefroot.clearUserPref("mail.account." + key + ".server");
271    } catch (e) {};
272    try {
273      // account-prefs are not removed, grrrr --> https://bugzilla.mozilla.org/show_bug.cgi?id=875675
274      prefroot.clearUserPref("mail.account." + key + ".identities");
275    } catch (e) {};
276  },
277
278  __removeAccount: function (checkAccount) {
279    Log.debug("__removeAccount")
280      // in new (post 0.5.0) Virtual Identity accounts the incomingServer of the account
281      // points to an incoming server of a different account. Cause the internal
282      // removeAccount function tries to removes the incomingServer ether, create
283      // a real one before calling this function.
284    if (!checkAccount.incomingServer || checkAccount.incomingServer.hostName != "virtualIdentity") {
285      // if not some of the 'old' accounts
286      checkAccount.incomingServer = account._AccountManager.
287      createIncomingServer("toRemove", "virtualIdentity", "pop3");
288    }
289
290    // remove the rootFolder of the account
291    try {
292      checkAccount.incomingServer.rootFolder.Delete();
293    } catch (e) {};
294
295    var key = checkAccount.key;
296    Log.debug("removing account " + key)
297      // remove the account
298    account._AccountManager.removeAccount(checkAccount);
299
300    // prevent useless increasing of lastKey https://bugzilla.mozilla.org/show_bug.cgi?id=485839
301    try {
302      var lastAccountKey = prefroot.getIntPref("mail.account.lastKey");
303      if ("account" + lastAccountKey == key)
304        prefroot.setIntPref("mail.account.lastKey", lastAccountKey - 1);
305    } catch (e) {};
306
307    account.__removeAccountPrefs(key);
308  },
309
310  removeUsedVIAccount: function () {
311    var mailWindow = Cc["@mozilla.org/appshell/window-mediator;1"].getService()
312      .QueryInterface(Ci.nsIWindowMediator)
313      .getMostRecentWindow("mail:3pane");
314    if (mailWindow) { // it's not sure that we have an open 3-pane-window
315      var selectedFolder = (mailWindow.gFolderTreeView) ? mailWindow.gFolderTreeView.getSelectedFolders()[0] : null;
316      var selectedMessages = (mailWindow.gFolderDisplay) ? mailWindow.gFolderDisplay.selectedMessages : null;
317    }
318    if (account._account) {
319      account.__removeAccount(account._account);
320      account._account = null;
321      try {
322        if (selectedFolder) mailWindow.gFolderTreeView.selectFolder(selectedFolder);
323        if (selectedMessages) mailWindow.gFolderDisplay.selectMessages(selectedMessages, false, false);
324      } catch (e) {};
325    }
326  },
327
328  createAccount: function (identityData, baseIdentity) {
329    if (account._account) { // if the Account is still created, then leave all like it is
330      alert("account still created, shouldn't happen");
331      return;
332    }
333    account._baseIdentity = baseIdentity;
334    /*
335        // the easiest way would be to get all requiered Attributes might be to duplicate the default account like this
336        var recentAccount = account._AccountManager.getAccount(vI.main.elements.Obj_MsgIdentity.selectedItem.getAttribute("accountkey"));
337        vI.main.VIdent_Account = account._AccountManager.duplicateAccount(recentAccount);
338        // but this ends up in the following exception:
339        // "Component returned failure code: 0x80004001 (NS_ERROR_NOT_IMPLEMENTED) [nsIMsg_AccountManager.duplicateAccount]"
340        // so I have to do this by hand ;(
341        */
342
343    account._account = account._AccountManager.createAccount();
344    prefroot.setBoolPref("mail.account." + account._account.key + ".vIdentity", true)
345    account._account.addIdentity(account._AccountManager.createIdentity());
346
347    Log.debug("createAccount create Identity based on baseIdentity (" + baseIdentity.key + ") " + baseIdentity.fullName + " <" + baseIdentity.email + ">");
348    // the new account uses the same incomingServer than the base one,
349    // it's especially required for NNTP cause incomingServer is used for sending newsposts.
350    // by pointing to the same incomingServer stored passwords can be reused
351    // the incomingServer has to be replaced before the account is removed, else it get removed ether
352    if (typeof (this._AccountManager.getServersForIdentity) == 'function') { // new style
353      var servers = this._AccountManager.getServersForIdentity(baseIdentity);
354    } else {
355      var servers = this._AccountManager.GetServersForIdentity(baseIdentity);
356    }
357    try {
358      if (typeof (this._AccountManager.getServersForIdentity) == 'function') { // new style
359        var server = servers.queryElementAt(0, Ci.nsIMsgIncomingServer);
360      } else {
361        var server = servers.QueryElementAt(0, Ci.nsIMsgIncomingServer);
362      }
363    } catch (NS_ERROR_FAILURE) {
364      Log.debug("createAccount missing incomingServer for baseIdentity, using default one");
365      var server = account._AccountManager.defaultAccount.incomingServer;
366    }
367    // we mark the server as invalid so that the account manager won't
368    // tell RDF about the new server - we don't need this server for long
369    // but we should restore it, because it's actually the same server as the one of the base identity
370    server.valid = false;
371    account._account.incomingServer = server;
372    server.valid = true;
373    account._copyIdentityData(identityData, baseIdentity);
374    account._copyPreferences();
375    account._unicodeConverter.charset = "UTF-8";
376    account._setupFcc();
377    account._setupDraft();
378    account._setupTemplates();
379  },
380
381  _copyIdentityData: function (identityData, baseIdentity) {
382    account._account.defaultIdentity.setCharAttribute("useremail", identityData.email);
383    account._account.defaultIdentity.setUnicharAttribute("fullName", identityData.fullName);
384
385    account._account.defaultIdentity.smtpServerKey = identityData.smtp.keyNice; // key with "" for vI.DEFAULT_SMTP_TAG
386    if (account._account.defaultIdentity.smtpServerKey == NO_SMTP_TAG)
387      account._account.defaultIdentity.smtpServerKey = baseIdentity.smtpServerKey;
388
389    Log.debug("Stored virtualIdentity (name " + account._account.defaultIdentity.fullName + " email " + account._account.defaultIdentity.email + " smtp " + account._account.defaultIdentity.smtpServerKey + ")");
390  },
391
392  _setupFcc: function () {
393    if (vIprefs.get("doFcc")) {
394      switch (vIprefs.get("fccFolderPickerMode")) {
395      case "2":
396        Log.debug("preparing Fcc --- use Settings of Default Account");
397        account._account.defaultIdentity.doFcc = account._AccountManager.defaultAccount.defaultIdentity.doFcc;
398        account._account.defaultIdentity.fccFolder = account._AccountManager.defaultAccount.defaultIdentity.fccFolder;
399        account._account.defaultIdentity.fccFolderPickerMode = account._AccountManager.defaultAccount.defaultIdentity.fccFolderPickerMode;
400        account._account.defaultIdentity.fccReplyFollowsParent = account._AccountManager.defaultAccount.defaultIdentity.fccReplyFollowsParent;
401        break;
402      case "3":
403        Log.debug("preparing Fcc --- use Settings of Modified Account");
404        account._account.defaultIdentity.doFcc = account._baseIdentity.doFcc;
405        account._account.defaultIdentity.fccFolder = account._baseIdentity.fccFolder;
406        account._account.defaultIdentity.fccFolderPickerMode = account._baseIdentity.fccFolderPickerMode;
407        account._account.defaultIdentity.fccReplyFollowsParent = account._baseIdentity.fccReplyFollowsParent;
408        break;
409      default:
410        Log.debug("preparing Fcc --- use Virtual Identity Settings");
411        account._account.defaultIdentity.doFcc = vIprefs.get("doFcc");
412        account._account.defaultIdentity.fccFolder = account._unicodeConverter.ConvertToUnicode(vIprefs.get("fccFolder"));
413        account._account.defaultIdentity.fccFolderPickerMode = vIprefs.get("fccFolderPickerMode");
414        account._account.defaultIdentity.fccReplyFollowsParent = vIprefs.get("fccReplyFollowsParent");
415
416        break;
417      }
418    } else {
419      dump("dont performing Fcc\n");
420      account._account.defaultIdentity.doFcc = false;
421    }
422    Log.debug("Stored (doFcc " + account._account.defaultIdentity.doFcc + " fccFolder " +
423      account._account.defaultIdentity.fccFolder + " fccFolderPickerMode " +
424      account._account.defaultIdentity.fccFolderPickerMode + "(" +
425      vIprefs.get("fccFolderPickerMode") + "))");
426  },
427
428  _setupDraft: function () {
429    switch (vIprefs.get("draftFolderPickerMode")) {
430    case "2":
431      Log.debug("preparing Draft --- use Settings of Default Account");
432      account._account.defaultIdentity.draftFolder = account._AccountManager.defaultAccount.defaultIdentity.draftFolder;
433      account._account.defaultIdentity.draftsFolderPickerMode = account._AccountManager.defaultAccount.defaultIdentity.draftsFolderPickerMode;
434      break;
435    case "3":
436      Log.debug("preparing Draft --- use Settings of Modified Account");
437      account._account.defaultIdentity.draftFolder = account._baseIdentity.draftFolder;
438      account._account.defaultIdentity.draftsFolderPickerMode = account._baseIdentity.draftsFolderPickerMode;
439      break;
440    default:
441      Log.debug("preparing Draft --- use Virtual Identity Settings");
442      account._account.defaultIdentity.draftFolder = account._unicodeConverter.ConvertToUnicode(vIprefs.get("draftFolder"));
443      account._account.defaultIdentity.draftsFolderPickerMode = vIprefs.get("draftFolderPickerMode");
444      break;
445    }
446    Log.debug("Stored (draftFolder " +
447      account._account.defaultIdentity.draftFolder + " draftsFolderPickerMode " +
448      account._account.defaultIdentity.draftsFolderPickerMode + "(" +
449      vIprefs.get("draftFolderPickerMode") + "))");
450  },
451
452  _setupTemplates: function () {
453    switch (vIprefs.get("stationeryFolderPickerMode")) {
454    case "2":
455      Log.debug("preparing Templates --- use Settings of Default Account");
456      account._account.defaultIdentity.stationeryFolder = account._AccountManager.defaultAccount.defaultIdentity.stationeryFolder;
457      account._account.defaultIdentity.tmplFolderPickerMode = account._AccountManager.defaultAccount.defaultIdentity.tmplFolderPickerMode;
458      break;
459    case "3":
460      Log.debug("preparing Templates --- use Settings of Modified Account");
461      account._account.defaultIdentity.stationeryFolder = account._baseIdentity.stationeryFolder;
462      account._account.defaultIdentity.tmplFolderPickerMode = account._baseIdentity.tmplFolderPickerMode;
463      break;
464    default:
465      Log.debug("preparing Templates --- use Virtual Identity Settings");
466      account._account.defaultIdentity.stationeryFolder = account._unicodeConverter.ConvertToUnicode(vIprefs.get("stationeryFolder"));
467      account._account.defaultIdentity.tmplFolderPickerMode = vIprefs.get("stationeryFolderPickerMode");
468      break;
469    }
470    Log.debug("Stored (stationeryFolder " +
471      account._account.defaultIdentity.stationeryFolder + " tmplFolderPickerMode " +
472      account._account.defaultIdentity.tmplFolderPickerMode + "(" +
473      vIprefs.get("stationeryFolderPickerMode") + "))");
474  }
475}
476
477function get_vIaccount() {
478  return account._account;
479};
480var vIaccount_cleanupSystem = account.cleanupSystem;
481var vIaccount_createAccount = account.createAccount;
482var vIaccount_removeUsedVIAccount = account.removeUsedVIAccount;
Note: See TracBrowser for help on using the repository browser.