summaryrefslogtreecommitdiffstats
path: root/toolkit/components/antitracking/test/browser/browser_staticPartition_saveAs.js
blob: b9984829eb271dbc2a677c7a27c2f00b23f9d4f0 (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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/**
 * Bug 1641270 - A test case for ensuring the save channel will use the correct
 *               cookieJarSettings when doing the saving and the cache would
 *               work as expected.
 */

"use strict";

Services.scriptloader.loadSubScript(
  "chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
  this
);

const TEST_IMAGE_URL = TEST_DOMAIN + TEST_PATH + "file_saveAsImage.sjs";
const TEST_VIDEO_URL = TEST_DOMAIN + TEST_PATH + "file_saveAsVideo.sjs";
const TEST_PAGEINFO_URL = TEST_DOMAIN + TEST_PATH + "file_saveAsPageInfo.html";

let MockFilePicker = SpecialPowers.MockFilePicker;
MockFilePicker.init(window.browsingContext);

const tempDir = createTemporarySaveDirectory();
MockFilePicker.displayDirectory = tempDir;

function createTemporarySaveDirectory() {
  let saveDir = Services.dirsvc.get("TmpD", Ci.nsIFile);
  saveDir.append("testsavedir");
  saveDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0o755);
  return saveDir;
}

function createPromiseForTransferComplete(aDesirableFileName) {
  return new Promise(resolve => {
    MockFilePicker.showCallback = fp => {
      info("MockFilePicker showCallback");

      let fileName = fp.defaultString;
      let destFile = tempDir.clone();
      destFile.append(fileName);

      if (aDesirableFileName) {
        is(fileName, aDesirableFileName, "The default file name is correct.");
      }

      MockFilePicker.setFiles([destFile]);
      MockFilePicker.filterIndex = 0; // kSaveAsType_Complete

      MockFilePicker.showCallback = null;
      mockTransferCallback = function (downloadSuccess) {
        ok(downloadSuccess, "File should have been downloaded successfully");
        mockTransferCallback = () => {};
        resolve();
      };
    };
  });
}

function createPromiseForObservingChannel(aURL, aPartitionKey) {
  return new Promise(resolve => {
    let observer = (aSubject, aTopic) => {
      if (aTopic === "http-on-modify-request") {
        let httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
        let reqLoadInfo = httpChannel.loadInfo;

        // Make sure this is the request which we want to check.
        if (!httpChannel.URI.spec.endsWith(aURL)) {
          return;
        }

        info(`Checking loadInfo for URI: ${httpChannel.URI.spec}\n`);
        is(
          reqLoadInfo.cookieJarSettings.partitionKey,
          aPartitionKey,
          "The loadInfo has the correct partition key"
        );

        Services.obs.removeObserver(observer, "http-on-modify-request");
        resolve();
      }
    };

    Services.obs.addObserver(observer, "http-on-modify-request");
  });
}

add_setup(async function () {
  info("Setting MockFilePicker.");
  mockTransferRegisterer.register();

  registerCleanupFunction(function () {
    mockTransferRegisterer.unregister();
    MockFilePicker.cleanup();
    tempDir.remove(true);
  });
});

