Wrappers/WatchedWindow.cs
author Thomas
Tue, 13 Nov 2018 10:55:32 +0100
branchOUT-497
changeset 2445 a485c287cb88
parent 2438 b503817d0f76
child 2446 d7cd7a1eeb6a
permissions -rw-r--r--
Move PrivacyState from FormRegionPrivacyStatus to WatchedWindow
Thomas@2359
     1
´╗┐using pEp.UI;
Thomas@2359
     2
using pEpCOMServerAdapterLib;
Thomas@2359
     3
using System;
Thomas@2359
     4
using System.ComponentModel;
Thomas@2359
     5
using System.Windows.Forms;
Thomas@2359
     6
using Outlook = Microsoft.Office.Interop.Outlook;
Thomas@2359
     7
Thomas@2359
     8
namespace pEp
Thomas@2359
     9
{
Thomas@2359
    10
    /// <summary>
Thomas@2359
    11
    /// Stores an Outlook Window with connected events.
Thomas@2359
    12
    /// </summary>
Thomas@2359
    13
    public abstract class WatchedWindow : IDisposable
Thomas@2359
    14
    {
Thomas@2359
    15
        private CryptableMailItem               cryptableMailItem           = null;
Thomas@2359
    16
        private bool                            displayMirrorRequested      = false;
Thomas@2359
    17
        private HandshakeDialog                 handshakeDialog             = null;
Thomas@2359
    18
        private bool                            isEnabled                   = true;
Thomas@2359
    19
        private bool                            isStarted                   = false;
Thomas@2359
    20
        private bool                            processingOngoing           = false;
Thomas@2359
    21
        private bool                            refreshOngoing              = false;
Thomas@2359
    22
        private bool                            repeatProcessing            = false;
Thomas@2359
    23
        private int                             repeatCounter               = 0;
Thomas@2359
    24
        private const int                       maxRepeatCount              = 5;
Thomas@2359
    25
Thomas@2360
    26
        #region Properties
Thomas@2359
    27
Thomas@2359
    28
        /// <summary>
Thomas@2359
    29
        /// The mail item that is connected to this Inspector/Explorer window.
Thomas@2359
    30
        /// </summary>
Thomas@2385
    31
        public Outlook.MailItem CurrentMailItem { get; set; } = null;
Thomas@2359
    32
Thomas@2359
    33
        /// <summary>
Thomas@2359
    34
        /// Gets or sets whether to disable the Force Protection option.
Thomas@2359
    35
        /// </summary>
Thomas@2359
    36
        public bool DisableForceProtection { get; set; } = false;
Thomas@2359
    37
Thomas@2359
    38
        /// <summary>
Thomas@2359
    39
        /// Gets or sets whether to send this message forcefully protected.
Thomas@2359
    40
        /// </summary>
Thomas@2359
    41
        public bool ForceProtection { get; set; } = false;
Thomas@2359
    42
Thomas@2359
    43
        /// <summary>
Thomas@2359
    44
        /// Gets or sets whether to send this message forcefully unencrypted.
Thomas@2359
    45
        /// </summary>
Thomas@2359
    46
        public bool ForceUnencrypted { get; set; } = false;
Thomas@2359
    47
Thomas@2359
    48
        /// <summary>
Thomas@2359
    49
        /// Gets or sets whether the message is a draft message.
Thomas@2359
    50
        /// </summary>
Thomas@2359
    51
        public bool IsDraft { get; set; } = false;
Thomas@2359
    52
Thomas@2359
    53
        /// <summary>
Thomas@2359
    54
        /// Gets or sets whether to always store this message as if on an untrusted server.
Thomas@2359
    55
        /// </summary>
Thomas@2359
    56
        public bool NeverUnsecure { get; set; } = false;
Thomas@2359
    57
Thomas@2359
    58
        /// <summary>
Thomas@2419
    59
        /// The privacy state of this form region.
Thomas@2419
    60
        /// </summary>
Thomas@2419
    61
        internal PrivacyState PrivacyState { get; private set; } = new PrivacyState();
Thomas@2419
    62
Thomas@2419
    63
        /// <summary>
Thomas@2359
    64
        /// Gets the rating of this message.
Thomas@2359
    65
        /// </summary>
Thomas@2419
    66
        public pEpRating Rating { get; private set; } = pEpRating.pEpRatingUndefined;
Thomas@2359
    67
Thomas@2359
    68
        /// <summary>
Thomas@2359
    69
        /// Sets the rating of this message and updates the UI.
Thomas@2359
    70
        /// </summary>
Thomas@2359
    71
        /// <param name="rating">The message rating.</param>
Thomas@2359
    72
        public void SetRating(pEpRating rating)
Thomas@2359
    73
        {
Thomas@2419
    74
            this.Rating = rating;
Thomas@2419
    75
            this.UpdatePrivacyStateAndUI();
Thomas@2359
    76
        }
Thomas@2359
    77
Thomas@2359
    78
        /// <summary>
Thomas@2359
    79
        /// The timer that schedules the updates of this window.
Thomas@2359
    80
        /// </summary>
Thomas@2359
    81
        public System.Windows.Forms.Timer TimerRefresh { get; set; } = new System.Windows.Forms.Timer();
Thomas@2360
    82
Thomas@2385
    83
        /// <summary>
Thomas@2385
    84
        /// Gets the associated Explorer/Inspector window. To be overwritten by child class.
Thomas@2385
    85
        /// </summary>
Thomas@2385
    86
        public abstract dynamic Window { get; }
Thomas@2385
    87
Thomas@2359
    88
        #endregion
Thomas@2359
    89
Thomas@2359
    90
        #region Constructors / Destructors
Thomas@2359
    91
Thomas@2359
    92
        /// <summary>
Thomas@2359
    93
        /// Destructor.
Thomas@2359
    94
        /// </summary>
Thomas@2359
    95
        ~WatchedWindow()
Thomas@2359
    96
        {
Thomas@2359
    97
            this.Dispose(true);
Thomas@2359
    98
        }
Thomas@2359
    99
        #endregion
Thomas@2359
   100
Thomas@2359
   101
        #region Methods
Thomas@2359
   102
        /**************************************************************
Thomas@2359
   103
         * 
Thomas@2359
   104
         * Methods
Thomas@2359
   105
         * 
Thomas@2359
   106
         *************************************************************/
Thomas@2359
   107
Thomas@2359
   108
        /// <summary>
Thomas@2359
   109
        /// Releases all resources and disconnects internal events.
Thomas@2359
   110
        /// </summary>
Thomas@2359
   111
        public void Dispose()
Thomas@2359
   112
        {
Thomas@2359
   113
            this.Dispose(true);
Thomas@2359
   114
        }
Thomas@2359
   115
Thomas@2359
   116
        /// <summary>
Thomas@2359
   117
        /// Clean up any resources being used.
Thomas@2359
   118
        /// </summary>
Thomas@2359
   119
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
Thomas@2359
   120
        protected virtual void Dispose(bool disposing)
Thomas@2359
   121
        {
Thomas@2359
   122
            if (disposing)
Thomas@2359
   123
            {
Thomas@2360
   124
                // Disconnect cryptable mail item
Thomas@2360
   125
                if (this.cryptableMailItem != null)
Thomas@2360
   126
                {
Thomas@2360
   127
                    try
Thomas@2360
   128
                    {
Thomas@2360
   129
                        this.cryptableMailItem.PropertyChanged -= MailItem_PropertyChanged;
Thomas@2360
   130
                        this.cryptableMailItem.ProcessingCompleted -= MailItem_ProcessingCompleted;
Thomas@2360
   131
                        this.cryptableMailItem.GetMirrorCompleted -= MailItem_GetMirrorCompleted;
Thomas@2360
   132
                        this.cryptableMailItem.Open -= MailItem_Open;
Thomas@2360
   133
                        this.cryptableMailItem.Send -= MailItem_Send;
Thomas@2360
   134
                        this.cryptableMailItem.OriginallyEncryptedStatusUpdated -= CryptableMailItem_OriginallyEncryptedStatusUpdated;
Thomas@2360
   135
                    }
Thomas@2360
   136
                    catch { }
Thomas@2360
   137
Thomas@2360
   138
                    this.cryptableMailItem.Dispose();
Thomas@2360
   139
                    this.cryptableMailItem = null;
Thomas@2360
   140
                }
Thomas@2360
   141
Thomas@2360
   142
                // Disconnect other
Thomas@2360
   143
                this.SetIsEnabled(false);
Thomas@2360
   144
Thomas@2359
   145
                // Set Outlook objects to null
Thomas@2385
   146
                this.CurrentMailItem = null;
Thomas@2360
   147
Thomas@2360
   148
                // Dispose of timer
Thomas@2360
   149
                this.TimerRefresh.Dispose();
Thomas@2359
   150
            }
Thomas@2359
   151
        }
Thomas@2360
   152
Thomas@2359
   153
        /// <summary>
Thomas@2359
   154
        /// Builds the latest state of the encryption status manager then shows the UI.
Thomas@2359
   155
        /// </summary>
Thomas@2359
   156
        public void BuildAndShowManager()
Thomas@2359
   157
        {
Thomas@2359
   158
            /* Resolve all recipients -- this ensures the identities list is correctly populated
Thomas@2359
   159
             * 
Thomas@2359
   160
             * Note: The PropertyChanged changed event must be disconnected before trying to resolve.
Thomas@2359
   161
             * This is because the resolve process can modify the contents of the mail item which triggers an event.
Thomas@2359
   162
             * The PropertyChanged event would then trigger a UI refresh cycle. However, because the GetManagerState itself 
Thomas@2359
   163
             * is called within the UI refresh, an infinite loop could occur trying to resolve a recipient that
Thomas@2359
   164
             * cannot be resolved (no address).
Thomas@2359
   165
             */
Thomas@2359
   166
            try
Thomas@2359
   167
            {
Thomas@2359
   168
                this.ResolveAllRecipients();
Thomas@2359
   169
            }
Thomas@2359
   170
            catch (Exception ex)
Thomas@2359
   171
            {
Thomas@2359
   172
                Log.Verbose("BuildAndShowManager: Error resolving recipients. " + ex.ToString());
Thomas@2359
   173
            }
Thomas@2359
   174
Thomas@2359
   175
            // Build the dialog
Thomas@2359
   176
            try
Thomas@2359
   177
            {
Thomas@2359
   178
                // The PEPMessage to build the dialog with
Thomas@2359
   179
                PEPMessage message = null;
Thomas@2359
   180
Thomas@2359
   181
                // The own identity to build the dialog with
Thomas@2359
   182
                PEPIdentity myself = this.cryptableMailItem?.Myself;
Thomas@2359
   183
Thomas@2359
   184
                // If message is a draft, create it directly from the Outlook mail item
Thomas@2359
   185
                if (this.IsDraft)
Thomas@2359
   186
                {
Thomas@2359
   187
                    Log.Verbose("BuildAndShowManager: Creating PEPMessage from draft.");
Thomas@2359
   188
Thomas@2385
   189
                    if (PEPMessage.Create(this.CurrentMailItem, out message) != Globals.ReturnStatus.Success)
Thomas@2359
   190
                    {
Thomas@2359
   191
                        Log.Error("BuildAndShowManager: Error creating PEPMessage from draft.");
Thomas@2359
   192
                        message = null;
Thomas@2359
   193
                    }
Thomas@2359
   194
                    else
Thomas@2359
   195
                    {
Thomas@2359
   196
                        // Calculate rating
Thomas@2359
   197
                        message.Rating = message.GetOutgoingRating();
Thomas@2359
   198
Thomas@2359
   199
                        // If Force Protection is set, assign a random GUID
Thomas@2359
   200
                        if ((this.ForceProtection) &&
Thomas@2359
   201
                            (this.DisableForceProtection == false))
Thomas@2359
   202
                        {
Thomas@2359
   203
                            message.ForceProtectionId = Guid.NewGuid().ToString();
Thomas@2359
   204
                        }
Thomas@2359
   205
Thomas@2359
   206
                        // If message is Force Unencrypted, assign it
Thomas@2359
   207
                        message.ForceUnencrypted = this.ForceUnencrypted;
Thomas@2359
   208
                    }
Thomas@2359
   209
                }
Thomas@2359
   210
                else
Thomas@2359
   211
                {
Thomas@2359
   212
                    // Else, use either the cryptable mail item's associated mirror or message
Thomas@2359
   213
                    message = this.cryptableMailItem?.Mirror ?? this.cryptableMailItem?.Message;
Thomas@2359
   214
                    Log.Verbose(string.Format("BuildAndShowManager: Message {0} retrieved from CryptableMailItem", ((message != null) ? "successfully" : "could not be")));
Thomas@2359
   215
Thomas@2359
   216
                    // As fallback, if we don't have a message yet, create it
Thomas@2359
   217
                    if (message == null)
Thomas@2359
   218
                    {
Thomas@2359
   219
                        Log.Verbose("BuildAndShowManager: Using fallback method to get message.");
Thomas@2359
   220
Thomas@2359
   221
                        Outlook.MailItem mirror = null;
Thomas@2359
   222
Thomas@2359
   223
                        try
Thomas@2359
   224
                        {
Thomas@2359
   225
                            // For securely stored mails, try to look up mirror
Thomas@2385
   226
                            if (this.CurrentMailItem?.GetIsSecurelyStored() == true)
Thomas@2359
   227
                            {
Thomas@2385
   228
                                mirror = this.CurrentMailItem?.GetMirror();
Thomas@2359
   229
Thomas@2359
   230
                                if (mirror != null)
Thomas@2359
   231
                                {
Thomas@2359
   232
                                    // If mirror is found, use it to create PEPMessage
Thomas@2359
   233
                                    Log.Verbose("BuildAndShowManager: Mirror found.");
Thomas@2359
   234
Thomas@2359
   235
                                    if (PEPMessage.Create(mirror, out message) != Globals.ReturnStatus.Success)
Thomas@2359
   236
                                    {
Thomas@2359
   237
                                        message = null;
Thomas@2359
   238
                                        Log.Error("BuildAndShowManager: Error creating PEPMessage.");
Thomas@2359
   239
                                    }
Thomas@2359
   240
                                    else
Thomas@2359
   241
                                    {
Thomas@2359
   242
                                        message.Rating = AdapterExtensions.ReevaluateMessageRating(message);
Thomas@2359
   243
                                    }
Thomas@2359
   244
                                }
Thomas@2359
   245
                                else
Thomas@2359
   246
                                {
Thomas@2359
   247
                                    // If no mirror is found, decrypt message and use decrypted one (do not 
Thomas@2359
   248
                                    // decrypt forcefully protected messages).
Thomas@2385
   249
                                    if ((PEPMessage.Create(this.CurrentMailItem, out message) == Globals.ReturnStatus.Success) &&
Thomas@2359
   250
                                        (string.IsNullOrEmpty(message.ForceProtectionId)))
Thomas@2359
   251
                                    {
Thomas@2359
   252
                                        var msgProcessor = new MsgProcessor();
Thomas@2359
   253
                                        PEPMessage decryptedMsg = null;
Thomas@2359
   254
                                        string[] keyList;
Thomas@2359
   255
                                        pEpDecryptFlags flags = pEpDecryptFlags.pEpDecryptFlagsNone;
Thomas@2359
   256
                                        pEpRating rating = msgProcessor.Decrypt(ref message, out decryptedMsg, out keyList, ref flags);
Thomas@2359
   257
                                        if (decryptedMsg != null)
Thomas@2359
   258
                                        {
Thomas@2359
   259
                                            message = decryptedMsg;
Thomas@2359
   260
                                        }
Thomas@2359
   261
                                        message.Rating = rating;
Thomas@2359
   262
                                    }
Thomas@2359
   263
                                    else
Thomas@2359
   264
                                    {
Thomas@2359
   265
                                        message = null;
Thomas@2359
   266
                                        Log.Error("BuildAndShowManager: Error creating PEPMessage from mirror.");
Thomas@2359
   267
                                    }
Thomas@2359
   268
                                }
Thomas@2359
   269
                            }
Thomas@2359
   270
Thomas@2359
   271
                            // If we don't have a PEPMessage yet, create it
Thomas@2359
   272
                            if (message == null)
Thomas@2359
   273
                            {
Thomas@2359
   274
                                Log.Verbose("BuildAndShowManager: Creating PEPMessage.");
Thomas@2359
   275
Thomas@2385
   276
                                if (PEPMessage.Create(this.CurrentMailItem, out message) != Globals.ReturnStatus.Success)
Thomas@2359
   277
                                {
Thomas@2359
   278
                                    message = null;
Thomas@2359
   279
                                    Log.Error("BuildAndShowManager: Error creating PEPMessage.");
Thomas@2359
   280
                                }
Thomas@2359
   281
                                else
Thomas@2359
   282
                                {
Thomas@2359
   283
                                    message.Rating = AdapterExtensions.ReevaluateMessageRating(message);
Thomas@2359
   284
                                }
Thomas@2359
   285
                            }
Thomas@2359
   286
Thomas@2359
   287
                            // Get myself identiy if we don't have it yet
Thomas@2359
   288
                            if (myself == null)
Thomas@2359
   289
                            {
Thomas@2385
   290
                                myself = this.CurrentMailItem.GetMyselfIdentity();
Thomas@2359
   291
                            }
Thomas@2359
   292
                        }
Thomas@2359
   293
                        catch (Exception ex)
Thomas@2359
   294
                        {
Thomas@2359
   295
                            Log.Error("FormRegionPrivacyStatus.Message: Error converting message. " + ex.ToString());
Thomas@2359
   296
                        }
Thomas@2359
   297
                        finally
Thomas@2359
   298
                        {
Thomas@2359
   299
                            mirror = null;
Thomas@2359
   300
                        }
Thomas@2359
   301
                    }
Thomas@2359
   302
                }
Thomas@2359
   303
Thomas@2359
   304
                // Build dialog
Thomas@2359
   305
                if (message != null)
Thomas@2359
   306
                {
Thomas@2359
   307
                    handshakeDialog = new HandshakeDialog(message, myself, this.IsDraft);
Thomas@2359
   308
                    handshakeDialog.OnUpdateStatus += HandshakeDialog_Updated;
Thomas@2359
   309
                    handshakeDialog.Closed += HandshakeDialog_Closed;
Thomas@2359
   310
                    handshakeDialog.Show();
Thomas@2359
   311
                }
Thomas@2359
   312
                else
Thomas@2359
   313
                {
Thomas@2359
   314
                    throw new Exception("Could not build handshake dialog. Message is null.");
Thomas@2359
   315
                }
Thomas@2359
   316
            }
Thomas@2359
   317
            catch (Exception ex)
Thomas@2359
   318
            {
Thomas@2359
   319
                Globals.StopAndSendCrashReport(ex);
Thomas@2359
   320
            }
Thomas@2359
   321
        }
Thomas@2359
   322
Thomas@2359
   323
        /// <summary>
Thomas@2445
   324
        /// Initializes the watched explorer or inspector window.
Thomas@2445
   325
        /// </summary>
Thomas@2445
   326
        /// <param name="isInlineResponse">Whether this window is an inline response.</param>
Thomas@2445
   327
        protected void InitializeWindow(bool isInlineResponse = false)
Thomas@2445
   328
        {
Thomas@2445
   329
            bool enableFormRegion = false;
Thomas@2445
   330
            bool cancelOpenEvent = false;
Thomas@2445
   331
            bool isSecureAttachedMail = false;
Thomas@2445
   332
            string messageId = null;
Thomas@2445
   333
            PEPCache.CacheItem cacheItem = null;
Thomas@2445
   334
Thomas@2445
   335
            try
Thomas@2445
   336
            {
Thomas@2445
   337
                // Check if draft
Thomas@2445
   338
                this.IsDraft = this.CurrentMailItem.GetIsDraft();
Thomas@2445
   339
Thomas@2445
   340
                /* Set immediately a provisional rating in order to have a less flickery
Thomas@2445
   341
                 * UI experience.
Thomas@2445
   342
                 * The provisional rating is either a stored rating or, in case we have a
Thomas@2445
   343
                 * reply message, the rating of the original (the item we reply to).
Thomas@2445
   344
                 * This provisional rating will be replace with the real one once the full
Thomas@2445
   345
                 * processing is complete.
Thomas@2445
   346
                 */
Thomas@2445
   347
                pEpRating provisionalRating = pEpRating.pEpRatingUndefined;
Thomas@2445
   348
Thomas@2445
   349
                // Try to get an original rating (in case of reply messages)
Thomas@2445
   350
                if ((this.IsDraft) &&
Thomas@2445
   351
                    (this.CurrentMailItem?.Recipients?.Count > 0))
Thomas@2445
   352
                {
Thomas@2445
   353
                    string originalRatingString = this.CurrentMailItem.GetUserProperty(CryptableMailItem.USER_PROPERTY_KEY_ORIGINAL_RATING) as string;
Thomas@2445
   354
Thomas@2445
   355
                    // If we have an original rating, parse it and set it.
Thomas@2445
   356
                    if (string.IsNullOrEmpty(originalRatingString) == false)
Thomas@2445
   357
                    {
Thomas@2445
   358
                        provisionalRating = AdapterExtensions.ParseRatingString(originalRatingString);
Thomas@2445
   359
                    }
Thomas@2445
   360
                }
Thomas@2445
   361
                else
Thomas@2445
   362
                {
Thomas@2445
   363
                    // Try to get item from cache
Thomas@2445
   364
                    cacheItem = PEPCache.GetItemFromCache(this.CurrentMailItem.EntryID);
Thomas@2445
   365
Thomas@2445
   366
                    if (cacheItem != null)
Thomas@2445
   367
                    {
Thomas@2445
   368
                        // Set rating from cache
Thomas@2445
   369
                        provisionalRating = cacheItem?.Rating ?? pEpRating.pEpRatingUndefined;
Thomas@2445
   370
                    }
Thomas@2445
   371
                    else
Thomas@2445
   372
                    {
Thomas@2445
   373
                        // Get rating from db
Thomas@2445
   374
                        provisionalRating = PEPDatabase.GetRating(this.CurrentMailItem.EntryID);
Thomas@2445
   375
Thomas@2445
   376
                        // If there is no rating in the db, use stored or default rating
Thomas@2445
   377
                        if (provisionalRating == pEpRating.pEpRatingUndefined)
Thomas@2445
   378
                        {
Thomas@2445
   379
                            provisionalRating = this.CurrentMailItem.GetStoredRating() ?? pEpRating.pEpRatingUndefined;
Thomas@2445
   380
                        }
Thomas@2445
   381
                    }
Thomas@2445
   382
                }
Thomas@2445
   383
Thomas@2445
   384
                // Only set rating if one has been retrieved
Thomas@2445
   385
                if (provisionalRating != pEpRating.pEpRatingUndefined)
Thomas@2445
   386
                {
Thomas@2445
   387
                    this.SetRating(provisionalRating);
Thomas@2445
   388
                    Log.Verbose("FormRegionPrivacyStatus_FormRegionShowing: Provisional rating {0} shown.", Enum.GetName(typeof(pEpRating), provisionalRating));
Thomas@2445
   389
                }
Thomas@2445
   390
Thomas@2445
   391
                // Do not process S/MIME messages
Thomas@2445
   392
                if (this.CurrentMailItem.GetIsSMIMEEnabled())
Thomas@2445
   393
                {
Thomas@2445
   394
                    Log.Verbose("FormRegionPrivacyStatus_FormRegionShowing: S/MIME message detected. Won't be processed.");
Thomas@2445
   395
Thomas@2445
   396
                    // Set unencrypted rating
Thomas@2445
   397
                    this.SetRating(pEpRating.pEpRatingUnencrypted);
Thomas@2445
   398
Thomas@2445
   399
                    // Set icon(s) if necessary     
Thomas@2445
   400
                    if ((IsDraft == false) &&
Thomas@2445
   401
                        (this.CurrentMailItem.SetEncryptionIcons()))
Thomas@2445
   402
                    {
Thomas@2445
   403
                        try
Thomas@2445
   404
                        {
Thomas@2445
   405
                            this.CurrentMailItem.Save();
Thomas@2445
   406
                        }
Thomas@2445
   407
                        catch (Exception ex)
Thomas@2445
   408
                        {
Thomas@2445
   409
                            Log.Error("FormRegionPrivacyStatus_FormRegionShowing: Error saving message after changing icon. " + ex.ToString());
Thomas@2445
   410
                        }
Thomas@2445
   411
                    }
Thomas@2445
   412
Thomas@2445
   413
                    return;
Thomas@2445
   414
                }
Thomas@2445
   415
Thomas@2445
   416
                /* Check if item is attached mail. For performance reasons,
Thomas@2445
   417
                 * only do the whole check if an item has been loaded to the
Thomas@2445
   418
                 * cache of attached mails and if item might be secure.
Thomas@2445
   419
                 */
Thomas@2445
   420
                if ((PEPAttachment.AttachedMailsCache.Count > 0) &&
Thomas@2445
   421
                    (this.CurrentMailItem.Attachments?.Count == 2))
Thomas@2445
   422
                {
Thomas@2445
   423
                    try
Thomas@2445
   424
                    {
Thomas@2445
   425
                        // Check if mail item is an attached mail
Thomas@2445
   426
                        if (this.CurrentMailItem.GetIsAttachedMail(out messageId))
Thomas@2445
   427
                        {
Thomas@2445
   428
                            Outlook.MailItem mirror = null;
Thomas@2445
   429
                            PEPMessage pEpMessage;
Thomas@2445
   430
Thomas@2445
   431
                            // Try to get the mirror
Thomas@2445
   432
                            mirror = this.CurrentMailItem.GetMirror(messageId);
Thomas@2445
   433
Thomas@2445
   434
                            // If mirror was not found, decrypt and create mirror
Thomas@2445
   435
                            if (mirror != null)
Thomas@2445
   436
                            {
Thomas@2445
   437
                                isSecureAttachedMail = true;
Thomas@2445
   438
                            }
Thomas@2445
   439
                            else
Thomas@2445
   440
                            {
Thomas@2445
   441
                                if ((PEPMessage.Create(this.CurrentMailItem, out pEpMessage) == Globals.ReturnStatus.Success) &&
Thomas@2445
   442
                                    (pEpMessage.IsSecure))
Thomas@2445
   443
                                {
Thomas@2445
   444
                                    PEPMessage decryptedMessage;
Thomas@2445
   445
                                    MsgProcessor msgProcessor = new MsgProcessor();
Thomas@2445
   446
                                    if (msgProcessor.Decrypt(pEpMessage, out decryptedMessage))
Thomas@2445
   447
                                    {
Thomas@2445
   448
                                        isSecureAttachedMail = true;
Thomas@2445
   449
                                        mirror = this.CurrentMailItem.CreateMirrorOMI(messageId);
Thomas@2445
   450
                                        decryptedMessage.ApplyTo(mirror, true, false);
Thomas@2445
   451
                                        mirror?.Save();
Thomas@2445
   452
                                    }
Thomas@2445
   453
                                    else
Thomas@2445
   454
                                    {
Thomas@2445
   455
                                        Log.Error("FormRegionPrivacyStatus_FormRegionShowing: Decryption of attached mail was not successful.");
Thomas@2445
   456
                                    }
Thomas@2445
   457
                                }
Thomas@2445
   458
                            }
Thomas@2445
   459
Thomas@2445
   460
                            // Check if attachment is being opened or if only the preview is needed
Thomas@2445
   461
                            if (CryptableMailItem.PreviewAttachedMailId?.Equals(messageId) != true)
Thomas@2445
   462
                            {
Thomas@2445
   463
                                // Display mirror and cancel opening of original
Thomas@2445
   464
                                cancelOpenEvent = true;
Thomas@2445
   465
                                mirror?.Display();
Thomas@2445
   466
                            }
Thomas@2445
   467
Thomas@2445
   468
                            // Not needed anymore after this point
Thomas@2445
   469
                            CryptableMailItem.PreviewAttachedMailId = null;
Thomas@2445
   470
                        }
Thomas@2445
   471
                    }
Thomas@2445
   472
                    catch (Exception ex)
Thomas@2445
   473
                    {
Thomas@2445
   474
                        messageId = null;
Thomas@2445
   475
                        Log.Error("FormRegionPrivacyStatus_FormRegionShowing: Error checking for attached mail. " + ex.ToString());
Thomas@2445
   476
                    }
Thomas@2445
   477
                }
Thomas@2445
   478
Thomas@2445
   479
                // Check for item from cache and show it if possible
Thomas@2445
   480
                if ((this.IsDraft == false) &&
Thomas@2445
   481
                    (cacheItem?.Mirror != null) &&
Thomas@2445
   482
                    (this.CurrentMailItem.GetIsInSecureStore()))
Thomas@2445
   483
                {
Thomas@2445
   484
                    WindowFormRegionCollection formRegions = null;
Thomas@2445
   485
                    try
Thomas@2445
   486
                    {
Thomas@2445
   487
                        formRegions = Globals.FormRegions[this.Window];
Thomas@2445
   488
                    }
Thomas@2445
   489
                    catch (Exception ex)
Thomas@2445
   490
                    {
Thomas@2445
   491
                        Log.Error("FormRegionPrivacyStatus_FormRegionShowing: Error getting form region collection. " + ex.ToString());
Thomas@2445
   492
                    }
Thomas@2445
   493
Thomas@2445
   494
                    this.GetFormRegionPreviewUnencrypted()?.DisplayState?.SetMessage(cacheItem.Mirror);
Thomas@2445
   495
                }
Thomas@2445
   496
Thomas@2445
   497
                this.cryptableMailItem = new CryptableMailItem(this.CurrentMailItem, provisionalRating);
Thomas@2445
   498
Thomas@2445
   499
                // Set inline response property
Thomas@2445
   500
                this.cryptableMailItem.IsInlineResponse = isInlineResponse;
Thomas@2445
   501
Thomas@2445
   502
                // Set properties for encrypted attached mail
Thomas@2445
   503
                if (isSecureAttachedMail)
Thomas@2445
   504
                {
Thomas@2445
   505
                    this.cryptableMailItem.MessageId = messageId;
Thomas@2445
   506
                    this.cryptableMailItem.IsSecureAttachedMail = true;
Thomas@2445
   507
                }
Thomas@2445
   508
Thomas@2445
   509
                // Connect cryptable mail item events
Thomas@2445
   510
                if (this.cryptableMailItem != null)
Thomas@2445
   511
                {
Thomas@2445
   512
                    // If we don't open the original, set property and return
Thomas@2445
   513
                    if (cancelOpenEvent)
Thomas@2445
   514
                    {
Thomas@2445
   515
                        this.cryptableMailItem.Open += MailItem_Open;
Thomas@2445
   516
                        this.cryptableMailItem.CancelOpen = true;
Thomas@2445
   517
                        return;
Thomas@2445
   518
                    }
Thomas@2445
   519
                    else
Thomas@2445
   520
                    {
Thomas@2445
   521
                        try
Thomas@2445
   522
                        {
Thomas@2445
   523
                            this.cryptableMailItem.PropertyChanged += MailItem_PropertyChanged;
Thomas@2445
   524
                            this.cryptableMailItem.ProcessingCompleted += MailItem_ProcessingCompleted;
Thomas@2445
   525
                            this.cryptableMailItem.GetMirrorCompleted += MailItem_GetMirrorCompleted;
Thomas@2445
   526
                            this.cryptableMailItem.Send += MailItem_Send;
Thomas@2445
   527
Thomas@2445
   528
                            if (this.cryptableMailItem.IsSecurelyStored)
Thomas@2445
   529
                            {
Thomas@2445
   530
                                this.cryptableMailItem.Open += MailItem_Open;
Thomas@2445
   531
                            }
Thomas@2445
   532
                        }
Thomas@2445
   533
                        catch (Exception ex)
Thomas@2445
   534
                        {
Thomas@2445
   535
                            Log.Error("FormRegionPrivacyStatus_FormRegionShowing: Error occured. " + ex.ToString());
Thomas@2445
   536
                        }
Thomas@2445
   537
Thomas@2445
   538
                        if (this.CurrentMailItem.GetIsPEPEnabled())
Thomas@2445
   539
                        {
Thomas@2445
   540
                            // If pEp is enabled, show the form region
Thomas@2445
   541
                            enableFormRegion = true;
Thomas@2445
   542
                        }
Thomas@2445
   543
                        else
Thomas@2445
   544
                        {
Thomas@2445
   545
                            /* If pEp is disabled, process item and show form region in the following cases:
Thomas@2445
   546
                             * 1. Incoming items: if decrypt always option is set
Thomas@2445
   547
                             * 2. Outgoing items: if EnableProtection option is set
Thomas@2445
   548
                             *                    Note: if this property isn't set, subscribe to originally 
Thomas@2445
   549
                             *                          encrypted status update event handler in case the 
Thomas@2445
   550
                             *                          current code runs before CryptableMailItem.MailItem_Reply
Thomas@2445
   551
                             *                          or CryptableMailItem.MailItem_Forward.
Thomas@2445
   552
                             */
Thomas@2445
   553
                            if (this.IsDraft)
Thomas@2445
   554
                            {
Thomas@2445
   555
                                enableFormRegion = true;
Thomas@2445
   556
                                this.cryptableMailItem.OriginallyEncryptedStatusUpdated += CryptableMailItem_OriginallyEncryptedStatusUpdated;
Thomas@2445
   557
                            }
Thomas@2445
   558
                            else
Thomas@2445
   559
                            {
Thomas@2445
   560
                                enableFormRegion = this.CurrentMailItem.GetIsDecryptAlwaysEnabled();
Thomas@2445
   561
                            }
Thomas@2445
   562
                        }
Thomas@2445
   563
                    }
Thomas@2445
   564
                }
Thomas@2445
   565
Thomas@2445
   566
                // Update pEp enabled status
Thomas@2445
   567
                this.SetIsEnabled(enableFormRegion);
Thomas@2445
   568
Thomas@2445
   569
                if (this.isEnabled)
Thomas@2445
   570
                {
Thomas@2445
   571
                    // If forcefully protected, run dedicated decryption
Thomas@2445
   572
                    if (this.CurrentMailItem.GetIsForcefullyProtected())
Thomas@2445
   573
                    {
Thomas@2445
   574
                        FPPMessage fppMessage = new FPPMessage(this.CurrentMailItem);
Thomas@2445
   575
                        if ((fppMessage?.GetMessageType() != null) ||
Thomas@2445
   576
                            (fppMessage?.CurrentMessage?.IsSecure == true))
Thomas@2445
   577
                        {
Thomas@2445
   578
                            fppMessage.ProcessIncoming(true);
Thomas@2445
   579
                        }
Thomas@2445
   580
                        else
Thomas@2445
   581
                        {
Thomas@2445
   582
                            this.TimerRefresh_Tick(null, new EventArgs());
Thomas@2445
   583
                        }
Thomas@2445
   584
                    }
Thomas@2445
   585
                    else
Thomas@2445
   586
                    {
Thomas@2445
   587
                        // Call the timer tick method manually to refresh data with no delay
Thomas@2445
   588
                        this.TimerRefresh_Tick(null, new EventArgs());
Thomas@2445
   589
                    }
Thomas@2445
   590
                }
Thomas@2445
   591
            }
Thomas@2445
   592
            catch (Exception e)
Thomas@2445
   593
            {
Thomas@2445
   594
                Log.Error("Window_SelectionChange: Error. " + e.Message);
Thomas@2445
   595
            }
Thomas@2445
   596
        }
Thomas@2445
   597
Thomas@2445
   598
        /// <summary>
Thomas@2359
   599
        /// Schedules for the pEp rating and UI (including displayed mirror) to be updated.
Thomas@2359
   600
        /// This can be called many times with no issue as the update is only run every n milliseconds.
Thomas@2359
   601
        /// </summary>
Thomas@2359
   602
        public void RequestRatingAndUIUpdate()
Thomas@2359
   603
        {
Thomas@2359
   604
            if (this.isEnabled)
Thomas@2359
   605
            {
Thomas@2359
   606
                this.TimerRefresh.Enabled = true;
Thomas@2359
   607
            }
Thomas@2359
   608
        }
Thomas@2359
   609
Thomas@2359
   610
        /// <summary>
Thomas@2359
   611
        /// Immediately starts the update of UI rating based on the associated mail item.
Thomas@2359
   612
        /// This will start decryption as necessary and also will update the displayed mirror.
Thomas@2359
   613
        /// This method by-passes the refresh timer completely.
Thomas@2359
   614
        /// WARNING: This method assumes the message is fully downloaded already.
Thomas@2359
   615
        /// </summary>
Thomas@2359
   616
        private void ImmediateRatingAndUIUpdate()
Thomas@2359
   617
        {
Thomas@2359
   618
            if ((this.isEnabled) &&
Thomas@2359
   619
                (this.cryptableMailItem != null))
Thomas@2359
   620
            {
Thomas@2359
   621
                Log.Verbose("ImmediateRatingAndUIUpdate: Starting processing.");
Thomas@2359
   622
Thomas@2359
   623
                // Start the rating calculation/decryption process
Thomas@2359
   624
                this.cryptableMailItem.StartProcessing();
Thomas@2359
   625
                this.processingOngoing = true;
Thomas@2385
   626
Thomas@2385
   627
                // If we have a draft message, fetch directly a preview outgoing rating
Thomas@2385
   628
                if (this.IsDraft)
Thomas@2385
   629
                {
Thomas@2385
   630
                    pEpRating rating = this.GetOutgoingRatingPreview();
Thomas@2385
   631
Thomas@2385
   632
                    if (rating != pEpRating.pEpRatingUndefined)
Thomas@2385
   633
                    {
Thomas@2385
   634
                        this.SetRating(rating);
Thomas@2385
   635
                    }
Thomas@2385
   636
                }
Thomas@2359
   637
            }
Thomas@2359
   638
        }
Thomas@2359
   639
Thomas@2359
   640
        /// <summary>
Thomas@2385
   641
        /// Gets a preview of the outgoing rating which is faster than the full version.
Thomas@2385
   642
        /// Caveat: might show a wrong rating in case of missing keys.
Thomas@2385
   643
        /// </summary>
Thomas@2385
   644
        /// <returns>A preview of the outgoing rating.</returns>
Thomas@2385
   645
        private pEpRating GetOutgoingRatingPreview()
Thomas@2385
   646
        {
Thomas@2385
   647
            pEpRating rating = pEpRating.pEpRatingUndefined;
Thomas@2385
   648
Thomas@2385
   649
            try
Thomas@2385
   650
            {
Thomas@2385
   651
                rating = this.CurrentMailItem?.GetOutgoingRating(false, true) ?? pEpRating.pEpRatingUndefined;
Thomas@2385
   652
            }
Thomas@2385
   653
            catch (Exception ex)
Thomas@2385
   654
            {
Thomas@2385
   655
                rating = pEpRating.pEpRatingUndefined;
Thomas@2385
   656
                Log.Error("ImmediateRatingAndUIUpdate: Error getting outgoing preview rating. " + ex.ToString());
Thomas@2385
   657
            }
Thomas@2385
   658
Thomas@2385
   659
            return rating;
Thomas@2385
   660
        }
Thomas@2385
   661
Thomas@2419
   662
        /// <summary>
Thomas@2419
   663
        /// Updates the privacy state and the UI (ribbon and form region).
Thomas@2419
   664
        /// </summary>
Thomas@2419
   665
        public void UpdatePrivacyStateAndUI()
Thomas@2419
   666
        {
Thomas@2419
   667
            try
Thomas@2419
   668
            {
Thomas@2419
   669
                this.PrivacyState = new PrivacyState(this.Rating,
Thomas@2419
   670
                                                     this.ForceProtection,
Thomas@2419
   671
                                                     this.ForceUnencrypted);
Thomas@2419
   672
                RibbonCustomizations.Invalidate();
Thomas@2445
   673
                this.GetFormRegionPrivacyStatus()?.UpdateFormRegion(this.PrivacyState);
Thomas@2419
   674
            }
Thomas@2419
   675
            catch (Exception ex)
Thomas@2419
   676
            {
Thomas@2419
   677
                Log.Error("UpdateUI: Error occured. " + ex.ToString());
Thomas@2419
   678
            }
Thomas@2419
   679
        }
Thomas@2385
   680
Thomas@2445
   681
        /// <summary>
Thomas@2445
   682
        /// Gathers all form regions for this WatchedWindow.
Thomas@2445
   683
        /// </summary>
Thomas@2445
   684
        /// <returns>The gathered form regions.</returns>
Thomas@2419
   685
        internal WindowFormRegionCollection GetFormRegions()
Thomas@2419
   686
        {
Thomas@2419
   687
            /* We have to find out here if the window is an explorer or an inspector.
Thomas@2419
   688
             * Calling Globals.FormRegions[] with an ambiguous window type leads to a crash.
Thomas@2419
   689
             */
Thomas@2419
   690
            Outlook.Explorer explorer;
Thomas@2419
   691
            Outlook.Inspector inspector;
Thomas@2419
   692
            WindowFormRegionCollection formRegions = null;
Thomas@2419
   693
            try
Thomas@2419
   694
            {
Thomas@2419
   695
                explorer = this.Window as Outlook.Explorer;
Thomas@2419
   696
                if (explorer != null)
Thomas@2419
   697
                {
Thomas@2419
   698
                    formRegions = Globals.FormRegions[explorer];
Thomas@2419
   699
                }
Thomas@2419
   700
                else
Thomas@2419
   701
                {
Thomas@2419
   702
                    inspector = this.Window as Outlook.Inspector;
Thomas@2419
   703
                    formRegions = Globals.FormRegions[inspector];
Thomas@2419
   704
                }
Thomas@2419
   705
            }
Thomas@2419
   706
            catch (Exception ex)
Thomas@2419
   707
            {
Thomas@2419
   708
                formRegions = null;
Thomas@2419
   709
                Log.Error("MailItem_GetMirrorCompleted: Error getting form regions collection. " + ex.ToString());
Thomas@2419
   710
            }
Thomas@2419
   711
            finally
Thomas@2419
   712
            {
Thomas@2419
   713
                explorer = null;
Thomas@2419
   714
                inspector = null;
Thomas@2419
   715
            }
Thomas@2419
   716
Thomas@2419
   717
            return formRegions;
Thomas@2419
   718
        }
Thomas@2419
   719
Thomas@2445
   720
        /// <summary>
Thomas@2445
   721
        /// Gets the FormRegionPrivacyStatus of this WatchedWindow (if available).
Thomas@2445
   722
        /// </summary>
Thomas@2445
   723
        /// <returns>The FormRegionPrivacyStatus of this window or null.</returns>
Thomas@2419
   724
        internal FormRegionPrivacyStatus GetFormRegionPrivacyStatus()
Thomas@2419
   725
        {
Thomas@2419
   726
            return this.GetFormRegions()?.FormRegionPrivacyStatus;
Thomas@2419
   727
        }
Thomas@2419
   728
Thomas@2445
   729
        /// <summary>
Thomas@2445
   730
        /// Gets the FormRegionPreviewUnencrypted of this WatchedWindow (if available).
Thomas@2445
   731
        /// </summary>
Thomas@2445
   732
        /// <returns>The FormRegionPreviewUnencrypted of this window or null.</returns>
Thomas@2419
   733
        internal FormRegionPreviewUnencrypted GetFormRegionPreviewUnencrypted()
Thomas@2419
   734
        {
Thomas@2419
   735
            return this.GetFormRegions()?.FormRegionPreviewUnencrypted;
Thomas@2419
   736
        }
Thomas@2385
   737
Thomas@2385
   738
        /// <summary>
Thomas@2359
   739
        /// Resets the Enabled status of this form region and recalculates the rating if necessary.
Thomas@2359
   740
        /// </summary>
Thomas@2359
   741
        /// <param name="enable">Whether to enable the form region.</param>
Thomas@2359
   742
        public void UpdateFormRegion(bool enable)
Thomas@2359
   743
        {
Thomas@2359
   744
            this.SetIsEnabled(enable);
Thomas@2359
   745
Thomas@2359
   746
            // Refresh the UI
Thomas@2359
   747
            if (enable)
Thomas@2359
   748
            {
Thomas@2359
   749
                this.ResolveAllRecipients();
Thomas@2359
   750
                this.RequestRatingAndUIUpdate();
Thomas@2359
   751
            }
Thomas@2359
   752
        }
Thomas@2359
   753
Thomas@2359
   754
        /// <summary>
Thomas@2359
   755
        /// Workaround method to update the current inspector window. This is done by moving the mail item
Thomas@2359
   756
        /// to a temporary folder first and then back to the current folder. Both folders CANNOT be the same.
Thomas@2359
   757
        /// As a fallback, the mail item stays in the temporary folder if moving back to the current folder
Thomas@2359
   758
        /// fails.
Thomas@2359
   759
        /// </summary>
Thomas@2359
   760
        private void UpdateInspector()
Thomas@2359
   761
        {
Thomas@2359
   762
            Outlook.Application application = null;
Thomas@2359
   763
            Outlook.Folder currentFolder = null;
Thomas@2359
   764
            Outlook.Folder tempFolder = null;
Thomas@2359
   765
            Outlook.Inspector currentInspector = null;
Thomas@2359
   766
            Outlook.Inspector newInspector = null;
Thomas@2359
   767
            Outlook.MailItem tempMailItem = null;
Thomas@2359
   768
            Outlook.Store store = null;
Thomas@2359
   769
            Outlook.MailItem omi = this.CurrentMailItem;
Thomas@2359
   770
Thomas@2359
   771
            if (omi != null)
Thomas@2359
   772
            {
Thomas@2359
   773
                try
Thomas@2359
   774
                {
Thomas@2359
   775
                    application = omi.Application;
Thomas@2359
   776
                    currentInspector = omi.GetInspector;
Thomas@2359
   777
                    currentFolder = omi.Parent as Outlook.Folder;
Thomas@2359
   778
Thomas@2359
   779
                    if ((currentInspector != null) &&
Thomas@2359
   780
                        (application != null) &&
Thomas@2359
   781
                        (currentFolder != null))
Thomas@2359
   782
                    {
Thomas@2359
   783
                        var left = currentInspector.Left;
Thomas@2359
   784
                        var top = currentInspector.Top;
Thomas@2359
   785
                        var width = currentInspector.Width;
Thomas@2359
   786
                        var height = currentInspector.Height;
Thomas@2359
   787
                        var windowState = currentInspector.WindowState;
Thomas@2359
   788
Thomas@2359
   789
                        /* Check, if in trusted store. In that case, use the default drafts folder
Thomas@2359
   790
                         * as temporary folder. If the store is untrusted, use the pEp drafts folder.
Thomas@2359
   791
                         */
Thomas@2359
   792
                        store = currentFolder.Store;
Thomas@2359
   793
                        if (store?.GetIsSecureStorageEnabled() ?? false)
Thomas@2359
   794
                        {
Thomas@2359
   795
                            tempFolder = Globals.ThisAddIn.GetPEPStoreDraftsFolder();
Thomas@2359
   796
                        }
Thomas@2359
   797
                        else
Thomas@2359
   798
                        {
Thomas@2359
   799
                            tempFolder = store.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts) as Outlook.Folder;
Thomas@2359
   800
                        }
Thomas@2359
   801
Thomas@2359
   802
                        if (tempFolder != null)
Thomas@2359
   803
                        {
Thomas@2359
   804
                            tempMailItem = omi.Move(tempFolder) as Outlook.MailItem;
Thomas@2359
   805
Thomas@2359
   806
                            if (tempMailItem != null)
Thomas@2359
   807
                            {
Thomas@2359
   808
                                try
Thomas@2359
   809
                                {
Thomas@2359
   810
                                    omi = tempMailItem.Move(currentFolder) as Outlook.MailItem;
Thomas@2359
   811
                                }
Thomas@2359
   812
                                catch
Thomas@2359
   813
                                {
Thomas@2359
   814
                                    omi = tempMailItem.Copy();
Thomas@2359
   815
                                }
Thomas@2359
   816
Thomas@2359
   817
                                newInspector = application.Inspectors.Add(omi);
Thomas@2359
   818
Thomas@2359
   819
                                if (windowState == Outlook.OlWindowState.olNormalWindow)
Thomas@2359
   820
                                {
Thomas@2359
   821
                                    newInspector.Left = left;
Thomas@2359
   822
                                    newInspector.Top = top;
Thomas@2359
   823
                                    newInspector.Width = width;
Thomas@2359
   824
                                    newInspector.Height = height;
Thomas@2359
   825
                                }
Thomas@2359
   826
Thomas@2359
   827
                                newInspector.Display();
Thomas@2359
   828
                                newInspector.WindowState = windowState;
Thomas@2359
   829
Thomas@2359
   830
                                repeatProcessing = false;
Thomas@2359
   831
                            }
Thomas@2359
   832
                        }
Thomas@2359
   833
                        else
Thomas@2359
   834
                        {
Thomas@2359
   835
                            Log.Error("UpdateInspector: Cannot get temporary folder.");
Thomas@2359
   836
                        }
Thomas@2359
   837
                    }
Thomas@2359
   838
                    else
Thomas@2359
   839
                    {
Thomas@2359
   840
                        Log.Verbose("UpdateInspector: Error retrieving inspector window or application.");
Thomas@2359
   841
                    }
Thomas@2359
   842
                }
Thomas@2359
   843
                catch (Exception ex)
Thomas@2359
   844
                {
Thomas@2359
   845
                    Log.Verbose("UpdateInspector: Error updating inspector window. " + ex.ToString());
Thomas@2359
   846
                }
Thomas@2359
   847
                finally
Thomas@2359
   848
                {
Thomas@2359
   849
                    application = null;
Thomas@2359
   850
                    currentInspector = null;
Thomas@2359
   851
                    newInspector = null;
Thomas@2359
   852
                    omi = null;
Thomas@2359
   853
                    tempMailItem = null;
Thomas@2359
   854
                }
Thomas@2359
   855
            }
Thomas@2359
   856
        }
Thomas@2359
   857
Thomas@2359
   858
        /// <summary>
Thomas@2359
   859
        /// Clears the associated unencrypted preview and displays the given note (if any).
Thomas@2359
   860
        /// </summary>
Thomas@2359
   861
        /// <param name="note">The note to display.</param>
Thomas@2359
   862
        private void SetNote(string note = null)
Thomas@2359
   863
        {
Thomas@2359
   864
            WindowFormRegionCollection formRegions = Globals.FormRegions[Globals.ThisAddIn.Application.ActiveWindow()];
Thomas@2359
   865
Thomas@2359
   866
            if ((formRegions != null) &&
Thomas@2359
   867
                (string.IsNullOrEmpty(note) == false))
Thomas@2359
   868
            {
Thomas@2359
   869
                if ((formRegions.FormRegionPreviewUnencrypted != null) &&
Thomas@2359
   870
                    (formRegions.FormRegionPreviewUnencrypted.Visible))
Thomas@2359
   871
                {
Thomas@2359
   872
                    formRegions.FormRegionPreviewUnencrypted.DisplayState.SetNote(note);
Thomas@2359
   873
                }
Thomas@2359
   874
            }
Thomas@2359
   875
        }
Thomas@2359
   876
Thomas@2359
   877
        /// <summary>
Thomas@2359
   878
        /// Sets whether processing of the mail item is enabled.
Thomas@2359
   879
        /// This should commonly be set from the .GetIsPEPEnabled() value.
Thomas@2359
   880
        /// </summary>
Thomas@2359
   881
        private void SetIsEnabled(bool enabled)
Thomas@2359
   882
        {
Thomas@2359
   883
            PEPIdentity currIdent;
Thomas@2359
   884
            Globals.ReturnStatus sts;
Thomas@2359
   885
            Outlook.Recipient currUser = null;
Thomas@2359
   886
            Outlook.Account currAccount = null;
Thomas@2359
   887
            Outlook.Account sendingAccount = null;
Thomas@2359
   888
            Outlook.NameSpace ns = null;
Thomas@2359
   889
Thomas@2359
   890
            this.isEnabled = enabled;
Thomas@2359
   891
Thomas@2359
   892
            if (enabled)
Thomas@2359
   893
            {
Thomas@2359
   894
                // Do not allow initialization more than once
Thomas@2359
   895
                if (this.isStarted == false)
Thomas@2359
   896
                {
Thomas@2359
   897
                    /* It's possible for new draft MailItems to be created outside the context of an account.
Thomas@2359
   898
                     * In this situation the SendUsingAccount will always be null which of course breaks several pEp operations.
Thomas@2359
   899
                     * The operations themselves cannot make the assumption about what account information to use.
Thomas@2359
   900
                     * Therefore, the situation is detected here and for draft mail items a null SendUsingAccount will be 
Thomas@2359
   901
                     * set with the session's default account.
Thomas@2359
   902
                     */
Thomas@2360
   903
                    if (this.IsDraft)
Thomas@2359
   904
                    {
Thomas@2360
   905
                        try
Thomas@2359
   906
                        {
Thomas@2385
   907
                            sendingAccount = this.CurrentMailItem.SendUsingAccount;
Thomas@2359
   908
                            if (sendingAccount == null)
Thomas@2359
   909
                            {
Thomas@2360
   910
                                ns = Globals.ThisAddIn.Application.Session;
Thomas@2360
   911
                                currUser = ns.CurrentUser;
Thomas@2359
   912
                                sts = PEPIdentity.Create(currUser, out currIdent);
Thomas@2359
   913
Thomas@2359
   914
                                if (sts == Globals.ReturnStatus.Success)
Thomas@2359
   915
                                {
Thomas@2359
   916
                                    sendingAccount = AccountExtensions.GetDefaultAccount(Outlook.OlDefaultFolders.olFolderDrafts);
Thomas@2359
   917
                                    if (sendingAccount != null)
Thomas@2359
   918
                                    {
Thomas@2385
   919
                                        this.CurrentMailItem.SendUsingAccount = currAccount;
Thomas@2359
   920
                                    }
Thomas@2359
   921
                                }
Thomas@2359
   922
                            }
Thomas@2359
   923
Thomas@2359
   924
                            // Check if account is already registered in pEp list and add it if necessary
Thomas@2359
   925
                            var acctSettings = Globals.ThisAddIn.Settings.GetAccountSettings(sendingAccount?.SmtpAddress);
Thomas@2359
   926
                            if (acctSettings == null)
Thomas@2359
   927
                            {
Thomas@2359
   928
                                Log.Verbose("SetIsEnabled: New account detected. Creating pEp settings.");
Thomas@2359
   929
Thomas@2359
   930
                                // Create pEp settings for the new account
Thomas@2359
   931
                                acctSettings = sendingAccount.CreatePEPSettings();
Thomas@2359
   932
Thomas@2359
   933
                                // Add account to list
Thomas@2359
   934
                                Globals.ThisAddIn.Settings.AccountsAddedWhileRunningList.Add(acctSettings?.SmtpAddress);
Thomas@2359
   935
                                Log.Verbose("SetIsEnabled: New account registered in pEp settings.");
Thomas@2359
   936
Thomas@2359
   937
                                // Generate key
Thomas@2359
   938
                                Globals.ThisAddIn.RegisterMyself(acctSettings);
Thomas@2359
   939
                                Log.Verbose("SetIsEnabled: Myself registered.");
Thomas@2359
   940
Thomas@2359
   941
                                // Set rules and view filters
Thomas@2438
   942
                                Globals.ThisAddIn.SetRulesAndViewFilters(sendingAccount, Globals.ThisAddIn.Settings.HideInternalMessages);
Thomas@2359
   943
                            }
Thomas@2359
   944
                        }
Thomas@2360
   945
                        catch (Exception ex)
Thomas@2360
   946
                        {
Thomas@2360
   947
                            Log.Error("SetIsEnabled: Error occured. " + ex.ToString());
Thomas@2360
   948
                        }
Thomas@2360
   949
                        finally
Thomas@2360
   950
                        {
Thomas@2360
   951
                            currAccount = null;
Thomas@2360
   952
                            currUser = null;
Thomas@2360
   953
                            ns = null;
Thomas@2360
   954
                            sendingAccount = null;
Thomas@2360
   955
                        }
Thomas@2359
   956
                    }
Thomas@2359
   957
Thomas@2359
   958
                    // Connect refresh timer
Thomas@2359
   959
                    this.TimerRefresh.Tick += TimerRefresh_Tick;
Thomas@2359
   960
                    this.isStarted = true;
Thomas@2359
   961
                }
Thomas@2359
   962
            }
Thomas@2359
   963
            else
Thomas@2359
   964
            {
Thomas@2359
   965
                // Stop and disconnect the refresh timer
Thomas@2359
   966
                this.TimerRefresh.Stop();
Thomas@2359
   967
                this.TimerRefresh.Enabled = false;
Thomas@2359
   968
                this.TimerRefresh.Tick -= TimerRefresh_Tick;
Thomas@2359
   969
Thomas@2359
   970
                this.isStarted = false;
Thomas@2359
   971
            }
Thomas@2359
   972
        }
Thomas@2359
   973
Thomas@2359
   974
        /// <summary>
Thomas@2359
   975
        /// Resolves all recipients of the Outlook mail item.
Thomas@2359
   976
        /// </summary>
Thomas@2359
   977
        private void ResolveAllRecipients()
Thomas@2359
   978
        {
Thomas@2359
   979
            if ((this.isEnabled) &&
Thomas@2359
   980
                (this.cryptableMailItem != null))
Thomas@2359
   981
            {
Thomas@2359
   982
                /*
Thomas@2359
   983
                 * Note: The PropertyChanged changed event must be disconnected before trying to resolve.
Thomas@2359
   984
                 * This is because the resolve process can modify the contents of the mail item which triggers an event.
Thomas@2359
   985
                 * The PropertyChanged event would then trigger a UI refresh cycle. However, because the GetManagerState itself 
Thomas@2359
   986
                 * is called within the UI refresh, an infinite loop could occur trying to resolve a recipient that
Thomas@2359
   987
                 * cannot be resolved(no address).
Thomas@2359
   988
                 */
Thomas@2359
   989
                try
Thomas@2359
   990
                {
Thomas@2359
   991
                    this.cryptableMailItem.PropertyChanged -= MailItem_PropertyChanged;
Thomas@2359
   992
                    this.cryptableMailItem.ResolveAllRecipients();
Thomas@2359
   993
                    this.cryptableMailItem.PropertyChanged += MailItem_PropertyChanged;
Thomas@2359
   994
                }
Thomas@2359
   995
                catch (Exception ex)
Thomas@2359
   996
                {
Thomas@2359
   997
                    Log.Error("Error resolving recipients. " + ex.ToString());
Thomas@2359
   998
                }
Thomas@2359
   999
            }
Thomas@2359
  1000
        }
Thomas@2359
  1001
        #endregion
Thomas@2359
  1002
Thomas@2359
  1003
        #region Event Handling
Thomas@2359
  1004
        /**************************************************************
Thomas@2359
  1005
         * 
Thomas@2359
  1006
         * Event Handling
Thomas@2359
  1007
         * 
Thomas@2359
  1008
         *************************************************************/
Thomas@2359
  1009
Thomas@2359
  1010
        /// <summary>
Thomas@2359
  1011
        /// Event handler for when the processing is completed in the associated mail item.
Thomas@2359
  1012
        /// This will then update the form region UI and the privacy status window as needed.
Thomas@2359
  1013
        /// </summary>
Thomas@2359
  1014
        private void MailItem_ProcessingCompleted(object sender, MsgProcessor.ProcessingCompletedEventArgs e)
Thomas@2359
  1015
        {
Thomas@2359
  1016
            Log.Verbose("MailItem_ProcessingComplete: Decryption completed.");
Thomas@2359
  1017
Thomas@2359
  1018
            try
Thomas@2359
  1019
            {
Thomas@2359
  1020
                // Marshal code back to UI thread as necessary
Thomas@2359
  1021
                KeySyncWizard.Wizard.Dispatcher.Invoke(new Action(() =>
Thomas@2359
  1022
                {
Thomas@2359
  1023
                    if (this.isEnabled)
Thomas@2359
  1024
                    {
Thomas@2359
  1025
                        try
Thomas@2359
  1026
                        {
Thomas@2359
  1027
                            this.SetRating(e.ProcessedRating);
Thomas@2359
  1028
Thomas@2359
  1029
                            // Set MAPI properties if needed
Thomas@2359
  1030
                            if (e.PropertiesToSet?.Count > 0)
Thomas@2359
  1031
                            {
Thomas@2385
  1032
                                this.CurrentMailItem?.SetMAPIProperties(e.PropertiesToSet);
Thomas@2359
  1033
                            }
Thomas@2359
  1034
                            Log.Verbose("MailItem_ProcessingComplete: Status bar updated with rating " + Enum.GetName(typeof(pEpRating), e.ProcessedRating));
Thomas@2359
  1035
                        }
Thomas@2359
  1036
                        catch (Exception ex)
Thomas@2359
  1037
                        {
Thomas@2359
  1038
                            Log.Verbose("MailItem_ProcessingComplete: Error. " + ex.ToString());
Thomas@2359
  1039
                        }
Thomas@2359
  1040
Thomas@2359
  1041
                        if (repeatProcessing &&
Thomas@2359
  1042
                            (repeatCounter++ < maxRepeatCount))
Thomas@2359
  1043
                        {
Thomas@2359
  1044
                            repeatProcessing = false;
Thomas@2359
  1045
                            this.RequestRatingAndUIUpdate();
Thomas@2359
  1046
                        }
Thomas@2359
  1047
                        else
Thomas@2359
  1048
                        {
Thomas@2359
  1049
                            /* Check if the mail item is in Outbox and update the inspector window if possible.
Thomas@2359
  1050
                             * This is the case when a submitted, but not yet sent email is opened again when working 
Thomas@2359
  1051
                             * offline or without internet connection. Without this update, Outlook removes the message class 
Thomas@2359
  1052
                             * "IPM.Note.SMIME.MultipartSigned" at the next send event and the message gets invalid and can't be
Thomas@2359
  1053
                             * opened again (i.e. is lost).
Thomas@2359
  1054
                             */
Thomas@2359
  1055
                            try
Thomas@2359
  1056
                            {
Thomas@2385
  1057
                                if ((this.CurrentMailItem?.GetIsSubmitted() == true) &&
Thomas@2359
  1058
                                    (this.IsDraft))
Thomas@2359
  1059
                                {
Thomas@2359
  1060
                                    UpdateInspector();
Thomas@2359
  1061
                                }
Thomas@2359
  1062
                            }
Thomas@2359
  1063
                            catch (Exception ex)
Thomas@2359
  1064
                            {
Thomas@2359
  1065
                                Log.Verbose("MailItem_ProcessingComplete: Error while checking if mail item is in outbox or updating inspector. " + ex.Message);
Thomas@2359
  1066
                            }
Thomas@2359
  1067
Thomas@2359
  1068
                            /* Create the unencrypted preview if the mail item is encrypted and
Thomas@2359
  1069
                             * it is in an encrypted (untrusted) store
Thomas@2359
  1070
                             * 
Thomas@2359
  1071
                             * This is done here because FormRegionPrivacyStatus has the cryptable mail item and
Thomas@2359
  1072
                             * it also is initialized after FormRegionPreviewUnencrypted.
Thomas@2359
  1073
                             */
Thomas@2359
  1074
                            try
Thomas@2359
  1075
                            {
Thomas@2359
  1076
                                if (this.cryptableMailItem.IsSecurelyStored || this.cryptableMailItem.IsSecureAttachedMail)
Thomas@2359
  1077
                                {
Thomas@2359
  1078
                                    Log.Verbose("MailItem_ProcessingComplete: Starting mirror location.");
Thomas@2359
  1079
                                    this.cryptableMailItem.StartGetMirror(this.cryptableMailItem.MessageId);
Thomas@2359
  1080
                                }
Thomas@2359
  1081
                                else
Thomas@2359
  1082
                                {
Thomas@2359
  1083
                                    this.SetNote();
Thomas@2359
  1084
                                }
Thomas@2359
  1085
                            }
Thomas@2359
  1086
                            catch (Exception ex)
Thomas@2359
  1087
                            {
Thomas@2359
  1088
                                // Error is possible in some situations where the mail item was deleted or moved while decryption was ongoing.
Thomas@2359
  1089
                                // While rare, just log the issue and stop the process
Thomas@2359
  1090
                                Log.Warning("MailItem_ProcessingComplete: Failed to start mirror location, " + ex.ToString());
Thomas@2359
  1091
                            }
Thomas@2359
  1092
Thomas@2359
  1093
                            /* OUT-470: Workaround until this is implemented in the engine:
Thomas@2359
  1094
                             * Only enable Force Protection if all recipients are grey
Thomas@2359
  1095
                             */
Thomas@2359
  1096
                            if (this.IsDraft)
Thomas@2359
  1097
                            {
Thomas@2359
  1098
                                bool disableForceProtection = false;
Thomas@2359
  1099
                                Outlook.Recipients recipients = null;
Thomas@2359
  1100
                                Outlook.Recipient recipient = null;
Thomas@2359
  1101
                                PEPIdentity pEpIdentity = null;
Thomas@2359
  1102
Thomas@2359
  1103
                                try
Thomas@2359
  1104
                                {
Thomas@2385
  1105
                                    recipients = this.CurrentMailItem?.Recipients;
Thomas@2359
  1106
                                    if (recipients?.Count > 0)
Thomas@2359
  1107
                                    {
Thomas@2359
  1108
                                        for (int i = 1; i <= recipients.Count; i++)
Thomas@2359
  1109
                                        {
Thomas@2359
  1110
                                            recipient = recipients[i];
Thomas@2359
  1111
                                            if ((PEPIdentity.Create(recipient, out pEpIdentity, false) == Globals.ReturnStatus.Success) &&
Thomas@2359
  1112
                                                ((PEPIdentity.GetIsOwnIdentity(pEpIdentity.Address) ||
Thomas@2359
  1113
                                                 (ThisAddIn.PEPEngine.IdentityRating(pEpIdentity.ToCOMType()) >= pEpRating.pEpRatingReliable))))
Thomas@2359
  1114
                                            {
Thomas@2359
  1115
                                                disableForceProtection = true;
Thomas@2359
  1116
                                                Log.Verbose("ToggleButtonForceProtection_GetEnabled: Secure recipient found. Disabling force protection.");
Thomas@2359
  1117
                                                break;
Thomas@2359
  1118
                                            }
Thomas@2359
  1119
                                        }
Thomas@2359
  1120
                                    }
Thomas@2359
  1121
                                    else
Thomas@2359
  1122
                                    {
Thomas@2359
  1123
                                        // If there aren't any recipients (anymore), reset values
Thomas@2359
  1124
                                        this.DisableForceProtection = false;
Thomas@2359
  1125
                                        this.ForceProtection = false;
Thomas@2359
  1126
                                        this.NeverUnsecure = false;
Thomas@2359
  1127
                                        this.ForceUnencrypted = false;
Thomas@2359
  1128
                                    }
Thomas@2359
  1129
                                }
Thomas@2359
  1130
                                catch (Exception ex)
Thomas@2359
  1131
                                {
Thomas@2359
  1132
                                    Log.Error("ToggleButtonForceProtection_GetEnabled: Error occured. " + ex.ToString());
Thomas@2359
  1133
                                }
Thomas@2359
  1134
                                finally
Thomas@2359
  1135
                                {
Thomas@2359
  1136
                                    recipient = null;
Thomas@2359
  1137
                                    recipients = null;
Thomas@2359
  1138
                                }
Thomas@2359
  1139
Thomas@2359
  1140
                                this.DisableForceProtection = disableForceProtection;
Thomas@2359
  1141
                            }
Thomas@2359
  1142
                        }
Thomas@2359
  1143
                    }
Thomas@2359
  1144
                }));
Thomas@2359
  1145
            }
Thomas@2359
  1146
            catch (Exception ex)
Thomas@2359
  1147
            {
Thomas@2359
  1148
                Log.Error("MailItem_ProcessingComplete: Error setting UI state, " + ex.ToString());
Thomas@2359
  1149
            }
Thomas@2359
  1150
Thomas@2359
  1151
            this.processingOngoing = false;
Thomas@2359
  1152
        }
Thomas@2359
  1153
Thomas@2359
  1154
        /// <summary>
Thomas@2359
  1155
        /// Event handler for when the get mirror locating process is complete for the associated mail item.
Thomas@2359
  1156
        /// This will then update the unencrypted preview in the UI.
Thomas@2359
  1157
        /// </summary>
Thomas@2359
  1158
        private void MailItem_GetMirrorCompleted(object sender, CryptableMailItem.GetMirrorCompletedEventArgs e)
Thomas@2359
  1159
        {
Thomas@2359
  1160
            try
Thomas@2359
  1161
            {
Thomas@2359
  1162
                // Marshal code back to UI thread as necessary
Thomas@2359
  1163
                KeySyncWizard.Wizard.Dispatcher.Invoke(new Action(() =>
Thomas@2359
  1164
                {
Thomas@2359
  1165
                    if (this.isEnabled)
Thomas@2359
  1166
                    {
Thomas@2359
  1167
                        // If the message was forcefully protected, there is no mirror and we show the actual message
Thomas@2359
  1168
                        if ((e.Mirror == null) &&
Thomas@2385
  1169
                            (this.CurrentMailItem?.GetIsForcefullyProtected() == true))
Thomas@2359
  1170
                        {
Thomas@2359
  1171
                            PEPMessage mirror = null;
Thomas@2385
  1172
                            if (PEPMessage.Create(this.CurrentMailItem, out mirror) == Globals.ReturnStatus.Success)
Thomas@2359
  1173
                            {
Thomas@2359
  1174
                                e.Mirror = mirror;
Thomas@2359
  1175
                            }
Thomas@2359
  1176
                        }
Thomas@2359
  1177
Thomas@2359
  1178
                        if ((e.Mirror == null) &&
Thomas@2359
  1179
                            (this.cryptableMailItem.LastProcessedStatus == Globals.ReturnStatus.Failure))
Thomas@2359
  1180
                        {
Thomas@2359
  1181
                            this.SetNote(Properties.Resources.Message_OpenError);
Thomas@2359
  1182
                            Log.Verbose("MailItem_GetMirrorComplete: Cannot display mirror, failure during decryption.");
Thomas@2359
  1183
                        }
Thomas@2359
  1184
                        else if ((e.Mirror == null) &&
Thomas@2359
  1185
                                 (this.cryptableMailItem.LastProcessedStatus == Globals.ReturnStatus.FailureNoConnection))
Thomas@2359
  1186
                        {
Thomas@2359
  1187
                            this.SetNote(Properties.Resources.Message_DecryptionNoConnection);
Thomas@2359
  1188
                            Log.Verbose("MailItem_GetMirrorComplete: Cannot display mirror, connection failure during decryption.");
Thomas@2359
  1189
                        }
Thomas@2359
  1190
                        else
Thomas@2359
  1191
                        {
Thomas@2419
  1192
                            FormRegionPreviewUnencrypted formRegionPreviewUnencrypted = this.GetFormRegionPreviewUnencrypted();
Thomas@2360
  1193
Thomas@2360
  1194
                            // If we have a FormRegionPreviewUnencrypted and it's visible, show preview
Thomas@2419
  1195
                            if (formRegionPreviewUnencrypted?.Visible == true)
Thomas@2360
  1196
                            {
Thomas@2419
  1197
                                formRegionPreviewUnencrypted.DisplayState.OriginalEntryId = this.CurrentMailItem?.EntryID;
Thomas@2419
  1198
                                formRegionPreviewUnencrypted.DisplayState.SetMessage(e.Mirror);
Thomas@2359
  1199
Thomas@2359
  1200
                                Log.Verbose("MailItem_GetMirrorComplete: Mirror found and displayed.");
Thomas@2359
  1201
                            }
Thomas@2360
  1202
                            else
Thomas@2360
  1203
                            {
Thomas@2360
  1204
                                Log.Error("MailItem_GetMirrorComplete: FormRegionPreviewUnencrypted is null or invisible.");
Thomas@2360
  1205
                            }
Thomas@2359
  1206
                        }
Thomas@2359
  1207
Thomas@2359
  1208
                        // Display the mirror if necessary
Thomas@2359
  1209
                        if ((this.cryptableMailItem != null) &&
Thomas@2359
  1210
                            (this.displayMirrorRequested))
Thomas@2359
  1211
                        {
Thomas@2359
  1212
                            this.cryptableMailItem.DisplayMirror();
Thomas@2359
  1213
                            this.displayMirrorRequested = false;
Thomas@2359
  1214
                        }
Thomas@2359
  1215
                    }
Thomas@2359
  1216
                }));
Thomas@2359
  1217
            }
Thomas@2359
  1218
            catch (Exception ex)
Thomas@2359
  1219
            {
Thomas@2359
  1220
                Log.Error("MailItem_GetMirrorComplete: Error displaying preview, " + ex.ToString());
Thomas@2359
  1221
            }
Thomas@2359
  1222
        }
Thomas@2359
  1223
Thomas@2359
  1224
        /// <summary>
Thomas@2359
  1225
        /// Event handler for the mail item originally encrypted status updated.
Thomas@2359
  1226
        /// This event is fired after the status has been updated with parent information following a
Thomas@2359
  1227
        /// forward or reply mail item event (on a different, likely parent, mail item).
Thomas@2359
  1228
        /// </summary>
Thomas@2359
  1229
        protected void CryptableMailItem_OriginallyEncryptedStatusUpdated(object sender, EventArgs e)
Thomas@2359
  1230
        {
Thomas@2359
  1231
            // Process the mail item now that the cache is updated
Thomas@2359
  1232
            if (this.cryptableMailItem.IsOriginallyEncrypted)
Thomas@2359
  1233
            {
Thomas@2359
  1234
                this.cryptableMailItem.StartProcessing();
Thomas@2359
  1235
            }
Thomas@2359
  1236
        }
Thomas@2359
  1237
Thomas@2359
  1238
        /// <summary>
Thomas@2359
  1239
        /// Event handler for when a mail item is being opened in an inspector.
Thomas@2359
  1240
        /// See: https://msdn.microsoft.com/en-us/library/office/ff865989.aspx
Thomas@2359
  1241
        /// </summary>
Thomas@2359
  1242
        /// <param name="cancel">Whether to cancel the event: Value is False when the event occurs. 
Thomas@2359
  1243
        /// If the event procedure sets this argument to True, the open operation is not completed 
Thomas@2359
  1244
        /// and the inspector is not displayed.</param>
Thomas@2359
  1245
        protected void MailItem_Open(ref bool cancel)
Thomas@2359
  1246
        {
Thomas@2359
  1247
            bool result;
Thomas@2359
  1248
Thomas@2359
  1249
            if ((this.isEnabled) &&
Thomas@2359
  1250
                (this.cryptableMailItem != null))
Thomas@2359
  1251
            {
Thomas@2359
  1252
                // If cryptable mail item is not to be opened, cancel opening
Thomas@2359
  1253
                if (this.cryptableMailItem.CancelOpen)
Thomas@2359
  1254
                {
Thomas@2359
  1255
                    cancel = true;
Thomas@2359
  1256
                }
Thomas@2359
  1257
                else if ((this.cryptableMailItem.IsSecurelyStored) &&
Thomas@2359
  1258
                         (this.cryptableMailItem.IsIncoming || this.cryptableMailItem.IsOriginallyEncrypted || !this.cryptableMailItem.IsDraft))
Thomas@2359
  1259
                {
Thomas@2359
  1260
                    // Try to open the mirror
Thomas@2359
  1261
                    result = this.cryptableMailItem.DisplayMirror();
Thomas@2359
  1262
Thomas@2359
  1263
                    if (result == false)
Thomas@2359
  1264
                    {
Thomas@2359
  1265
                        // Set flag to open after decryption/mirror location
Thomas@2359
  1266
                        this.displayMirrorRequested = true;
Thomas@2359
  1267
                    }
Thomas@2359
  1268
Thomas@2359
  1269
                    // Always cancel opening the original
Thomas@2359
  1270
                    cancel = true;
Thomas@2359
  1271
                }
Thomas@2359
  1272
            }
Thomas@2359
  1273
        }
Thomas@2359
  1274
Thomas@2359
  1275
        /// <summary>
Thomas@2359
  1276
        /// Event handler for when a mail item is sent.
Thomas@2359
  1277
        /// See: https://msdn.microsoft.com/en-us/library/office/ff865379.aspx
Thomas@2359
  1278
        /// </summary>
Thomas@2359
  1279
        /// <param name="cancel">Whether to cancel the event: Value is False when the event occurs. 
Thomas@2359
  1280
        /// If the event procedure sets this argument to True, the send operation is not completed 
Thomas@2359
  1281
        /// and the inspector is left open.</param>
Thomas@2359
  1282
        protected void MailItem_Send(ref bool cancel)
Thomas@2359
  1283
        {
Thomas@2359
  1284
            DialogResult result;
Thomas@2359
  1285
Thomas@2359
  1286
            if (this.isEnabled)
Thomas@2359
  1287
            {
Thomas@2359
  1288
                if ((this.cryptableMailItem.IsBeingProcessed) ||
Thomas@2359
  1289
                    (this.processingOngoing))
Thomas@2359
  1290
                {
Thomas@2385
  1291
                    /* If the mail item is still being processed, this means that the message might go out with
Thomas@2385
  1292
                     * a different rating than the one that was shown in the UI when sending was initiated.
Thomas@2385
  1293
                     * As a trade-off between security and user experience, we make at least sure that the
Thomas@2385
  1294
                     * current outgoing rating preview (which is only wrong under rare circumstances) is not
Thomas@2385
  1295
                     * smaller than the one shown in the UI. If this is the case, just abort sending.
Thomas@2385
  1296
                     */
Thomas@2385
  1297
                    pEpRating outgoingPreviewRating = this.GetOutgoingRatingPreview();
Thomas@2385
  1298
                    if (this.Rating != outgoingPreviewRating)
Thomas@2385
  1299
                    {
Thomas@2385
  1300
                        if (this.Rating > outgoingPreviewRating)
Thomas@2385
  1301
                        {
Thomas@2385
  1302
                            Log.Verbose("MailItem_Send: Mail item still being processed.");
Thomas@2385
  1303
                            cancel = true;
Thomas@2385
  1304
                            return;
Thomas@2385
  1305
                        }
Thomas@2385
  1306
Thomas@2385
  1307
                        this.SetRating(outgoingPreviewRating);
Thomas@2385
  1308
                    }
Thomas@2359
  1309
                }
Thomas@2359
  1310
Thomas@2385
  1311
Thomas@2359
  1312
                // Show warning message if needed
Thomas@2359
  1313
                if ((Globals.ThisAddIn.Settings.IsSecurityLossWarningEnabled) &&
Thomas@2359
  1314
                    (this.Rating < pEpRating.pEpRatingUnreliable) &&
Thomas@2359
  1315
                    (this.cryptableMailItem.IsOriginallyEncrypted))
Thomas@2359
  1316
                {
Thomas@2359
  1317
Thomas@2359
  1318
#if READER_RELEASE_MODE
Thomas@2359
  1319
                    FormReaderSplash warningMessage = new FormReaderSplash(true);
Thomas@2359
  1320
                    result = warningMessage.ShowDialog();
Thomas@2359
  1321
Thomas@2359
  1322
                    if (result != DialogResult.OK)
Thomas@2359
  1323
                    {
Thomas@2359
  1324
                        // Cancel sending
Thomas@2359
  1325
                        cancel = true;
Thomas@2359
  1326
                    }
Thomas@2359
  1327
#else
Thomas@2359
  1328
                    result = MessageBox.Show(Properties.Resources.Message_WarningSecurityLoss,
Thomas@2359
  1329
                                             Properties.Resources.Message_TitleConfirmOperation,
Thomas@2359
  1330
                                             MessageBoxButtons.YesNo,
Thomas@2359
  1331
                                             MessageBoxIcon.Warning);
Thomas@2359
  1332
Thomas@2359
  1333
                    if (result == DialogResult.No)
Thomas@2359
  1334
                    {
Thomas@2359
  1335
                        // Cancel sending
Thomas@2359
  1336
                        cancel = true;
Thomas@2359
  1337
                    }
Thomas@2359
  1338
#endif
Thomas@2359
  1339
                }
Thomas@2359
  1340
Thomas@2359
  1341
                if (cancel == false)
Thomas@2359
  1342
                {
Thomas@2359
  1343
                    // Set pEp options if needed
Thomas@2359
  1344
                    if ((this.ForceProtection) &&
Thomas@2359
  1345
                        (this.DisableForceProtection == false))
Thomas@2359
  1346
                    {
Thomas@2385
  1347
                        this.CurrentMailItem?.SetPEPProperty(MailItemExtensions.PEPProperty.ForceProtection, Guid.NewGuid().ToString());
Thomas@2359
  1348
                    }
Thomas@2359
  1349
                    else if (this.ForceUnencrypted)
Thomas@2359
  1350
                    {
Thomas@2385
  1351
                        this.CurrentMailItem?.SetPEPProperty(MailItemExtensions.PEPProperty.ForceUnencrypted, true);
Thomas@2359
  1352
                    }
Thomas@2359
  1353
Thomas@2359
  1354
                    if (this.NeverUnsecure)
Thomas@2359
  1355
                    {
Thomas@2385
  1356
                        this.CurrentMailItem?.SetPEPProperty(MailItemExtensions.PEPProperty.NeverUnsecure, true);
Thomas@2359
  1357
                    }
Thomas@2359
  1358
Thomas@2359
  1359
                    // Stop and disconnect the refresh timer
Thomas@2359
  1360
                    // This is necessary so an ongoing refresh doesn't try to access a mail item as it's being moved
Thomas@2359
  1361
                    this.TimerRefresh.Stop();
Thomas@2359
  1362
                    this.TimerRefresh.Enabled = false;
Thomas@2359
  1363
                    this.TimerRefresh.Tick -= TimerRefresh_Tick;
Thomas@2359
  1364
                }
Thomas@2359
  1365
            }
Thomas@2359
  1366
        }
Thomas@2359
  1367
Thomas@2359
  1368
        /// <summary>
Thomas@2359
  1369
        /// Event handler for when a mail item property is changed.
Thomas@2359
  1370
        /// See: https://msdn.microsoft.com/en-us/library/office/ff866739.aspx
Thomas@2359
  1371
        /// </summary>
Thomas@2359
  1372
        /// <param name="propertyName">The name of the property that was changed.</param>
Thomas@2359
  1373
        protected void MailItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
Thomas@2359
  1374
        {
Thomas@2359
  1375
            switch (e.PropertyName.ToUpperInvariant())
Thomas@2359
  1376
            {
Thomas@2359
  1377
                case "BCC":
Thomas@2359
  1378
                    {
Thomas@2359
  1379
                        // Outlook always fires Bcc, Cc and To together so only "TO" is used
Thomas@2359
  1380
                        break;
Thomas@2359
  1381
                    }
Thomas@2359
  1382
                case "CC":
Thomas@2359
  1383
                    {
Thomas@2359
  1384
                        // Outlook always fires Bcc, Cc and To together so only "TO" is used
Thomas@2359
  1385
                        break;
Thomas@2359
  1386
                    }
Thomas@2359
  1387
                case "SENTONBEHALFOFNAME":
Thomas@2359
  1388
                    {
Thomas@2359
  1389
                        // Always fired with "SENDUSINGACCOUNT" so is ignored
Thomas@2359
  1390
                        break;
Thomas@2359
  1391
                    }
Thomas@2359
  1392
                case "SENDUSINGACCOUNT":
Thomas@2359
  1393
                    {
Thomas@2359
  1394
                        // Update pEp enabled status
Thomas@2359
  1395
                        this.isStarted = false;
Thomas@2359
  1396
                        this.SetIsEnabled((this.CurrentMailItem)?.GetEnableFormRegion() ?? false);
Thomas@2359
  1397
Thomas@2359
  1398
                        // Refresh the UI
Thomas@2359
  1399
                        this.ResolveAllRecipients();
Thomas@2359
  1400
                        this.RequestRatingAndUIUpdate();
Thomas@2359
  1401
                        RibbonCustomizations.Invalidate();
Thomas@2359
  1402
Thomas@2359
  1403
                        break;
Thomas@2359
  1404
                    }
Thomas@2359
  1405
                case "TO":
Thomas@2359
  1406
                    {
Thomas@2359
  1407
                        if (this.isEnabled)
Thomas@2359
  1408
                        {
Thomas@2359
  1409
                            this.RequestRatingAndUIUpdate();
Thomas@2359
  1410
                        }
Thomas@2359
  1411
                        break;
Thomas@2359
  1412
                    }
Thomas@2359
  1413
            }
Thomas@2359
  1414
        }
Thomas@2359
  1415
Thomas@2359
  1416
        /// <summary>
Thomas@2359
  1417
        /// Event handler for when a handshake dialog was updated.
Thomas@2359
  1418
        /// </summary>
Thomas@2359
  1419
        protected void HandshakeDialog_Updated(object sender, EventArgs e)
Thomas@2359
  1420
        {
Thomas@2359
  1421
            // Update current form region
Thomas@2359
  1422
            this.RequestRatingAndUIUpdate();
Thomas@2360
  1423
Thomas@2359
  1424
            /* If a handshake is performed while having the same message open both in an inspector
Thomas@2359
  1425
             * and an Window window, the one that didn't trigger the handshake won't get updated
Thomas@2359
  1426
             * automatically. Therefore, after a handshake, we also update all other open windows.
Thomas@2359
  1427
             */
Thomas@2359
  1428
            try
Thomas@2359
  1429
            {
Thomas@2360
  1430
                Globals.ThisAddIn.RecalculateAllWindows(this);
Thomas@2359
  1431
            }
Thomas@2359
  1432
            catch (Exception ex)
Thomas@2359
  1433
            {
Thomas@2359
  1434
                Log.Error("HandshakeDialog_Updated: Error updating other windows. " + ex.Message);
Thomas@2359
  1435
            }
Thomas@2359
  1436
        }
Thomas@2359
  1437
Thomas@2359
  1438
        /// <summary>
Thomas@2359
  1439
        /// Event handler for when a handshake dialog was closed.
Thomas@2359
  1440
        /// </summary>
Thomas@2359
  1441
        protected void HandshakeDialog_Closed(object sender, EventArgs e)
Thomas@2359
  1442
        {
Thomas@2359
  1443
            if (this.handshakeDialog != null)
Thomas@2359
  1444
            {
Thomas@2359
  1445
                this.handshakeDialog.OnUpdateStatus -= HandshakeDialog_Updated;
Thomas@2359
  1446
                this.handshakeDialog.Closed -= HandshakeDialog_Closed;
Thomas@2359
  1447
                this.handshakeDialog = null;
Thomas@2359
  1448
            }
Thomas@2359
  1449
        }
Thomas@2359
  1450
Thomas@2359
  1451
        /// <summary>
Thomas@2359
  1452
        /// Event handler called after the refresh timer has elapsed.
Thomas@2359
  1453
        /// </summary>
Thomas@2359
  1454
        private void TimerRefresh_Tick(object sender, EventArgs e)
Thomas@2359
  1455
        {
Thomas@2359
  1456
            bool tryAgain = false;
Thomas@2359
  1457
#pragma warning disable 219
Thomas@2359
  1458
            bool markForDownload = false;
Thomas@2359
  1459
#pragma warning restore 219
Thomas@2359
  1460
            this.TimerRefresh.Enabled = false; // Only once
Thomas@2359
  1461
            Outlook.OlDownloadState dlState;
Thomas@2359
  1462
Thomas@2359
  1463
            /* The Refresh/UI_Update process:
Thomas@2359
  1464
             * There are the following components:
Thomas@2359
  1465
             *   1. TimerRefresh_Tick
Thomas@2359
  1466
             *        This is the main timer tick event handler called any time
Thomas@2359
  1467
             *        a refresh was requested (RequestRatingAndUIUpdate) and hasn't been run yet. 
Thomas@2359
  1468
             *        A refresh is requested either at initialization or when a property changes
Thomas@2359
  1469
             *        (such as MailItem_PropertyChanged). It is on a timer as many 
Thomas@2359
  1470
             *        property change events could occur rapidy, but only one refresh should
Thomas@2359
  1471
             *        occur for performance reasons.
Thomas@2359
  1472
             * 
Thomas@2359
  1473
             *   2. ImmediateRatingAndUIUpdate
Thomas@2359
  1474
             *        This will re-calculate the mail item's rating.
Thomas@2359
  1475
             *        This internally just calls CryptableMailItem.StartProcessing.
Thomas@2359
  1476
             * 
Thomas@2359
  1477
             *   3. MailItem_ProcessingCompleted
Thomas@2359
  1478
             *        When processing of the mail item is complete, this even handler will be called.
Thomas@2359
  1479
             *        This will update the UI with the latest rating then call StartGetMirror.
Thomas@2359
  1480
             *        The CopyStateToUI method is used which means any open privacy status form will also
Thomas@2359
  1481
             *        be updated.
Thomas@2359
  1482
             * 
Thomas@2359
  1483
             *   4. MailItem_GetMirrorComplete
Thomas@2359
  1484
             *        This is the final step in updating the UI, after a mirror is located, it's contents
Thomas@2359
  1485
             *        will be shown in the unencrypted preview.
Thomas@2359
  1486
             * 
Thomas@2359
  1487
             * The general calling sequence is as shown above 1->4 with each component calling the next.
Thomas@2359
  1488
             * However, for methods that update the mail item directly, commonly only 2->4 is needed.
Thomas@2359
  1489
             */
Thomas@2359
  1490
Thomas@2359
  1491
            // Ensure the tick method is not called more than once
Thomas@2359
  1492
            if ((this.isEnabled) &&
Thomas@2359
  1493
                (refreshOngoing == false))
Thomas@2359
  1494
            {
Thomas@2359
  1495
                this.refreshOngoing = true;
Thomas@2359
  1496
Thomas@2359
  1497
                if ((this.cryptableMailItem != null) &&
Thomas@2359
  1498
                    (this.cryptableMailItem.IsBeingProcessed == false))
Thomas@2359
  1499
                {
Thomas@2359
  1500
                    // Attempt to get the download state
Thomas@2359
  1501
                    try
Thomas@2359
  1502
                    {
Thomas@2359
  1503
                        dlState = this.cryptableMailItem.DownloadState;
Thomas@2359
  1504
                    }
Thomas@2359
  1505
                    catch (Exception ex)
Thomas@2359
  1506
                    {
Thomas@2359
  1507
                        Log.Warning("TimerRefresh_Tick: Get DownloadState failed, " + ex.ToString());
Thomas@2359
  1508
Thomas@2359
  1509
                        // Assume everything is downloaded, but try to download again as well
Thomas@2359
  1510
                        dlState = Outlook.OlDownloadState.olFullItem;
Thomas@2359
  1511
                        markForDownload = true;
Thomas@2359
  1512
                    }
Thomas@2359
  1513
Thomas@2359
  1514
                    if (dlState == Outlook.OlDownloadState.olFullItem)
Thomas@2359
  1515
                    {
Thomas@2359
  1516
                        this.ImmediateRatingAndUIUpdate();
Thomas@2359
  1517
                    }
Thomas@2359
  1518
                    else
Thomas@2359
  1519
                    {
Thomas@2359
  1520
                        markForDownload = true;
Thomas@2359
  1521
                    }
Thomas@2359
  1522
Thomas@2359
  1523
                    /* 12/16/2016: It could be verified via testing that setting the MarkForDownload property
Thomas@2359
  1524
                     * can be a way to crash Outlook under certain circumstances (e.g. with IMAP on Outlook 2010 or on Windows 7). 
Thomas@2359
  1525
                     * This then is not caught by a try/catch block and therefore has to be considered an Outlook bug.
Thomas@2359
  1526
                     * It seems that in newer versions of Outlook/Windows, they fixed it, causing exceptions, if at all.
Thomas@2359
  1527
                     * For now, the following is commented out to prevent a crash. If at any point we see that header-only
Thomas@2359
  1528
                     * messages cause bigger issues, this decision has to be reevaluated.
Thomas@2359
  1529
                     */
Thomas@2359
  1530
                    //if (markForDownload)
Thomas@2359
  1531
                    //{
Thomas@2359
  1532
                    //    // Try to mark the message for full download
Thomas@2359
  1533
                    //    try
Thomas@2359
  1534
                    //    {
Thomas@2359
  1535
                    //        this.cryptableMailItem.MarkForDownload = Outlook.OlRemoteStatus.olMarkedForDownload;
Thomas@2359
  1536
                    //        tryAgain = true;
Thomas@2359
  1537
                    //    }
Thomas@2359
  1538
                    //    catch (Exception ex)
Thomas@2359
  1539
                    //    {
Thomas@2359
  1540
                    //        Log.Warning("TimerRefresh_Tick: MarkForDownload failed, " + ex.ToString());
Thomas@2359
  1541
                    //    }
Thomas@2359
  1542
                    //}
Thomas@2359
  1543
                }
Thomas@2359
  1544
                else
Thomas@2359
  1545
                {
Thomas@2359
  1546
                    repeatProcessing = true;
Thomas@2359
  1547
                }
Thomas@2359
  1548
Thomas@2359
  1549
                // Set the timer to refresh again later automatically
Thomas@2359
  1550
                if (tryAgain)
Thomas@2359
  1551
                {
Thomas@2359
  1552
                    this.TimerRefresh.Interval = 100;
Thomas@2359
  1553
                    this.TimerRefresh.Enabled = true;
Thomas@2359
  1554
                }
Thomas@2359
  1555
Thomas@2359
  1556
                this.refreshOngoing = false;
Thomas@2359
  1557
            }
Thomas@2359
  1558
        }
Thomas@2359
  1559
Thomas@2359
  1560
        #endregion
Thomas@2359
  1561
    }
Thomas@2359
  1562
}