summaryrefslogtreecommitdiffstats
path: root/toolkit/crashreporter/content/crashes.js
blob: b8f88f285e68f21d076f9b88a188f4355f31f39f (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
/* 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/. */

let reportURL;

const { CrashReports } = ChromeUtils.importESModule(
  "resource://gre/modules/CrashReports.sys.mjs"
);

ChromeUtils.defineESModuleGetters(this, {
  CrashSubmit: "resource://gre/modules/CrashSubmit.sys.mjs",
});

document.addEventListener("DOMContentLoaded", () => {
  populateReportLists();
  document
    .getElementById("clearUnsubmittedReports")
    .addEventListener("click", () => {
      clearUnsubmittedReports().catch(console.error);
    });
  document
    .getElementById("submitAllUnsubmittedReports")
    .addEventListener("click", () => {
      submitAllUnsubmittedReports().catch(console.error);
    });
  document
    .getElementById("clearSubmittedReports")
    .addEventListener("click", () => {
      clearSubmittedReports().catch(console.error);
    });
});

const buildID = Services.appinfo.appBuildID;

/**
 * Adds the crash reports with submission buttons and links
 * to the unsubmitted and submitted crash report lists.
 * If breakpad.reportURL is not set, displays a misconfiguration message
 * instead.
 */
function populateReportLists() {
  try {
    reportURL = Services.prefs.getCharPref("breakpad.reportURL");
    // Ignore any non http/https urls
    if (!/^https?:/i.test(reportURL)) {
      reportURL = null;
    }
  } catch (e) {
    reportURL = null;
  }
  if (!reportURL) {
    document.getElementById("noConfig").classList.remove("hidden");
    return;
  }

  const reports = CrashReports.getReports();
  const dateFormatter = new Services.intl.DateTimeFormat(undefined, {
    timeStyle: "short",
    dateStyle: "short",
  });
  reports.forEach(report =>
    addReportRow(report.pending, report.id, report.date, dateFormatter)
  );
  showAppropriateSections();
}

/**
 * Adds a crash report with the appropriate submission button
 * or viewing link to the unsubmitted or submitted report list
 * based on isPending.
 *
 * @param {Boolean} isPending     whether the crash is up for submission
 * @param {String}  id            the unique id of the crash report
 * @param {Date}    date          either the date of crash or date of submission
 * @param {Object}  dateFormatter formatter for presenting dates to users
 */
function addReportRow(isPending, id, date, dateFormatter) {
  const rowTemplate = document.getElementById("crashReportRow");
  const row = document
    .importNode(rowTemplate.content, true)
    .querySelector("tr");
  row.id = id;

  const cells = row.querySelectorAll("td");
  cells[0].appendChild(document.createTextNode(id));
  cells[1].appendChild(document.createTextNode(dateFormatter.format(date)));

  if (isPending) {
    const buttonTemplate = document.getElementById("crashSubmitButton");
    const button = document
      .importNode(buttonTemplate.content, true)
      .querySelector("button");
    const buttonText = button.querySelector("span");
    button.addEventListener("click", () =>
      submitPendingReport(id, row, button, buttonText, dateFormatter)
    );
    cells[2].appendChild(button);
    document.getElementById("unsubmitted").appendChild(row);
  } else {
    const linkTemplate = document.getElementById("viewCrashLink");
    const link = document
      .importNode(linkTemplate.content, true)
      .querySelector("a");
    link.href = `${reportURL}${id}`;
    cells[2].appendChild(link);
    document.getElementById("submitted").appendChild(row);
  }
}

/**
 * Shows or hides each of the unsubmitted and submitted report list
 * based on whether they contain at least one crash report.
 * If hidden, the submitted report list is replaced by a message
 * indicating that no crash reports have been submitted.
 */
function showAppropriateSections() {
  let hasUnsubmitted =
    document.getElementById("unsubmitted").childElementCount > 0;
  document
    .getElementById("reportListUnsubmitted")
    .classList.toggle("hidden", !hasUnsubmitted);

  let hasSubmitted = document.getElementById("submitted").childElementCount > 0;
  document
    .getElementById("reportListSubmitted")
    .classList.toggle("hidden", !hasSubmitted);
  document
    .getElementById("noSubmittedReports")
    .classList.toggle("hidden", hasSubmitted);
}

/**
 * Changes the provided button to display a spinner. Then, tries to submit the
 * crash report for the provided id. On success, removes the crash report from
 * the list of unsubmitted crash reports and adds a new crash report to the list
 * of submitted crash reports. On failure, changes the provided button to display
 * a red error message.
 *
 * @param {String}              reportId      the unique id of the crash report
 * @param {HTMLTableRowElement} row           the table row of the crash report
 * @param {HTMLButtonElement}   button        the button pressed to start the submission
 * @param {HTMLSpanElement}     buttonText    the text inside the pressed button
 * @param {Object}              dateFormatter formatter for presenting dates to users
 */
function submitPendingReport(reportId, row, button, buttonText, dateFormatter) {
  button.classList.add("submitting");
  document.getElementById("submitAllUnsubmittedReports").disabled = true;
  CrashSubmit.submit(reportId, CrashSubmit.SUBMITTED_FROM_ABOUT_CRASHES, {
    noThrottle: true,
  })
    .then(
      remoteCrashID => {
        document.getElementById("unsubmitted").removeChild(row);
        const report = CrashReports.getReports().filter(
          report => report.id === remoteCrashID
        );
        addReportRow(false, remoteCrashID, report.date, dateFormatter);
        showAppropriateSections();
        dispatchCustomEvent("CrashSubmitSucceeded");
      },
      () => {
        button.classList.remove("submitting");
        button.classList.add("failed-to-submit");
        document.l10n.setAttributes(
          buttonText,
          "submit-crash-button-failure-label"
        );
        dispatchCustomEvent("CrashSubmitFailed");
      }
    )
    .finally(() => {
      document.getElementById("submitAllUnsubmittedReports").disabled = false;
    });
}

/**
 * Deletes unsubmitted and old crash reports from the user's device.
 * Then, hides the list of unsubmitted crash reports.
 */
async function clearUnsubmittedReports() {
  const [title, description] = await document.l10n.formatValues([
    { id: "delete-confirm-title" },
    { id: "delete-unsubmitted-description" },
  ]);
  if (!Services.prompt.confirm(window, title, description)) {
    return;
  }

  await enqueueCleanup(() => cleanupFolder(CrashReports.pendingDir.path));
  await enqueueCleanup(clearOldReports);
  document.getElementById("reportListUnsubmitted").classList.add("hidden");
}

/**
 * Submits all the pending crash reports and removes all pending reports from pending reports list
 * and add them to submitted crash reports.
 */
async function submitAllUnsubmittedReports() {
  for (
    var i = 0;
    i < document.getElementById("unsubmitted").childNodes.length;
    i++
  ) {
    document
      .getElementById("unsubmitted")
      .childNodes[i].cells[2].childNodes[0].click();
  }
}

/**
 * Deletes submitted and old crash reports from the user's device.
 * Then, hides the list of submitted crash reports.
 */
async function clearSubmittedReports() {
  const [title, description] = await document.l10n.formatValues([
    { id: "delete-confirm-title" },
    { id: "delete-submitted-description" },
  ]);
  if (!Services.prompt.confirm(window, title, description)) {
    return;
  }

  await enqueueCleanup(async () =>
    cleanupFolder(
      CrashReports.submittedDir.path,
      async entry => entry.name.startsWith("bp-") && entry.name.endsWith(".txt")
    )
  );
  await enqueueCleanup(clearOldReports);
  document.getElementById("reportListSubmitted").classList.add("hidden");
  document.getElementById("noSubmittedReports").classList.remove("hidden");
}

/**
 * Deletes old crash reports from the user's device.
 */
async function clearOldReports() {
  const oneYearAgo = Date.now() - 31586000000;
  await cleanupFolder(CrashReports.reportsDir.path, async entry => {
    if (
      !entry.name.startsWith("InstallTime") ||
      entry.name == "InstallTime" + buildID
    ) {
      return false;
    }

    const stat = await IOUtils.stat(entry.path);
    return stat.lastModified < oneYearAgo;
  });
}

/**
 * Deletes files from the user's device at the specified path
 * that match the provided filter.
 *
 * @param {String}   path   the directory location to delete form
 * @param {Function} filter function taking in a file entry and
 *                          returning whether to delete the file
 */
async function cleanupFolder(path, filter) {
  function entry(path) {
    return {
      path,
      name: PathUtils.filename(path),
    };
  }
  let children;
  try {
    children = await IOUtils.getChildren(path);
  } catch (e) {
    if (DOMException.isInstance(e) || e.name !== "NotFoundError") {
      throw e;
    }
  }

  for (const childPath of children) {
    if (!filter || (await filter(entry(childPath)))) {
      await IOUtils.remove(childPath);
    }
  }
}

/**
 * Dispatches an event with the specified name.
 *
 * @param {String} name the name of the event
 */
function dispatchCustomEvent(name) {
  document.dispatchEvent(
    new CustomEvent(name, { bubbles: true, cancelable: false })
  );
}

let cleanupQueue = Promise.resolve();

/**
 * Enqueue a cleanup function.
 *
 * Instead of directly calling cleanup functions as a result of DOM
 * interactions, queue them through this function so that we do not have
 * overlapping executions of cleanup functions.
 *
 * Cleanup functions overlapping could cause a race where one function is
 * attempting to stat a file while another function is attempting to delete it,
 * causing an exception.
 *
 * @param fn The cleanup function to call. It will be called once the last
 *           cleanup function has resolved.
 *
 * @returns A promise to await instead of awaiting the cleanup function.
 */
function enqueueCleanup(fn) {
  cleanupQueue = cleanupQueue.then(fn);
  return cleanupQueue;
}