add_task(async function testContextMenuSaveImage() {
  let uuidGenerator = Services.uuid;

  for (let networkIsolation of [true, false]) {
    for (let partitionPerSite of [true, false]) {
      await SpecialPowers.pushPrefEnv({
        set: [
          ["privacy.partition.network_state", networkIsolation],
          ["privacy.dynamic_firstparty.use_site", partitionPerSite],
        ],
      });

      // We use token to separate the caches.
      let token = uuidGenerator.generateUUID().toString();
      const testImageURL = `${TEST_IMAGE_URL}?token=${token}`;

      info(`Open a new tab for testing "Save image as" in context menu.`);
      let tab = await BrowserTestUtils.openNewForegroundTab(
        gBrowser,
        TEST_TOP_PAGE
      );

      info(`Insert the testing image into the tab.`);
      await SpecialPowers.spawn(
        tab.linkedBrowser,
        [testImageURL],
        async url => {
          let img = content.document.createElement("img");
          let loaded = new content.Promise(resolve => {
            img.onload = resolve;
          });
          content.document.body.appendChild(img);
          img.setAttribute("id", "image1");
          img.src = url;
          await loaded;
        }
      );

      info("Open the context menu.");
      let popupShownPromise = BrowserTestUtils.waitForEvent(
        document,
        "popupshown"
      );

      await BrowserTestUtils.synthesizeMouseAtCenter(
        "#image1",
        {
          type: "contextmenu",
          button: 2,
        },
        tab.linkedBrowser
      );

      await popupShownPromise;

      let partitionKey = partitionPerSite
        ? "(http,example.net)"
        : "example.net";

      let transferCompletePromise = createPromiseForTransferComplete();
      let observerPromise = createPromiseForObservingChannel(
        testImageURL,
        partitionKey
      );

      let saveElement = document.getElementById("context-saveimage");
      info("Triggering the save process.");
      saveElement.doCommand();

      info("Waiting for the channel.");
      await observerPromise;

      info("Wait until the save is finished.");
      await transferCompletePromise;

      info("Close the context menu.");
      let contextMenu = document.getElementById("contentAreaContextMenu");
      let popupHiddenPromise = BrowserTestUtils.waitForEvent(
        contextMenu,
        "popuphidden"
      );
      contextMenu.hidePopup();
      await popupHiddenPromise;

      // Check if there will be only one network request. The another one should
      // be from cache.
      let res = await fetch(`${TEST_IMAGE_URL}?token=${token}&result`);
      let res_text = await res.text();
      is(res_text, "1", "The image should be loaded only once.");

      BrowserTestUtils.removeTab(tab);
    }
  }
});

add_task(async function testContextMenuSaveVideo() {
  let uuidGenerator = Services.uuid;

  for (let networkIsolation of [true, false]) {
    for (let partitionPerSite of [true, false]) {
      await SpecialPowers.pushPrefEnv({
        set: [
          ["privacy.partition.network_state", networkIsolation],
          ["privacy.dynamic_firstparty.use_site", partitionPerSite],
        ],
      });

      // We use token to separate the caches.
      let token = uuidGenerator.generateUUID().toString();
      const testVideoURL = `${TEST_VIDEO_URL}?token=${token}`;

      info(`Open a new tab for testing "Save Video as" in context menu.`);
      let tab = await BrowserTestUtils.openNewForegroundTab(
        gBrowser,
        TEST_TOP_PAGE
      );

      info(`Insert the testing video into the tab.`);
      await SpecialPowers.spawn(
        tab.linkedBrowser,
        [testVideoURL],
        async url => {
          let video = content.document.createElement("video");
          let loaded = new content.Promise(resolve => {
            video.onloadeddata = resolve;
          });
          content.document.body.appendChild(video);
          video.setAttribute("id", "video1");
          video.src = url;
          await loaded;
        }
      );

      info("Open the context menu.");
      let popupShownPromise = BrowserTestUtils.waitForEvent(
        document,
        "popupshown"
      );

      await BrowserTestUtils.synthesizeMouseAtCenter(
        "#video1",
        {
          type: "contextmenu",
          button: 2,
        },
        tab.linkedBrowser
      );

      await popupShownPromise;

      let partitionKey = partitionPerSite
        ? "(http,example.net)"
        : "example.net";

      // We also check the default file name, see Bug 1679325.
      let transferCompletePromise = createPromiseForTransferComplete(
        "file_saveAsVideo.webm"
      );
      let observerPromise = createPromiseForObservingChannel(
        testVideoURL,
        partitionKey
      );

      let saveElement = document.getElementById("context-savevideo");
      info("Triggering the save process.");
      saveElement.doCommand();

      info("Waiting for the channel.");
      await observerPromise;

      info("Wait until the save is finished.");
      await transferCompletePromise;

      info("Close the context menu.");
      let contextMenu = document.getElementById("contentAreaContextMenu");
      let popupHiddenPromise = BrowserTestUtils.waitForEvent(
        contextMenu,
        "popuphidden"
      );
      contextMenu.hidePopup();
      await popupHiddenPromise;

      // Check if there will be only one network request. The another one should
      // be from cache.
      let res = await fetch(`${TEST_VIDEO_URL}?token=${token}&result`);
      let res_text = await res.text();
      is(res_text, "1", "The video should be loaded only once.");

      BrowserTestUtils.removeTab(tab);
    }
  }
});

