Use PEPSettings to check for own identities and always use a userId OUT-401
authorThomas
Tue, 13 Feb 2018 15:18:56 +0100
branchOUT-401
changeset 2003 c0dfc0f23c17
parent 1999 dfab19314f7d
child 2004 fef678d01f1f
Use PEPSettings to check for own identities and always use a userId - if in cache, use the one from cache - if not in cache and contact item available, use contact item id - if not in cache and no contact, use address entry id
PEPIdentity.cs
PEPSettings.cs
ThisAddIn.cs
UI/HandshakeDialog.xaml.cs
--- a/PEPIdentity.cs	Mon Feb 12 16:40:36 2018 +0100
+++ b/PEPIdentity.cs	Tue Feb 13 15:18:56 2018 +0100
@@ -3,8 +3,6 @@
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Linq;
-using System.Runtime.InteropServices;
-using System.Text.RegularExpressions;
 using Outlook = Microsoft.Office.Interop.Outlook;
 
 namespace pEp
@@ -844,19 +842,19 @@
         /// <returns>True if the given address represents an own identity, otherwise false.</returns>
         public static bool GetIsOwnIdentity(string address)
         {
-            bool isMyself;
-            Outlook.Account account;
+            bool isMyself = false;
 
-            account = PEPIdentity.GetOwnAccount(address);
-            isMyself = (account != null ? true : false);
-
-            if (account != null)
+            try
             {
-                // Marshal.ReleaseComObject(account);
-                account = null;
+                isMyself = Globals.ThisAddIn.Settings.AccountSettingsList.Any(a => (a.SmtpAddress?.Equals(address) == true));
+            }
+            catch (Exception ex)
+            {
+                isMyself = false;
+                Log.Error("GetIsOwnIdentity: Error determining if own identity. " + ex.ToString());
             }
 
-            return (isMyself);
+            return isMyself;
         }
 
         /// <summary>
@@ -1144,7 +1142,7 @@
                             own = new PEPIdentity();
                             own.Address = address;
                             own.UserName = userName;
-                            own.UserId = Globals.ThisAddIn.GetUserId(own.Address, null); // Not using 'myself ID'
+                            own.UserId = Globals.ThisAddIn.GetUserId(own.Address); // Not using 'myself ID'
 
                             // Update the identity in the pEp engine (and get fingerprint)
                             try
@@ -1288,7 +1286,7 @@
                     }
 
                     // Add user ID
-                    newIdentity.UserId = Globals.ThisAddIn.GetUserId(newIdentity.Address, null);
+                    newIdentity.UserId = Globals.ThisAddIn.GetUserId(newIdentity.Address);
                 }
             }
             catch (Exception ex)
@@ -1510,7 +1508,7 @@
                                     catch { }
 
                                     // Add the user ID
-                                    from.UserId = Globals.ThisAddIn.GetUserId(from.Address, contact);
+                                    from.UserId = Globals.ThisAddIn.GetUserId(from.Address, contact, sender);
 
                                     status = Globals.ReturnStatus.Success;
                                 }
@@ -1541,7 +1539,7 @@
                                 catch { }
 
                                 // Add the user ID
-                                from.UserId = Globals.ThisAddIn.GetUserId(from.Address, contact);
+                                from.UserId = Globals.ThisAddIn.GetUserId(from.Address, contact, sender);
 
                                 status = Globals.ReturnStatus.Success;
                             }
@@ -1578,7 +1576,7 @@
                         catch { }
 
                         // Add the user ID
-                        from.UserId = Globals.ThisAddIn.GetUserId(from.Address, contact);
+                        from.UserId = Globals.ThisAddIn.GetUserId(from.Address, contact, sender);
 
                         status = Globals.ReturnStatus.Success;
                     }
@@ -1735,7 +1733,7 @@
                 // Get the unique user ID if possible (Assume no contact is available)
                 if (string.IsNullOrEmpty(newIdent.Address) == false)
                 {
-                    newIdent.UserId = Globals.ThisAddIn.GetUserId(newIdent.Address, null);
+                    newIdent.UserId = Globals.ThisAddIn.GetUserId(newIdent.Address);
                 }
             }
 
@@ -1960,7 +1958,7 @@
                                         currContact = null;
                                     }
 
-                                    newIdent2.UserId = Globals.ThisAddIn.GetUserId(newIdent2.Address, currContact);
+                                    newIdent2.UserId = Globals.ThisAddIn.GetUserId(newIdent2.Address, currContact, currAddressEntry);
                                     newIdent.Members.Add(newIdent2);
                                 }
                             }
