File: downloads.js

package info (click to toggle)
wine-gecko-2.21 2.21%2Bdfsg2-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 646,272 kB
  • ctags: 630,086
  • sloc: cpp: 2,895,786; ansic: 1,502,970; python: 156,675; asm: 115,373; java: 111,421; sh: 63,309; xml: 62,872; makefile: 58,685; perl: 19,182; objc: 3,461; yacc: 2,051; lex: 979; pascal: 929; exp: 449; php: 244; lisp: 228; awk: 211; sed: 26; csh: 21; ada: 16; ruby: 3
file content (469 lines) | stat: -rw-r--r-- 15,469 bytes parent folder | download | duplicates (5)
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
// -*- Mode: js2; tab-width: 2; indent-tabs-mode: nil; js2-basic-offset: 2; js2-skip-preprocessor-directives: t; -*-
/* 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/. */

const URI_GENERIC_ICON_DOWNLOAD = "chrome://browser/skin/images/alert-downloads-30.png";

var Downloads = {
  _inited: false,
  _progressAlert: null,

  get manager() {
    return Cc["@mozilla.org/download-manager;1"]
             .getService(Ci.nsIDownloadManager);
  },

  _getReferrerOrSource: function dh__getReferrerOrSource(aDownload) {
    return aDownload.referrer.spec || aDownload.source.spec;
  },

  _getLocalFile: function dh__getLocalFile(aFileURI) {
    // XXX it's possible that using a null char-set here is bad

    const fileUrl = Services.io.newURI(aFileURI.spec || aFileURI, null, null).QueryInterface(Ci.nsIFileURL);
    return fileUrl.file.clone().QueryInterface(Ci.nsILocalFile);
  },

  init: function dh_init() {
    if (this._inited)
      return;

    this._inited = true;

    Services.obs.addObserver(this, "dl-start", true);
    Services.obs.addObserver(this, "dl-done", true);
  },

  uninit: function dh_uninit() {
    Services.obs.removeObserver(this, "dl-start");
    Services.obs.removeObserver(this, "dl-done");
  },

  openDownload: function dh_openDownload(aDownload) {
    // expects xul item
    let id = aDownload.getAttribute("downloadId");
    let download = this.manager.getDownload(id)
    let fileURI = download.target;
    let file = this._getLocalFile(fileURI);

    try {
      file.launch();
    } catch (ex) { }
  },

  removeDownload: function dh_removeDownload(aDownload) {
    // aDownload is the XUL element here,
    // and .target currently returns the target attribute (string value)
    let id = aDownload.getAttribute("downloadId");
    let download = this.manager.getDownload(id);

    if (download) {
      // TODO <sfoster> add class/mark element for removal transition?
      this.manager.removeDownload(id);
    }
  },

  cancelDownload: function dh_cancelDownload(aDownload) {
    let id = aDownload.getAttribute("downloadId");
    let download = this.manager.getDownload(id)
    this.manager.cancelDownload(id);

    let fileURI = download.target;
    let file = this._getLocalFile(fileURI);

    if (file.exists())
      file.remove(false);
  },

  pauseDownload: function dh_pauseDownload(aDownload) {
    let id = aDownload.getAttribute("downloadId");
    this.manager.pauseDownload(id);
  },

  resumeDownload: function dh_resumeDownload(aDownload) {
    let id = aDownload.getAttribute("downloadId");
    this.manager.resumeDownload(id);
  },

  retryDownload: function dh_retryDownload(aDownload) {
    let id = aDownload.getAttribute("downloadId");
    this.manager.retryDownload(id);
  },

  showPage: function dh_showPage(aDownload) {
    let id = aDownload.getAttribute("downloadId");
    let download = this.manager.getDownload(id)
    let uri = this._getReferrerOrSource(download);
    if (uri)
      BrowserUI.newTab(uri, Browser.selectedTab);
  },

  showAlert: function dh_showAlert(aName, aMessage, aTitle, aIcon) {
    var notifier = Cc["@mozilla.org/alerts-service;1"]
                     .getService(Ci.nsIAlertsService);

    // Callback for tapping on the alert popup
    let observer = {
      observe: function (aSubject, aTopic, aData) {
        if (aTopic == "alertclickcallback")
          PanelUI.show("downloads-container");
      }
    };

    if (!aTitle)
      aTitle = Strings.browser.GetStringFromName("alertDownloads");

    if (!aIcon)
      aIcon = URI_GENERIC_ICON_DOWNLOAD;

    notifier.showAlertNotification(aIcon, aTitle, aMessage, true, "", observer, aName);
  },

  observe: function (aSubject, aTopic, aData) {
    let download = aSubject.QueryInterface(Ci.nsIDownload);
    let msgKey = "";

    switch (aTopic) {
      case "dl-start":
        msgKey = "alertDownloadsStart";
        if (!this._progressAlert) {
          this._progressAlert = new AlertDownloadProgressListener();
          this.manager.addListener(this._progressAlert);
        }
        break;
      case "dl-done":
        msgKey = "alertDownloadsDone";
        break;
    }

    if (msgKey) {
      let message = Strings.browser.formatStringFromName(msgKey, [download.displayName], 1);
      let url = download.target.spec.replace("file:", "download:");
      this.showAlert(url, message);
    }
  },

  QueryInterface: function (aIID) {
    if (!aIID.equals(Ci.nsIObserver) &&
        !aIID.equals(Ci.nsISupportsWeakReference) &&
        !aIID.equals(Ci.nsISupports))
      throw Components.results.NS_ERROR_NO_INTERFACE;
    return this;
  }
};

