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

source: modules/vI_account.js @ 3c9c29

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

bugfix for unified folder view - increasing prefs.js

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