summaryrefslogtreecommitdiffstats
path: root/uriloader/exthandler/tests/mochitest/browser_download_preferred_action.js
blob: b66266ec9e9a061e74d73c730d278e7bb9eb24ac (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const { DownloadIntegration } = ChromeUtils.importESModule(
  "resource://gre/modules/DownloadIntegration.sys.mjs"
);
const { FileTestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/FileTestUtils.sys.mjs"
);
const gHandlerService = Cc[
  "@mozilla.org/uriloader/handler-service;1"
].getService(Ci.nsIHandlerService);
const gMIMEService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
const localHandlerAppFactory = Cc["@mozilla.org/uriloader/local-handler-app;1"];

const ROOT_URL = getRootDirectory(gTestPath).replace(
  "chrome://mochitests/content",
  "https://example.com"
);

const FILE_TYPES_MIME_SETTINGS = {};

// File types to test
const FILE_TYPES_TO_TEST = [
  // application/ms-word files cannot render in the browser so
  // handleInternally does not work for it
  {
    extension: "doc",
    mimeType: "application/ms-word",
    blockHandleInternally: true,
  },
  {
    extension: "pdf",
    mimeType: "application/pdf",
  },
  {
    extension: "pdf",
    mimeType: "application/unknown",
  },
  {
    extension: "pdf",
    mimeType: "binary/octet-stream",
  },
  // text/plain files automatically render in the browser unless
  // the CD header explicitly tells the browser to download it
  {
    extension: "txt",
    mimeType: "text/plain",
    requireContentDispositionHeader: true,
  },
  {
    extension: "xml",
    mimeType: "binary/octet-stream",
  },
].map(file => {
  return {
    ...file,
    url: `${ROOT_URL}mime_type_download.sjs?contentType=${file.mimeType}&extension=${file.extension}`,
  };
});

// Preferred action types to apply to each downloaded file
const PREFERRED_ACTIONS = [
  "saveToDisk",
  "alwaysAsk",
  "useHelperApp",
  "handleInternally",
  "useSystemDefault",
].map(property => {
  let label = property.replace(/([A-Z])/g, " $1");
  label = label.charAt(0).toUpperCase() + label.slice(1);
  return {
    id: Ci.nsIHandlerInfo[property],
    label,
  };
});

async function createDownloadTest(
  downloadList,
  localHandlerApp,
  file,
  action,
  useContentDispositionHeader
) {
  // Skip handleInternally case for files that cannot be handled internally
  if (
    action.id === Ci.nsIHandlerInfo.handleInternally &&
    file.blockHandleInternally
  ) {
    return;
  }
  let skipDownload =
    action.id === Ci.nsIHandlerInfo.handleInternally &&
    file.mimeType === "application/pdf";
  // Types that require the CD header only display as handleInternally
  // when the CD header is missing
  if (file.requireContentDispositionHeader && !useContentDispositionHeader) {
    if (action.id === Ci.nsIHandlerInfo.handleInternally) {
      skipDownload = true;
    } else {
      return;
    }
  }
  info(
    `Testing download with mime-type ${file.mimeType} and extension ${
      file.extension
    }, preferred action "${action.label}," and ${
      useContentDispositionHeader
        ? "Content-Disposition: attachment"
        : "no Content-Disposition"
    } header.`
  );
  info("Preparing for download...");
  // apply preferredAction settings
  let mimeSettings = gMIMEService.getFromTypeAndExtension(
    file.mimeType,
    file.extension
  );
  mimeSettings.preferredAction = action.id;
  mimeSettings.alwaysAskBeforeHandling =
    action.id === Ci.nsIHandlerInfo.alwaysAsk;
  if (action.id === Ci.nsIHandlerInfo.useHelperApp) {
    mimeSettings.preferredApplicationHandler = localHandlerApp;
  }
  gHandlerService.store(mimeSettings);
  // delayed check for files opened in a new tab, except for skipped downloads
  let expectViewInBrowserTab =
    action.id === Ci.nsIHandlerInfo.handleInternally && !skipDownload;
  let viewInBrowserTabOpened = null;
  if (expectViewInBrowserTab) {
    viewInBrowserTabOpened = BrowserTestUtils.waitForNewTab(
      gBrowser,
      uri => uri.includes("file://"),
      true
    );
  }
  // delayed check for launched files
  let expectLaunch =
    action.id === Ci.nsIHandlerInfo.useSystemDefault ||
    action.id === Ci.nsIHandlerInfo.useHelperApp;
  let oldLaunchFile = DownloadIntegration.launchFile;
  let fileLaunched = null;
  if (expectLaunch) {
    fileLaunched = Promise.withResolvers();
    DownloadIntegration.launchFile = () => {
      ok(
        expectLaunch,
        `The file ${file.mimeType} should be launched with an external application.`
      );
      fileLaunched.resolve();
    };
  }
  info(`Start download of ${file.url}`);
  let dialogWindowPromise = BrowserTestUtils.domWindowOpenedAndLoaded();
  let downloadFinishedPromise = skipDownload
    ? null
    : promiseDownloadFinished(downloadList);
  BrowserTestUtils.startLoadingURIString(gBrowser.selectedBrowser, file.url);
  if (action.id === Ci.nsIHandlerInfo.alwaysAsk) {
    info("Check Always Ask dialog.");
    let dialogWindow = await dialogWindowPromise;
    is(
      dialogWindow.location.href,
      "chrome://mozapps/content/downloads/unknownContentType.xhtml",
      "Should show unknownContentType dialog for Always Ask preferred actions."
    );
    let doc = dialogWindow.document;
    let dialog = doc.querySelector("#unknownContentType");
    let acceptButton = dialog.getButton("accept");
    acceptButton.disabled = false;
    let saveItem = doc.querySelector("#save");
    saveItem.disabled = false;
    saveItem.click();
    dialog.acceptDialog();
  }
  let download = null;
  let downloadPath = null;
  if (!skipDownload) {
    info("Wait for download to finish...");
    download = await downloadFinishedPromise;
    downloadPath = download.target.path;
  }
  // check delayed assertions
  if (expectLaunch) {
    info("Wait for file to be launched in external application...");
    await fileLaunched.promise;
  }
  if (expectViewInBrowserTab) {
    info("Wait for file to be opened in new tab...");
    let viewInBrowserTab = await viewInBrowserTabOpened;
    ok(
      viewInBrowserTab,
      `The file ${file.mimeType} should be opened in a new tab.`
    );
    BrowserTestUtils.removeTab(viewInBrowserTab);
  }
  info("Checking for saved file...");
  let saveFound = downloadPath && (await IOUtils.exists(downloadPath));
  info("Cleaning up...");
  if (saveFound) {
    try {
      info(`Deleting file ${downloadPath}...`);
      await IOUtils.remove(downloadPath);
    } catch (ex) {
      info(`Error: ${ex}`);
    }
  }
  info("Removing download from list...");
  await downloadList.removeFinished();
  info("Clearing settings...");
  DownloadIntegration.launchFile = oldLaunchFile;
  info("Asserting results...");
  if (download) {
    ok(download.succeeded, "Download should complete successfully");
    ok(
      !download._launchedFromPanel,
      "Download should never be launched from panel"
    );
  }
  if (skipDownload) {
    ok(!saveFound, "Download should not be saved to disk");
  } else {
    ok(saveFound, "Download should be saved to disk");
  }
}

add_task(async function test_download_preferred_action() {
  // Prepare tests
  for (const index in FILE_TYPES_TO_TEST) {
    let file = FILE_TYPES_TO_TEST[index];
    let originalMimeSettings = gMIMEService.getFromTypeAndExtension(
      file.mimeType,
      file.extension
    );
    if (gHandlerService.exists(originalMimeSettings)) {
      FILE_TYPES_MIME_SETTINGS[index] = originalMimeSettings;
    }
  }
  let downloadList = await Downloads.getList(Downloads.PUBLIC);
  let oldLaunchFile = DownloadIntegration.launchFile;
  registerCleanupFunction(async function () {
    await removeAllDownloads();
    DownloadIntegration.launchFile = oldLaunchFile;
    Services.prefs.clearUserPref(
      "browser.download.always_ask_before_handling_new_types"
    );
    BrowserTestUtils.startLoadingURIString(
      gBrowser.selectedBrowser,
      "about:home"
    );
    for (const index in FILE_TYPES_TO_TEST) {
      let file = FILE_TYPES_TO_TEST[index];
      let mimeSettings = gMIMEService.getFromTypeAndExtension(
        file.mimeType,
        file.extension
      );
      if (FILE_TYPES_MIME_SETTINGS[index]) {
        gHandlerService.store(FILE_TYPES_MIME_SETTINGS[index]);
      } else {
        gHandlerService.remove(mimeSettings);
      }
    }
  });
  await SpecialPowers.pushPrefEnv({
    set: [["browser.download.always_ask_before_handling_new_types", false]],
  });
  let launcherPath = FileTestUtils.getTempFile("app-launcher").path;
  let localHandlerApp = localHandlerAppFactory.createInstance(
    Ci.nsILocalHandlerApp
  );
  localHandlerApp.executable = new FileUtils.File(launcherPath);
  localHandlerApp.executable.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0o755);
  // run tests
  for (const file of FILE_TYPES_TO_TEST) {
    // The CD header specifies the download file extension on download
    let fileNoHeader = file;
    let fileWithHeader = structuredClone(file);
    fileWithHeader.url += "&withHeader";
    for (const action of PREFERRED_ACTIONS) {
      // Clone file objects to prevent side-effects between iterations
      await createDownloadTest(
        downloadList,
        localHandlerApp,
        structuredClone(fileWithHeader),
        action,
        true
      );
      await createDownloadTest(
        downloadList,
        localHandlerApp,
        structuredClone(fileNoHeader),
        action,
        false
      );
    }
  }
});