/**
 * Wraps a list/grid control implementing nsIDOMXULSelectControlElement and
 * fills it with the user's downloads.  It observes download notifications,
 * so it'll automatically update to reflect current download progress.
 *
 * @param           aSet    Control implementing nsIDOMXULSelectControlElement.
 * @param {Number}  aLimit  Maximum number of items to show in the view.
 */
function DownloadsView(aSet, aLimit) {
  this._set = aSet;
  this._limit = aLimit;

  this._progress = new DownloadProgressListener(this);
  Downloads.manager.addListener(this._progress);

  // Look for the removed download notification
  let obs = Cc["@mozilla.org/observer-service;1"].
                  getService(Ci.nsIObserverService);
  obs.addObserver(this, "download-manager-remove-download-guid", false);

  this.getDownloads();
}

DownloadsView.prototype = {
  _progress: null,
  _stmt: null,
  _timeoutID: null,
  _set: null,
  _limit: null,

  _getItemForDownloadGuid: function dv__getItemForDownload(aGuid) {
    return this._set.querySelector("richgriditem[downloadGuid='" + aGuid + "']");
  },

  _getItemForDownload: function dv__getItemForDownload(aDownload) {
    return this._set.querySelector("richgriditem[downloadId='" + aDownload.id + "']");
  },

  _getDownloadForItem: function dv__getDownloadForItem(anItem) {
    let id = anItem.getAttribute("downloadId");
    return Downloads.manager.getDownload(id);
  },

  _getAttrsForDownload: function dv__getAttrsForDownload(aDownload) {
    // expects a DownloadManager download object
    return {
      typeName: 'download',
      downloadId: aDownload.id,
      downloadGuid: aDownload.guid,
      name: aDownload.displayName,
      target: aDownload.target,
      iconURI: "moz-icon://" + aDownload.displayName + "?size=64",
      date: DownloadUtils.getReadableDates(new Date())[0],
      domain: DownloadUtils.getURIHost(aDownload.source.spec)[0],
      size: this._getDownloadSize(aDownload.size),
      state: aDownload.state
    };

  },
  _updateItemWithAttrs: function dv__updateItemWithAttrs(anItem, aAttrs) {
    for (let name in aAttrs)
      anItem.setAttribute(name, aAttrs[name]);
  },

  _getDownloadSize: function dv__getDownloadSize (aSize) {
    let displaySize = DownloadUtils.convertByteUnits(aSize);
    if (displaySize[0] > 0) // [0] is size, [1] is units
      return displaySize.join("");
    else
      return Strings.browser.GetStringFromName("downloadsUnknownSize");
  },

  _initStatement: function dv__initStatement() {
    if (this._stmt)
      this._stmt.finalize();

    let limitClause = this._limit ? ("LIMIT " + this._limit) : "";

    this._stmt = Downloads.manager.DBConnection.createStatement(
      "SELECT id, guid, name, target, source, state, startTime, endTime, referrer, " +
             "currBytes, maxBytes, state IN (?1, ?2, ?3, ?4, ?5) isActive " +
      "FROM moz_downloads " +
      "ORDER BY isActive DESC, endTime DESC, startTime DESC " +
      limitClause);
  },

  _stepDownloads: function dv__stepDownloads(aNumItems) {
    try {
      if (!this._stmt.executeStep()) {
        // final record;
        this._stmt.finalize();
        this._stmt = null;
        this._fire("DownloadsReady", this._set);
        return;
      }
      let attrs = {
        typeName: 'download',
        // TODO: <sfoster> the remove event gives us guid not id; should we use guid as the download (record) id?
        downloadGuid: this._stmt.row.guid,
        downloadId: this._stmt.row.id,
        name: this._stmt.row.name,
        target: this._stmt.row.target,
        iconURI: "moz-icon://" + this._stmt.row.name + "?size=25",
        date: DownloadUtils.getReadableDates(new Date(this._stmt.row.endTime / 1000))[0],
        domain: DownloadUtils.getURIHost(this._stmt.row.source)[0],
        size: this._getDownloadSize(this._stmt.row.maxBytes),
        state: this._stmt.row.state
      };

      let item = this._set.appendItem(attrs.target, attrs.downloadId);
      this._updateItemWithAttrs(item, attrs);
    } catch (e) {
      // Something went wrong when stepping or getting values, so quit
      this._stmt.reset();
      return;
    }

    // Add another item to the list if we should;
    // otherwise, let the UI update and continue later
    if (aNumItems > 1) {
      this._stepDownloads(aNumItems - 1);
    } else {
      // Use a shorter delay for earlier downloads to display them faster
      let delay = Math.min(this._set.itemCount * 10, 300);
      let self = this;
      this._timeoutID = setTimeout(function() { self._stepDownloads(5); }, delay);
    }
  },

  _fire: function _fire(aName, anElement) {
    let event = document.createEvent("Events");
    event.initEvent(aName, true, true);
    anElement.dispatchEvent(event);
  },

  observe: function dv_managerObserver(aSubject, aTopic, aData) {
    // observer-service message handler
    switch (aTopic) {
      case "download-manager-remove-download-guid":
        let guid = aSubject.QueryInterface(Ci.nsISupportsCString);
        this.removeDownload({
          guid: guid
        });
        return;
    }
  },

  getDownloads: function dv_getDownloads() {
    this._initStatement();
    clearTimeout(this._timeoutID);

    // Since we're pulling in all downloads, clear the list to avoid duplication
    this.clearDownloads();

    this._stmt.reset();
    this._stmt.bindInt32Parameter(0, Ci.nsIDownloadManager.DOWNLOAD_NOTSTARTED);
    this._stmt.bindInt32Parameter(1, Ci.nsIDownloadManager.DOWNLOAD_DOWNLOADING);
    this._stmt.bindInt32Parameter(2, Ci.nsIDownloadManager.DOWNLOAD_PAUSED);
    this._stmt.bindInt32Parameter(3, Ci.nsIDownloadManager.DOWNLOAD_QUEUED);
    this._stmt.bindInt32Parameter(4, Ci.nsIDownloadManager.DOWNLOAD_SCANNING);

    // Take a quick break before we actually start building the list
    let self = this;
    this._timeoutID = setTimeout(function() {
      self._stepDownloads(1);
    }, 0);
  },

  clearDownloads: function dv_clearDownloads() {
    while (this._set.itemCount > 0)
      this._set.removeItemAt(0);
  },

  addDownload: function dv_addDownload(aDownload) {
    // expects a download manager download object
    let attrs = this._getAttrsForDownload(aDownload);
    let item = this._set.insertItemAt(0, attrs.target, attrs.downloadId);
    this._updateItemWithAttrs(item, attrs);
  },

  updateDownload: function dv_updateDownload(aDownload) {
    // expects a download manager download object
    let item = this._getItemForDownload(aDownload);

    if (!item)
      return;

    let attrs = this._getAttrsForDownload(aDownload);
    this._updateItemWithAttrs(item, attrs);
  },

  removeDownload: function dv_removeDownload(aDownload) {
    // expects an object with id or guid property
    let item;
    if (aDownload.id) {
      item = this._getItemForDownload(aDownload.id);
    } else if (aDownload.guid) {
      item = this._getItemForDownloadGuid(aDownload.guid);
    }
    if (!item)
      return;

    let idx = this._set.getIndexOfItem(item);
    if (idx < 0)
        return;
    // any transition needed here?
    this._set.removeItemAt(idx);
  },

  destruct: function dv_destruct() {
    Downloads.manager.removeListener(this._progress);
  }
};

