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

source: modules/vI_rdfDatasource.js @ 573656

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

adaptions for missing 3pane window (if called by mailto:)

  • Property mode set to 100644
File size: 56.7 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 = ["rdfDatasource", "rdfDatasourceAccess", "rdfDatasourceImporter"]
26
27Components.utils.import("resource://v_identity/vI_log.js");
28let Log = setupLogging("virtualIdentity.rdfDatasource");
29
30Components.utils.import("resource://v_identity/vI_prefs.js");
31Components.utils.import("resource://v_identity/vI_identityData.js");
32Components.utils.import("resource://gre/modules/Services.jsm");
33
34// if no 3pane-window found, return current window
35function get3PaneWindow() {
36  var windowMediator = Components.classes['@mozilla.org/appshell/window-mediator;1']
37    .getService(Components.interfaces.nsIWindowMediator);
38  var mail3paneWindow = windowMediator.getMostRecentWindow("mail:3pane");
39  if (!mail3paneWindow) return windowMediator.getMostRecentWindow(null);
40  return mail3paneWindow;
41};
42
43function rdfDatasource(rdfFileName, dontRegisterObserver) {
44    this._rdfFileName = rdfFileName;
45    if (this._rdfFileName) this.init();
46    if (!dontRegisterObserver) this.AccountManagerObserver.register();
47    try {
48      this._extVersion = get3PaneWindow().virtualIdentityExtension.extensionVersion;
49    } catch (e) { }
50}
51
52rdfDatasource.prototype = {
53    _extVersion :       null,
54    _rdfVersion :       "0.0.5",
55    _rdfService :       Components.classes["@mozilla.org/rdf/rdf-service;1"]
56                            .getService(Components.interfaces.nsIRDFService),
57    _rdfDataSource :    null,
58    _rdfFileName :      null,
59    _rdfNS :            "http://virtual-id.absorb.it/",
60    _rdfNSStorage :     "vIStorage",
61    _rdfNSEmail :       "vIStorage/email",
62    _rdfNSMaillist :    "vIStorage/maillist",
63    _rdfNSNewsgroup :   "vIStorage/newsgroup",
64    _rdfNSFilter :      "vIStorage/filter",
65    _rdfNSAccounts :    "vIAccounts",
66    _rdfNSIdentities :  "vIAccounts/id",
67    _rdfNSSMTPservers : "vIAccounts/smtp",
68   
69    _virtualIdentityID : "{dddd428e-5ac8-4a81-9f78-276c734f75b8}",
70   
71    _emailContainer : Components.classes["@mozilla.org/rdf/container;1"]
72            .createInstance(Components.interfaces.nsIRDFContainer),
73
74    _maillistContainer : Components.classes["@mozilla.org/rdf/container;1"]
75            .createInstance(Components.interfaces.nsIRDFContainer),
76
77    _newsgroupContainer : Components.classes["@mozilla.org/rdf/container;1"]
78            .createInstance(Components.interfaces.nsIRDFContainer),
79
80    _filterContainer : Components.classes["@mozilla.org/rdf/container;1"]
81            .createInstance(Components.interfaces.nsIRDFContainer),
82
83    _identityContainer : Components.classes["@mozilla.org/rdf/container;1"]
84            .createInstance(Components.interfaces.nsIRDFContainer),
85
86    _smtpContainer : Components.classes["@mozilla.org/rdf/container;1"]
87            .createInstance(Components.interfaces.nsIRDFContainer),
88   
89    getContainer : function (type) {
90        switch (type) {
91            case "email": return this._emailContainer;
92            case "maillist": return this._maillistContainer;
93            case "newsgroup": return this._newsgroupContainer;
94            case "filter": return this._filterContainer;
95            case "identity": return this._identityContainer;
96            case "smtp": return this._smtpContainer;
97        }
98        return null;
99    },
100
101    init: function() {
102//         Log.debug("init.");
103
104        this._openRdfDataSource();
105        if (!this._rdfDataSource) return;
106        this._initContainers();
107        if (this.rdfUpgradeRequired()) this.rdfUpgrade();
108       
109        // store version everytime to recognize downgrades later
110        this.storeRDFVersion();
111           
112//         this.refreshAccountInfo();
113//         Log.debug("init done.");
114    },
115   
116    _openRdfDataSource: function() {
117//         if (!this._rdfFileName || this._rdfDataSource);
118        var protoHandler = Components.classes["@mozilla.org/network/protocol;1?name=file"]
119            .getService(Components.interfaces.nsIFileProtocolHandler)
120        var newFile = Components.classes["@mozilla.org/file/local;1"]
121                    .createInstance(Components.interfaces.nsILocalFile);
122       
123        var file = Components.classes["@mozilla.org/file/directory_service;1"]
124            .getService(Components.interfaces.nsIProperties)
125            .get("ProfD", Components.interfaces.nsIFile);
126        var delimiter = (file.path.match(/\\/))?"\\":"/";
127
128        newFile.initWithPath(file.path + delimiter + this._rdfFileName);
129        var fileURI = protoHandler.newFileURI(newFile);
130
131        Log.debug("init: read rdf from '" + fileURI.spec + "'");
132
133        this._rdfDataSource =
134            this._rdfService.GetDataSourceBlocking(fileURI.spec);
135           
136//         Log.debug("read rdf from '" + fileURI.spec + "' done." + this._rdfService);
137    },
138   
139    _initContainers: function() {
140        try {   // will possibly fail before upgrade
141            var storageRes = this._rdfService
142                .GetResource(this._rdfNS + this._rdfNSEmail);
143            this._emailContainer.Init(this._rdfDataSource, storageRes);
144            storageRes = this._rdfService
145                .GetResource(this._rdfNS + this._rdfNSMaillist);
146            this._maillistContainer.Init(this._rdfDataSource, storageRes);
147            storageRes = this._rdfService
148                .GetResource(this._rdfNS + this._rdfNSNewsgroup);
149            this._newsgroupContainer.Init(this._rdfDataSource, storageRes);
150            storageRes = this._rdfService
151                .GetResource(this._rdfNS + this._rdfNSFilter);
152            this._filterContainer.Init(this._rdfDataSource, storageRes);
153            storageRes = this._rdfService
154                .GetResource(this._rdfNS + this._rdfNSIdentities);
155            this._identityContainer.Init(this._rdfDataSource, storageRes);
156            storageRes = this._rdfService
157                .GetResource(this._rdfNS + this._rdfNSSMTPservers);
158            this._smtpContainer.Init(this._rdfDataSource, storageRes);
159        } catch (e) { };
160    },
161
162    // ******************************************************************************************
163    // **************    BEGIN RDF UPGRADE CODE    **********************************************
164    rdfUpgradeRequired: function() {
165        var oldRdfVersion = this.getCurrentRDFFileVersion();
166        var versionChecker = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
167            .getService(Components.interfaces.nsIVersionComparator);
168        return (!oldRdfVersion || versionChecker.compare(oldRdfVersion, this._rdfVersion) < 0)
169    },
170    // **************    RDF UPGRADE CODE    ****************************************************
171    extUpgradeRequired: function() {
172        if (!this._extVersion) return false;
173        var oldExtVersion = this.getCurrentExtFileVersion()
174        var versionChecker = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
175            .getService(Components.interfaces.nsIVersionComparator);
176        return (!oldExtVersion || versionChecker.compare(oldExtVersion, this._extVersion) < 0) 
177    },
178    // **************    RDF UPGRADE CODE    ****************************************************
179    rdfUpgrade : function() {
180        var currentVersion = this.getCurrentRDFFileVersion();
181        Log.debug("checking for previous version of rdf, found " + 
182            currentVersion + " - rdf-upgrade required.")
183        switch (currentVersion) {
184            case null:
185            case "0.0.1":
186            case "0.0.2":
187                this._createRDFContainers(); // no break
188            case "0.0.3":
189                this._tagDefaultSMTP();
190            case "0.0.4":
191            default:
192                this._createAccountInfoContainers();
193        }
194        this.storeRDFVersion();
195        Log.debug("rdf-upgrade to " + this.getCurrentRDFFileVersion() + " done.");
196    },
197    // **************    RDF UPGRADE CODE    ****************************************************
198    // only used for upgrade to 0.0.3 - loop through all ressources.
199    _transferAllResources : function () {
200        Log.debug("upgrade: transferAllResources");
201        var enumerator = this._rdfDataSource.GetAllResources();
202        while (enumerator && enumerator.hasMoreElements()) {
203            var resource = enumerator.getNext();
204            resource.QueryInterface(Components.interfaces.nsIRDFResource);
205           
206            var type; var name;
207            if (resource.ValueUTF8.match(new RegExp(this._rdfNS + this._rdfNSEmail + "/", "i")))
208                { type = "email"; name = RegExp.rightContext }
209            else if (resource.ValueUTF8.match(new RegExp(this._rdfNS + this._rdfNSNewsgroup + "/", "i")))
210                { type = "newsgroup"; name = RegExp.rightContext }
211            else if (resource.ValueUTF8.match(new RegExp(this._rdfNS + this._rdfNSMaillist + "/", "i")))
212                { type = "maillist"; name = RegExp.rightContext }
213            else continue;
214           
215            var container = this.getContainer(type);
216            this._setRDFValue(resource, "name", name);
217           
218            if (container.IndexOf(resource) == -1) container.AppendElement(resource);
219        }
220    },
221    // **************    RDF UPGRADE CODE    ****************************************************
222    _tagDefaultSMTP: function() {
223        Log.debug("upgrade: tagDefaultSMTP");
224        for each (let treeType in Array("email", "maillist", "newsgroup", "filter")) {
225            var enumerator = this.getContainer(treeType).GetElements();
226            while (enumerator && enumerator.hasMoreElements()) {
227                var resource = enumerator.getNext();
228                resource.QueryInterface(Components.interfaces.nsIRDFResource);
229                var smtp = this._getRDFValue(resource, "smtp")
230                if (!smtp || smtp == "") this._setRDFValue(resource, "smtp", DEFAULT_SMTP_TAG);
231            }
232        }
233    },
234    // **************    RDF UPGRADE CODE    ****************************************************
235    _createAccountInfoContainers: function() {
236        Log.debug("upgrade: createAccountInfoContainers");
237        var rdfContainerUtils = Components.classes["@mozilla.org/rdf/container-utils;1"].
238            getService(Components.interfaces.nsIRDFContainerUtils);
239       
240        var accountRes = this._rdfService
241            .GetResource(this._rdfNS + this._rdfNSAccounts);
242        var identityRes = this._rdfService
243            .GetResource(this._rdfNS + this._rdfNSIdentities);
244        var smtpRes = this._rdfService
245            .GetResource(this._rdfNS + this._rdfNSSMTPservers);
246        this._setRDFValue(accountRes, "name", "Accounts");
247        this._setRDFValue(identityRes, "name", "Identities");
248        this._setRDFValue(smtpRes, "name", "SMTP-Server");
249       
250        rdfContainerUtils.MakeBag(this._rdfDataSource, accountRes);
251        rdfContainerUtils.MakeBag(this._rdfDataSource, identityRes);
252        rdfContainerUtils.MakeBag(this._rdfDataSource, smtpRes);
253
254        var accountContainer = Components.classes["@mozilla.org/rdf/container;1"].
255            createInstance(Components.interfaces.nsIRDFContainer);
256       
257        // initialize container with accountRes
258        accountContainer.Init(this._rdfDataSource, accountRes);
259        // append all new containers to accountRes
260        if (accountContainer.IndexOf(identityRes) == -1) accountContainer.AppendElement(identityRes);
261        if (accountContainer.IndexOf(smtpRes) == -1) accountContainer.AppendElement(smtpRes);
262       
263        this._initContainers();
264        this.refreshAccountInfo();
265    },
266    // **************    RDF UPGRADE CODE    ****************************************************
267    _createRDFContainers: function() {
268        Log.debug("upgrade: createRDFContainers");
269        var rdfContainerUtils = Components.classes["@mozilla.org/rdf/container-utils;1"].
270            getService(Components.interfaces.nsIRDFContainerUtils);
271
272        var storageRes = this._rdfService
273            .GetResource(this._rdfNS + this._rdfNSStorage);
274        var emailRes = this._rdfService
275            .GetResource(this._rdfNS + this._rdfNSEmail);
276        var maillistRes = this._rdfService
277            .GetResource(this._rdfNS + this._rdfNSMaillist);
278        var newsgroupRes = this._rdfService
279            .GetResource(this._rdfNS + this._rdfNSNewsgroup);
280        var filterRes = this._rdfService
281            .GetResource(this._rdfNS + this._rdfNSFilter);
282        this._setRDFValue(emailRes, "name", "E-Mail");
283        this._setRDFValue(maillistRes, "name", "Mailing-List");
284        this._setRDFValue(newsgroupRes, "name", "Newsgroup");
285        this._setRDFValue(filterRes, "name", "Filter");
286
287        rdfContainerUtils.MakeBag(this._rdfDataSource, storageRes);
288        rdfContainerUtils.MakeBag(this._rdfDataSource, emailRes);
289        rdfContainerUtils.MakeBag(this._rdfDataSource, maillistRes);
290        rdfContainerUtils.MakeBag(this._rdfDataSource, newsgroupRes);
291        // use a sequence for the filters, order does matter
292        rdfContainerUtils.MakeSeq(this._rdfDataSource, filterRes);
293       
294        var container = Components.classes["@mozilla.org/rdf/container;1"].
295            createInstance(Components.interfaces.nsIRDFContainer);
296       
297        // initialize container with storageRes
298        container.Init(this._rdfDataSource, storageRes);
299        // append all new containers to storageRes
300        if (container.IndexOf(emailRes) == -1) container.AppendElement(emailRes);
301        if (container.IndexOf(maillistRes) == -1) container.AppendElement(maillistRes);
302        if (container.IndexOf(newsgroupRes) == -1) container.AppendElement(newsgroupRes);
303        if (container.IndexOf(filterRes) == -1) container.AppendElement(filterRes);
304       
305        this._initContainers();
306       
307        this._transferAllResources();
308    },
309    // **************    END RDF UPGRADE CODE    ************************************************
310    // ******************************************************************************************
311       
312    getCurrentRDFFileVersion: function() {
313        return this._getRDFValue(
314            this._rdfService.GetResource(this._rdfNS + "virtualIdentity"), "rdfVersion");
315    },
316   
317    getCurrentExtFileVersion: function() {
318        return this._getRDFValue(
319            this._rdfService.GetResource(this._rdfNS + "virtualIdentity"), "version");
320    },
321   
322    storeRDFVersion: function() {
323        this._setRDFValue(
324            this._rdfService.GetResource(this._rdfNS + "virtualIdentity"), "rdfVersion",
325            this._rdfVersion);
326        this._flush();
327    },
328   
329    storeExtVersion: function() {
330        this._setRDFValue(
331            this._rdfService.GetResource(this._rdfNS + "virtualIdentity"), "version", this._extVersion)
332        this._flush();
333    },
334
335    clean : function() {
336        this.AccountManagerObserver.unregister();
337        this._flush();
338    },
339
340    _flush : function() {
341        this._rdfDataSource.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
342        this._rdfDataSource.Flush();
343    },
344   
345    refreshAccountInfo : function() {
346        try {   // will possibly fail before upgrade
347            this.cleanAccountInfo(); this.storeAccountInfo();
348        } catch (e) {};
349    },
350   
351    cleanAccountInfo : function() {
352        Log.debug("cleanAccountInfo");
353       
354        var enumerator = this._identityContainer.GetElements();
355        while (enumerator && enumerator.hasMoreElements()) {
356            var resource = enumerator.getNext();
357            resource.QueryInterface(Components.interfaces.nsIRDFResource);
358            this._unsetRDFValue(resource, "identityName", this._getRDFValue(resource, "identityName"))
359            this._unsetRDFValue(resource, "fullName", this._getRDFValue(resource, "fullName"))
360            this._unsetRDFValue(resource, "email", this._getRDFValue(resource, "email"))
361            this._identityContainer.RemoveElement(resource, false);
362        }
363
364        enumerator = this._smtpContainer.GetElements();
365        while (enumerator && enumerator.hasMoreElements()) {
366            var resource = enumerator.getNext();
367            resource.QueryInterface(Components.interfaces.nsIRDFResource);
368            this._unsetRDFValue(resource, "label", this._getRDFValue(resource, "label"))
369            this._unsetRDFValue(resource, "hostname", this._getRDFValue(resource, "hostname"))
370            this._unsetRDFValue(resource, "username", this._getRDFValue(resource, "username"))
371            this._smtpContainer.RemoveElement(resource, false);
372        }   
373    },
374   
375    getRelevantIDs : function() {
376        var relevantIDs = new Object();
377        // search relevant Identities
378        for each (let treeType in Array("email", "maillist", "newsgroup", "filter")) {
379            var enumerator = this.getContainer(treeType).GetElements();
380            while (enumerator && enumerator.hasMoreElements()) {
381                var resource = enumerator.getNext();
382                resource.QueryInterface(Components.interfaces.nsIRDFResource);
383                var id = this._getRDFValue(resource, "id")
384                if (id) {
385                    if (!relevantIDs[id]) relevantIDs[id] = 1; else relevantIDs[id] += 1;
386                }
387            }
388        }
389        return relevantIDs;
390    },
391   
392    searchIdentityMismatch : function() {
393        Log.debug("searchIdentityMismatch");
394
395        var relevantIDs = this.getRelevantIDs();
396        var mismatchIDs = [];
397       
398        var AccountManager = Components.classes["@mozilla.org/messenger/account-manager;1"]
399            .getService(Components.interfaces.nsIMsgAccountManager);
400        for (var id in relevantIDs) {
401            var found = false;
402            for (var i = 0; i < AccountManager.accounts.Count(); i++) {
403                var account = AccountManager.accounts.GetElementAt(i)
404                    .QueryInterface(Components.interfaces.nsIMsgAccount);
405                for (var j = 0; j < account.identities.Count(); j++) {
406                    var identity = account.identities.GetElementAt(j).QueryInterface(Components.interfaces.nsIMsgIdentity);
407                    if (id == identity.key) { found = true; break; }
408                }
409                if (found) break;
410            }
411            var resource = this._rdfService.GetResource(this._rdfNS + this._rdfNSIdentities + "/" + id);
412            var rdfIdentityName = this._getRDFValue(resource, "identityName");
413            var rdfEmail = this._getRDFValue(resource, "email");
414            var rdfFullName = this._getRDFValue(resource, "fullName")
415           
416            if ( !found || rdfIdentityName != identity.identityName && rdfEmail != identity.email)
417            mismatchIDs.push( { oldkey: id, label : rdfIdentityName, ext1: rdfEmail, ext2: rdfFullName, count: relevantIDs[id], key: "" } )
418        }
419        if (mismatchIDs.length > 0) {
420            Log.debug(" found mismatches on id(s).");
421            get3PaneWindow().openDialog("chrome://v_identity/content/vI_rdfAccountMismatchDialog.xul",0,
422                    "chrome, dialog, modal, alwaysRaised, resizable=yes", "identity", mismatchIDs,
423                    /* callback chance: */ this).focus();
424            return true;
425        }
426        else {
427            Log.debug(" found no mismatch");
428            return false;
429        }
430    },
431   
432    repairAccountMismatch : function(type, mismatchItems) {
433        var keyField = (type == "identity")?"id":"smtp" // field to change is 'id' or 'smtp' dependent on type
434        for (var i = 0; i < mismatchItems.length; i++) {
435            Log.debug("repairAccountMismatch change " + mismatchItems[i].oldkey + " into " + mismatchItems[i].key);
436            // search relevant Identities
437            for each (let treeType in Array("email", "maillist", "newsgroup", "filter")) {
438                var enumerator = this.getContainer(treeType).GetElements();
439                while (enumerator && enumerator.hasMoreElements()) {
440                    var resource = enumerator.getNext();
441                    resource.QueryInterface(Components.interfaces.nsIRDFResource);
442                    if (this._getRDFValue(resource, keyField) == mismatchItems[i].oldkey) {
443                        if (mismatchItems[i].key == "") this._unsetRDFValue(resource, keyField, mismatchItems[i].oldkey)
444                        else this._setRDFValue(resource, keyField, mismatchItems[i].key)
445                    }
446                }
447            }
448        }
449    },
450   
451    getRelevantSMTPs : function() {
452        var relevantSMTPs = new Object();
453        // search relevant SMTPs
454        for each (let treeType in Array("email", "maillist", "newsgroup", "filter")) {
455            var enumerator = this.getContainer(treeType).GetElements();
456            while (enumerator && enumerator.hasMoreElements()) {
457                var resource = enumerator.getNext();
458                resource.QueryInterface(Components.interfaces.nsIRDFResource);
459                var smtp = this._getRDFValue(resource, "smtp")
460                if (smtp && smtp != DEFAULT_SMTP_TAG) {
461                    if (!relevantSMTPs[smtp]) relevantSMTPs[smtp] = 1; else relevantSMTPs[smtp] += 1;
462                }
463            }
464        }
465        return relevantSMTPs;
466    },
467   
468    searchSmtpMismatch : function() {
469        Log.debug("searchSmtpMismatch");
470
471        var relevantSMTPs = this.getRelevantSMTPs();
472        var mismatchSMTPs = [];
473       
474        for (var smtp in relevantSMTPs) {
475            var servers = Components.classes["@mozilla.org/messengercompose/smtp;1"]
476                .getService(Components.interfaces.nsISmtpService).smtpServers;
477            var found = false;
478            while (servers && servers.hasMoreElements()) {
479                var server = servers.getNext();
480                if (server instanceof Components.interfaces.nsISmtpServer && 
481                    !server.redirectorType && smtp == server.key) {
482                    found = true; break;
483                }
484            }
485            var resource = this._rdfService.GetResource(this._rdfNS + this._rdfNSSMTPservers + "/" + smtp);
486            var rdfSMTPlabel = this._getRDFValue(resource, "label");
487            var rdfHostname = this._getRDFValue(resource, "hostname");
488            var rdfUsername = this._getRDFValue(resource, "username")
489            if (!found || rdfSMTPlabel != (server.description?server.description:server.hostname) && rdfHostname != server.hostname)
490                    mismatchSMTPs.push( { oldkey: smtp, label : rdfSMTPlabel, ext1: rdfHostname, ext2: rdfUsername, count: relevantSMTPs[smtp], key: "" } )
491        }
492        if (mismatchSMTPs.length > 0) {
493            Log.debug(" found mismatches on smtp(s).");
494            get3PaneWindow().openDialog("chrome://v_identity/content/vI_rdfAccountMismatchDialog.xul",0,
495                    "chrome, dialog, modal, alwaysRaised, resizable=yes", "smtp", mismatchSMTPs,
496                    /* callback: */ this).focus();
497            return true;
498        }
499        else {
500            Log.debug(" found no mismatch");
501            return false;
502        }
503    },
504
505    storeAccountInfo : function() {
506        Log.debug("storeAccounts");
507
508        var AccountManager = Components.classes["@mozilla.org/messenger/account-manager;1"]
509            .getService(Components.interfaces.nsIMsgAccountManager);
510        for (let i = 0; i < AccountManager.accounts.Count(); i++) {
511            var account = AccountManager.accounts.QueryElementAt(i, Components.interfaces.nsIMsgAccount);
512            for (let j = 0; j < account.identities.Count(); j++) {
513                var identity = account.identities.QueryElementAt(j, Components.interfaces.nsIMsgIdentity);
514//                 Log.debug("storeAccounts identity store id " + identity.key);
515
516                var resource = this._rdfService.GetResource(this._rdfNS + this._rdfNSIdentities + "/" + identity.key);
517                this._setRDFValue(resource, "identityName", identity.identityName);
518                this._setRDFValue(resource, "fullName", identity.fullName);
519                this._setRDFValue(resource, "email", identity.email);
520               
521                var position = this._identityContainer.IndexOf(resource); // check for index in new recType
522                if (position != -1) this._identityContainer.InsertElementAt(resource, position, false);
523                else this._identityContainer.AppendElement(resource);
524            }
525        }
526       
527        function storeSmtp(server, parent) {
528//             Log.debug("storeAccounts smtp store id " + server.key);
529            var resource = parent._rdfService.GetResource(parent._rdfNS + parent._rdfNSSMTPservers + "/" + server.key);
530            parent._setRDFValue(resource, "label", (server.description?server.description:server.hostname));
531            parent._setRDFValue(resource, "hostname", server.hostname);
532            parent._setRDFValue(resource, "username", server.username);
533            var position = parent._smtpContainer.IndexOf(resource); // check for index in new recType
534            if (position != -1) parent._smtpContainer.InsertElementAt(resource, position, false);
535            else parent._smtpContainer.AppendElement(resource);
536        }
537       
538        var servers = Components.classes["@mozilla.org/messengercompose/smtp;1"]
539            .getService(Components.interfaces.nsISmtpService).smtpServers;
540        while (servers && servers.hasMoreElements()) {
541            var server = servers.getNext(); 
542            if (server instanceof Components.interfaces.nsISmtpServer && !server.redirectorType) storeSmtp(server, this);
543        }
544
545//         Log.debug("storeAccounts done");
546    },
547
548    export : function(rdfFileName) {
549        var filePicker = Components.classes["@mozilla.org/filepicker;1"]
550            .createInstance(Components.interfaces.nsIFilePicker);
551        filePicker.init(get3PaneWindow(), "", Components.interfaces.nsIFilePicker.modeSave);
552        filePicker.appendFilters(Components.interfaces.nsIFilePicker.filterAll | Components.interfaces.nsIFilePicker.filterText );
553        filePicker.appendFilter("RDF Files","*.rdf");
554       
555        if (filePicker.show() != Components.interfaces.nsIFilePicker.returnCancel) {
556            var rdfDataFile = Components.classes["@mozilla.org/file/local;1"]
557                .createInstance(Components.interfaces.nsILocalFile);
558            var file = Components.classes["@mozilla.org/file/directory_service;1"]
559                .getService(Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile);
560            var delimiter = (file.path.match(/\\/))?"\\":"/";
561            rdfDataFile.initWithPath(file.path + delimiter + rdfFileName);
562
563            rdfDataFile.copyTo(filePicker.file.parent,filePicker.file.leafName);
564        }
565    },
566   
567    _getRDFResourceForVIdentity : function (recDescription, recType) {
568        if (!this._rdfDataSource) return null;
569        if (!recDescription) {
570            Log.debug("_getRDFResourceForVIdentity: no Recipient given.");
571            return null;
572        }
573        var _rdfNSRecType = null
574        switch (recType) {
575            case "email": _rdfNSRecType = this._rdfNSEmail; break;
576            case "newsgroup" : _rdfNSRecType = this._rdfNSNewsgroup; break;
577            case "maillist" : _rdfNSRecType = this._rdfNSMaillist; break;
578            case "filter" : _rdfNSRecType = this._rdfNSFilter; break;
579        }
580        return this._rdfService.GetResource(this._rdfNS + _rdfNSRecType + "/" + recDescription);
581       
582       
583    },
584   
585    removeVIdentityFromRDF : function (resource, recType) {
586//      Log.debug("removeVIdentityFromRDF " + resource.ValueUTF8);
587        this._unsetRDFValue(resource, "email", this._getRDFValue(resource, "email"))
588        this._unsetRDFValue(resource, "fullName", this._getRDFValue(resource, "fullName"))
589        this._unsetRDFValue(resource, "id", this._getRDFValue(resource, "id"))
590        this._unsetRDFValue(resource, "smtp", this._getRDFValue(resource, "smtp"))
591        this._unsetRDFValue(resource, "name", this._getRDFValue(resource, "name"))
592       
593        let self = this;
594        var extras = new identityDataExtras(self, resource)
595        extras.loopThroughExtras(
596          function (extra) {
597            extra.value = self._unsetRDFValue(resource, extra.field, extra.value) });
598       
599        this.getContainer(recType).RemoveElement(resource, true);
600    },
601   
602    _unsetRDFValue : function (resource, field, value) {
603//      Log.debug("_unsetRDFValue " + this._rdfService  + " " + this._rdfDataSource);
604        var predicate = this._rdfService.GetResource(this._rdfNS + "rdf#" + field);
605        var name = this._rdfService.GetLiteral(value?value:"");
606        var target = this._rdfDataSource.GetTarget(resource, predicate, true);
607        if (target instanceof Components.interfaces.nsIRDFLiteral) {
608            this._rdfDataSource.Unassert(resource, predicate, name, true);
609            return null;
610        }
611        else return value;
612    },
613   
614    // this will be used from rdfDataTree to get all RDF values, callFunction is vI.rdfDataTreeCollection.__addNewDatum
615    readAllEntriesFromRDF : function (addNewDatum, treeType, idData) {
616//      Log.debug("readAllEntriesFromRDF " + this._rdfService  + " " + this._rdfDataSource + " " + this);
617        var enumerator = this.getContainer(treeType).GetElements();
618        while (enumerator && enumerator.hasMoreElements()) {
619            var resource = enumerator.getNext();
620            resource.QueryInterface(Components.interfaces.nsIRDFResource);
621            var name = this._getRDFValue(resource, "name")
622            var email = this._getRDFValue(resource, "email")
623            var fullName = this._getRDFValue(resource, "fullName")
624            var id = this._getRDFValue(resource, "id")
625            var smtp = this._getRDFValue(resource, "smtp")
626            var used = this._getRDFValue(resource, "timeUsed")
627            var changed = this._getRDFValue(resource, "timeChanged")
628            if (!smtp) smtp = NO_SMTP_TAG;
629            let self = this;
630            var localIdentityData = new identityData(email, fullName, id, smtp, new identityDataExtras(self, resource))
631            addNewDatum (resource, name, localIdentityData, idData, used, changed)
632        }
633    },
634   
635    __getDescriptionAndType : function (recipient, recipientType) {
636        if (recipientType == "addr_newsgroups") return { recDesc : recipient, recType : "newsgroup" }
637        else if (this.__isMailingList(recipient)) {
638            Log.debug("__getDescriptionAndType: '" + recipient + "' is MailList");
639            return { recDesc : this.__getMailListName(recipient), recType : "maillist" }
640        }
641        else {
642            Log.debug("__getDescriptionAndType: '" + recipient + "' is no MailList");
643            var localIdentityData = new identityData(recipient, null, null, null, null, null, null);
644            return { recDesc : localIdentityData.combinedName, recType : "email" }
645        }
646    },
647   
648    // --------------------------------------------------------------------
649    // check if recipient is a mailing list.
650    // Similiar to Thunderbird, if there are muliple cards with the same displayName the mailinglist is preferred
651    // see also https://bugzilla.mozilla.org/show_bug.cgi?id=408575
652    __isMailingList: function(recipient) {
653        let abManager = Components.classes["@mozilla.org/abmanager;1"]
654            .getService(Components.interfaces.nsIAbManager);
655        let allAddressBooks = abManager.directories;
656        while (allAddressBooks.hasMoreElements()) {
657            let ab = allAddressBooks.getNext();
658            if (ab instanceof Components.interfaces.nsIAbDirectory && !ab.isRemote) {
659                let abdirectory = abManager.getDirectory(ab.URI + 
660                    "?(and(DisplayName,=," + encodeURIComponent(this.__getMailListName(recipient)) + ")(IsMailList,=,TRUE))");
661                if (abdirectory) {
662                    try {   // just try, sometimes there are no childCards at all...
663                        let cards = abdirectory.childCards;
664                        if (cards.hasMoreElements()) return true;   // only interested if there is at least one element...
665                    } catch(e) { }
666                }
667            }
668        }
669        return false;
670    }, 
671   
672    // --------------------------------------------------------------------
673   
674    __getMailListName : function(recipient) {
675        if (recipient.match(/<[^>]*>/) || recipient.match(/$/)) {
676            var mailListName = RegExp.leftContext + RegExp.rightContext
677            mailListName = mailListName.replace(/^\s+|\s+$/g,"")
678        }
679        return mailListName;
680    },
681
682    findMatchingFilter : function (recipient, recipientType) {
683        var recDescription = this.__getDescriptionAndType(recipient, recipientType).recDesc;
684        Log.debug("findMatchingFilter for " + recDescription);
685        var enumerator = this._filterContainer.GetElements();
686        while (enumerator && enumerator.hasMoreElements()) {
687            var resource = enumerator.getNext();
688            resource.QueryInterface(Components.interfaces.nsIRDFResource);
689            var filter = this._getRDFValue(resource, "name");
690           
691            const filterType = { None : 0, RegExp : 1, StrCmp : 2 }
692            var recentfilterType;
693
694            if (filter == "") continue;
695            if (/^\/(.*)\/$/.exec(filter)) {
696              Log.debug("findMatchingFilter with RegExp '" + filter.replace(/\\/g,"\\\\") + "'");
697              recentfilterType = filterType.RegExp;
698            }
699            else {
700              Log.debug("findMatchingFilter, compare with '" + filter + "'");
701              recentfilterType = filterType.StrCmp;
702            }
703           
704            switch (recentfilterType) {
705                case filterType.RegExp:
706                    try {   /^\/(.*)\/$/.exec(filter);
707                        if (recDescription.match(new RegExp(RegExp.$1,"i"))) {
708                            Log.debug("findMatchingFilter found stored data.");
709                            return this._readVIdentityFromRDF(resource);
710                        }
711                    }
712                    catch(vErr) { }; break;
713                case filterType.StrCmp:
714                    if (recDescription.toLowerCase().indexOf(filter.toLowerCase()) != -1) {
715                        Log.debug("findMatchingFilter found stored data.");
716                        return this._readVIdentityFromRDF(resource);
717                    }
718                    break;
719            }
720        }
721        Log.debug("findMatchingFilter no match found.");
722        return null;
723    },
724   
725    readVIdentityFromRDF : function (recipient, recipientType) {
726        var storedRecipient = this.__getDescriptionAndType(recipient, recipientType);
727        var email = this._rdfService.GetResource(this._rdfNS + "rdf#email");
728        var resource = this._getRDFResourceForVIdentity(storedRecipient.recDesc, storedRecipient.recType);
729        if (!resource) return null;
730        if (!this._rdfDataSource.hasArcOut(resource, email)) {
731            // no data available --> give up.
732            Log.debug("readVIdentityFromRDF no data found.");
733            return null;
734        }
735        Log.debug("readVIdentityFromRDF found stored data.");
736       
737        return this._readVIdentityFromRDF(resource);
738    },
739   
740    _readVIdentityFromRDF : function (resource) {
741        var email = this._getRDFValue(resource, "email")
742        var fullName = this._getRDFValue(resource, "fullName")
743        var id = this._getRDFValue(resource, "id")
744        var smtp = this._getRDFValue(resource, "smtp")
745        if (!smtp) smtp = NO_SMTP_TAG;
746       
747        let _date = new Date();
748        this._setRDFValue(resource, "timeUsed", _date.getTime());
749       
750        Log.debug("email='" + email + 
751            "' fullName='" + fullName + "' id='" + id + "' smtp='" + smtp + "'");
752       
753        let self = this;
754        var localIdentityData = new identityData(email, fullName, id, smtp, new identityDataExtras(self, resource))
755        return localIdentityData;
756    },
757
758    _getRDFValue : function (resource, field) {
759//         Log.debug("_getRDFValue " + this._rdfService  + " " + this._rdfDataSource + " " + this);
760        var predicate = this._rdfService.GetResource(this._rdfNS + "rdf#" + field);
761        var target = this._rdfDataSource.GetTarget(resource, predicate, true);
762        if (target instanceof Components.interfaces.nsIRDFLiteral) return target.Value
763        else return null;
764    },
765   
766    updateRDFFromVIdentity : function(identityData, recipientName, recipientType) {
767        var recipient = this.__getDescriptionAndType(recipientName, recipientType)
768        this.updateRDF(recipient.recDesc, recipient.recType, identityData,
769            vIprefs.get("storage_store_base_id"),
770            vIprefs.get("storage_store_SMTP"),
771            null, null);
772    },
773   
774    removeRDF : function (recDescription, recType) {
775        var resource = this._getRDFResourceForVIdentity(recDescription, recType);
776        if (!resource) return null;
777        this.removeVIdentityFromRDF(resource, recType);
778        return resource;
779    },
780
781    updateRDF : function (recDescription, recType, localIdentityData, storeBaseID, storeSMTP, prevRecDescription, prevRecType) {
782//         Log.debug("(" + this._rdfNS + "): updateRDF recDescription=" + recDescription + " localIdentityData.email=" + localIdentityData.email);
783       
784//      if (!localIdentityData.email) {
785//          Log.debug("updateRDF: no Sender-email for Recipient, aborting.");
786//          return;
787//      }
788        if (!recDescription || recDescription.length == 0) return;
789
790        if (!prevRecDescription) prevRecDescription = recDescription;
791        if (!prevRecType) prevRecType = recType;
792
793        var resource = this._getRDFResourceForVIdentity(prevRecDescription, prevRecType);
794        if (!resource) return;
795//      Log.debug("updateRDF " + resource.ValueUTF8);
796       
797        var position = this.getContainer(recType).IndexOf(resource); // check for index in new recType
798        this.removeVIdentityFromRDF(resource, prevRecType);
799       
800        resource = this._getRDFResourceForVIdentity(recDescription, recType);
801
802        this._setRDFValue(resource, "email", localIdentityData.email);
803        this._setRDFValue(resource, "fullName", localIdentityData.fullName);
804        if (storeBaseID)
805            this._setRDFValue(resource, "id", localIdentityData.id.key);
806        else    this._unsetRDFValue(resource, "id", this._getRDFValue(resource, "id"))
807        if (storeSMTP && localIdentityData.smtp.key != NO_SMTP_TAG)
808            this._setRDFValue(resource, "smtp", localIdentityData.smtp.key);
809        else    this._unsetRDFValue(resource, "smtp", this._getRDFValue(resource, "smtp"))
810        this._setRDFValue(resource, "name", recDescription);
811 
812        if (localIdentityData.extras) {
813          let self = this;
814          localIdentityData.extras.loopThroughExtras(
815            function (extra) {
816              extra.value = self._setRDFValue(resource, extra.field, extra.value) });
817//           Log.debug("extras: " + localIdentityData.extras.status());
818        }
819       
820        let _date = new Date();
821        this._setRDFValue(resource, "timeChanged", _date.getTime());
822       
823//      Log.debug("updateRDF add " + resource.ValueUTF8 + " at position " + position);
824        if (position != -1) this.getContainer(recType).InsertElementAt(resource, position, true);
825        else this.getContainer(recType).AppendElement(resource);
826    },
827
828    _setRDFValue : function (resource, field, value) {
829//      Log.debug("_setRDFValue " + resource.ValueUTF8 + " " + field + " " + value);
830        if (!value) return value; // return if some value was not set.
831//      Log.debug("_setRDFValue " + this._rdfService + " " + this._rdfDataSource);
832        var predicate = this._rdfService.GetResource(this._rdfNS + "rdf#" + field);
833        var name = this._rdfService.GetLiteral(value);
834        var target = this._rdfDataSource.GetTarget(resource, predicate, true);
835       
836        if (target instanceof Components.interfaces.nsIRDFLiteral)
837            this._rdfDataSource.Change(resource, predicate, target, name);
838        else    this._rdfDataSource.Assert(resource, predicate, name, true);
839        return value;
840    },
841
842    //  code adapted from http://xulsolutions.blogspot.com/2006/07/creating-uninstall-script-for.html
843    AccountManagerObserver : {
844        _uninstall : false,
845        observe : function(subject, topic, data) {
846            if (topic == "am-smtpChanges" || topic == "am-acceptChanges") {
847                Log.debug("account/smtp changes observed");
848                this.searchIdentityMismatch();
849                this.searchSmtpMismatch();
850                this.refreshAccountInfo();
851            }
852        },
853        register : function() {
854            Log.debug("register AccountManagerObserver");
855            var obsService = Components.classes["@mozilla.org/observer-service;1"].
856                getService(Components.interfaces.nsIObserverService)
857            obsService.addObserver(this, "am-smtpChanges", false);
858            obsService.addObserver(this, "am-acceptChanges", false);
859        },
860        unregister : function() {
861            var obsService = Components.classes["@mozilla.org/observer-service;1"].
862                getService(Components.interfaces.nsIObserverService)
863            try {
864                obsService.removeObserver(this, "am-smtpChanges");
865                obsService.removeObserver(this, "am-acceptChanges");
866            } catch(e) { };
867        }
868    }
869}
870
871
872function rdfDatasourceAccess() {
873    this._rdfDataSource = new rdfDatasource("virtualIdentity.rdf", false);
874    this.stringBundle = Services.strings.createBundle("chrome://v_identity/locale/v_identity.properties");
875}
876
877rdfDatasourceAccess.prototype = {
878    _rdfDataSource : null,
879    stringBundle : null,
880   
881    clean : function() {
882        this._rdfDataSource.clean();
883    },
884   
885    updateVIdentityFromStorage : function(recipientName, recipientType, currentIdentity, currentIdentityIsVid, isNotFirstInputElement, currentWindow) {
886        var localIdentities = new identityCollection();
887        localIdentities.addWithoutDuplicates(this._rdfDataSource.readVIdentityFromRDF(recipientName, recipientType));
888        if (localIdentities.number == 1) Log.debug("using data from direct match");
889        localIdentities.addWithoutDuplicates(this._rdfDataSource.findMatchingFilter(recipientName, recipientType));
890       
891        var returnValue = {}; returnValue.identityCollection = localIdentities; returnValue.result = "drop";
892        if (localIdentities.number == 0) {
893            Log.debug("updateVIdentityFromStorage no usable Storage-Data found.");
894        }
895        else {
896            Log.debug("compare with current Identity");
897            if (vIprefs.get("storage_getOneOnly") &&        // if requested to retrieve only storageID for first recipient entered
898                isNotFirstInputElement &&                           // and it is now not the first recipient entered
899                !localIdentities.identityDataCollection[0].equalsIdentity(currentIdentity, false).equal) {      // and this id is different than the current used one
900                    StorageNotification.info(this.stringBundle.GetStringFromName("vident.smartIdentity.vIStorageCollidingIdentity"));
901//                  returnValue.result = "drop";    // this is the default value
902            }
903            // only update fields if new Identity is different than old one.
904            else {
905                Log.debug("updateVIdentityFromStorage check if storage-data matches current Identity.");
906                var compResult = localIdentities.identityDataCollection[0].equalsIdentity(currentIdentity, true);
907                if (!compResult.equal) {
908                    var warning = this.__getWarning("replaceVIdentity", recipientName, compResult.compareMatrix);
909                    if (    !currentIdentityIsVid ||
910                        !vIprefs.get("storage_warn_vI_replace") ||
911                        (this.__askWarning(warning, currentWindow) == "accept")) {
912                            returnValue.result = "accept";
913                    }
914                }
915                else {
916                    returnValue.result = "equal";
917                }
918            }
919        }
920        return returnValue;
921    },
922   
923    storeVIdentityToAllRecipients : function(identityData, recipients, currentWindow) {
924        var multipleRecipients = (recipients.length > 1);
925        var dontUpdateMultipleNoEqual = (vIprefs.get("storage_dont_update_multiple") && multipleRecipients)
926        Log.debug("storeVIdentityToAllRecipients dontUpdateMultipleNoEqual='" + dontUpdateMultipleNoEqual + "'")
927       
928        let returnValue = { update : "cancel" };
929        for (var j = 0; j < recipients.length; j++) {
930            returnValue = this.__updateStorageFromVIdentity(identityData, recipients[j].recipient, recipients[j].recipientType, dontUpdateMultipleNoEqual, currentWindow);
931            if (returnValue.update != "accept")  break;
932        }
933        return returnValue;
934    },
935
936    getVIdentityFromAllRecipients : function(allIdentities, recipients) {
937        if (!vIprefs.get("storage"))
938            { Log.debug("Storage deactivated"); return; }
939        var initnumber = allIdentities.number;
940        for (var j = 0; j < recipients.length; j++) {
941            allIdentities.addWithoutDuplicates(this._rdfDataSource.readVIdentityFromRDF(recipients[j].recipient, recipients[j].recipientType));
942            allIdentities.addWithoutDuplicates(this._rdfDataSource.findMatchingFilter(recipients[j].recipient, recipients[j].recipientType));
943        }
944        Log.debug("found " + (allIdentities.number-initnumber) + " address(es)")
945    },
946
947    __updateStorageFromVIdentity : function(identityData, recipient, recipientType, dontUpdateMultipleNoEqual, currentWindow) {
948        Log.debug("__updateStorageFromVIdentity.")
949        var storageDataByType = this._rdfDataSource.readVIdentityFromRDF(recipient, recipientType);
950        var storageDataByFilter = this._rdfDataSource.findMatchingFilter(recipient, recipientType);
951       
952        // update (storing) of data by type is required if there is
953        // no data stored by type (or different data stored) and no equal filter found
954        var storageDataByTypeCompResult = storageDataByType?storageDataByType.equalsIdentity(identityData, true):null;
955        var storageDataByTypeEqual = (storageDataByType && storageDataByTypeCompResult.equal);
956        var storageDataByFilterEqual = (storageDataByFilter && storageDataByFilter.equalsIdentity(identityData, false).equal);
957       
958        var doUpdate = "accept";
959        if (    (!storageDataByType && !storageDataByFilterEqual) ||
960            (!storageDataByTypeEqual && !storageDataByFilterEqual && !dontUpdateMultipleNoEqual) ) {
961            Log.debug("__updateStorageFromVIdentity updating")
962            if (storageDataByType && !storageDataByTypeEqual && vIprefs.get("storage_warn_update")) {
963                Log.debug("__updateStorageFromVIdentity overwrite warning");
964                doUpdate = this.__askWarning(this.__getWarning("updateStorage", recipient, storageDataByTypeCompResult.compareMatrix), currentWindow);
965            }
966        }
967        if (doUpdate == "accept") this._rdfDataSource.updateRDFFromVIdentity(identityData, recipient, recipientType);
968        return { update : doUpdate, storedIdentity : storageDataByType };
969    },
970   
971    __getWarning : function(warningCase, recipient, compareMatrix) {
972        var warning = { title: null, recLabel : null, recipient : null, warning : null, css: null, query : null, class : null };
973        warning.title = this.stringBundle.GetStringFromName("vident." + warningCase + ".title")
974        warning.recLabel = this.stringBundle.GetStringFromName("vident." + warningCase + ".recipient") + ":";
975        warning.recipient = recipient;
976        warning.warning = 
977            "<table class='" + warningCase + "'><thead><tr><th class='col1'/>" +
978                "<th class='col2'>" + this.stringBundle.GetStringFromName("vident." + warningCase + ".currentIdentity") + "</th>" +
979                "<th class='col3'>" + this.stringBundle.GetStringFromName("vident." + warningCase + ".storedIdentity") + "</th>" +
980            "</tr></thead>" +
981            "<tbody>" + compareMatrix + "</tbody>" +
982            "</table>"
983        warning.css = "vI.DialogBrowser.css";
984        warning.query = this.stringBundle.GetStringFromName("vident." + warningCase + ".query");
985        warning.class = warningCase;
986        return warning;
987    },
988
989    __askWarning : function(warning, currentWindow) {
990        var retVar = { returnValue: null };
991        var answer = currentWindow.openDialog("chrome://v_identity/content/vI_Dialog.xul","",
992                    "chrome, dialog, modal, alwaysRaised, resizable=yes",
993                     warning, retVar)
994        Log.debug("retVar.returnValue=" + retVar.returnValue)
995        return retVar.returnValue;
996    },
997}
998
999
1000// create with name of the file to import into
1001function rdfDatasourceImporter(rdfFileName) {
1002    this._rdfFileName = rdfFileName;
1003    if (this._rdfFileName) this.import();
1004}
1005
1006rdfDatasourceImporter.prototype = {
1007    _rdfService :       Components.classes["@mozilla.org/rdf/rdf-service;1"]
1008                            .getService(Components.interfaces.nsIRDFService),
1009    _rdfDataSource :    null,
1010    _rdfFileName :      null,
1011    _rdfImportDataSource :    null,
1012
1013    _getMatchingIdentity : function(name, email, fullName) {
1014        var AccountManager = Components.classes["@mozilla.org/messenger/account-manager;1"]
1015            .getService(Components.interfaces.nsIMsgAccountManager);
1016        for (let i = 0; i < AccountManager.accounts.Count(); i++) {
1017            var account = AccountManager.accounts.QueryElementAt(i, Components.interfaces.nsIMsgAccount);
1018            for (let j = 0; j < account.identities.Count(); j++) {
1019                var identity = account.identities.QueryElementAt(j, Components.interfaces.nsIMsgIdentity);
1020                if (name == identity.identityName || (fullName == identity.fullName && email == identity.email)) return identity.key;
1021            }
1022        }
1023        return null;
1024    },
1025   
1026    _getMatchingSMTP : function(label, hostname, username) {
1027        var servers = Components.classes["@mozilla.org/messengercompose/smtp;1"]
1028            .getService(Components.interfaces.nsISmtpService).smtpServers;
1029        while (servers && servers.hasMoreElements()) {
1030            var server = servers.getNext(); 
1031            if (server instanceof Components.interfaces.nsISmtpServer && !server.redirectorType)
1032                if (label == (server.description?server.description:server.hostname) || (hostname == server.hostname && username == server.username))
1033                    return server.key;
1034        }
1035        return null;
1036    },
1037   
1038    _translateRelevantIDs : function() {
1039        var relevantIDs = this._rdfImportDataSource.getRelevantIDs();
1040        for (var id in relevantIDs) {
1041            var resource = this._rdfService.GetResource(this._rdfImportDataSource._rdfNS + this._rdfImportDataSource._rdfNSIdentities + "/" + id);
1042            var values = { id : null, identityName : null, email : null, fullName : null }
1043            values.identityName = this._rdfImportDataSource._getRDFValue(resource, "identityName");
1044            values.email = this._rdfImportDataSource._getRDFValue(resource, "email");
1045            values.fullName = this._rdfImportDataSource._getRDFValue(resource, "fullName");
1046            values.id = this._getMatchingIdentity(values.identityName, values.email, values.fullName);
1047            values.id = values.id?values.id:"import_" + id
1048            relevantIDs[id] = values;
1049            Log.debug("import: translate relevant ID from previous '" + id + "' to current '" + relevantIDs[id].id + "'");
1050        }
1051        return relevantIDs;
1052    },
1053   
1054    _storeMappedIDs : function(relevantIDs) {
1055        for (var id in relevantIDs) {
1056            if (relevantIDs[id].id == "import_" + id) {
1057                var resource = this._rdfService
1058                    .GetResource(this._rdfDataSource._rdfNS + this._rdfDataSource._rdfNSIdentities + "/" + relevantIDs[id].id);
1059                this._rdfDataSource._setRDFValue(resource, "identityName", relevantIDs[id].identityName);
1060                this._rdfDataSource._setRDFValue(resource, "fullName", relevantIDs[id].fullName);
1061                this._rdfDataSource._setRDFValue(resource, "email", relevantIDs[id].email);
1062               
1063                var position = this._rdfDataSource._identityContainer.IndexOf(resource); // check for index in new recType
1064                if (position != -1) this._rdfDataSource._identityContainer.InsertElementAt(resource, position, false);
1065                else this._rdfDataSource._identityContainer.AppendElement(resource);
1066            }
1067        }
1068    },
1069   
1070    _translateRelevantSMTPs : function() {
1071        var relevantSMTPs = this._rdfImportDataSource.getRelevantSMTPs();
1072        for (var smtp in relevantSMTPs) {
1073            var resource = this._rdfService.GetResource(this._rdfImportDataSource._rdfNS + this._rdfImportDataSource._rdfNSSMTPservers + "/" + smtp);
1074            var values = { smtp : null, label : null, hostname : null, username : null }
1075            values.label = this._rdfImportDataSource._getRDFValue(resource, "label");
1076            values.hostname = this._rdfImportDataSource._getRDFValue(resource, "hostname");
1077            values.username = this._rdfImportDataSource._getRDFValue(resource, "username");
1078            values.smtp =  this._getMatchingSMTP(values.label, values.hostname, values.username);
1079            values.smtp = values.smtp?values.smtp:"import_" + smtp;
1080            relevantSMTPs[smtp] = values;
1081            Log.debug("import: translate relevant SMTP from previous '" + smtp + "' to current '" + relevantSMTPs[smtp].smtp + "'");
1082        }
1083        return relevantSMTPs;
1084    },
1085   
1086    _storeMappedSMTPs : function(relevantSMTPs) {
1087        for (var smtp in relevantSMTPs) {
1088            if (relevantSMTPs[smtp].smtp == "import_" + smtp) {
1089                var resource = this._rdfService
1090                    .GetResource(this._rdfDataSource._rdfNS + this._rdfDataSource._rdfNSSMTPservers + "/" + relevantSMTPs[smtp].smtp);
1091                this._rdfDataSource._setRDFValue(resource, "label", relevantSMTPs[smtp].label);
1092                this._rdfDataSource._setRDFValue(resource, "hostname", relevantSMTPs[smtp].hostname);
1093                this._rdfDataSource._setRDFValue(resource, "username", relevantSMTPs[smtp].username);
1094               
1095                var position = this._rdfDataSource._smtpContainer.IndexOf(resource); // check for index in new recType
1096                if (position != -1) this._rdfDataSource._smtpContainer.InsertElementAt(resource, position, false);
1097                else this._rdfDataSource._smtpContainer.AppendElement(resource);
1098            }
1099        }
1100    },
1101   
1102    import : function() {
1103        var filePicker = Components.classes["@mozilla.org/filepicker;1"]
1104            .createInstance(Components.interfaces.nsIFilePicker);
1105
1106        filePicker.init(get3PaneWindow(), "", Components.interfaces.nsIFilePicker.modeOpen);
1107        filePicker.appendFilter("RDF Files","*.rdf");
1108        filePicker.appendFilters(Components.interfaces.nsIFilePicker.filterText | Components.interfaces.nsIFilePicker.filterAll );
1109       
1110        if (filePicker.show() == Components.interfaces.nsIFilePicker.returnOK) {
1111            Log.debug("import: preparation:");
1112           
1113            var importRdfDataFile = Components.classes["@mozilla.org/file/local;1"]
1114                .createInstance(Components.interfaces.nsILocalFile);
1115            var file = Components.classes["@mozilla.org/file/directory_service;1"]
1116                .getService(Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile);
1117            var delimiter = (file.path.match(/\\/))?"\\":"/";
1118            importRdfDataFile.initWithPath(file.path + delimiter + this._rdfFileName + "_import");
1119            filePicker.file.copyTo(importRdfDataFile.parent,importRdfDataFile.leafName);
1120
1121            Log.debug("import: copied file from " + filePicker.file.path + " to " + importRdfDataFile.path + "'");
1122           
1123            // init Datasources
1124            this._rdfImportDataSource = new rdfDatasource(importRdfDataFile.leafName, true);
1125           
1126            // search matching IDs and SMTPs for anyones used in import-file
1127            var relevantIDs = this._translateRelevantIDs();
1128            var relevantSMTPs = this._translateRelevantSMTPs();
1129           
1130            Log.debug("import: preparation done.");
1131           
1132            for each (let treeType in Array("email", "maillist", "newsgroup", "filter")) {
1133                // re-initialize importDataSource to point rdfService to the right Resources
1134                this._rdfImportDataSource = new rdfDatasource(importRdfDataFile.leafName, true);
1135                var container = this._rdfImportDataSource.getContainer(treeType)
1136                if (container.GetCount() == 0) continue;
1137                Log.debug("importing " + treeType + ": " + container.GetCount()+ " datasets from " + this._rdfImportDataSource._rdfDataSource.URI);
1138                var enumerator = container.GetElements();
1139                // re-initialize dataSource to point rdfService to the right Resources
1140                this._rdfDataSource = new rdfDatasource(this._rdfFileName, true);
1141                var count = 0;
1142                while (enumerator.hasMoreElements()) {
1143                    var resource = enumerator.getNext(); count += 1;
1144                    resource.QueryInterface(Components.interfaces.nsIRDFResource);
1145//                     Log.debug(" " + count + " ");
1146                    var name = this._rdfImportDataSource._getRDFValue(resource, "name")
1147                    var email = this._rdfImportDataSource._getRDFValue(resource, "email")
1148                    var fullName = this._rdfImportDataSource._getRDFValue(resource, "fullName")
1149                    var id = this._rdfImportDataSource._getRDFValue(resource, "id")
1150                    id = id?relevantIDs[id].id:null
1151                    var smtp = this._rdfImportDataSource._getRDFValue(resource, "smtp")
1152                    smtp = (smtp && smtp != DEFAULT_SMTP_TAG)?relevantSMTPs[smtp].smtp:smtp
1153                    var localIdentityData = new identityData(email, fullName, id, smtp, new identityDataExtras(this._rdfImportDataSource, resource))
1154                   
1155                    this._rdfDataSource.updateRDF(name, treeType, localIdentityData, false, false, null, null)
1156                    var resource = this._rdfDataSource._getRDFResourceForVIdentity(name, treeType);
1157                    if (id) this._rdfDataSource._setRDFValue(resource, "id", id);       // localIdentityData can only store valid id's, this one might be a temporary invalid id
1158                    if (smtp) this._rdfDataSource._setRDFValue(resource, "smtp", smtp); // localIdentityData can only store valid smtp's, this one might be a temporary invalid smtp
1159                }
1160            }
1161           
1162            Log.debug("import: removing temporary file " + importRdfDataFile.path);
1163            this._rdfImportDataSource = null; importRdfDataFile.remove(false);
1164            Log.debug("import: import done.");
1165           
1166            Log.debug("import: cleaning ID/SMTP storages:");
1167            this._rdfDataSource = new rdfDatasource(this._rdfFileName, true);
1168           
1169            this._storeMappedIDs(relevantIDs);
1170            this._rdfDataSource.searchIdentityMismatch();
1171            this._storeMappedSMTPs(relevantSMTPs);
1172            this._rdfDataSource.searchSmtpMismatch();
1173           
1174            this._rdfDataSource.refreshAccountInfo();
1175            this._rdfDataSource.clean();
1176            this._rdfDataSource = null;
1177            Log.debug("import: cleaning ID/SMTP storages done.");
1178            Log.debug("IMPORT DONE.");
1179        }
1180    }
1181}
Note: See TracBrowser for help on using the repository browser.