summaryrefslogtreecommitdiffstats
path: root/comm/mail/test/browser/cloudfile/browser_attachmentItem.js
blob: 18c3d92e413dd6a363af8d3b251b647d279ef78a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * Tests Filelink attachment item behaviour.
 */

"use strict";

var utils = ChromeUtils.import("resource://testing-common/mozmill/utils.jsm");
var { gMockFilePicker, gMockFilePickReg, select_attachments } =
  ChromeUtils.import("resource://testing-common/mozmill/AttachmentHelpers.jsm");
var { getFile, gMockCloudfileManager, MockCloudfileAccount } =
  ChromeUtils.import("resource://testing-common/mozmill/CloudfileHelpers.jsm");
var {
  add_cloud_attachments,
  convert_selected_to_cloud_attachment,
  close_compose_window,
  open_compose_new_mail,
} = ChromeUtils.import("resource://testing-common/mozmill/ComposeHelpers.jsm");
var { close_popup, mc } = ChromeUtils.import(
  "resource://testing-common/mozmill/FolderDisplayHelpers.jsm"
);

var { cloudFileAccounts } = ChromeUtils.import(
  "resource:///modules/cloudFileAccounts.jsm"
);

var kAttachmentItemContextID = "msgComposeAttachmentItemContext";

// Prepare the mock prompt.
var originalPromptService = Services.prompt;
var mockPromptService = {
  alertCount: 0,
  alert() {
    this.alertCount++;
  },
  QueryInterface: ChromeUtils.generateQI(["nsIPromptService"]),
};

add_setup(function () {
  Services.prompt = mockPromptService;
  gMockFilePickReg.register();
  gMockCloudfileManager.register();
});

registerCleanupFunction(function () {
  gMockCloudfileManager.unregister();
  gMockFilePickReg.unregister();
  Services.prompt = originalPromptService;
});

/**
 * Test that when an upload has been started, we can cancel and restart
 * the upload, and then cancel again.  For this test, we repeat this
 * 3 times.
 */
add_task(async function test_upload_cancel_repeat() {
  const kFile = "./data/testFile1";

  // Prepare the mock file picker to return our test file.
  let file = new FileUtils.File(getTestFilePath(kFile));
  gMockFilePicker.returnFiles = [file];

  let provider = new MockCloudfileAccount();
  provider.init("someKey");
  let cw = open_compose_new_mail(mc);

  // We've got a compose window open, and our mock Filelink provider
  // ready.  Let's attach a file...
  cw.window.AttachFile();

  // Now we override the uploadFile function of the MockCloudfileAccount
  // so that we're perpetually uploading...
  let promise;
  let started;
  provider.uploadFile = function (window, aFile) {
    return new Promise((resolve, reject) => {
      promise = { resolve, reject };
      started = true;
    });
  };

  const kAttempts = 3;
  for (let i = 0; i < kAttempts; i++) {
    promise = null;
    started = false;

    let bucket = cw.window.document.getElementById("attachmentBucket");
    Assert.equal(
      bucket.itemCount,
      1,
      "Should find correct number of attachments before converting."
    );

    // Select the attachment, and choose to convert it to a Filelink
    select_attachments(cw, 0)[0];
    cw.window.convertSelectedToCloudAttachment(provider);
    utils.waitFor(() => started);

    await assert_can_cancel_upload(cw, provider, promise, file);
    await new Promise(resolve => setTimeout(resolve));

    // A cancelled conversion must not remove the attachment.
    Assert.equal(
      bucket.itemCount,
      1,
      "Should find correct number of attachments after converting."
    );
  }

  close_compose_window(cw);
});

/**
 * Test that we can cancel a whole series of files being uploaded at once.
 */
add_task(async function test_upload_multiple_and_cancel() {
  const kFiles = ["./data/testFile1", "./data/testFile2", "./data/testFile3"];

  // Prepare the mock file picker to return our test file.
  let files = collectFiles(kFiles);
  gMockFilePicker.returnFiles = files;

  let provider = new MockCloudfileAccount();
  provider.init("someKey");
  let cw = open_compose_new_mail();

  let promises = {};
  provider.uploadFile = function (window, aFile) {
    return new Promise((resolve, reject) => {
      promises[aFile.leafName] = { resolve, reject };
    });
  };

  add_cloud_attachments(cw, provider, false);

  let bucket = cw.window.document.getElementById("attachmentBucket");
  Assert.equal(
    bucket.itemCount,
    kFiles.length,
    "Should find correct number of attachments before uploading."
  );

  for (let i = files.length - 1; i >= 0; --i) {
    await assert_can_cancel_upload(
      cw,
      provider,
      promises[files[i].leafName],
      files[i]
    );
  }

  // The cancelled attachment uploads should have been removed.
  Assert.equal(
    bucket.itemCount,
    0,
    "Should find correct number of attachments after uploading."
  );

  close_compose_window(cw);
});

