summaryrefslogtreecommitdiffstats
path: root/mobile/android/components/HelperAppDialog.js
blob: f127fb0b3b7cf966a4b7a8049b87e26178790a08 (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
361
362
363
364
365
366
367
368
369
370
371
372
373
// -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
/* 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/. */

/*globals ContentAreaUtils */

const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;

const APK_MIME_TYPE = "application/vnd.android.package-archive";

const OMA_DOWNLOAD_DESCRIPTOR_MIME_TYPE = "application/vnd.oma.dd+xml";
const OMA_DRM_MESSAGE_MIME = "application/vnd.oma.drm.message";
const OMA_DRM_CONTENT_MIME = "application/vnd.oma.drm.content";
const OMA_DRM_RIGHTS_MIME = "application/vnd.oma.drm.rights+wbxml";

const PREF_BD_USEDOWNLOADDIR = "browser.download.useDownloadDir";
const URI_GENERIC_ICON_DOWNLOAD = "drawable://alert_download";

Cu.import("resource://gre/modules/Downloads.jsm");
Cu.import("resource://gre/modules/FileUtils.jsm");
Cu.import("resource://gre/modules/HelperApps.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/NetUtil.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

XPCOMUtils.defineLazyModuleGetter(this, "RuntimePermissions", "resource://gre/modules/RuntimePermissions.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Messaging", "resource://gre/modules/Messaging.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Snackbars", "resource://gre/modules/Snackbars.jsm");

// -----------------------------------------------------------------------
// HelperApp Launcher Dialog
// -----------------------------------------------------------------------

XPCOMUtils.defineLazyGetter(this, "ContentAreaUtils", function() {
  let ContentAreaUtils = {};
  Services.scriptloader.loadSubScript("chrome://global/content/contentAreaUtils.js", ContentAreaUtils);
  return ContentAreaUtils;
});

function HelperAppLauncherDialog() { }

HelperAppLauncherDialog.prototype = {
  classID: Components.ID("{e9d277a0-268a-4ec2-bb8c-10fdf3e44611}"),
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIHelperAppLauncherDialog]),

  /**
   * Returns false if `url` represents a local or special URL that we don't
   * wish to ever download.
   *
   * Returns true otherwise.
   */
  _canDownload: function (url, alreadyResolved=false) {
    // The common case.
    if (url.schemeIs("http") ||
        url.schemeIs("https") ||
        url.schemeIs("ftp")) {
      return true;
    }

    // The less-common opposite case.
    if (url.schemeIs("chrome") ||
        url.schemeIs("jar") ||
        url.schemeIs("resource") ||
        url.schemeIs("wyciwyg") ||
        url.schemeIs("file")) {
      return false;
    }

    // For all other URIs, try to resolve them to an inner URI, and check that.
    if (!alreadyResolved) {
      let innerURI = NetUtil.newChannel({
        uri: url,
        loadUsingSystemPrincipal: true
      }).URI;

      if (!url.equals(innerURI)) {
        return this._canDownload(innerURI, true);
      }
    }

    // Anything else is fine to download.
    return true;
  },

  /**
   * Returns true if `launcher` represents a download for which we wish
   * to prompt.
   */
  _shouldPrompt: function (launcher) {
    let mimeType = this._getMimeTypeFromLauncher(launcher);

    // Straight equality: nsIMIMEInfo normalizes.
    return APK_MIME_TYPE == mimeType || OMA_DOWNLOAD_DESCRIPTOR_MIME_TYPE == mimeType;
  },

  /**
   * Returns true if `launcher` represents a download for which we wish to
   * offer a "Save to disk" option.
   */
  _shouldAddSaveToDiskIntent: function(launcher) {
      let mimeType = this._getMimeTypeFromLauncher(launcher);

      // We can't handle OMA downloads. So don't even try. (Bug 1219078)
      return mimeType != OMA_DOWNLOAD_DESCRIPTOR_MIME_TYPE;
  },

  /**
   * Returns true if `launcher`represents a download that should not be handled by Firefox
   * or a third-party app and instead be forwarded to Android's download manager.
   */
  _shouldForwardToAndroidDownloadManager: function(aLauncher) {
    let forwardDownload = Services.prefs.getBoolPref('browser.download.forward_oma_android_download_manager');
    if (!forwardDownload) {
      return false;
    }

    let mimeType = aLauncher.MIMEInfo.MIMEType;
    if (!mimeType) {
      mimeType = ContentAreaUtils.getMIMETypeForURI(aLauncher.source) || "";
    }

    return [
      OMA_DOWNLOAD_DESCRIPTOR_MIME_TYPE,
      OMA_DRM_MESSAGE_MIME,
      OMA_DRM_CONTENT_MIME,
      OMA_DRM_RIGHTS_MIME
    ].indexOf(mimeType) != -1;
  },

  show: function hald_show(aLauncher, aContext, aReason) {
    if (!this._canDownload(aLauncher.source)) {
      this._refuseDownload(aLauncher);
      return;
    }

    if (this._shouldForwardToAndroidDownloadManager(aLauncher)) {
      Task.spawn(function* () {
        try {
          let hasPermission = yield RuntimePermissions.waitForPermissions(RuntimePermissions.WRITE_EXTERNAL_STORAGE);
          if (hasPermission) {
            this._downloadWithAndroidDownloadManager(aLauncher);
            aLauncher.cancel(Cr.NS_BINDING_ABORTED);
          }
        } finally {
        }
      }.bind(this)).catch(Cu.reportError);
      return;
    }

    let bundle = Services.strings.createBundle("chrome://browser/locale/browser.properties");

    let defaultHandler = new Object();
    let apps = HelperApps.getAppsForUri(aLauncher.source, {
      mimeType: aLauncher.MIMEInfo.MIMEType,
    });

    if (this._shouldAddSaveToDiskIntent(aLauncher)) {
      // Add a fake intent for save to disk at the top of the list.
      apps.unshift({
        name: bundle.GetStringFromName("helperapps.saveToDisk"),
        packageName: "org.mozilla.gecko.Download",
        iconUri: "drawable://icon",
        selected: true, // Default to download for files
        launch: function() {
          // Reset the preferredAction here.
          aLauncher.MIMEInfo.preferredAction = Ci.nsIMIMEInfo.saveToDisk;
          aLauncher.saveToDisk(null, false);
          return true;
        }
      });
    }

    // We do not handle this download and there are no apps that want to do it
    if (apps.length === 0) {
      this._refuseDownload(aLauncher);
      return;
    }

    let callback = function(app) {
      aLauncher.MIMEInfo.preferredAction = Ci.nsIMIMEInfo.useHelperApp;
      if (!app.launch(aLauncher.source)) {
        // Once the app is done we need to get rid of the temp file. This shouldn't
        // get run in the saveToDisk case.
        aLauncher.cancel(Cr.NS_BINDING_ABORTED);
      }
    }

    // See if the user already marked something as the default for this mimetype,
    // and if that app is still installed.
    let preferredApp = this._getPreferredApp(aLauncher);
    if (preferredApp) {
      let pref = apps.filter(function(app) {
        return app.packageName === preferredApp;
      });

      if (pref.length > 0) {
        callback(pref[0]);
        return;
      }
    }

    // If there's only one choice, and we don't want to prompt, go right ahead
    // and choose that app automatically.
    if (!this._shouldPrompt(aLauncher) && (apps.length === 1)) {
      callback(apps[0]);
      return;
    }

    // Otherwise, let's go through the prompt.
    HelperApps.prompt(apps, {
      title: bundle.GetStringFromName("helperapps.pick"),
      buttons: [
        bundle.GetStringFromName("helperapps.alwaysUse"),
        bundle.GetStringFromName("helperapps.useJustOnce")
      ],
      // Tapping an app twice should choose "Just once".
      doubleTapButton: 1
    }, (data) => {
      if (data.button < 0) {
        return;
      }

      callback(apps[data.icongrid0]);

      if (data.button === 0) {
        this._setPreferredApp(aLauncher, apps[data.icongrid0]);
      }
    });
  },

  _refuseDownload: function(aLauncher) {
    aLauncher.cancel(Cr.NS_BINDING_ABORTED);

    Services.console.logStringMessage("Refusing download of non-downloadable file.");

    let bundle = Services.strings.createBundle("chrome://browser/locale/handling.properties");
    let failedText = bundle.GetStringFromName("download.blocked");

    Snackbars.show(failedText, Snackbars.LENGTH_LONG);
  },

  _downloadWithAndroidDownloadManager(aLauncher) {
    let mimeType = aLauncher.MIMEInfo.MIMEType;
    if (!mimeType) {
      mimeType = ContentAreaUtils.getMIMETypeForURI(aLauncher.source) || "";
    }

    Messaging.sendRequest({
      'type': 'Download:AndroidDownloadManager',
      'uri': aLauncher.source.spec,
      'mimeType': mimeType,
      'filename': aLauncher.suggestedFileName
    });
  },

  _getPrefName: function getPrefName(mimetype) {
    return "browser.download.preferred." + mimetype.replace("\\", ".");
  },

  _getMimeTypeFromLauncher: function (launcher) {
    let mime = launcher.MIMEInfo.MIMEType;
    if (!mime)
      mime = ContentAreaUtils.getMIMETypeForURI(launcher.source) || "";
    return mime;
  },

  _getPreferredApp: function getPreferredApp(launcher) {
    let mime = this._getMimeTypeFromLauncher(launcher);
    if (!mime)
      return;

    try {
      return Services.prefs.getCharPref(this._getPrefName(mime));
    } catch(ex) {
      Services.console.logStringMessage("Error getting pref for " + mime + ".");
    }
    return null;
  },

  _setPreferredApp: function setPreferredApp(launcher, app) {
    let mime = this._getMimeTypeFromLauncher(launcher);
    if (!mime)
      return;

    if (app)
      Services.prefs.setCharPref(this._getPrefName(mime), app.packageName);
    else
      Services.prefs.clearUserPref(this._getPrefName(mime));
  },

  promptForSaveToFileAsync: function (aLauncher, aContext, aDefaultFile,
                                      aSuggestedFileExt, aForcePrompt) {
    Task.spawn(function* () {
      let file = null;
      try {
        let hasPermission = yield RuntimePermissions.waitForPermissions(RuntimePermissions.WRITE_EXTERNAL_STORAGE);
        if (hasPermission) {
          // If we do have the STORAGE permission then pick the public downloads directory as destination
          // for this file. Without the permission saveDestinationAvailable(null) will be called which
          // will effectively cancel the download.
          let preferredDir = yield Downloads.getPreferredDownloadsDirectory();
          file = this.validateLeafName(new FileUtils.File(preferredDir),
                                       aDefaultFile, aSuggestedFileExt);
        }
      } finally {
        // The file argument will be null in case any exception occurred.
        aLauncher.saveDestinationAvailable(file);
      }
    }.bind(this)).catch(Cu.reportError);
  },

  validateLeafName: function hald_validateLeafName(aLocalFile, aLeafName, aFileExt) {
    if (!(aLocalFile && this.isUsableDirectory(aLocalFile)))
      return null;

    // Remove any leading periods, since we don't want to save hidden files
    // automatically.
    aLeafName = aLeafName.replace(/^\.+/, "");

    if (aLeafName == "")
      aLeafName = "unnamed" + (aFileExt ? "." + aFileExt : "");
    aLocalFile.append(aLeafName);

    this.makeFileUnique(aLocalFile);
    return aLocalFile;
  },

  makeFileUnique: function hald_makeFileUnique(aLocalFile) {
    try {
      // Note - this code is identical to that in
      //   toolkit/content/contentAreaUtils.js.
      // If you are updating this code, update that code too! We can't share code
      // here since this is called in a js component.
      let collisionCount = 0;
      while (aLocalFile.exists()) {
        collisionCount++;
        if (collisionCount == 1) {
          // Append "(2)" before the last dot in (or at the end of) the filename
          // special case .ext.gz etc files so we don't wind up with .tar(2).gz
          if (aLocalFile.leafName.match(/\.[^\.]{1,3}\.(gz|bz2|Z)$/i))
            aLocalFile.leafName = aLocalFile.leafName.replace(/\.[^\.]{1,3}\.(gz|bz2|Z)$/i, "(2)$&");
          else
            aLocalFile.leafName = aLocalFile.leafName.replace(/(\.[^\.]*)?$/, "(2)$&");
        }
        else {
          // replace the last (n) in the filename with (n+1)
          aLocalFile.leafName = aLocalFile.leafName.replace(/^(.*\()\d+\)/, "$1" + (collisionCount+1) + ")");
        }
      }
      aLocalFile.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
    }
    catch (e) {
      dump("*** exception in validateLeafName: " + e + "\n");

      if (e.result == Cr.NS_ERROR_FILE_ACCESS_DENIED)
        throw e;

      if (aLocalFile.leafName == "" || aLocalFile.isDirectory()) {
        aLocalFile.append("unnamed");
        if (aLocalFile.exists())
          aLocalFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
      }
    }
  },

  isUsableDirectory: function hald_isUsableDirectory(aDirectory) {
    return aDirectory.exists() && aDirectory.isDirectory() && aDirectory.isWritable();
  },
};

this.NSGetFactory = XPCOMUtils.generateNSGetFactory([HelperAppLauncherDialog]);