add_task(async function testSavePageInOfflineMode() {
  for (let networkIsolation of [true, false]) {
    for (let partitionPerSite of [true, false]) {
      await SpecialPowers.pushPrefEnv({
        set: [
          ["privacy.partition.network_state", networkIsolation],
          ["privacy.dynamic_firstparty.use_site", partitionPerSite],
        ],
      });

      let partitionKey = partitionPerSite
        ? "(http,example.net)"
        : "example.net";

      info(`Open a new tab which loads an image`);
      let tab = await BrowserTestUtils.openNewForegroundTab(
        gBrowser,
        TEST_IMAGE_URL
      );

      info("Toggle on the offline mode");
      BrowserOffline.toggleOfflineStatus();

      info("Open file menu and trigger 'Save Page As'");
      let menubar = document.getElementById("main-menubar");
      let filePopup = document.getElementById("menu_FilePopup");

      // We only use the shortcut keys to open the file menu in Windows and Linux.
      // Mac doesn't have a shortcut to only open the file menu. Instead, we directly
      // trigger the save in MAC without any UI interactions.
      if (Services.appinfo.OS !== "Darwin") {
        let menubarActive = BrowserTestUtils.waitForEvent(
          menubar,
          "DOMMenuBarActive"
        );
        EventUtils.synthesizeKey("KEY_F10");
        await menubarActive;

        let popupShownPromise = BrowserTestUtils.waitForEvent(
          filePopup,
          "popupshown"
        );
        // In window, it still needs one extra down key to open the file menu.
        if (Services.appinfo.OS === "WINNT") {
          EventUtils.synthesizeKey("KEY_ArrowDown");
        }
        await popupShownPromise;
      }

      let transferCompletePromise = createPromiseForTransferComplete();
      let observerPromise = createPromiseForObservingChannel(
        TEST_IMAGE_URL,
        partitionKey
      );

      info("Triggering the save process.");
      let fileSavePageAsElement = document.getElementById("menu_savePage");
      fileSavePageAsElement.doCommand();

      info("Waiting for the channel.");
      await observerPromise;

      info("Wait until the save is finished.");
      await transferCompletePromise;

      // Close the file menu.
      if (Services.appinfo.OS !== "Darwin") {
        let popupHiddenPromise = BrowserTestUtils.waitForEvent(
          filePopup,
          "popuphidden"
        );
        filePopup.hidePopup();
        await popupHiddenPromise;
      }

      info("Toggle off the offline mode");
      BrowserOffline.toggleOfflineStatus();

      // Clean up
      BrowserTestUtils.removeTab(tab);

      // Clean up the cache count on the server side.
      await fetch(`${TEST_IMAGE_URL}?result`);
      await new Promise(resolve => {
        Services.clearData.deleteData(Ci.nsIClearDataService.CLEAR_ALL, () =>
          resolve()
        );
      });
    }
  }
});

