services/sync/modules/addonutils.js

Thu, 22 Jan 2015 13:21:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 22 Jan 2015 13:21:57 +0100
branch
TOR_BUG_9701
changeset 15
b8a032363ba2
permissions
-rw-r--r--

Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6

     1 /* This Source Code Form is subject to the terms of the Mozilla Public
     2  * License, v. 2.0. If a copy of the MPL was not distributed with this
     3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     5 "use strict";
     7 this.EXPORTED_SYMBOLS = ["AddonUtils"];
     9 const {interfaces: Ci, utils: Cu} = Components;
    11 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
    12 Cu.import("resource://gre/modules/Log.jsm");
    13 Cu.import("resource://services-sync/util.js");
    15 XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
    16   "resource://gre/modules/AddonManager.jsm");
    17 XPCOMUtils.defineLazyModuleGetter(this, "AddonRepository",
    18   "resource://gre/modules/addons/AddonRepository.jsm");
    20 function AddonUtilsInternal() {
    21   this._log = Log.repository.getLogger("Sync.AddonUtils");
    22   this._log.Level = Log.Level[Svc.Prefs.get("log.logger.addonutils")];
    23 }
    24 AddonUtilsInternal.prototype = {
    25   /**
    26    * Obtain an AddonInstall object from an AddonSearchResult instance.
    27    *
    28    * The callback will be invoked with the result of the operation. The
    29    * callback receives 2 arguments, error and result. Error will be falsy
    30    * on success or some kind of error value otherwise. The result argument
    31    * will be an AddonInstall on success or null on failure. It is possible
    32    * for the error to be falsy but result to be null. This could happen if
    33    * an install was not found.
    34    *
    35    * @param addon
    36    *        AddonSearchResult to obtain install from.
    37    * @param cb
    38    *        Function to be called with result of operation.
    39    */
    40   getInstallFromSearchResult:
    41     function getInstallFromSearchResult(addon, cb, requireSecureURI=true) {
    43     this._log.debug("Obtaining install for " + addon.id);
    45     // Verify that the source URI uses TLS. We don't allow installs from
    46     // insecure sources for security reasons. The Addon Manager ensures that
    47     // cert validation, etc is performed.
    48     if (requireSecureURI) {
    49       let scheme = addon.sourceURI.scheme;
    50       if (scheme != "https") {
    51         cb(new Error("Insecure source URI scheme: " + scheme), addon.install);
    52         return;
    53       }
    54     }
    56     // We should theoretically be able to obtain (and use) addon.install if
    57     // it is available. However, the addon.sourceURI rewriting won't be
    58     // reflected in the AddonInstall, so we can't use it. If we ever get rid
    59     // of sourceURI rewriting, we can avoid having to reconstruct the
    60     // AddonInstall.
    61     AddonManager.getInstallForURL(
    62       addon.sourceURI.spec,
    63       function handleInstall(install) {
    64         cb(null, install);
    65       },
    66       "application/x-xpinstall",
    67       undefined,
    68       addon.name,
    69       addon.iconURL,
    70       addon.version
    71     );
    72   },
    74   /**
    75    * Installs an add-on from an AddonSearchResult instance.
    76    *
    77    * The options argument defines extra options to control the install.
    78    * Recognized keys in this map are:
    79    *
    80    *   syncGUID - Sync GUID to use for the new add-on.
    81    *   enabled - Boolean indicating whether the add-on should be enabled upon
    82    *             install.
    83    *   requireSecureURI - Boolean indicating whether to require a secure
    84    *     URI to install from. This defaults to true.
    85    *
    86    * When complete it calls a callback with 2 arguments, error and result.
    87    *
    88    * If error is falsy, result is an object. If error is truthy, result is
    89    * null.
    90    *
    91    * The result object has the following keys:
    92    *
    93    *   id      ID of add-on that was installed.
    94    *   install AddonInstall that was installed.
    95    *   addon   Addon that was installed.
    96    *
    97    * @param addon
    98    *        AddonSearchResult to install add-on from.
    99    * @param options
   100    *        Object with additional metadata describing how to install add-on.
   101    * @param cb
   102    *        Function to be invoked with result of operation.
   103    */
   104   installAddonFromSearchResult:
   105     function installAddonFromSearchResult(addon, options, cb) {
   106     this._log.info("Trying to install add-on from search result: " + addon.id);
   108     if (options.requireSecureURI === undefined) {
   109       options.requireSecureURI = true;
   110     }
   112     this.getInstallFromSearchResult(addon, function onResult(error, install) {
   113       if (error) {
   114         cb(error, null);
   115         return;
   116       }
   118       if (!install) {
   119         cb(new Error("AddonInstall not available: " + addon.id), null);
   120         return;
   121       }
   123       try {
   124         this._log.info("Installing " + addon.id);
   125         let log = this._log;
   127         let listener = {
   128           onInstallStarted: function onInstallStarted(install) {
   129             if (!options) {
   130               return;
   131             }
   133             if (options.syncGUID) {
   134               log.info("Setting syncGUID of " + install.name  +": " +
   135                        options.syncGUID);
   136               install.addon.syncGUID = options.syncGUID;
   137             }
   139             // We only need to change userDisabled if it is disabled because
   140             // enabled is the default.
   141             if ("enabled" in options && !options.enabled) {
   142               log.info("Marking add-on as disabled for install: " +
   143                        install.name);
   144               install.addon.userDisabled = true;
   145             }
   146           },
   147           onInstallEnded: function(install, addon) {
   148             install.removeListener(listener);
   150             cb(null, {id: addon.id, install: install, addon: addon});
   151           },
   152           onInstallFailed: function(install) {
   153             install.removeListener(listener);
   155             cb(new Error("Install failed: " + install.error), null);
   156           },
   157           onDownloadFailed: function(install) {
   158             install.removeListener(listener);
   160             cb(new Error("Download failed: " + install.error), null);
   161           }
   162         };
   163         install.addListener(listener);
   164         install.install();
   165       }
   166       catch (ex) {
   167         this._log.error("Error installing add-on: " + Utils.exceptionstr(ex));
   168         cb(ex, null);
   169       }
   170     }.bind(this), options.requireSecureURI);
   171   },
   173   /**
   174    * Uninstalls the Addon instance and invoke a callback when it is done.
   175    *
   176    * @param addon
   177    *        Addon instance to uninstall.
   178    * @param cb
   179    *        Function to be invoked when uninstall has finished. It receives a
   180    *        truthy value signifying error and the add-on which was uninstalled.
   181    */
   182   uninstallAddon: function uninstallAddon(addon, cb) {
   183     let listener = {
   184       onUninstalling: function(uninstalling, needsRestart) {
   185         if (addon.id != uninstalling.id) {
   186           return;
   187         }
   189         // We assume restartless add-ons will send the onUninstalled event
   190         // soon.
   191         if (!needsRestart) {
   192           return;
   193         }
   195         // For non-restartless add-ons, we issue the callback on uninstalling
   196         // because we will likely never see the uninstalled event.
   197         AddonManager.removeAddonListener(listener);
   198         cb(null, addon);
   199       },
   200       onUninstalled: function(uninstalled) {
   201         if (addon.id != uninstalled.id) {
   202           return;
   203         }
   205         AddonManager.removeAddonListener(listener);
   206         cb(null, addon);
   207       }
   208     };
   209     AddonManager.addAddonListener(listener);
   210     addon.uninstall();
   211   },
   213   /**
   214    * Installs multiple add-ons specified by metadata.
   215    *
   216    * The first argument is an array of objects. Each object must have the
   217    * following keys:
   218    *
   219    *   id - public ID of the add-on to install.
   220    *   syncGUID - syncGUID for new add-on.
   221    *   enabled - boolean indicating whether the add-on should be enabled.
   222    *   requireSecureURI - Boolean indicating whether to require a secure
   223    *     URI when installing from a remote location. This defaults to
   224    *     true.
   225    *
   226    * The callback will be called when activity on all add-ons is complete. The
   227    * callback receives 2 arguments, error and result.
   228    *
   229    * If error is truthy, it contains a string describing the overall error.
   230    *
   231    * The 2nd argument to the callback is always an object with details on the
   232    * overall execution state. It contains the following keys:
   233    *
   234    *   installedIDs  Array of add-on IDs that were installed.
   235    *   installs      Array of AddonInstall instances that were installed.
   236    *   addons        Array of Addon instances that were installed.
   237    *   errors        Array of errors encountered. Only has elements if error is
   238    *                 truthy.
   239    *
   240    * @param installs
   241    *        Array of objects describing add-ons to install.
   242    * @param cb
   243    *        Function to be called when all actions are complete.
   244    */
   245   installAddons: function installAddons(installs, cb) {
   246     if (!cb) {
   247       throw new Error("Invalid argument: cb is not defined.");
   248     }
   250     let ids = [];
   251     for each (let addon in installs) {
   252       ids.push(addon.id);
   253     }
   255     AddonRepository.getAddonsByIDs(ids, {
   256       searchSucceeded: function searchSucceeded(addons, addonsLength, total) {
   257         this._log.info("Found " + addonsLength + "/" + ids.length +
   258                        " add-ons during repository search.");
   260         let ourResult = {
   261           installedIDs: [],
   262           installs:     [],
   263           addons:       [],
   264           errors:       []
   265         };
   267         if (!addonsLength) {
   268           cb(null, ourResult);
   269           return;
   270         }
   272         let expectedInstallCount = 0;
   273         let finishedCount = 0;
   274         let installCallback = function installCallback(error, result) {
   275           finishedCount++;
   277           if (error) {
   278             ourResult.errors.push(error);
   279           } else {
   280             ourResult.installedIDs.push(result.id);
   281             ourResult.installs.push(result.install);
   282             ourResult.addons.push(result.addon);
   283           }
   285           if (finishedCount >= expectedInstallCount) {
   286             if (ourResult.errors.length > 0) {
   287               cb(new Error("1 or more add-ons failed to install"), ourResult);
   288             } else {
   289               cb(null, ourResult);
   290             }
   291           }
   292         }.bind(this);
   294         let toInstall = [];
   296         // Rewrite the "src" query string parameter of the source URI to note
   297         // that the add-on was installed by Sync and not something else so
   298         // server-side metrics aren't skewed (bug 708134). The server should
   299         // ideally send proper URLs, but this solution was deemed too
   300         // complicated at the time the functionality was implemented.
   301         for each (let addon in addons) {
   302           // sourceURI presence isn't enforced by AddonRepository. So, we skip
   303           // add-ons without a sourceURI.
   304           if (!addon.sourceURI) {
   305             this._log.info("Skipping install of add-on because missing " +
   306                            "sourceURI: " + addon.id);
   307             continue;
   308           }
   310           toInstall.push(addon);
   312           // We should always be able to QI the nsIURI to nsIURL. If not, we
   313           // still try to install the add-on, but we don't rewrite the URL,
   314           // potentially skewing metrics.
   315           try {
   316             addon.sourceURI.QueryInterface(Ci.nsIURL);
   317           } catch (ex) {
   318             this._log.warn("Unable to QI sourceURI to nsIURL: " +
   319                            addon.sourceURI.spec);
   320             continue;
   321           }
   323           let params = addon.sourceURI.query.split("&").map(
   324             function rewrite(param) {
   326             if (param.indexOf("src=") == 0) {
   327               return "src=sync";
   328             } else {
   329               return param;
   330             }
   331           });
   333           addon.sourceURI.query = params.join("&");
   334         }
   336         expectedInstallCount = toInstall.length;
   338         if (!expectedInstallCount) {
   339           cb(null, ourResult);
   340           return;
   341         }
   343         // Start all the installs asynchronously. They will report back to us
   344         // as they finish, eventually triggering the global callback.
   345         for each (let addon in toInstall) {
   346           let options = {};
   347           for each (let install in installs) {
   348             if (install.id == addon.id) {
   349               options = install;
   350               break;
   351             }
   352           }
   354           this.installAddonFromSearchResult(addon, options, installCallback);
   355         }
   357       }.bind(this),
   359       searchFailed: function searchFailed() {
   360         cb(new Error("AddonRepository search failed"), null);
   361       },
   362     });
   363   },
   365   /**
   366    * Update the user disabled flag for an add-on.
   367    *
   368    * The supplied callback will ba called when the operation is
   369    * complete. If the new flag matches the existing or if the add-on
   370    * isn't currently active, the function will fire the callback
   371    * immediately. Else, the callback is invoked when the AddonManager
   372    * reports the change has taken effect or has been registered.
   373    *
   374    * The callback receives as arguments:
   375    *
   376    *   (Error) Encountered error during operation or null on success.
   377    *   (Addon) The add-on instance being operated on.
   378    *
   379    * @param addon
   380    *        (Addon) Add-on instance to operate on.
   381    * @param value
   382    *        (bool) New value for add-on's userDisabled property.
   383    * @param cb
   384    *        (function) Callback to be invoked on completion.
   385    */
   386   updateUserDisabled: function updateUserDisabled(addon, value, cb) {
   387     if (addon.userDisabled == value) {
   388       cb(null, addon);
   389       return;
   390     }
   392     let listener = {
   393       onEnabling: function onEnabling(wrapper, needsRestart) {
   394         this._log.debug("onEnabling: " + wrapper.id);
   395         if (wrapper.id != addon.id) {
   396           return;
   397         }
   399         // We ignore the restartless case because we'll get onEnabled shortly.
   400         if (!needsRestart) {
   401           return;
   402         }
   404         AddonManager.removeAddonListener(listener);
   405         cb(null, wrapper);
   406       }.bind(this),
   408       onEnabled: function onEnabled(wrapper) {
   409         this._log.debug("onEnabled: " + wrapper.id);
   410         if (wrapper.id != addon.id) {
   411           return;
   412         }
   414         AddonManager.removeAddonListener(listener);
   415         cb(null, wrapper);
   416       }.bind(this),
   418       onDisabling: function onDisabling(wrapper, needsRestart) {
   419         this._log.debug("onDisabling: " + wrapper.id);
   420         if (wrapper.id != addon.id) {
   421           return;
   422         }
   424         if (!needsRestart) {
   425           return;
   426         }
   428         AddonManager.removeAddonListener(listener);
   429         cb(null, wrapper);
   430       }.bind(this),
   432       onDisabled: function onDisabled(wrapper) {
   433         this._log.debug("onDisabled: " + wrapper.id);
   434         if (wrapper.id != addon.id) {
   435           return;
   436         }
   438         AddonManager.removeAddonListener(listener);
   439         cb(null, wrapper);
   440       }.bind(this),
   442       onOperationCancelled: function onOperationCancelled(wrapper) {
   443         this._log.debug("onOperationCancelled: " + wrapper.id);
   444         if (wrapper.id != addon.id) {
   445           return;
   446         }
   448         AddonManager.removeAddonListener(listener);
   449         cb(new Error("Operation cancelled"), wrapper);
   450       }.bind(this)
   451     };
   453     // The add-on listeners are only fired if the add-on is active. If not, the
   454     // change is silently updated and made active when/if the add-on is active.
   456     if (!addon.appDisabled) {
   457       AddonManager.addAddonListener(listener);
   458     }
   460     this._log.info("Updating userDisabled flag: " + addon.id + " -> " + value);
   461     addon.userDisabled = !!value;
   463     if (!addon.appDisabled) {
   464       cb(null, addon);
   465       return;
   466     }
   467     // Else the listener will handle invoking the callback.
   468   },
   470 };
   472 XPCOMUtils.defineLazyGetter(this, "AddonUtils", function() {
   473   return new AddonUtilsInternal();
   474 });

mercurial