summaryrefslogtreecommitdiffstats
path: root/browser/components/downloads/test/browser/browser_downloads_context_menu_delete_file.js
blob: 4615f0a369f00ae8a5e6b4112bcf289abf12aab7 (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

var { DownloadHistory } = ChromeUtils.importESModule(
  "resource://gre/modules/DownloadHistory.sys.mjs"
);
let gDownloadDir;
let downloads = [];

async function createDownloadFiles() {
  if (!gDownloadDir) {
    gDownloadDir = await setDownloadDir();
  }
  info("Created download directory: " + gDownloadDir);
  info("Setting path for download file");
  downloads.push({
    state: DownloadsCommon.DOWNLOAD_FINISHED,
    contentType: "text/plain",
    target: await createDownloadedFile(
      PathUtils.join(gDownloadDir, "downloaded.txt"),
      "Test file"
    ),
  });
  downloads.push({
    state: DownloadsCommon.DOWNLOAD_FINISHED,
    contentType: "text/javascript",
    target: await createDownloadedFile(
      PathUtils.join(gDownloadDir, "downloaded.js"),
      "Test file"
    ),
  });
}

add_setup(startServer);

registerCleanupFunction(async function () {
  await task_resetState();
  await PlacesUtils.history.clear();
});

add_task(async function test_download_deleteFile() {
  await SpecialPowers.pushPrefEnv({
    set: [
      ["browser.download.always_ask_before_handling_new_types", false],
      ["browser.download.alwaysOpenPanel", false],
      ["browser.download.clearHistoryOnDelete", 2],
    ],
  });

  // remove download files, empty out collections
  let downloadList = await Downloads.getList(Downloads.ALL);
  let downloadCount = (await downloadList.getAll()).length;
  is(downloadCount, 0, "At the start of the test, there should be 0 downloads");
  await task_resetState();
  await createDownloadFiles();
  await task_addDownloads(downloads);
  await task_openPanel();
  await TestUtils.waitForCondition(() => {
    let downloadsListBox = document.getElementById("downloadsListBox");
    downloadsListBox.removeAttribute("disabled");
    return downloadsListBox.childElementCount == downloads.length;
  });

  info("trigger the context menu");
  let itemTarget = document.querySelector(
    "#downloadsListBox richlistitem .downloadMainArea"
  );
  let contextMenu = await openContextMenu(itemTarget);
  let deleteFileItem = contextMenu.querySelector(
    '[command="downloadsCmd_deleteFile"]'
  );
  ok(
    !BrowserTestUtils.is_hidden(deleteFileItem),
    "deleteFileItem should be visible"
  );

  let target1 = downloads[1].target;
  ok(target1.exists(), "downloaded.txt should exist");
  info(`file path: ${target1.path}`);
  let hiddenPromise = BrowserTestUtils.waitForEvent(
    DownloadsPanel.panel,
    "popuphidden"
  );

  contextMenu.activateItem(deleteFileItem);

  await TestUtils.waitForCondition(() => !target1.exists());

  await TestUtils.waitForCondition(() => {
    let downloadsListBox = document.getElementById("downloadsListBox");
    downloadsListBox.removeAttribute("disabled");
    return downloadsListBox.childElementCount == 1;
  });

  await SpecialPowers.pushPrefEnv({
    set: [["browser.download.clearHistoryOnDelete", 0]],
  });
  info("trigger the context menu again");
  let itemTarget2 = document.querySelector(
    "#downloadsListBox richlistitem .downloadMainArea"
  );
  let contextMenu2 = await openContextMenu(itemTarget2);
  ok(
    !BrowserTestUtils.is_hidden(deleteFileItem),
    "deleteFileItem should be visible"
  );
  let target2 = downloads[0].target;
  ok(target2.exists(), "downloaded.js should exist");
  info(`file path: ${target2.path}`);
  contextMenu2.activateItem(deleteFileItem);
  await TestUtils.waitForCondition(() => !target2.exists());

  let downloadsListBox = document.getElementById("downloadsListBox");
  downloadsListBox.removeAttribute("disabled");
  Assert.greater(
    downloadsListBox.childElementCount,
    0,
    "There should be a download in the list"
  );

  ok(
    !DownloadsView.richListBox.selectedItem._shell.isCommandEnabled(
      "downloadsCmd_deleteFile"
    ),
    "Delete file command should be disabled"
  );

  DownloadsPanel.hidePanel();
  await hiddenPromise;
});

add_task(async function test_about_downloads_deleteFile_for_history_download() {
  await task_resetState();
  await PlacesUtils.history.clear();

  if (!gDownloadDir) {
    gDownloadDir = await setDownloadDir();
  }

  let targetFile = await createDownloadedFile(
    PathUtils.join(gDownloadDir, "test-download.txt"),
    "blah blah blah"
  );
  let endTime;
  try {
    endTime = targetFile.creationTime;
  } catch (e) {
    endTime = Date.now();
  }
  let download = {
    source: {
      url: httpUrl(targetFile.leafName),
      isPrivate: false,
    },
    target: {
      path: targetFile.path,
      size: targetFile.fileSize,
    },
    succeeded: true,
    stopped: true,
    endTime,
    fileSize: targetFile.fileSize,
    state: 1,
  };

  function promiseWaitForVisit(aUrl) {
    return new Promise(resolve => {
      function listener(aEvents) {
        Assert.equal(aEvents.length, 1);
        let event = aEvents[0];
        Assert.equal(event.type, "page-visited");
        if (event.url == aUrl) {
          PlacesObservers.removeListener(["page-visited"], listener);
          resolve([
            event.visitTime,
            event.transitionType,
            event.lastKnownTitle,
          ]);
        }
      }
      PlacesObservers.addListener(["page-visited"], listener);
    });
  }

  function waitForAnnotation(sourceUriSpec, annotationName) {
    return TestUtils.waitForCondition(async () => {
      let pageInfo = await PlacesUtils.history.fetch(sourceUriSpec, {
        includeAnnotations: true,
      });
      return pageInfo && pageInfo.annotations.has(annotationName);
    }, `Should have found annotation ${annotationName} for ${sourceUriSpec}.`);
  }

  // Add the download to history using the XPCOM service, then use the
  // DownloadHistory module to save the associated metadata.
  let promiseFileAnnotation = waitForAnnotation(
    download.source.url,
    "downloads/destinationFileURI"
  );
  let promiseMetaAnnotation = waitForAnnotation(
    download.source.url,
    "downloads/metaData"
  );
  let promiseVisit = promiseWaitForVisit(download.source.url);
  await DownloadHistory.addDownloadToHistory(download);
  await promiseVisit;
  await DownloadHistory.updateMetaData(download);
  await Promise.all([promiseFileAnnotation, promiseMetaAnnotation]);

  let win = await openLibrary("Downloads");
  registerCleanupFunction(function () {
    win?.close();
  });

  let box = win.document.getElementById("downloadsListBox");
  ok(box, "Should have list of downloads");
  is(box.children.length, 1, "Should have 1 download.");
  let kid = box.firstChild;
  let desc = kid.querySelector(".downloadTarget");
  let dl = kid._shell.download;
  // This would just be an `is` check, but stray temp files
  // if this test (or another in this dir) ever fails could throw that off.
  ok(
    desc.value.includes("test-download"),
    `Label '${desc.value}' should include 'test-download'`
  );
  ok(kid.selected, "First item should be selected.");
  ok(dl.placesNode, "Download should have history.");
  ok(targetFile.exists(), "Download target should exist.");
  let contextMenu = win.document.getElementById("downloadsContextMenu");
  let popupShownPromise = BrowserTestUtils.waitForEvent(
    contextMenu,
    "popupshown"
  );
  EventUtils.synthesizeMouseAtCenter(
    kid,
    { type: "contextmenu", button: 2 },
    win
  );
  await popupShownPromise;
  let popupHiddenPromise = BrowserTestUtils.waitForEvent(
    contextMenu,
    "popuphidden"
  );
  contextMenu.activateItem(
    contextMenu.querySelector(".downloadDeleteFileMenuItem")
  );
  await popupHiddenPromise;
  await TestUtils.waitForCondition(() => !targetFile.exists());
  info("History download target deleted.");
});