@@ -2104,7 +2102,7 @@
                 // Get the unique user ID if possible
                 if (string.IsNullOrEmpty(newIdent.Address) == false)
                 {
-                    newIdent.UserId = Globals.ThisAddIn.GetUserId(newIdent.Address, contact);
+                    newIdent.UserId = Globals.ThisAddIn.GetUserId(newIdent.Address, contact, addressEntry);
                 }
 
                 identityCreated = true;
--- a/PEPSettings.cs	Mon Feb 12 16:40:36 2018 +0100
+++ b/PEPSettings.cs	Tue Feb 13 15:18:56 2018 +0100
@@ -30,6 +30,8 @@
             AllMessages
         }
 
+        public const string PEP_OWN_USER_ID                                     = "pEpForOutlook_pEp_own_userId";
+
         public const string REG_KEY_SOFTWARE                                    = "Software";
         public const string REG_KEY_PEP                                         = "pEp";
         public const string REG_KEY_PEP_FOR_OUTLOOK                             = "Outlook";
@@ -46,6 +48,7 @@
         public const string REG_NAME_ACCOUNT_SETTING_SENT_FOLDER_ENTRYID        = "SentFolderEntryId";
         public const string REG_NAME_ACCOUNT_SETTING_SMTP_ADDRESS               = "SmtpAddress";
         public const string REG_NAME_ACCOUNT_SETTING_TYPE                       = "Type";
+        public const string REG_NAME_ACCOUNT_SETTING_USER_NAME                  = "UserName";
         public const string REG_NAME_ACCOUNT_WHITELIST                          = "AccountWhitelist";
         public const string REG_NAME_CRASH_REPORT_SEND_ADDRESS                  = "CrashReportSendAddress";
         public const string REG_NAME_DEFAULT_CODEPAGE_OUT                       = "Default_CodePageOut"; // Name defined by Microsoft
@@ -77,6 +80,7 @@
         public const string                ACCOUNT_SETTING_SENT_FOLDER_ENTRYID_DEFAULT        = null;
         public const string                ACCOUNT_SETTING_SMTP_ADDRESS_DEFAULT               = null;
         public const string                ACCOUNT_SETTING_TYPE_DEFAULT                       = null;
+        public const string                ACCOUNT_SETTING_USER_NAME_DEFAULT                  = null;  
         public static readonly string[]    ACCOUNT_WHITELIST_DEFAULT                          = new string[] { };
         public static Disclaimer           ADD_DISCLAIMER_DEFAULT                             = Disclaimer.None;
         public const string                CRASH_REPORT_SEND_ADDRESS_DEFAULT                  = "crashreport@prettyeasyprivacy.com";
@@ -782,6 +786,11 @@
                                             {
                                                 keyAcctSettings.SetValue(PEPSettings.REG_NAME_ACCOUNT_SETTING_TYPE, acctSettings.Type, RegistryValueKind.String);
                                             }
+
+                                            if (acctSettings.UserName != null)
+                                            {
+                                                keyAcctSettings.SetValue(PEPSettings.REG_NAME_ACCOUNT_SETTING_USER_NAME, acctSettings.UserName, RegistryValueKind.String);
+                                            }
                                         }
                                     }
                                 }
@@ -1051,6 +1060,17 @@
                                                         isPropertySet = true;
                                                     }
                                                 }
+
+                                                // UserName
+                                                value = keyAcctSettings.GetValue(PEPSettings.REG_NAME_ACCOUNT_SETTING_USER_NAME, null);
+                                                if (value != null)
+                                                {
+                                                    if (string.IsNullOrWhiteSpace((string)value) == false)
+                                                    {
+                                                        acctSettings.UserName = ((string)value).Trim();
+                                                        isPropertySet = true;
+                                                    }
+                                                }
                                             }
                                         }
                                         catch { }
@@ -1806,6 +1826,7 @@
             protected string        _SentFolderEntryId;
             protected string        _SmtpAddress;
             protected string        _Type;
