summaryrefslogtreecommitdiffstats
path: root/chromium/chrome/browser/resources/offline_pages/offline_internals.js
blob: fa4ddffd6aa31b41a082b44beff03e8ca5cea765 (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
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import './strings.m.js';

import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {$} from 'chrome://resources/js/util.m.js';

import {IsLogging, OfflineInternalsBrowserProxy, OfflineInternalsBrowserProxyImpl, OfflinePage, SavePageRequest} from './offline_internals_browser_proxy.js';

/** @type {!Array<OfflinePage>} */
let offlinePages = [];

/** @type {!Array<SavePageRequest>} */
let savePageRequests = [];

/** @type {!OfflineInternalsBrowserProxy} */
const browserProxy = OfflineInternalsBrowserProxyImpl.getInstance();

/**
 * Fill stored pages table.
 * @param {!Array<OfflinePage>} pages An array object representing
 *     stored offline pages.
 */
function fillStoredPages(pages) {
  const storedPagesTable = $('stored-pages');
  storedPagesTable.textContent = '';

  const template = $('stored-pages-table-row');
  const td = template.content.querySelectorAll('td');
  for (let pageIndex = 0; pageIndex < pages.length; pageIndex++) {
    const page = pages[pageIndex];
    td[0].textContent = pageIndex + 1;
    const checkbox = td[1].querySelector('input');
    checkbox.setAttribute('value', page.id);

    const link = td[2].querySelector('a');
    link.setAttribute('href', page.onlineUrl);
    const maxUrlCharsPerLine = 50;
    if (page.onlineUrl.length > maxUrlCharsPerLine) {
      link.textContent = '';
      for (let i = 0; i < page.onlineUrl.length; i += maxUrlCharsPerLine) {
        link.textContent += page.onlineUrl.slice(i, i + maxUrlCharsPerLine);
        link.textContent += '\r\n';
      }
    } else {
      link.textContent = page.onlineUrl;
    }

    td[3].textContent = page.namespace;
    td[4].textContent = Math.round(page.size / 1024);

    const row = document.importNode(template.content, true);
    storedPagesTable.appendChild(row);
  }
  offlinePages = pages;
}

/**
 * Fill requests table.
 * @param {!Array<SavePageRequest>} requests An array object representing
 *     the request queue.
 */
function fillRequestQueue(requests) {
  const requestQueueTable = $('request-queue');
  requestQueueTable.textContent = '';

  const template = $('request-queue-table-row');
  const td = template.content.querySelectorAll('td');
  for (const request of requests) {
    const checkbox = td[0].querySelector('input');
    checkbox.setAttribute('value', request.id);

    td[1].textContent = request.onlineUrl;
    td[2].textContent = new Date(request.creationTime);
    td[3].textContent = request.status;
    td[4].textContent = request.requestOrigin;

    const row = document.importNode(template.content, true);
    requestQueueTable.appendChild(row);
  }
  savePageRequests = requests;
}

/**
 * Fills the event logs section.
 * @param {!Array<string>} logs A list of log strings.
 */
function fillEventLog(logs) {
  const element = $('logs');
  element.textContent = '';
  for (const log of logs) {
    const logItem = document.createElement('li');
    logItem.textContent = log;
    element.appendChild(logItem);
  }
}

/**
 * Refresh all displayed information.
 */
function refreshAll() {
  browserProxy.getStoredPages().then(fillStoredPages);
  browserProxy.getRequestQueue().then(fillRequestQueue);
  browserProxy.getNetworkStatus().then(function(networkStatus) {
    $('current-status').textContent = networkStatus;
  });
  browserProxy.getLimitlessPrefetchingEnabled().then(function(enabled) {
    $('limitless-prefetching-checkbox').checked = enabled;
  });
  browserProxy.getPrefetchTestingHeaderValue().then(function(value) {
    switch (value) {
      case 'ForceEnable':
        $('testing-header-enable').checked = true;
        break;
      case 'ForceDisable':
        $('testing-header-disable').checked = true;
        break;
      default:
        $('testing-header-default').checked = true;
    }
  });
  refreshLog();
}

/**
 * Callback when pages are deleted.
 * @param {string} status The status of the request.
 */
function pagesDeleted(status) {
  $('page-actions-info').textContent = status;
  browserProxy.getStoredPages().then(fillStoredPages);
}

/**
 * Callback when requests are deleted.
 */
function requestsDeleted(status) {
  $('request-queue-actions-info').textContent = status;
  browserProxy.getRequestQueue().then(fillRequestQueue);
}

/**
 * Callback for prefetch actions.
 * @param {string} info The result of performing the prefetch actions.
 */
function setPrefetchResult(info) {
  $('prefetch-actions-info').textContent = info;
}

/**
 * Error callback for prefetch actions.
 * @param {*} error The error that resulted from the prefetch call.
 */
function prefetchResultError(error) {
  const errorText = error && error.message ? error.message : error;

  $('prefetch-actions-info').textContent = 'Error: ' + errorText;
}

/**
 * Downloads all the stored page and request queue information into a file.
 * Also translates all the fields representing datetime into human-readable
 * date strings.
 * TODO(chili): Create a CSV writer that can abstract out the line joining.
 */
function dumpAsJson() {
  const json = JSON.stringify(
      {offlinePages: offlinePages, savePageRequests: savePageRequests},
      function(key, value) {
        return key.endsWith('Time') ? new Date(value).toString() : value;
      },
      2);

  $('dump-box').value = json;
  $('dump-info').textContent = '';
  $('dump-modal').showModal();
  $('dump-box').select();
}

function closeDump() {
  $('dump-modal').close();
  $('dump-box').value = '';
}

function copyDump() {
  $('dump-box').select();
  document.execCommand('copy');
  $('dump-info').textContent = 'Copied to clipboard!';
}

/**
 * Updates the status strings.
 * @param {!IsLogging} logStatus Status of logging.
 */
function updateLogStatus(logStatus) {
  $('model-checkbox').checked = logStatus.modelIsLogging;
  $('request-checkbox').checked = logStatus.queueIsLogging;
  $('prefetch-checkbox').checked = logStatus.prefetchIsLogging;
}

/**
 * Sets all checkboxes with a specific name to the same checked status as the
 * provided source checkbox.
 * @param {HTMLElement} source The checkbox controlling the checked
 *     status.
 * @param {string} checkboxesName The name identifying the checkboxes to set.
 */
function toggleAllCheckboxes(source, checkboxesName) {
  const checkboxes = document.getElementsByName(checkboxesName);
  for (const checkbox of checkboxes) {
    checkbox.checked = source.checked;
  }
}

/**
 * Return the item ids for the selected checkboxes with a given name.
 * @param {string} checkboxesName The name identifying the checkboxes to
 *     query.
 * @return {!Array<string>} An array of selected ids.
 */
function getSelectedIdsFor(checkboxesName) {
  const checkboxes = document.querySelectorAll(
      `input[type="checkbox"][name="${checkboxesName}"]:checked`);
  return Array.from(checkboxes).map(c => c.value);
}

/**
 * Refreshes the logs.
 */
function refreshLog() {
  browserProxy.getEventLogs().then(fillEventLog);
  browserProxy.getLoggingState().then(updateLogStatus);
}

/**
 * Calls scheduleNwake and indicates how long the scheduled delay will be.
 */
function ensureBackgroundTaskScheduledWithDelay() {
  browserProxy.scheduleNwake()
      .then((result) => {
        // The delays in these messages should correspond to the scheduling
        // delays defined in PrefetchBackgroundTaskScheduler.java.
        if ($('limitless-prefetching-checkbox').checked) {
          setPrefetchResult(
              result +
              ' (Limitless mode enabled; background task scheduled to run' +
              ' in a few seconds.)');
        } else {
          setPrefetchResult(
              result +
              ' (Limitless mode disabled; background task scheduled to run' +
              ' in several minutes.)');
        }
      })
      .catch(prefetchResultError);
}

function initialize() {
  const incognito = loadTimeData.getBoolean('isIncognito');
  ['delete-selected-pages', 'delete-selected-requests', 'model-checkbox',
   'request-checkbox', 'refresh']
      .forEach(el => $(el).disabled = incognito);

  $('delete-selected-pages').onclick = function() {
    const pageIds = getSelectedIdsFor('stored');
    browserProxy.deleteSelectedPages(pageIds).then(pagesDeleted);
  };
  $('delete-selected-requests').onclick = function() {
    const requestIds = getSelectedIdsFor('requests');
    browserProxy.deleteSelectedRequests(requestIds).then(requestsDeleted);
  };
  $('refresh').onclick = refreshAll;
  $('dump').onclick = dumpAsJson;
  $('close-dump').onclick = closeDump;
  $('copy-to-clipboard').onclick = copyDump;
  $('model-checkbox').onchange = (evt) => {
    browserProxy.setRecordPageModel(evt.target.checked);
  };
  $('request-checkbox').onchange = (evt) => {
    browserProxy.setRecordRequestQueue(evt.target.checked);
  };
  $('prefetch-checkbox').onchange = (evt) => {
    browserProxy.setRecordPrefetchService(evt.target.checked);
  };
  $('refresh-logs').onclick = refreshLog;
  $('add-to-queue').onclick = function() {
    const saveUrls = $('url').value.split(',');
    let counter = saveUrls.length;
    $('save-url-state').textContent = '';
    for (let i = 0; i < saveUrls.length; i++) {
      browserProxy.addToRequestQueue(saveUrls[i]).then(function(state) {
        if (state) {
          $('save-url-state').textContent +=
              saveUrls[i] + ' has been added to queue.\n';
          $('url').value = '';
          counter--;
          if (counter == 0) {
            browserProxy.getRequestQueue().then(fillRequestQueue);
          }
        } else {
          $('save-url-state').textContent +=
              saveUrls[i] + ' failed to be added to queue.\n';
        }
      });
    }
  };
  $('schedule-nwake').onclick = function() {
    browserProxy.scheduleNwake()
        .then(setPrefetchResult)
        .catch(prefetchResultError);
  };
  $('cancel-nwake').onclick = function() {
    browserProxy.cancelNwake()
        .then(setPrefetchResult)
        .catch(prefetchResultError);
  };
  $('show-notification').onclick = function() {
    browserProxy.showPrefetchNotification().then(setPrefetchResult);
  };
  $('generate-page-bundle').onclick = function() {
    browserProxy.generatePageBundle($('generate-urls').value)
        .then(setPrefetchResult)
        .catch(prefetchResultError);
  };
  $('get-operation').onclick = function() {
    browserProxy.getOperation($('operation-name').value)
        .then(setPrefetchResult)
        .catch(prefetchResultError);
  };
  $('download-archive').onclick = function() {
    browserProxy.downloadArchive($('download-name').value);
  };
  $('toggle-all-stored').onclick = function() {
    toggleAllCheckboxes($('toggle-all-stored'), 'stored');
  };
  $('toggle-all-requests').onclick = function() {
    toggleAllCheckboxes($('toggle-all-requests'), 'requests');
  };
  $('limitless-prefetching-checkbox').onchange = (evt) => {
    browserProxy.setLimitlessPrefetchingEnabled(evt.target.checked);
    if (evt.target.checked) {
      ensureBackgroundTaskScheduledWithDelay();
    }
  };
  // Helper for setting prefetch testing header from a radio button.
  const setPrefetchTestingHeader = function(evt) {
    browserProxy.setPrefetchTestingHeaderValue(evt.target.value);
    ensureBackgroundTaskScheduledWithDelay();
  };
  $('testing-header-default').onchange = setPrefetchTestingHeader;
  $('testing-header-enable').onchange = setPrefetchTestingHeader;
  $('testing-header-disable').onchange = setPrefetchTestingHeader;
  if (!incognito) {
    refreshAll();
  }
}

document.addEventListener('DOMContentLoaded', initialize);