/**
 * Helper function that takes an upload in progress, and cancels it,
 * ensuring that the nsIMsgCloudFileProvider.uploadCanceled status message
 * is returned to the passed in listener.
 *
 * @param aController the compose window controller to use.
 * @param aProvider a MockCloudfileAccount for which the uploads have already
 *                  started.
 * @param aListener the nsIRequestObserver passed to aProvider's uploadFile
 *                  function.
 * @param aTargetFile the nsIFile to cancel the upload for.
 */
async function assert_can_cancel_upload(
  aController,
  aProvider,
  aPromise,
  aTargetFile
) {
  let cancelled = false;

  // Override the provider's cancelFileUpload function.  We can do this because
  // it's assumed that the provider is a MockCloudfileAccount.
  aProvider.cancelFileUpload = function (window, aFileToCancel) {
    if (aTargetFile.equals(aFileToCancel)) {
      aPromise.reject(
        Components.Exception(
          "Upload cancelled.",
          cloudFileAccounts.constants.uploadCancelled
        )
      );
      cancelled = true;
    }
  };

  // Retrieve the attachment bucket index for the target file...
  let index = get_attachmentitem_index_for_file(aController, aTargetFile);

  // Select that attachmentitem in the bucket
  select_attachments(aController, index)[0];

  // Bring up the context menu, and click cancel.
  let cmd = aController.window.document.getElementById("cmd_cancelUpload");
  aController.window.updateAttachmentItems();

  Assert.ok(!cmd.hidden, "cmd_cancelUpload should be shown");
  Assert.ok(!cmd.disabled, "cmd_cancelUpload should be enabled");

  let attachmentItem =
    aController.window.document.getElementById("attachmentBucket").selectedItem;
  let contextMenu = aController.window.document.getElementById(
    "msgComposeAttachmentItemContext"
  );

  let popupPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
  EventUtils.synthesizeMouseAtCenter(
    attachmentItem,
    { type: "contextmenu", button: 2 },
    attachmentItem.ownerGlobal
  );
  await popupPromise;

  let cancelItem = aController.window.document.getElementById(
    "composeAttachmentContext_cancelUploadItem"
  );
  if (AppConstants.platform == "macosx") {
    // We need to use click() since the synthesizeMouseAtCenter doesn't work for
    // context menu items on macos.
    cancelItem.click();
  } else {
    EventUtils.synthesizeMouseAtCenter(cancelItem, {}, cancelItem.ownerGlobal);
    await new Promise(resolve => setTimeout(resolve));
  }

  // Close the popup, and wait for the cancellation to be complete.
  await close_popup(
    aController,
    aController.window.document.getElementById(kAttachmentItemContextID)
  );
  utils.waitFor(() => cancelled);
}

/**
 * A helper function to find the attachment bucket index for a particular
 * nsIFile. Returns null if no attachmentitem is found.
 *
 * @param aController the compose window controller to use.
 * @param aFile the nsIFile to search for.
 */
function get_attachmentitem_index_for_file(aController, aFile) {
  // Get the fileUrl from the file.
  let fileUrl = aController.window.FileToAttachment(aFile).url;

  // Get the bucket, and go through each item looking for the matching
  // attachmentitem.
  let bucket = aController.window.document.getElementById("attachmentBucket");
  for (let i = 0; i < bucket.getRowCount(); ++i) {
    let attachmentitem = bucket.getItemAtIndex(i);
    if (attachmentitem.attachment.url == fileUrl) {
      return i;
    }
  }
  return null;
}

/**
 * Helper function to start uploads and check number and icon of attachments
 * after successful or failed uploads.
 *
 * @param error - to be returned error by uploadFile in case of failure
 * @param expectedAttachments - number of expected attachments at the end of the test
 * @param expectedAlerts - number of expected alerts at the end of the test
 */