+            protected string        _UserName;
 
             /**************************************************************
              * 
@@ -1993,6 +2014,22 @@
                 }
             }
 
+            /// <summary>
+            /// Gets or sets the UserName of the account.
+            /// </summary>
+            public string UserName
+            {
+                get { return (this._UserName); }
+                set
+                {
+                    if (object.Equals(this._UserName, value) == false)
+                    {
+                        this._UserName = value;
+                        this.RaisePropertyChangedEvent(nameof(this.UserName));
+                    }
+                }
+            }
+
             /**************************************************************
              * 
              * Methods
@@ -2023,6 +2060,7 @@
                 this._SentFolderEntryId = PEPSettings.ACCOUNT_SETTING_SENT_FOLDER_ENTRYID_DEFAULT;
                 this._SmtpAddress = PEPSettings.ACCOUNT_SETTING_SMTP_ADDRESS_DEFAULT;
                 this._Type = PEPSettings.ACCOUNT_SETTING_TYPE_DEFAULT;
+                this._UserName = PEPSettings.ACCOUNT_SETTING_USER_NAME_DEFAULT;
 
                 this.RaisePropertyChangedEvent(nameof(this.AddDisclaimer));
                 this.RaisePropertyChangedEvent(nameof(this.DisclaimerText));
@@ -2033,6 +2071,7 @@
                 this.RaisePropertyChangedEvent(nameof(this.SentFolderEntryId));
                 this.RaisePropertyChangedEvent(nameof(this.SmtpAddress));
                 this.RaisePropertyChangedEvent(nameof(this.Type));
+                this.RaisePropertyChangedEvent(nameof(this.UserName));
             }
 
             /// <summary>
@@ -2052,6 +2091,7 @@
                 copy.SentFolderEntryId = this._SentFolderEntryId;
                 copy.SmtpAddress = this._SmtpAddress;
                 copy.Type = this._Type;
+                copy.UserName = this._UserName;
 
                 return (copy);
             }
--- a/ThisAddIn.cs	Mon Feb 12 16:40:36 2018 +0100
+++ b/ThisAddIn.cs	Tue Feb 13 15:18:56 2018 +0100
@@ -141,7 +141,7 @@
                         // several times, we need to prevent infinite recursion in case of engine
                         // initializaition failure.
                         if (_PEPEngineException != null)
-                           return null;
+                            return null;
                         _PEPEngineException = ex;
 
                         string summaryMessage = Properties.Resources.Message_InitError + " " +
@@ -245,6 +245,7 @@
                                 acctSettings = new PEPSettings.PEPAccountSettings();
                                 acctSettings.SmtpAddress = account.SmtpAddress;
                                 acctSettings.Type = account.AccountType.ToString();
+                                acctSettings.UserName = account.UserName;
 
                                 // Qualify server trust if not ActiveSync (always trusted as mails don't get synced back to server)
                                 if (account.AccountType != Outlook.OlAccountType.olEas)
@@ -530,61 +531,40 @@
         /// </summary>
         internal void RegisterMyself()
         {
-            Outlook.NameSpace ns = null;
-            Outlook.Account account = null;
-            Outlook.Accounts accounts = null;
-            Outlook.Recipient currUser = null;
             pEpIdentity ownIdentity;
 
-            try
+            if (Globals.ThisAddIn.Settings.AccountSettingsList != null)
             {
-                ns = this.Application.Session;
-                accounts = ns.Accounts;
-
-                for (int i = 1; i <= accounts.Count; i++)
+                foreach (var acctSetting in Globals.ThisAddIn.Settings.AccountSettingsList)
                 {
-                    account = accounts[i];
-                    currUser = account.CurrentUser;
-
-                    ownIdentity = new pEpIdentity();
-                    ownIdentity.Address = account.SmtpAddress;
-                    ownIdentity.UserName = (currUser != null ? currUser.Name : null);
-                    ownIdentity.UserId = Globals.ThisAddIn.GetUserId(ownIdentity.Address, null);
-
-                    /* Disable key sync if it is an imap account or sync is disabled globally
-                     * AND per account. For new accounts, the sync setting per account gets set
-                     * to "false" during SyncAccountsList().
-                     */
-                    try
+                    // Create pEpIdentity
+                    ownIdentity = new pEpIdentity
                     {
-                        foreach (var acctSettings in this._Settings.AccountSettingsList)
-                        {
-                            if (acctSettings.EqualsByAddress(ownIdentity.Address))
-                            {
-                                if ((acctSettings.Type.Contains("Imap")) ||
-                                    ((this._Settings.IsSyncEnabledForAllAccounts == false) &&
-                                    (acctSettings.IsSyncEnabled == false)))
-                                {
-                                    ownIdentity.Flags = pEpIdentityFlags.pEpIdfNotForSync;
-                                }
-                                break;
-                            }
-                        }
-                    }
-                    catch (Exception ex)
+                        Address = acctSetting.SmtpAddress,
+                        UserId = PEPSettings.PEP_OWN_USER_ID,
+                        UserName = acctSetting.UserName
+                    };
+
+                    // Add to userId cache
+                    this.userIdCache[ownIdentity.Address] = ownIdentity.UserId;
+
+                    // Set not for sync flag if necessary
+                    if ((acctSetting.Type.Contains("Imap")) ||
+                        ((Globals.ThisAddIn.Settings.IsSyncEnabledForAllAccounts == false) &&
+                         (acctSetting.IsSyncEnabled == false)))
                     {
-                        Log.Verbose("RegisterMyself: Error setting sync flag for new account. " + ex.ToString());
+                        ownIdentity.Flags = pEpIdentityFlags.pEpIdfNotForSync;
                     }
 
                     // Log information if invalid
                     if (string.IsNullOrWhiteSpace(ownIdentity.Address))
                     {
-                        Log.Warning("RegisterMyself: Myself[" + i.ToString() + "] doesn't have an address.");
+                        Log.Warning("RegisterMyself: Myself doesn't have an address.");
                     }
 
                     if (string.IsNullOrWhiteSpace(ownIdentity.UserName))
                     {
-                        Log.Warning("RegisterMyself: Myself[" + i.ToString() + "] doesn't have a user name.");
+                        Log.Warning("RegisterMyself: Myself doesn't have a user name.");
                     }
 
                     /* Call engine to register myself (doesn't matter if already done in a past instance)
@@ -603,54 +583,8 @@
                     {
                         Log.Warning("RegisterMyself: Engine returned exception, " + ex.ToString());
                     }
-
-                    // Release objects
-                    if (account != null)
-                    {
-                        // Marshal.ReleaseComObject(account);
-                        account = null;
-                    }
-
-                    if (currUser != null)
-                    {
-                        // Marshal.ReleaseComObject(currUser);
-                        currUser = null;
-                    }
                 }
             }
-            catch (Exception ex)
-            {
-                Log.Error("RegisterMyself: Failure occured, " + ex.ToString());
-            }
-            finally
-            {
-                // Release objects
-                if (ns != null)
-                {
-                    //Marshal.ReleaseComObject(ns);
-                    ns = null;
-                }
-
-                if (account != null)
-                {
-                    //Marshal.ReleaseComObject(account);
-                    account = null;
-                }
-
-                if (accounts != null)
-                {
-                    //Marshal.ReleaseComObject(accounts);
-                    accounts = null;
-                }
-
-                if (currUser != null)
-                {
-                    //Marshal.ReleaseComObject(currUser);
-                    currUser = null;
-                }
-            }
-
-            return;
         }
 
         /// <summary>
@@ -659,9 +593,12 @@
         /// <param name="address">The address to get the user ID for.</param>
         /// <param name="contact">The contact associated with the address (if any).
         /// This value can be null and is not required for 'myself' user IDs.</param>
+        /// <param name="addressEntry">The addressEntry associated with the address (if any).
+        /// This value can be null and is not required for 'myself' user IDs.</param>
         /// <returns>The user ID (Outlook EntryID) for the given address</returns>
         internal string GetUserId(string address,
-                                  Outlook.ContactItem contact)
+                                  Outlook.ContactItem contact = null,
+                                  Outlook.AddressEntry addressEntry = null)
         {
             string id = null;
             Outlook.Folder contactFolder = null;
@@ -689,7 +626,7 @@
                         // Check if the address is myself
                         if (PEPIdentity.GetIsOwnIdentity(address))
                         {
-                            id = "pEp_own_userId"; // Alternatively, null or empty could be used
+                            id = PEPSettings.PEP_OWN_USER_ID;
                             this.userIdCache[address] = id;
                         }
                     }
@@ -710,10 +647,13 @@
                         }
                     }
 
-                    /* If no user ID is found at this point, return null.
-                     * The engine supports 'virtual users' that are only uniquely identified by address.
-                     * Virtual users will be automatically upgraded if a contact is ever created for the email address.
-                     */
+                    // Use the addressEntry ID if available
+                    if ((id == null) &&
+                        (addressEntry != null))
+                    {
+                        id = addressEntry.ID;
+                        this.userIdCache[address] = id;
+                    }
                 }
             }
             catch (Exception ex)
--- a/UI/HandshakeDialog.xaml.cs	Mon Feb 12 16:40:36 2018 +0100
+++ b/UI/HandshakeDialog.xaml.cs	Tue Feb 13 15:18:56 2018 +0100
@@ -165,8 +165,6 @@
 
                     /* Update the identities to get fingerprints and add to list. If a recipient is an own identity,
                      * don't add it to the list, as we don't do handshakes with own identities.
-                     * Recipients without color are stored temporarily in a separate list and are appended to
-                     * the end of the actual recipients list, as they are hidden by default.
                      */
                     foreach (var recipient in recipients)
                     {