add_task(async function testPageInfoMediaSaveAs() {
  for (let networkIsolation of [true, false]) {
    for (let partitionPerSite of [true, false]) {
      await SpecialPowers.pushPrefEnv({
        set: [
          ["privacy.partition.network_state", networkIsolation],
          ["privacy.dynamic_firstparty.use_site", partitionPerSite],
        ],
      });

      let partitionKey = partitionPerSite
        ? "(http,example.net)"
        : "example.net";

      info(
        `Open a new tab for testing "Save AS" in the media panel of the page info.`
      );
      let tab = await BrowserTestUtils.openNewForegroundTab(
        gBrowser,
        TEST_PAGEINFO_URL
      );

      info("Open the media panel of the pageinfo.");
      let pageInfo = BrowserPageInfo(
        gBrowser.selectedBrowser.currentURI.spec,
        "mediaTab"
      );

      await BrowserTestUtils.waitForEvent(pageInfo, "page-info-init");

      let imageTree = pageInfo.document.getElementById("imagetree");
      let imageRowsNum = imageTree.view.rowCount;

      is(imageRowsNum, 2, "There should be two media items here.");

      for (let i = 0; i < imageRowsNum; i++) {
        imageTree.view.selection.select(i);
        imageTree.ensureRowIsVisible(i);
        imageTree.focus();

        // Wait until the preview is loaded.
        let preview = pageInfo.document.getElementById("thepreviewimage");
        let mediaType = pageInfo.gImageView.data[i][1]; // COL_IMAGE_TYPE
        if (mediaType == "Image") {
          await BrowserTestUtils.waitForEvent(preview, "load");
        } else if (mediaType == "Video") {
          await BrowserTestUtils.waitForEvent(preview, "canplaythrough");
        }

        let url = pageInfo.gImageView.data[i][0]; // COL_IMAGE_ADDRESS
        info(`Start to save the media item with URL: ${url}`);

        let transferCompletePromise = createPromiseForTransferComplete();

        // Observe the channel and check if it has the correct partitionKey.
        let observerPromise = createPromiseForObservingChannel(
          url,
          partitionKey
        );

        info("Triggering the save process.");
        let saveElement = pageInfo.document.getElementById("imagesaveasbutton");
        saveElement.doCommand();

        info("Waiting for the channel.");
        await observerPromise;

        info("Wait until the save is finished.");
        await transferCompletePromise;
      }

      pageInfo.close();
      BrowserTestUtils.removeTab(tab);
    }
  }
});

add_task(async function testPageInfoMediaMultipleSelectedSaveAs() {
  for (let networkIsolation of [true, false]) {
    for (let partitionPerSite of [true, false]) {
      await SpecialPowers.pushPrefEnv({
        set: [
          ["privacy.partition.network_state", networkIsolation],
          ["privacy.dynamic_firstparty.use_site", partitionPerSite],
        ],
      });

      let partitionKey = partitionPerSite
        ? "(http,example.net)"
        : "example.net";

      info(
        `Open a new tab for testing "Save AS" in the media panel of the page info.`
      );
      let tab = await BrowserTestUtils.openNewForegroundTab(
        gBrowser,
        TEST_PAGEINFO_URL
      );

      info("Open the media panel of the pageinfo.");
      let pageInfo = BrowserPageInfo(
        gBrowser.selectedBrowser.currentURI.spec,
        "mediaTab"
      );

      await BrowserTestUtils.waitForEvent(pageInfo, "page-info-init");

      // Make sure the preview image is loaded in order to avoid interfering
      // following tests.
      let preview = pageInfo.document.getElementById("thepreviewimage");
      await BrowserTestUtils.waitForCondition(() => {
        return preview.complete;
      });

      let imageTree = pageInfo.document.getElementById("imagetree");
      let imageRowsNum = imageTree.view.rowCount;

      is(imageRowsNum, 2, "There should be two media items here.");

      imageTree.view.selection.selectAll();
      imageTree.focus();

      let url = pageInfo.gImageView.data[0][0]; // COL_IMAGE_ADDRESS
      info(`Start to save the media item with URL: ${url}`);

      let transferCompletePromise = createPromiseForTransferComplete();
      let observerPromises = [];

      // Observe all channels and check if they have the correct partitionKey.
      for (let i = 0; i < imageRowsNum; ++i) {
        let observerPromise = createPromiseForObservingChannel(
          url,
          partitionKey
        );
        observerPromises.push(observerPromise);
      }

      info("Triggering the save process.");
      let saveElement = pageInfo.document.getElementById("imagesaveasbutton");
      saveElement.doCommand();

      info("Waiting for the all channels.");
      await Promise.all(observerPromises);

      info("Wait until the save is finished.");
      await transferCompletePromise;

      pageInfo.close();
      BrowserTestUtils.removeTab(tab);
    }
  }
});