async function test_upload(cw, error, expectedAttachments, expectedAlerts = 0) {
  const kFiles = ["./data/testFile1", "./data/testFile2", "./data/testFile3"];

  // Prepare the mock file picker to return our test file.
  let files = collectFiles(kFiles);
  gMockFilePicker.returnFiles = files;

  let provider = new MockCloudfileAccount();
  provider.init("someKey");

  // Override the uploadFile function of the MockCloudfileAccount.
  let promises = [];
  provider.uploadFile = function (window, aFile) {
    return new Promise((resolve, reject) => {
      promises.push({
        resolve,
        reject,
        upload: {
          url: `https://example.org/${aFile.leafName}`,
          size: aFile.fileSize,
          path: aFile.path,
        },
      });
    });
  };

  add_cloud_attachments(cw, provider, false);
  utils.waitFor(() => promises.length == kFiles.length);

  let bucket = cw.window.document.getElementById("attachmentBucket");
  Assert.equal(
    bucket.itemCount,
    kFiles.length,
    "Should find correct number of attachments before uploading."
  );

  for (let item of bucket.itemChildren) {
    is(
      item.querySelector("img.attachmentcell-icon").src,
      "chrome://global/skin/icons/loading.png",
      "CloudFile icon should be the loading spinner."
    );
  }

  for (let promise of promises) {
    if (error) {
      promise.reject(error);
    } else {
      promise.resolve(promise.upload);
    }
  }
  await new Promise(resolve => setTimeout(resolve));

  Assert.equal(
    bucket.itemCount,
    expectedAttachments,
    "Should find correct number of attachments after uploading."
  );
  // Check if the spinner is no longer shown, but the expected moz-icon.
  for (let item of bucket.itemChildren) {
    ok(
      item
        .querySelector("img.attachmentcell-icon")
        .src.startsWith("moz-icon://testFile"),
      "CloudFile icon should be correct."
    );
  }

  // Check and reset the prompt mock service.
  is(
    expectedAlerts,
    Services.prompt.alertCount,
    "Number of expected alert prompts should be correct."
  );
  Services.prompt.alertCount = 0;
}

/**
 * Check if attachment is removed if upload failed.
 */
add_task(async function test_error_upload() {
  let cw = open_compose_new_mail();
  await test_upload(
    cw,
    Components.Exception(
      "Upload error.",
      cloudFileAccounts.constants.uploadErr
    ),
    0,
    3
  );
  close_compose_window(cw);
});

/**
 * Check if attachment is not removed if upload is successful.
 */
add_task(async function test_successful_upload() {
  let cw = open_compose_new_mail();
  await test_upload(cw, null, 3, 0);
  close_compose_window(cw);
});

/**
 * Check if the original cloud attachment is kept, after converting it to another
 * provider failed.
 */
add_task(async function test_error_conversion() {
  let cw = open_compose_new_mail();
  let bucket = cw.window.document.getElementById("attachmentBucket");

  // Upload 3 files to the standard provider.
  await test_upload(cw, null, 3, 0);

  // Define another provider.
  let providerB = new MockCloudfileAccount();
  providerB.init("someOtherKey");

  let uploadPromise = null;
  providerB.uploadFile = function (window, aFile) {
    return new Promise((resolve, reject) => {
      uploadPromise = { resolve, reject };
    });
  };

  select_attachments(cw, 0);
  convert_selected_to_cloud_attachment(cw, providerB, false);

  let uploadError = new Promise(resolve => {
    bucket.addEventListener("attachment-move-failed", resolve, {
      once: true,
    });
  });

  // Reject the upload, causing the conversion to fail.
  uploadPromise.reject(
    new Components.Exception(
      "Upload error.",
      cloudFileAccounts.constants.uploadErr
    )
  );
  await uploadError;

  // Wait for the showLocalizedCloudFileAlert() to localize the error message.
  await new Promise(resolve => setTimeout(resolve));

  is(
    Services.prompt.alertCount,
    1,
    "Number of expected alert prompts should be correct."
  );
  Services.prompt.alertCount = 0;

  // Check that we still have the 3 attachments we started with.
  Assert.equal(
    bucket.itemCount,
    3,
    "Should find correct number of attachments."
  );
  for (let i = 0; i < bucket.itemCount; i++) {
    let item = bucket.itemChildren[i];
    Assert.equal(
      item.attachment.sendViaCloud,
      true,
      "Attachment should be a cloud attachment."
    );
    Assert.equal(
      item.attachment.cloudFileAccountKey,
      "someKey",
      "Attachment should be hosted by the correct provider."
    );
  }

  close_compose_window(cw);
});