var DownloadsPanelView = {
  _view: null,

  get _grid() { return document.getElementById("downloads-list"); },
  get visible() { return PanelUI.isPaneVisible("downloads-container"); },

  init: function init() {
    this._view = new DownloadsView(this._grid);
  },

  show: function show() {
    this._grid.arrangeItems();
  },

  uninit: function uninit() {
    this._view.destruct();
  }
};

/**
 * Notifies a DownloadsView about updates in the state of various downloads.
 *
 * @param aView An instance of DownloadsView.
 */
function DownloadProgressListener(aView) {
  this._view = aView;
}

DownloadProgressListener.prototype = {
  _view: null,

  //////////////////////////////////////////////////////////////////////////////
  //// nsIDownloadProgressListener
  onDownloadStateChange: function dPL_onDownloadStateChange(aState, aDownload) {
    let state = aDownload.state;
    switch (state) {
      case Ci.nsIDownloadManager.DOWNLOAD_QUEUED:
      case Ci.nsIDownloadManager.DOWNLOAD_BLOCKED_POLICY:
        this._view.addDownload(aDownload);
        break;
      case Ci.nsIDownloadManager.DOWNLOAD_FAILED:
      case Ci.nsIDownloadManager.DOWNLOAD_CANCELED:
      case Ci.nsIDownloadManager.DOWNLOAD_BLOCKED_PARENTAL:
      case Ci.nsIDownloadManager.DOWNLOAD_DIRTY:
      case Ci.nsIDownloadManager.DOWNLOAD_FINISHED:
        break;
    }

    this._view.updateDownload(aDownload);
  },

  onProgressChange: function dPL_onProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress, aDownload) {
    // TODO <jwilde>: Add more detailed progress information.
    this._view.updateDownload(aDownload);
  },

  onStateChange: function(aWebProgress, aRequest, aState, aStatus, aDownload) { },
  onSecurityChange: function(aWebProgress, aRequest, aState, aDownload) { },

  //////////////////////////////////////////////////////////////////////////////
  //// nsISupports
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIDownloadProgressListener])
};


