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