/**
 * Tracks download progress so that additional information can be displayed
 * about its download in alert popups.
 */
function AlertDownloadProgressListener() { }

AlertDownloadProgressListener.prototype = {
  //////////////////////////////////////////////////////////////////////////////
  //// nsIDownloadProgressListener
  onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress, aDownload) {
    let strings = Strings.browser;
    let availableSpace = -1;

    try {
      // diskSpaceAvailable is not implemented on all systems
      let availableSpace = aDownload.targetFile.diskSpaceAvailable;
    } catch(ex) { }

    let contentLength = aDownload.size;
    if (availableSpace > 0 && contentLength > 0 && contentLength > availableSpace) {
      Downloads.showAlert(aDownload.target.spec.replace("file:", "download:"),
                          strings.GetStringFromName("alertDownloadsNoSpace"),
                          strings.GetStringFromName("alertDownloadsSize"));
      Downloads.cancelDownload(aDownload.id);
    }
  },

  onDownloadStateChange: function(aState, aDownload) { },
  onStateChange: function(aWebProgress, aRequest, aState, aStatus, aDownload) { },
  onSecurityChange: function(aWebProgress, aRequest, aState, aDownload) { },

  //////////////////////////////////////////////////////////////////////////////
  //// nsISupports
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIDownloadProgressListener])
};