summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorwolfbeast <mcwerewolf@wolfbeast.com>2019-02-13 19:25:03 +0100
committerwolfbeast <mcwerewolf@wolfbeast.com>2019-02-13 19:25:03 +0100
commit1e0da1994d03786571f4f97399595c5910f3a4c2 (patch)
treefe6c042a351c598863ca2f9c5e088d55e4162609
parent43d44975b1f49df640916cca5f6a0b138696da3c (diff)
downloadUXP-1e0da1994d03786571f4f97399595c5910f3a4c2.tar
UXP-1e0da1994d03786571f4f97399595c5910f3a4c2.tar.gz
UXP-1e0da1994d03786571f4f97399595c5910f3a4c2.tar.lz
UXP-1e0da1994d03786571f4f97399595c5910f3a4c2.tar.xz
UXP-1e0da1994d03786571f4f97399595c5910f3a4c2.zip
Remove the WebExtension Add-on Manager from our tree.
Tag #936
-rw-r--r--toolkit/mozapps/webextensions/AddonContentPolicy.cpp478
-rw-r--r--toolkit/mozapps/webextensions/AddonContentPolicy.h22
-rw-r--r--toolkit/mozapps/webextensions/AddonManager.jsm3666
-rw-r--r--toolkit/mozapps/webextensions/AddonManagerWebAPI.cpp171
-rw-r--r--toolkit/mozapps/webextensions/AddonManagerWebAPI.h33
-rw-r--r--toolkit/mozapps/webextensions/AddonPathService.cpp258
-rw-r--r--toolkit/mozapps/webextensions/AddonPathService.h55
-rw-r--r--toolkit/mozapps/webextensions/GMPInstallManager.jsm523
-rw-r--r--toolkit/mozapps/webextensions/LightweightThemeManager.jsm909
-rw-r--r--toolkit/mozapps/webextensions/addonManager.js296
-rw-r--r--toolkit/mozapps/webextensions/amInstallTrigger.js240
-rw-r--r--toolkit/mozapps/webextensions/amWebAPI.js269
-rw-r--r--toolkit/mozapps/webextensions/amWebInstallListener.js348
-rw-r--r--toolkit/mozapps/webextensions/content/about.js103
-rw-r--r--toolkit/mozapps/webextensions/content/eula.js25
-rw-r--r--toolkit/mozapps/webextensions/content/extensions.css270
-rw-r--r--toolkit/mozapps/webextensions/content/extensions.js3827
-rw-r--r--toolkit/mozapps/webextensions/content/extensions.xml2008
-rw-r--r--toolkit/mozapps/webextensions/content/extensions.xul715
-rw-r--r--toolkit/mozapps/webextensions/content/newaddon.xul67
-rw-r--r--toolkit/mozapps/webextensions/content/setting.xml486
-rw-r--r--toolkit/mozapps/webextensions/content/update.js663
-rw-r--r--toolkit/mozapps/webextensions/content/update.xul194
-rw-r--r--toolkit/mozapps/webextensions/extensions.manifest18
-rw-r--r--toolkit/mozapps/webextensions/internal/APIExtensionBootstrap.js39
-rw-r--r--toolkit/mozapps/webextensions/internal/AddonConstants.jsm31
-rw-r--r--toolkit/mozapps/webextensions/internal/AddonRepository.jsm1988
-rw-r--r--toolkit/mozapps/webextensions/internal/AddonRepository_SQLiteMigrator.jsm522
-rw-r--r--toolkit/mozapps/webextensions/internal/GMPProvider.jsm699
-rw-r--r--toolkit/mozapps/webextensions/internal/LightweightThemeImageOptimizer.jsm180
-rw-r--r--toolkit/mozapps/webextensions/internal/PluginProvider.jsm600
-rw-r--r--toolkit/mozapps/webextensions/internal/WebExtensionBootstrap.js39
-rw-r--r--toolkit/mozapps/webextensions/internal/XPIProvider.jsm9217
-rw-r--r--toolkit/mozapps/webextensions/internal/XPIProviderUtils.js2239
-rw-r--r--toolkit/mozapps/webextensions/internal/moz.build31
-rw-r--r--toolkit/mozapps/webextensions/jar.mn35
-rw-r--r--toolkit/mozapps/webextensions/moz.build57
37 files changed, 0 insertions, 31321 deletions
diff --git a/toolkit/mozapps/webextensions/AddonContentPolicy.cpp b/toolkit/mozapps/webextensions/AddonContentPolicy.cpp
deleted file mode 100644
index 90e53b2ea..000000000
--- a/toolkit/mozapps/webextensions/AddonContentPolicy.cpp
+++ /dev/null
@@ -1,478 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#include "AddonContentPolicy.h"
-
-#include "mozilla/dom/nsCSPUtils.h"
-#include "nsCOMPtr.h"
-#include "nsContentPolicyUtils.h"
-#include "nsContentTypeParser.h"
-#include "nsContentUtils.h"
-#include "nsIConsoleService.h"
-#include "nsIContentSecurityPolicy.h"
-#include "nsIContent.h"
-#include "nsIDocument.h"
-#include "nsIEffectiveTLDService.h"
-#include "nsIScriptError.h"
-#include "nsIStringBundle.h"
-#include "nsIUUIDGenerator.h"
-#include "nsIURI.h"
-#include "nsNetCID.h"
-#include "nsNetUtil.h"
-
-using namespace mozilla;
-
-/* Enforces content policies for WebExtension scopes. Currently:
- *
- * - Prevents loading scripts with a non-default JavaScript version.
- * - Checks custom content security policies for sufficiently stringent
- * script-src and object-src directives.
- */
-
-#define VERSIONED_JS_BLOCKED_MESSAGE \
- u"Versioned JavaScript is a non-standard, deprecated extension, and is " \
- u"not supported in WebExtension code. For alternatives, please see: " \
- u"https://developer.mozilla.org/Add-ons/WebExtensions/Tips"
-
-AddonContentPolicy::AddonContentPolicy()
-{
-}
-
-AddonContentPolicy::~AddonContentPolicy()
-{
-}
-
-NS_IMPL_ISUPPORTS(AddonContentPolicy, nsIContentPolicy, nsIAddonContentPolicy)
-
-static nsresult
-GetWindowIDFromContext(nsISupports* aContext, uint64_t *aResult)
-{
- NS_ENSURE_TRUE(aContext, NS_ERROR_FAILURE);
-
- nsCOMPtr<nsIContent> content = do_QueryInterface(aContext);
- NS_ENSURE_TRUE(content, NS_ERROR_FAILURE);
-
- nsCOMPtr<nsIDocument> document = content->OwnerDoc();
- NS_ENSURE_TRUE(document, NS_ERROR_FAILURE);
-
- nsCOMPtr<nsPIDOMWindowInner> window = document->GetInnerWindow();
- NS_ENSURE_TRUE(window, NS_ERROR_FAILURE);
-
- *aResult = window->WindowID();
- return NS_OK;
-}
-
-static nsresult
-LogMessage(const nsAString &aMessage, nsIURI* aSourceURI, const nsAString &aSourceSample,
- nsISupports* aContext)
-{
- nsCOMPtr<nsIScriptError> error = do_CreateInstance(NS_SCRIPTERROR_CONTRACTID);
- NS_ENSURE_TRUE(error, NS_ERROR_OUT_OF_MEMORY);
-
- nsCString sourceName = aSourceURI->GetSpecOrDefault();
-
- uint64_t windowID = 0;
- GetWindowIDFromContext(aContext, &windowID);
-
- nsresult rv =
- error->InitWithWindowID(aMessage, NS_ConvertUTF8toUTF16(sourceName),
- aSourceSample, 0, 0, nsIScriptError::errorFlag,
- "JavaScript", windowID);
- NS_ENSURE_SUCCESS(rv, rv);
-
- nsCOMPtr<nsIConsoleService> console = do_GetService(NS_CONSOLESERVICE_CONTRACTID);
- NS_ENSURE_TRUE(console, NS_ERROR_OUT_OF_MEMORY);
-
- console->LogMessage(error);
- return NS_OK;
-}
-
-
-// Content policy enforcement:
-
-NS_IMETHODIMP
-AddonContentPolicy::ShouldLoad(uint32_t aContentType,
- nsIURI* aContentLocation,
- nsIURI* aRequestOrigin,
- nsISupports* aContext,
- const nsACString& aMimeTypeGuess,
- nsISupports* aExtra,
- nsIPrincipal* aRequestPrincipal,
- int16_t* aShouldLoad)
-{
- MOZ_ASSERT(aContentType == nsContentUtils::InternalContentPolicyTypeToExternal(aContentType),
- "We should only see external content policy types here.");
-
- *aShouldLoad = nsIContentPolicy::ACCEPT;
-
- if (!aRequestOrigin) {
- return NS_OK;
- }
-
- // Only apply this policy to requests from documents loaded from
- // moz-extension URLs, or to resources being loaded from moz-extension URLs.
- bool equals;
- if (!((NS_SUCCEEDED(aContentLocation->SchemeIs("moz-extension", &equals)) && equals) ||
- (NS_SUCCEEDED(aRequestOrigin->SchemeIs("moz-extension", &equals)) && equals))) {
- return NS_OK;
- }
-
- if (aContentType == nsIContentPolicy::TYPE_SCRIPT) {
- NS_ConvertUTF8toUTF16 typeString(aMimeTypeGuess);
- nsContentTypeParser mimeParser(typeString);
-
- // Reject attempts to load JavaScript scripts with a non-default version.
- nsAutoString mimeType, version;
- if (NS_SUCCEEDED(mimeParser.GetType(mimeType)) &&
- nsContentUtils::IsJavascriptMIMEType(mimeType) &&
- NS_SUCCEEDED(mimeParser.GetParameter("version", version))) {
- *aShouldLoad = nsIContentPolicy::REJECT_REQUEST;
-
- LogMessage(NS_MULTILINE_LITERAL_STRING(VERSIONED_JS_BLOCKED_MESSAGE),
- aRequestOrigin, typeString, aContext);
- return NS_OK;
- }
- }
-
- return NS_OK;
-}
-
-NS_IMETHODIMP
-AddonContentPolicy::ShouldProcess(uint32_t aContentType,
- nsIURI* aContentLocation,
- nsIURI* aRequestOrigin,
- nsISupports* aRequestingContext,
- const nsACString& aMimeTypeGuess,
- nsISupports* aExtra,
- nsIPrincipal* aRequestPrincipal,
- int16_t* aShouldProcess)
-{
- MOZ_ASSERT(aContentType == nsContentUtils::InternalContentPolicyTypeToExternal(aContentType),
- "We should only see external content policy types here.");
-
- *aShouldProcess = nsIContentPolicy::ACCEPT;
- return NS_OK;
-}
-
-
-// CSP Validation:
-
-static const char* allowedSchemes[] = {
- "blob",
- "filesystem",
- nullptr
-};
-
-static const char* allowedHostSchemes[] = {
- "https",
- "moz-extension",
- nullptr
-};
-
-/**
- * Validates a CSP directive to ensure that it is sufficiently stringent.
- * In particular, ensures that:
- *
- * - No remote sources are allowed other than from https: schemes
- *
- * - No remote sources specify host wildcards for generic domains
- * (*.blogspot.com, *.com, *)
- *
- * - All remote sources and local extension sources specify a host
- *
- * - No scheme sources are allowed other than blob:, filesystem:,
- * moz-extension:, and https:
- *
- * - No keyword sources are allowed other than 'none', 'self', 'unsafe-eval',
- * and hash sources.
- */
-class CSPValidator final : public nsCSPSrcVisitor {
- public:
- CSPValidator(nsAString& aURL, CSPDirective aDirective, bool aDirectiveRequired = true) :
- mURL(aURL),
- mDirective(CSP_CSPDirectiveToString(aDirective)),
- mFoundSelf(false)
- {
- // Start with the default error message for a missing directive, since no
- // visitors will be called if the directive isn't present.
- if (aDirectiveRequired) {
- FormatError("csp.error.missing-directive");
- }
- }
-
- // Visitors
-
- bool visitSchemeSrc(const nsCSPSchemeSrc& src) override
- {
- nsAutoString scheme;
- src.getScheme(scheme);
-
- if (SchemeInList(scheme, allowedHostSchemes)) {
- FormatError("csp.error.missing-host", scheme);
- return false;
- }
- if (!SchemeInList(scheme, allowedSchemes)) {
- FormatError("csp.error.illegal-protocol", scheme);
- return false;
- }
- return true;
- };
-
- bool visitHostSrc(const nsCSPHostSrc& src) override
- {
- nsAutoString scheme, host;
-
- src.getScheme(scheme);
- src.getHost(host);
-
- if (scheme.LowerCaseEqualsLiteral("https")) {
- if (!HostIsAllowed(host)) {
- FormatError("csp.error.illegal-host-wildcard", scheme);
- return false;
- }
- } else if (scheme.LowerCaseEqualsLiteral("moz-extension")) {
- // The CSP parser silently converts 'self' keywords to the origin
- // URL, so we need to reconstruct the URL to see if it was present.
- if (!mFoundSelf) {
- nsAutoString url(u"moz-extension://");
- url.Append(host);
-
- mFoundSelf = url.Equals(mURL);
- }
-
- if (host.IsEmpty() || host.EqualsLiteral("*")) {
- FormatError("csp.error.missing-host", scheme);
- return false;
- }
- } else if (!SchemeInList(scheme, allowedSchemes)) {
- FormatError("csp.error.illegal-protocol", scheme);
- return false;
- }
-
- return true;
- };
-
- bool visitKeywordSrc(const nsCSPKeywordSrc& src) override
- {
- switch (src.getKeyword()) {
- case CSP_NONE:
- case CSP_SELF:
- case CSP_UNSAFE_EVAL:
- return true;
-
- default:
- NS_ConvertASCIItoUTF16 keyword(CSP_EnumToKeyword(src.getKeyword()));
-
- FormatError("csp.error.illegal-keyword", keyword);
- return false;
- }
- };
-
- bool visitNonceSrc(const nsCSPNonceSrc& src) override
- {
- FormatError("csp.error.illegal-keyword", NS_LITERAL_STRING("'nonce-*'"));
- return false;
- };
-
- bool visitHashSrc(const nsCSPHashSrc& src) override
- {
- return true;
- };
-
- // Accessors
-
- inline nsAString& GetError()
- {
- return mError;
- };
-
- inline bool FoundSelf()
- {
- return mFoundSelf;
- };
-
-
- // Formatters
-
- template <typename... T>
- inline void FormatError(const char* aName, const T ...aParams)
- {
- const char16_t* params[] = { mDirective.get(), aParams.get()... };
- FormatErrorParams(aName, params, MOZ_ARRAY_LENGTH(params));
- };
-
- private:
- // Validators
-
- bool HostIsAllowed(nsAString& host)
- {
- if (host.First() == '*') {
- if (host.EqualsLiteral("*") || host[1] != '.') {
- return false;
- }
-
- host.Cut(0, 2);
-
- nsCOMPtr<nsIEffectiveTLDService> tldService =
- do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
-
- if (!tldService) {
- return false;
- }
-
- NS_ConvertUTF16toUTF8 cHost(host);
- nsAutoCString publicSuffix;
-
- nsresult rv = tldService->GetPublicSuffixFromHost(cHost, publicSuffix);
-
- return NS_SUCCEEDED(rv) && !cHost.Equals(publicSuffix);
- }
-
- return true;
- };
-
- bool SchemeInList(nsAString& scheme, const char** schemes)
- {
- for (; *schemes; schemes++) {
- if (scheme.LowerCaseEqualsASCII(*schemes)) {
- return true;
- }
- }
- return false;
- };
-
-
- // Formatters
-
- already_AddRefed<nsIStringBundle>
- GetStringBundle()
- {
- nsCOMPtr<nsIStringBundleService> sbs =
- mozilla::services::GetStringBundleService();
- NS_ENSURE_TRUE(sbs, nullptr);
-
- nsCOMPtr<nsIStringBundle> stringBundle;
- sbs->CreateBundle("chrome://global/locale/extensions.properties",
- getter_AddRefs(stringBundle));
-
- return stringBundle.forget();
- };
-
- void FormatErrorParams(const char* aName, const char16_t** aParams, int32_t aLength)
- {
- nsresult rv = NS_ERROR_FAILURE;
-
- nsCOMPtr<nsIStringBundle> stringBundle = GetStringBundle();
-
- if (stringBundle) {
- NS_ConvertASCIItoUTF16 name(aName);
-
- rv = stringBundle->FormatStringFromName(name.get(), aParams, aLength,
- getter_Copies(mError));
- }
-
- if (NS_WARN_IF(NS_FAILED(rv))) {
- mError.AssignLiteral("An unexpected error occurred");
- }
- };
-
-
- // Data members
-
- nsAutoString mURL;
- NS_ConvertASCIItoUTF16 mDirective;
- nsXPIDLString mError;
-
- bool mFoundSelf;
-};
-
-/**
- * Validates a custom content security policy string for use by an add-on.
- * In particular, ensures that:
- *
- * - Both object-src and script-src directives are present, and meet
- * the policies required by the CSPValidator class
- *
- * - The script-src directive includes the source 'self'
- */
-NS_IMETHODIMP
-AddonContentPolicy::ValidateAddonCSP(const nsAString& aPolicyString,
- nsAString& aResult)
-{
- nsresult rv;
-
- // Validate against a randomly-generated extension origin.
- // There is no add-on-specific behavior in the CSP code, beyond the ability
- // for add-ons to specify a custom policy, but the parser requires a valid
- // origin in order to operate correctly.
- nsAutoString url(u"moz-extension://");
- {
- nsCOMPtr<nsIUUIDGenerator> uuidgen = services::GetUUIDGenerator();
- NS_ENSURE_TRUE(uuidgen, NS_ERROR_FAILURE);
-
- nsID id;
- rv = uuidgen->GenerateUUIDInPlace(&id);
- NS_ENSURE_SUCCESS(rv, rv);
-
- char idString[NSID_LENGTH];
- id.ToProvidedString(idString);
-
- MOZ_RELEASE_ASSERT(idString[0] == '{' && idString[NSID_LENGTH - 2] == '}',
- "UUID generator did not return a valid UUID");
-
- url.AppendASCII(idString + 1, NSID_LENGTH - 3);
- }
-
-
- RefPtr<BasePrincipal> principal =
- BasePrincipal::CreateCodebasePrincipal(NS_ConvertUTF16toUTF8(url));
-
- nsCOMPtr<nsIContentSecurityPolicy> csp;
- rv = principal->EnsureCSP(nullptr, getter_AddRefs(csp));
- NS_ENSURE_SUCCESS(rv, rv);
-
-
- csp->AppendPolicy(aPolicyString, false, false);
-
- const nsCSPPolicy* policy = csp->GetPolicy(0);
- if (!policy) {
- CSPValidator validator(url, nsIContentSecurityPolicy::SCRIPT_SRC_DIRECTIVE);
- aResult.Assign(validator.GetError());
- return NS_OK;
- }
-
- bool haveValidDefaultSrc = false;
- {
- CSPDirective directive = nsIContentSecurityPolicy::DEFAULT_SRC_DIRECTIVE;
- CSPValidator validator(url, directive);
-
- haveValidDefaultSrc = policy->visitDirectiveSrcs(directive, &validator);
- }
-
- aResult.SetIsVoid(true);
- {
- CSPDirective directive = nsIContentSecurityPolicy::SCRIPT_SRC_DIRECTIVE;
- CSPValidator validator(url, directive, !haveValidDefaultSrc);
-
- if (!policy->visitDirectiveSrcs(directive, &validator)) {
- aResult.Assign(validator.GetError());
- } else if (!validator.FoundSelf()) {
- validator.FormatError("csp.error.missing-source", NS_LITERAL_STRING("'self'"));
- aResult.Assign(validator.GetError());
- }
- }
-
- if (aResult.IsVoid()) {
- CSPDirective directive = nsIContentSecurityPolicy::OBJECT_SRC_DIRECTIVE;
- CSPValidator validator(url, directive, !haveValidDefaultSrc);
-
- if (!policy->visitDirectiveSrcs(directive, &validator)) {
- aResult.Assign(validator.GetError());
- }
- }
-
- return NS_OK;
-}
diff --git a/toolkit/mozapps/webextensions/AddonContentPolicy.h b/toolkit/mozapps/webextensions/AddonContentPolicy.h
deleted file mode 100644
index 4c8af4828..000000000
--- a/toolkit/mozapps/webextensions/AddonContentPolicy.h
+++ /dev/null
@@ -1,22 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#include "nsIContentPolicy.h"
-#include "nsIAddonPolicyService.h"
-
-class AddonContentPolicy : public nsIContentPolicy,
- public nsIAddonContentPolicy
-{
-protected:
- virtual ~AddonContentPolicy();
-
-public:
- AddonContentPolicy();
-
- NS_DECL_ISUPPORTS
- NS_DECL_NSICONTENTPOLICY
- NS_DECL_NSIADDONCONTENTPOLICY
-};
diff --git a/toolkit/mozapps/webextensions/AddonManager.jsm b/toolkit/mozapps/webextensions/AddonManager.jsm
deleted file mode 100644
index a3bcbb504..000000000
--- a/toolkit/mozapps/webextensions/AddonManager.jsm
+++ /dev/null
@@ -1,3666 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cr = Components.results;
-const Cu = Components.utils;
-
-// Cannot use Services.appinfo here, or else xpcshell-tests will blow up, as
-// most tests later register different nsIAppInfo implementations, which
-// wouldn't be reflected in Services.appinfo anymore, as the lazy getter
-// underlying it would have been initialized if we used it here.
-if ("@mozilla.org/xre/app-info;1" in Cc) {
- let runtime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
- if (runtime.processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) {
- // Refuse to run in child processes.
- throw new Error("You cannot use the AddonManager in child processes!");
- }
-}
-
-Cu.import("resource://gre/modules/AppConstants.jsm");
-
-const MOZ_COMPATIBILITY_NIGHTLY = !['aurora', 'beta', 'release', 'esr'].includes(AppConstants.MOZ_UPDATE_CHANNEL);
-
-const PREF_BLOCKLIST_PINGCOUNTVERSION = "extensions.blocklist.pingCountVersion";
-const PREF_DEFAULT_PROVIDERS_ENABLED = "extensions.defaultProviders.enabled";
-const PREF_EM_UPDATE_ENABLED = "extensions.update.enabled";
-const PREF_EM_LAST_APP_VERSION = "extensions.lastAppVersion";
-const PREF_EM_LAST_PLATFORM_VERSION = "extensions.lastPlatformVersion";
-const PREF_EM_AUTOUPDATE_DEFAULT = "extensions.update.autoUpdateDefault";
-const PREF_EM_STRICT_COMPATIBILITY = "extensions.strictCompatibility";
-const PREF_EM_CHECK_UPDATE_SECURITY = "extensions.checkUpdateSecurity";
-const PREF_EM_UPDATE_BACKGROUND_URL = "extensions.update.background.url";
-const PREF_APP_UPDATE_ENABLED = "app.update.enabled";
-const PREF_APP_UPDATE_AUTO = "app.update.auto";
-const PREF_EM_HOTFIX_ID = "extensions.hotfix.id";
-const PREF_EM_HOTFIX_LASTVERSION = "extensions.hotfix.lastVersion";
-const PREF_EM_HOTFIX_URL = "extensions.hotfix.url";
-const PREF_EM_CERT_CHECKATTRIBUTES = "extensions.hotfix.cert.checkAttributes";
-const PREF_EM_HOTFIX_CERTS = "extensions.hotfix.certs.";
-const PREF_MATCH_OS_LOCALE = "intl.locale.matchOS";
-const PREF_SELECTED_LOCALE = "general.useragent.locale";
-const UNKNOWN_XPCOM_ABI = "unknownABI";
-
-const PREF_MIN_WEBEXT_PLATFORM_VERSION = "extensions.webExtensionsMinPlatformVersion";
-const PREF_WEBAPI_TESTING = "extensions.webapi.testing";
-
-const UPDATE_REQUEST_VERSION = 2;
-const CATEGORY_UPDATE_PARAMS = "extension-update-params";
-
-const XMLURI_BLOCKLIST = "http://www.mozilla.org/2006/addons-blocklist";
-
-const KEY_PROFILEDIR = "ProfD";
-const KEY_APPDIR = "XCurProcD";
-const FILE_BLOCKLIST = "blocklist.xml";
-
-const BRANCH_REGEXP = /^([^\.]+\.[0-9]+[a-z]*).*/gi;
-const PREF_EM_CHECK_COMPATIBILITY = "extensions.enableCompatibilityChecking";
-
-const TOOLKIT_ID = "toolkit@mozilla.org";
-
-const VALID_TYPES_REGEXP = /^[\w\-]+$/;
-
-const WEBAPI_INSTALL_HOSTS = ["addons.mozilla.org", "testpilot.firefox.com"];
-const WEBAPI_TEST_INSTALL_HOSTS = [
- "addons.allizom.org", "addons-dev.allizom.org",
- "testpilot.stage.mozaws.net", "testpilot.dev.mozaws.net",
- "example.com",
-];
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/AsyncShutdown.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "AddonRepository",
- "resource://gre/modules/addons/AddonRepository.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Extension",
- "resource://gre/modules/Extension.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "CertUtils", function() {
- let certUtils = {};
- Components.utils.import("resource://gre/modules/CertUtils.jsm", certUtils);
- return certUtils;
-});
-
-const INTEGER = /^[1-9]\d*$/;
-
-this.EXPORTED_SYMBOLS = [ "AddonManager", "AddonManagerPrivate" ];
-
-const CATEGORY_PROVIDER_MODULE = "addon-provider-module";
-
-// A list of providers to load by default
-const DEFAULT_PROVIDERS = [
- "resource://gre/modules/addons/XPIProvider.jsm",
- "resource://gre/modules/LightweightThemeManager.jsm"
-];
-
-Cu.import("resource://gre/modules/Log.jsm");
-// Configure a logger at the parent 'addons' level to format
-// messages for all the modules under addons.*
-const PARENT_LOGGER_ID = "addons";
-var parentLogger = Log.repository.getLogger(PARENT_LOGGER_ID);
-parentLogger.level = Log.Level.Warn;
-var formatter = new Log.BasicFormatter();
-// Set parent logger (and its children) to append to
-// the Javascript section of the Browser Console
-parentLogger.addAppender(new Log.ConsoleAppender(formatter));
-// Set parent logger (and its children) to
-// also append to standard out
-parentLogger.addAppender(new Log.DumpAppender(formatter));
-
-// Create a new logger (child of 'addons' logger)
-// for use by the Addons Manager
-const LOGGER_ID = "addons.manager";
-var logger = Log.repository.getLogger(LOGGER_ID);
-
-// Provide the ability to enable/disable logging
-// messages at runtime.
-// If the "extensions.logging.enabled" preference is
-// missing or 'false', messages at the WARNING and higher
-// severity should be logged to the JS console and standard error.
-// If "extensions.logging.enabled" is set to 'true', messages
-// at DEBUG and higher should go to JS console and standard error.
-const PREF_LOGGING_ENABLED = "extensions.logging.enabled";
-const NS_PREFBRANCH_PREFCHANGE_TOPIC_ID = "nsPref:changed";
-
-const UNNAMED_PROVIDER = "<unnamed-provider>";
-function providerName(aProvider) {
- return aProvider.name || UNNAMED_PROVIDER;
-}
-
-/**
- * Preference listener which listens for a change in the
- * "extensions.logging.enabled" preference and changes the logging level of the
- * parent 'addons' level logger accordingly.
- */
-var PrefObserver = {
- init: function() {
- Services.prefs.addObserver(PREF_LOGGING_ENABLED, this, false);
- Services.obs.addObserver(this, "xpcom-shutdown", false);
- this.observe(null, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID, PREF_LOGGING_ENABLED);
- },
-
- observe: function(aSubject, aTopic, aData) {
- if (aTopic == "xpcom-shutdown") {
- Services.prefs.removeObserver(PREF_LOGGING_ENABLED, this);
- Services.obs.removeObserver(this, "xpcom-shutdown");
- }
- else if (aTopic == NS_PREFBRANCH_PREFCHANGE_TOPIC_ID) {
- let debugLogEnabled = false;
- try {
- debugLogEnabled = Services.prefs.getBoolPref(PREF_LOGGING_ENABLED);
- }
- catch (e) {
- }
- if (debugLogEnabled) {
- parentLogger.level = Log.Level.Debug;
- }
- else {
- parentLogger.level = Log.Level.Warn;
- }
- }
- }
-};
-
-PrefObserver.init();
-
-/**
- * Calls a callback method consuming any thrown exception. Any parameters after
- * the callback parameter will be passed to the callback.
- *
- * @param aCallback
- * The callback method to call
- */
-function safeCall(aCallback, ...aArgs) {
- try {
- aCallback.apply(null, aArgs);
- }
- catch (e) {
- logger.warn("Exception calling callback", e);
- }
-}
-
-/**
- * Creates a function that will call the passed callback catching and logging
- * any exceptions.
- *
- * @param aCallback
- * The callback method to call
- */
-function makeSafe(aCallback) {
- return function(...aArgs) {
- safeCall(aCallback, ...aArgs);
- }
-}
-
-/**
- * Report an exception thrown by a provider API method.
- */
-function reportProviderError(aProvider, aMethod, aError) {
- let method = `provider ${providerName(aProvider)}.${aMethod}`;
- AddonManagerPrivate.recordException("AMI", method, aError);
- logger.error("Exception calling " + method, aError);
-}
-
-/**
- * Calls a method on a provider if it exists and consumes any thrown exception.
- * Any parameters after the aDefault parameter are passed to the provider's method.
- *
- * @param aProvider
- * The provider to call
- * @param aMethod
- * The method name to call
- * @param aDefault
- * A default return value if the provider does not implement the named
- * method or throws an error.
- * @return the return value from the provider, or aDefault if the provider does not
- * implement method or throws an error
- */
-function callProvider(aProvider, aMethod, aDefault, ...aArgs) {
- if (!(aMethod in aProvider))
- return aDefault;
-
- try {
- return aProvider[aMethod].apply(aProvider, aArgs);
- }
- catch (e) {
- reportProviderError(aProvider, aMethod, e);
- return aDefault;
- }
-}
-
-/**
- * Calls a method on a provider if it exists and consumes any thrown exception.
- * Parameters after aMethod are passed to aProvider.aMethod().
- * The last parameter must be a callback function.
- * If the provider does not implement the method, or the method throws, calls
- * the callback with 'undefined'.
- *
- * @param aProvider
- * The provider to call
- * @param aMethod
- * The method name to call
- */
-function callProviderAsync(aProvider, aMethod, ...aArgs) {
- let callback = aArgs[aArgs.length - 1];
- if (!(aMethod in aProvider)) {
- callback(undefined);
- return undefined;
- }
- try {
- return aProvider[aMethod].apply(aProvider, aArgs);
- }
- catch (e) {
- reportProviderError(aProvider, aMethod, e);
- callback(undefined);
- return undefined;
- }
-}
-
-/**
- * Calls a method on a provider if it exists and consumes any thrown exception.
- * Parameters after aMethod are passed to aProvider.aMethod() and an additional
- * callback is added for the provider to return a result to.
- *
- * @param aProvider
- * The provider to call
- * @param aMethod
- * The method name to call
- * @return {Promise}
- * @resolves The result the provider returns, or |undefined| if the provider
- * does not implement the method or the method throws.
- * @rejects Never
- */
-function promiseCallProvider(aProvider, aMethod, ...aArgs) {
- return new Promise(resolve => {
- callProviderAsync(aProvider, aMethod, ...aArgs, resolve);
- });
-}
-
-/**
- * Gets the currently selected locale for display.
- * @return the selected locale or "en-US" if none is selected
- */
-function getLocale() {
- try {
- if (Services.prefs.getBoolPref(PREF_MATCH_OS_LOCALE))
- return Services.locale.getLocaleComponentForUserAgent();
- }
- catch (e) { }
-
- try {
- let locale = Services.prefs.getComplexValue(PREF_SELECTED_LOCALE,
- Ci.nsIPrefLocalizedString);
- if (locale)
- return locale;
- }
- catch (e) { }
-
- try {
- return Services.prefs.getCharPref(PREF_SELECTED_LOCALE);
- }
- catch (e) { }
-
- return "en-US";
-}
-
-function webAPIForAddon(addon) {
- if (!addon) {
- return null;
- }
-
- let result = {};
-
- // By default just pass through any plain property, the webidl will
- // control access. Also filter out private properties, regular Addon
- // objects are okay but MockAddon used in tests has non-serializable
- // private properties.
- for (let prop in addon) {
- if (prop[0] != "_" && typeof(addon[prop]) != "function") {
- result[prop] = addon[prop];
- }
- }
-
- // A few properties are computed for a nicer API
- result.isEnabled = !addon.userDisabled;
- result.canUninstall = Boolean(addon.permissions & AddonManager.PERM_CAN_UNINSTALL);
-
- return result;
-}
-
-/**
- * A helper class to repeatedly call a listener with each object in an array
- * optionally checking whether the object has a method in it.
- *
- * @param aObjects
- * The array of objects to iterate through
- * @param aMethod
- * An optional method name, if not null any objects without this method
- * will not be passed to the listener
- * @param aListener
- * A listener implementing nextObject and noMoreObjects methods. The
- * former will be called with the AsyncObjectCaller as the first
- * parameter and the object as the second. noMoreObjects will be passed
- * just the AsyncObjectCaller
- */
-function AsyncObjectCaller(aObjects, aMethod, aListener) {
- this.objects = [...aObjects];
- this.method = aMethod;
- this.listener = aListener;
-
- this.callNext();
-}
-
-AsyncObjectCaller.prototype = {
- objects: null,
- method: null,
- listener: null,
-
- /**
- * Passes the next object to the listener or calls noMoreObjects if there
- * are none left.
- */
- callNext: function() {
- if (this.objects.length == 0) {
- this.listener.noMoreObjects(this);
- return;
- }
-
- let object = this.objects.shift();
- if (!this.method || this.method in object)
- this.listener.nextObject(this, object);
- else
- this.callNext();
- }
-};
-
-/**
- * Listens for a browser changing origin and cancels the installs that were
- * started by it.
- */
-function BrowserListener(aBrowser, aInstallingPrincipal, aInstalls) {
- this.browser = aBrowser;
- this.principal = aInstallingPrincipal;
- this.installs = aInstalls;
- this.installCount = aInstalls.length;
-
- aBrowser.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION);
- Services.obs.addObserver(this, "message-manager-close", true);
-
- for (let install of this.installs)
- install.addListener(this);
-
- this.registered = true;
-}
-
-BrowserListener.prototype = {
- browser: null,
- installs: null,
- installCount: null,
- registered: false,
-
- unregister: function() {
- if (!this.registered)
- return;
- this.registered = false;
-
- Services.obs.removeObserver(this, "message-manager-close");
- // The browser may have already been detached
- if (this.browser.removeProgressListener)
- this.browser.removeProgressListener(this);
-
- for (let install of this.installs)
- install.removeListener(this);
- this.installs = null;
- },
-
- cancelInstalls: function() {
- for (let install of this.installs) {
- try {
- install.cancel();
- }
- catch (e) {
- // Some installs may have already failed or been cancelled, ignore these
- }
- }
- },
-
- observe: function(subject, topic, data) {
- if (subject != this.browser.messageManager)
- return;
-
- // The browser's message manager has closed and so the browser is
- // going away, cancel all installs
- this.cancelInstalls();
- },
-
- onLocationChange: function(webProgress, request, location) {
- if (this.browser.contentPrincipal && this.principal.subsumes(this.browser.contentPrincipal))
- return;
-
- // The browser has navigated to a new origin so cancel all installs
- this.cancelInstalls();
- },
-
- onDownloadCancelled: function(install) {
- // Don't need to hear more events from this install
- install.removeListener(this);
-
- // Once all installs have ended unregister everything
- if (--this.installCount == 0)
- this.unregister();
- },
-
- onDownloadFailed: function(install) {
- this.onDownloadCancelled(install);
- },
-
- onInstallFailed: function(install) {
- this.onDownloadCancelled(install);
- },
-
- onInstallEnded: function(install) {
- this.onDownloadCancelled(install);
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupportsWeakReference,
- Ci.nsIWebProgressListener,
- Ci.nsIObserver])
-};
-
-/**
- * This represents an author of an add-on (e.g. creator or developer)
- *
- * @param aName
- * The name of the author
- * @param aURL
- * The URL of the author's profile page
- */
-function AddonAuthor(aName, aURL) {
- this.name = aName;
- this.url = aURL;
-}
-
-AddonAuthor.prototype = {
- name: null,
- url: null,
-
- // Returns the author's name, defaulting to the empty string
- toString: function() {
- return this.name || "";
- }
-}
-
-/**
- * This represents an screenshot for an add-on
- *
- * @param aURL
- * The URL to the full version of the screenshot
- * @param aWidth
- * The width in pixels of the screenshot
- * @param aHeight
- * The height in pixels of the screenshot
- * @param aThumbnailURL
- * The URL to the thumbnail version of the screenshot
- * @param aThumbnailWidth
- * The width in pixels of the thumbnail version of the screenshot
- * @param aThumbnailHeight
- * The height in pixels of the thumbnail version of the screenshot
- * @param aCaption
- * The caption of the screenshot
- */
-function AddonScreenshot(aURL, aWidth, aHeight, aThumbnailURL,
- aThumbnailWidth, aThumbnailHeight, aCaption) {
- this.url = aURL;
- if (aWidth) this.width = aWidth;
- if (aHeight) this.height = aHeight;
- if (aThumbnailURL) this.thumbnailURL = aThumbnailURL;
- if (aThumbnailWidth) this.thumbnailWidth = aThumbnailWidth;
- if (aThumbnailHeight) this.thumbnailHeight = aThumbnailHeight;
- if (aCaption) this.caption = aCaption;
-}
-
-AddonScreenshot.prototype = {
- url: null,
- width: null,
- height: null,
- thumbnailURL: null,
- thumbnailWidth: null,
- thumbnailHeight: null,
- caption: null,
-
- // Returns the screenshot URL, defaulting to the empty string
- toString: function() {
- return this.url || "";
- }
-}
-
-
-/**
- * This represents a compatibility override for an addon.
- *
- * @param aType
- * Overrride type - "compatible" or "incompatible"
- * @param aMinVersion
- * Minimum version of the addon to match
- * @param aMaxVersion
- * Maximum version of the addon to match
- * @param aAppID
- * Application ID used to match appMinVersion and appMaxVersion
- * @param aAppMinVersion
- * Minimum version of the application to match
- * @param aAppMaxVersion
- * Maximum version of the application to match
- */
-function AddonCompatibilityOverride(aType, aMinVersion, aMaxVersion, aAppID,
- aAppMinVersion, aAppMaxVersion) {
- this.type = aType;
- this.minVersion = aMinVersion;
- this.maxVersion = aMaxVersion;
- this.appID = aAppID;
- this.appMinVersion = aAppMinVersion;
- this.appMaxVersion = aAppMaxVersion;
-}
-
-AddonCompatibilityOverride.prototype = {
- /**
- * Type of override - "incompatible" or "compatible".
- * Only "incompatible" is supported for now.
- */
- type: null,
-
- /**
- * Min version of the addon to match.
- */
- minVersion: null,
-
- /**
- * Max version of the addon to match.
- */
- maxVersion: null,
-
- /**
- * Application ID to match.
- */
- appID: null,
-
- /**
- * Min version of the application to match.
- */
- appMinVersion: null,
-
- /**
- * Max version of the application to match.
- */
- appMaxVersion: null
-};
-
-
-/**
- * A type of add-on, used by the UI to determine how to display different types
- * of add-ons.
- *
- * @param aID
- * The add-on type ID
- * @param aLocaleURI
- * The URI of a localized properties file to get the displayable name
- * for the type from
- * @param aLocaleKey
- * The key for the string in the properties file or the actual display
- * name if aLocaleURI is null. Include %ID% to include the type ID in
- * the key
- * @param aViewType
- * The optional type of view to use in the UI
- * @param aUIPriority
- * The priority is used by the UI to list the types in order. Lower
- * values push the type higher in the list.
- * @param aFlags
- * An option set of flags that customize the display of the add-on in
- * the UI.
- */
-function AddonType(aID, aLocaleURI, aLocaleKey, aViewType, aUIPriority, aFlags) {
- if (!aID)
- throw Components.Exception("An AddonType must have an ID", Cr.NS_ERROR_INVALID_ARG);
-
- if (aViewType && aUIPriority === undefined)
- throw Components.Exception("An AddonType with a defined view must have a set UI priority",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!aLocaleKey)
- throw Components.Exception("An AddonType must have a displayable name",
- Cr.NS_ERROR_INVALID_ARG);
-
- this.id = aID;
- this.uiPriority = aUIPriority;
- this.viewType = aViewType;
- this.flags = aFlags;
-
- if (aLocaleURI) {
- XPCOMUtils.defineLazyGetter(this, "name", () => {
- let bundle = Services.strings.createBundle(aLocaleURI);
- return bundle.GetStringFromName(aLocaleKey.replace("%ID%", aID));
- });
- }
- else {
- this.name = aLocaleKey;
- }
-}
-
-var gStarted = false;
-var gStartupComplete = false;
-var gCheckCompatibility = true;
-var gStrictCompatibility = true;
-var gCheckUpdateSecurityDefault = true;
-var gCheckUpdateSecurity = gCheckUpdateSecurityDefault;
-var gUpdateEnabled = true;
-var gAutoUpdateDefault = true;
-var gHotfixID = null;
-var gWebExtensionsMinPlatformVersion = null;
-var gShutdownBarrier = null;
-var gRepoShutdownState = "";
-var gShutdownInProgress = false;
-var gPluginPageListener = null;
-
-/**
- * This is the real manager, kept here rather than in AddonManager to keep its
- * contents hidden from API users.
- */
-var AddonManagerInternal = {
- managerListeners: [],
- installListeners: [],
- addonListeners: [],
- typeListeners: [],
- pendingProviders: new Set(),
- providers: new Set(),
- providerShutdowns: new Map(),
- types: {},
- startupChanges: {},
- // Store telemetry details per addon provider
- telemetryDetails: {},
- upgradeListeners: new Map(),
-
- recordTimestamp: function(name, value) {
- this.TelemetryTimestamps.add(name, value);
- },
-
- validateBlocklist: function() {
- let appBlocklist = FileUtils.getFile(KEY_APPDIR, [FILE_BLOCKLIST]);
-
- // If there is no application shipped blocklist then there is nothing to do
- if (!appBlocklist.exists())
- return;
-
- let profileBlocklist = FileUtils.getFile(KEY_PROFILEDIR, [FILE_BLOCKLIST]);
-
- // If there is no blocklist in the profile then copy the application shipped
- // one there
- if (!profileBlocklist.exists()) {
- try {
- appBlocklist.copyTo(profileBlocklist.parent, FILE_BLOCKLIST);
- }
- catch (e) {
- logger.warn("Failed to copy the application shipped blocklist to the profile", e);
- }
- return;
- }
-
- let fileStream = Cc["@mozilla.org/network/file-input-stream;1"].
- createInstance(Ci.nsIFileInputStream);
- try {
- let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"].
- createInstance(Ci.nsIConverterInputStream);
- fileStream.init(appBlocklist, FileUtils.MODE_RDONLY, FileUtils.PERMS_FILE, 0);
- cstream.init(fileStream, "UTF-8", 0, 0);
-
- let data = "";
- let str = {};
- let read = 0;
- do {
- read = cstream.readString(0xffffffff, str);
- data += str.value;
- } while (read != 0);
-
- let parser = Cc["@mozilla.org/xmlextras/domparser;1"].
- createInstance(Ci.nsIDOMParser);
- var doc = parser.parseFromString(data, "text/xml");
- }
- catch (e) {
- logger.warn("Application shipped blocklist could not be loaded", e);
- return;
- }
- finally {
- try {
- fileStream.close();
- }
- catch (e) {
- logger.warn("Unable to close blocklist file stream", e);
- }
- }
-
- // If the namespace is incorrect then ignore the application shipped
- // blocklist
- if (doc.documentElement.namespaceURI != XMLURI_BLOCKLIST) {
- logger.warn("Application shipped blocklist has an unexpected namespace (" +
- doc.documentElement.namespaceURI + ")");
- return;
- }
-
- // If there is no lastupdate information then ignore the application shipped
- // blocklist
- if (!doc.documentElement.hasAttribute("lastupdate"))
- return;
-
- // If the application shipped blocklist is older than the profile blocklist
- // then do nothing
- if (doc.documentElement.getAttribute("lastupdate") <=
- profileBlocklist.lastModifiedTime)
- return;
-
- // Otherwise copy the application shipped blocklist to the profile
- try {
- appBlocklist.copyTo(profileBlocklist.parent, FILE_BLOCKLIST);
- }
- catch (e) {
- logger.warn("Failed to copy the application shipped blocklist to the profile", e);
- }
- },
-
- /**
- * Start up a provider, and register its shutdown hook if it has one
- */
- _startProvider(aProvider, aAppChanged, aOldAppVersion, aOldPlatformVersion) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- logger.debug(`Starting provider: ${providerName(aProvider)}`);
- callProvider(aProvider, "startup", null, aAppChanged, aOldAppVersion, aOldPlatformVersion);
- if ('shutdown' in aProvider) {
- let name = providerName(aProvider);
- let AMProviderShutdown = () => {
- // If the provider has been unregistered, it will have been removed from
- // this.providers. If it hasn't been unregistered, then this is a normal
- // shutdown - and we move it to this.pendingProviders incase we're
- // running in a test that will start AddonManager again.
- if (this.providers.has(aProvider)) {
- this.providers.delete(aProvider);
- this.pendingProviders.add(aProvider);
- }
-
- return new Promise((resolve, reject) => {
- logger.debug("Calling shutdown blocker for " + name);
- resolve(aProvider.shutdown());
- })
- .catch(err => {
- logger.warn("Failure during shutdown of " + name, err);
- AddonManagerPrivate.recordException("AMI", "Async shutdown of " + name, err);
- });
- };
- logger.debug("Registering shutdown blocker for " + name);
- this.providerShutdowns.set(aProvider, AMProviderShutdown);
- AddonManager.shutdown.addBlocker(name, AMProviderShutdown);
- }
-
- this.pendingProviders.delete(aProvider);
- this.providers.add(aProvider);
- logger.debug(`Provider finished startup: ${providerName(aProvider)}`);
- },
-
- _getProviderByName(aName) {
- for (let provider of this.providers) {
- if (providerName(provider) == aName)
- return provider;
- }
- return undefined;
- },
-
- /**
- * Initializes the AddonManager, loading any known providers and initializing
- * them.
- */
- startup: function() {
- try {
- if (gStarted)
- return;
-
- this.recordTimestamp("AMI_startup_begin");
-
- // clear this for xpcshell test restarts
- for (let provider in this.telemetryDetails)
- delete this.telemetryDetails[provider];
-
- let appChanged = undefined;
-
- let oldAppVersion = null;
- try {
- oldAppVersion = Services.prefs.getCharPref(PREF_EM_LAST_APP_VERSION);
- appChanged = Services.appinfo.version != oldAppVersion;
- }
- catch (e) { }
-
- Extension.browserUpdated = appChanged;
-
- let oldPlatformVersion = null;
- try {
- oldPlatformVersion = Services.prefs.getCharPref(PREF_EM_LAST_PLATFORM_VERSION);
- }
- catch (e) { }
-
- if (appChanged !== false) {
- logger.debug("Application has been upgraded");
- Services.prefs.setCharPref(PREF_EM_LAST_APP_VERSION,
- Services.appinfo.version);
- Services.prefs.setCharPref(PREF_EM_LAST_PLATFORM_VERSION,
- Services.appinfo.platformVersion);
- Services.prefs.setIntPref(PREF_BLOCKLIST_PINGCOUNTVERSION,
- (appChanged === undefined ? 0 : -1));
- this.validateBlocklist();
- }
-
- try {
- gCheckCompatibility = Services.prefs.getBoolPref(PREF_EM_CHECK_COMPATIBILITY);
- } catch (e) {}
- Services.prefs.addObserver(PREF_EM_CHECK_COMPATIBILITY, this, false);
-
- try {
- gStrictCompatibility = Services.prefs.getBoolPref(PREF_EM_STRICT_COMPATIBILITY);
- } catch (e) {}
- Services.prefs.addObserver(PREF_EM_STRICT_COMPATIBILITY, this, false);
-
- try {
- let defaultBranch = Services.prefs.getDefaultBranch("");
- gCheckUpdateSecurityDefault = defaultBranch.getBoolPref(PREF_EM_CHECK_UPDATE_SECURITY);
- } catch (e) {}
-
- try {
- gCheckUpdateSecurity = Services.prefs.getBoolPref(PREF_EM_CHECK_UPDATE_SECURITY);
- } catch (e) {}
- Services.prefs.addObserver(PREF_EM_CHECK_UPDATE_SECURITY, this, false);
-
- try {
- gUpdateEnabled = Services.prefs.getBoolPref(PREF_EM_UPDATE_ENABLED);
- } catch (e) {}
- Services.prefs.addObserver(PREF_EM_UPDATE_ENABLED, this, false);
-
- try {
- gAutoUpdateDefault = Services.prefs.getBoolPref(PREF_EM_AUTOUPDATE_DEFAULT);
- } catch (e) {}
- Services.prefs.addObserver(PREF_EM_AUTOUPDATE_DEFAULT, this, false);
-
- try {
- gHotfixID = Services.prefs.getCharPref(PREF_EM_HOTFIX_ID);
- } catch (e) {}
- Services.prefs.addObserver(PREF_EM_HOTFIX_ID, this, false);
-
- try {
- gWebExtensionsMinPlatformVersion = Services.prefs.getCharPref(PREF_MIN_WEBEXT_PLATFORM_VERSION);
- } catch (e) {}
- Services.prefs.addObserver(PREF_MIN_WEBEXT_PLATFORM_VERSION, this, false);
-
- let defaultProvidersEnabled = true;
- try {
- defaultProvidersEnabled = Services.prefs.getBoolPref(PREF_DEFAULT_PROVIDERS_ENABLED);
- } catch (e) {}
- AddonManagerPrivate.recordSimpleMeasure("default_providers", defaultProvidersEnabled);
-
- // Ensure all default providers have had a chance to register themselves
- if (defaultProvidersEnabled) {
- for (let url of DEFAULT_PROVIDERS) {
- try {
- let scope = {};
- Components.utils.import(url, scope);
- // Sanity check - make sure the provider exports a symbol that
- // has a 'startup' method
- let syms = Object.keys(scope);
- if ((syms.length < 1) ||
- (typeof scope[syms[0]].startup != "function")) {
- logger.warn("Provider " + url + " has no startup()");
- AddonManagerPrivate.recordException("AMI", "provider " + url, "no startup()");
- }
- logger.debug("Loaded provider scope for " + url + ": " + Object.keys(scope).toSource());
- }
- catch (e) {
- AddonManagerPrivate.recordException("AMI", "provider " + url + " load failed", e);
- logger.error("Exception loading default provider \"" + url + "\"", e);
- }
- }
- }
-
- // Load any providers registered in the category manager
- let catman = Cc["@mozilla.org/categorymanager;1"].
- getService(Ci.nsICategoryManager);
- let entries = catman.enumerateCategory(CATEGORY_PROVIDER_MODULE);
- while (entries.hasMoreElements()) {
- let entry = entries.getNext().QueryInterface(Ci.nsISupportsCString).data;
- let url = catman.getCategoryEntry(CATEGORY_PROVIDER_MODULE, entry);
-
- try {
- Components.utils.import(url, {});
- logger.debug(`Loaded provider scope for ${url}`);
- }
- catch (e) {
- AddonManagerPrivate.recordException("AMI", "provider " + url + " load failed", e);
- logger.error("Exception loading provider " + entry + " from category \"" +
- url + "\"", e);
- }
- }
-
- // Register our shutdown handler with the AsyncShutdown manager
- gShutdownBarrier = new AsyncShutdown.Barrier("AddonManager: Waiting for providers to shut down.");
- AsyncShutdown.profileBeforeChange.addBlocker("AddonManager: shutting down.",
- this.shutdownManager.bind(this),
- {fetchState: this.shutdownState.bind(this)});
-
- // Once we start calling providers we must allow all normal methods to work.
- gStarted = true;
-
- for (let provider of this.pendingProviders) {
- this._startProvider(provider, appChanged, oldAppVersion, oldPlatformVersion);
- }
-
- // If this is a new profile just pretend that there were no changes
- if (appChanged === undefined) {
- for (let type in this.startupChanges)
- delete this.startupChanges[type];
- }
-
- // Support for remote about:plugins. Note that this module isn't loaded
- // at the top because Services.appinfo is defined late in tests.
- let { RemotePages } = Cu.import("resource://gre/modules/RemotePageManager.jsm", {});
-
- gPluginPageListener = new RemotePages("about:plugins");
- gPluginPageListener.addMessageListener("RequestPlugins", this.requestPlugins);
-
- gStartupComplete = true;
- this.recordTimestamp("AMI_startup_end");
- }
- catch (e) {
- logger.error("startup failed", e);
- AddonManagerPrivate.recordException("AMI", "startup failed", e);
- }
-
- logger.debug("Completed startup sequence");
- this.callManagerListeners("onStartup");
- },
-
- /**
- * Registers a new AddonProvider.
- *
- * @param aProvider
- * The provider to register
- * @param aTypes
- * An optional array of add-on types
- */
- registerProvider: function(aProvider, aTypes) {
- if (!aProvider || typeof aProvider != "object")
- throw Components.Exception("aProvider must be specified",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (aTypes && !Array.isArray(aTypes))
- throw Components.Exception("aTypes must be an array or null",
- Cr.NS_ERROR_INVALID_ARG);
-
- this.pendingProviders.add(aProvider);
-
- if (aTypes) {
- for (let type of aTypes) {
- if (!(type.id in this.types)) {
- if (!VALID_TYPES_REGEXP.test(type.id)) {
- logger.warn("Ignoring invalid type " + type.id);
- return;
- }
-
- this.types[type.id] = {
- type: type,
- providers: [aProvider]
- };
-
- let typeListeners = this.typeListeners.slice(0);
- for (let listener of typeListeners)
- safeCall(() => listener.onTypeAdded(type));
- }
- else {
- this.types[type.id].providers.push(aProvider);
- }
- }
- }
-
- // If we're registering after startup call this provider's startup.
- if (gStarted) {
- this._startProvider(aProvider);
- }
- },
-
- /**
- * Unregisters an AddonProvider.
- *
- * @param aProvider
- * The provider to unregister
- * @return Whatever the provider's 'shutdown' method returns (if anything).
- * For providers that have async shutdown methods returning Promises,
- * the caller should wait for that Promise to resolve.
- */
- unregisterProvider: function(aProvider) {
- if (!aProvider || typeof aProvider != "object")
- throw Components.Exception("aProvider must be specified",
- Cr.NS_ERROR_INVALID_ARG);
-
- this.providers.delete(aProvider);
- // The test harness will unregister XPIProvider *after* shutdown, which is
- // after the provider will have been moved from providers to
- // pendingProviders.
- this.pendingProviders.delete(aProvider);
-
- for (let type in this.types) {
- this.types[type].providers = this.types[type].providers.filter(p => p != aProvider);
- if (this.types[type].providers.length == 0) {
- let oldType = this.types[type].type;
- delete this.types[type];
-
- let typeListeners = this.typeListeners.slice(0);
- for (let listener of typeListeners)
- safeCall(() => listener.onTypeRemoved(oldType));
- }
- }
-
- // If we're unregistering after startup but before shutting down,
- // remove the blocker for this provider's shutdown and call it.
- // If we're already shutting down, just let gShutdownBarrier call it to avoid races.
- if (gStarted && !gShutdownInProgress) {
- logger.debug("Unregistering shutdown blocker for " + providerName(aProvider));
- let shutter = this.providerShutdowns.get(aProvider);
- if (shutter) {
- this.providerShutdowns.delete(aProvider);
- gShutdownBarrier.client.removeBlocker(shutter);
- return shutter();
- }
- }
- return undefined;
- },
-
- /**
- * Mark a provider as safe to access via AddonManager APIs, before its
- * startup has completed.
- *
- * Normally a provider isn't marked as safe until after its (synchronous)
- * startup() method has returned. Until a provider has been marked safe,
- * it won't be used by any of the AddonManager APIs. markProviderSafe()
- * allows a provider to mark itself as safe during its startup; this can be
- * useful if the provider wants to perform tasks that block startup, which
- * happen after its required initialization tasks and therefore when the
- * provider is in a safe state.
- *
- * @param aProvider Provider object to mark safe
- */
- markProviderSafe: function(aProvider) {
- if (!gStarted) {
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
- }
-
- if (!aProvider || typeof aProvider != "object") {
- throw Components.Exception("aProvider must be specified",
- Cr.NS_ERROR_INVALID_ARG);
- }
-
- if (!this.pendingProviders.has(aProvider)) {
- return;
- }
-
- this.pendingProviders.delete(aProvider);
- this.providers.add(aProvider);
- },
-
- /**
- * Calls a method on all registered providers if it exists and consumes any
- * thrown exception. Return values are ignored. Any parameters after the
- * method parameter are passed to the provider's method.
- * WARNING: Do not use for asynchronous calls; callProviders() does not
- * invoke callbacks if provider methods throw synchronous exceptions.
- *
- * @param aMethod
- * The method name to call
- * @see callProvider
- */
- callProviders: function(aMethod, ...aArgs) {
- if (!aMethod || typeof aMethod != "string")
- throw Components.Exception("aMethod must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- let providers = [...this.providers];
- for (let provider of providers) {
- try {
- if (aMethod in provider)
- provider[aMethod].apply(provider, aArgs);
- }
- catch (e) {
- reportProviderError(provider, aMethod, e);
- }
- }
- },
-
- /**
- * Report the current state of asynchronous shutdown
- */
- shutdownState() {
- let state = [];
- if (gShutdownBarrier) {
- state.push({
- name: gShutdownBarrier.client.name,
- state: gShutdownBarrier.state
- });
- }
- state.push({
- name: "AddonRepository: async shutdown",
- state: gRepoShutdownState
- });
- return state;
- },
-
- /**
- * Shuts down the addon manager and all registered providers, this must clean
- * up everything in order for automated tests to fake restarts.
- * @return Promise{null} that resolves when all providers and dependent modules
- * have finished shutting down
- */
- shutdownManager: Task.async(function*() {
- logger.debug("shutdown");
- this.callManagerListeners("onShutdown");
-
- gRepoShutdownState = "pending";
- gShutdownInProgress = true;
- // Clean up listeners
- Services.prefs.removeObserver(PREF_EM_CHECK_COMPATIBILITY, this);
- Services.prefs.removeObserver(PREF_EM_STRICT_COMPATIBILITY, this);
- Services.prefs.removeObserver(PREF_EM_CHECK_UPDATE_SECURITY, this);
- Services.prefs.removeObserver(PREF_EM_UPDATE_ENABLED, this);
- Services.prefs.removeObserver(PREF_EM_AUTOUPDATE_DEFAULT, this);
- Services.prefs.removeObserver(PREF_EM_HOTFIX_ID, this);
- gPluginPageListener.destroy();
- gPluginPageListener = null;
-
- let savedError = null;
- // Only shut down providers if they've been started.
- if (gStarted) {
- try {
- yield gShutdownBarrier.wait();
- }
- catch (err) {
- savedError = err;
- logger.error("Failure during wait for shutdown barrier", err);
- AddonManagerPrivate.recordException("AMI", "Async shutdown of AddonManager providers", err);
- }
- }
-
- // Shut down AddonRepository after providers (if any).
- try {
- gRepoShutdownState = "in progress";
- yield AddonRepository.shutdown();
- gRepoShutdownState = "done";
- }
- catch (err) {
- savedError = err;
- logger.error("Failure during AddonRepository shutdown", err);
- AddonManagerPrivate.recordException("AMI", "Async shutdown of AddonRepository", err);
- }
-
- logger.debug("Async provider shutdown done");
- this.managerListeners.splice(0, this.managerListeners.length);
- this.installListeners.splice(0, this.installListeners.length);
- this.addonListeners.splice(0, this.addonListeners.length);
- this.typeListeners.splice(0, this.typeListeners.length);
- this.providerShutdowns.clear();
- for (let type in this.startupChanges)
- delete this.startupChanges[type];
- gStarted = false;
- gStartupComplete = false;
- gShutdownBarrier = null;
- gShutdownInProgress = false;
- if (savedError) {
- throw savedError;
- }
- }),
-
- requestPlugins: function({ target: port }) {
- // Lists all the properties that plugins.html needs
- const NEEDED_PROPS = ["name", "pluginLibraries", "pluginFullpath", "version",
- "isActive", "blocklistState", "description",
- "pluginMimeTypes"];
- function filterProperties(plugin) {
- let filtered = {};
- for (let prop of NEEDED_PROPS) {
- filtered[prop] = plugin[prop];
- }
- return filtered;
- }
-
- AddonManager.getAddonsByTypes(["plugin"], function(aPlugins) {
- port.sendAsyncMessage("PluginList", aPlugins.map(filterProperties));
- });
- },
-
- /**
- * Notified when a preference we're interested in has changed.
- *
- * @see nsIObserver
- */
- observe: function(aSubject, aTopic, aData) {
- switch (aData) {
- case PREF_EM_CHECK_COMPATIBILITY: {
- let oldValue = gCheckCompatibility;
- try {
- gCheckCompatibility = Services.prefs.getBoolPref(PREF_EM_CHECK_COMPATIBILITY);
- } catch (e) {
- gCheckCompatibility = true;
- }
-
- this.callManagerListeners("onCompatibilityModeChanged");
-
- if (gCheckCompatibility != oldValue)
- this.updateAddonAppDisabledStates();
-
- break;
- }
- case PREF_EM_STRICT_COMPATIBILITY: {
- let oldValue = gStrictCompatibility;
- try {
- gStrictCompatibility = Services.prefs.getBoolPref(PREF_EM_STRICT_COMPATIBILITY);
- } catch (e) {
- gStrictCompatibility = true;
- }
-
- this.callManagerListeners("onCompatibilityModeChanged");
-
- if (gStrictCompatibility != oldValue)
- this.updateAddonAppDisabledStates();
-
- break;
- }
- case PREF_EM_CHECK_UPDATE_SECURITY: {
- let oldValue = gCheckUpdateSecurity;
- try {
- gCheckUpdateSecurity = Services.prefs.getBoolPref(PREF_EM_CHECK_UPDATE_SECURITY);
- } catch (e) {
- gCheckUpdateSecurity = true;
- }
-
- this.callManagerListeners("onCheckUpdateSecurityChanged");
-
- if (gCheckUpdateSecurity != oldValue)
- this.updateAddonAppDisabledStates();
-
- break;
- }
- case PREF_EM_UPDATE_ENABLED: {
- let oldValue = gUpdateEnabled;
- try {
- gUpdateEnabled = Services.prefs.getBoolPref(PREF_EM_UPDATE_ENABLED);
- } catch (e) {
- gUpdateEnabled = true;
- }
-
- this.callManagerListeners("onUpdateModeChanged");
- break;
- }
- case PREF_EM_AUTOUPDATE_DEFAULT: {
- let oldValue = gAutoUpdateDefault;
- try {
- gAutoUpdateDefault = Services.prefs.getBoolPref(PREF_EM_AUTOUPDATE_DEFAULT);
- } catch (e) {
- gAutoUpdateDefault = true;
- }
-
- this.callManagerListeners("onUpdateModeChanged");
- break;
- }
- case PREF_EM_HOTFIX_ID: {
- try {
- gHotfixID = Services.prefs.getCharPref(PREF_EM_HOTFIX_ID);
- } catch (e) {
- gHotfixID = null;
- }
- break;
- }
- case PREF_MIN_WEBEXT_PLATFORM_VERSION: {
- gWebExtensionsMinPlatformVersion = Services.prefs.getCharPref(PREF_MIN_WEBEXT_PLATFORM_VERSION);
- break;
- }
- }
- },
-
- /**
- * Replaces %...% strings in an addon url (update and updateInfo) with
- * appropriate values.
- *
- * @param aAddon
- * The Addon representing the add-on
- * @param aUri
- * The string representation of the URI to escape
- * @param aAppVersion
- * The optional application version to use for %APP_VERSION%
- * @return The appropriately escaped URI.
- */
- escapeAddonURI: function(aAddon, aUri, aAppVersion)
- {
- if (!aAddon || typeof aAddon != "object")
- throw Components.Exception("aAddon must be an Addon object",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!aUri || typeof aUri != "string")
- throw Components.Exception("aUri must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (aAppVersion && typeof aAppVersion != "string")
- throw Components.Exception("aAppVersion must be a string or null",
- Cr.NS_ERROR_INVALID_ARG);
-
- var addonStatus = aAddon.userDisabled || aAddon.softDisabled ? "userDisabled"
- : "userEnabled";
-
- if (!aAddon.isCompatible)
- addonStatus += ",incompatible";
- if (aAddon.blocklistState == Ci.nsIBlocklistService.STATE_BLOCKED)
- addonStatus += ",blocklisted";
- if (aAddon.blocklistState == Ci.nsIBlocklistService.STATE_SOFTBLOCKED)
- addonStatus += ",softblocked";
-
- try {
- var xpcomABI = Services.appinfo.XPCOMABI;
- } catch (ex) {
- xpcomABI = UNKNOWN_XPCOM_ABI;
- }
-
- let uri = aUri.replace(/%ITEM_ID%/g, aAddon.id);
- uri = uri.replace(/%ITEM_VERSION%/g, aAddon.version);
- uri = uri.replace(/%ITEM_STATUS%/g, addonStatus);
- uri = uri.replace(/%APP_ID%/g, Services.appinfo.ID);
- uri = uri.replace(/%APP_VERSION%/g, aAppVersion ? aAppVersion :
- Services.appinfo.version);
- uri = uri.replace(/%REQ_VERSION%/g, UPDATE_REQUEST_VERSION);
- uri = uri.replace(/%APP_OS%/g, Services.appinfo.OS);
- uri = uri.replace(/%APP_ABI%/g, xpcomABI);
- uri = uri.replace(/%APP_LOCALE%/g, getLocale());
- uri = uri.replace(/%CURRENT_APP_VERSION%/g, Services.appinfo.version);
-
- // Replace custom parameters (names of custom parameters must have at
- // least 3 characters to prevent lookups for something like %D0%C8)
- var catMan = null;
- uri = uri.replace(/%(\w{3,})%/g, function(aMatch, aParam) {
- if (!catMan) {
- catMan = Cc["@mozilla.org/categorymanager;1"].
- getService(Ci.nsICategoryManager);
- }
-
- try {
- var contractID = catMan.getCategoryEntry(CATEGORY_UPDATE_PARAMS, aParam);
- var paramHandler = Cc[contractID].getService(Ci.nsIPropertyBag2);
- return paramHandler.getPropertyAsAString(aParam);
- }
- catch (e) {
- return aMatch;
- }
- });
-
- // escape() does not properly encode + symbols in any embedded FVF strings.
- return uri.replace(/\+/g, "%2B");
- },
-
- /**
- * Performs a background update check by starting an update for all add-ons
- * that can be updated.
- * @return Promise{null} Resolves when the background update check is complete
- * (the resulting addon installations may still be in progress).
- */
- backgroundUpdateCheck: function() {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- let buPromise = Task.spawn(function*() {
- let hotfixID = this.hotfixID;
-
- let appUpdateEnabled = Services.prefs.getBoolPref(PREF_APP_UPDATE_ENABLED) &&
- Services.prefs.getBoolPref(PREF_APP_UPDATE_AUTO);
- let checkHotfix = hotfixID && appUpdateEnabled;
-
- logger.debug("Background update check beginning");
-
- Services.obs.notifyObservers(null, "addons-background-update-start", null);
-
- if (this.updateEnabled) {
- let scope = {};
- Components.utils.import("resource://gre/modules/LightweightThemeManager.jsm", scope);
- scope.LightweightThemeManager.updateCurrentTheme();
-
- let allAddons = yield new Promise((resolve, reject) => this.getAllAddons(resolve));
-
- // Repopulate repository cache first, to ensure compatibility overrides
- // are up to date before checking for addon updates.
- yield AddonRepository.backgroundUpdateCheck();
-
- // Keep track of all the async add-on updates happening in parallel
- let updates = [];
-
- for (let addon of allAddons) {
- if (addon.id == hotfixID) {
- continue;
- }
-
- // Check all add-ons for updates so that any compatibility updates will
- // be applied
- updates.push(new Promise((resolve, reject) => {
- addon.findUpdates({
- onUpdateAvailable: function(aAddon, aInstall) {
- // Start installing updates when the add-on can be updated and
- // background updates should be applied.
- logger.debug("Found update for add-on ${id}", aAddon);
- if (aAddon.permissions & AddonManager.PERM_CAN_UPGRADE &&
- AddonManager.shouldAutoUpdate(aAddon)) {
- // XXX we really should resolve when this install is done,
- // not when update-available check completes, no?
- logger.debug(`Starting upgrade install of ${aAddon.id}`);
- aInstall.install();
- }
- },
-
- onUpdateFinished: aAddon => { logger.debug("onUpdateFinished for ${id}", aAddon); resolve(); }
- }, AddonManager.UPDATE_WHEN_PERIODIC_UPDATE);
- }));
- }
- yield Promise.all(updates);
- }
-
- if (checkHotfix) {
- var hotfixVersion = "";
- try {
- hotfixVersion = Services.prefs.getCharPref(PREF_EM_HOTFIX_LASTVERSION);
- }
- catch (e) { }
-
- let url = null;
- if (Services.prefs.getPrefType(PREF_EM_HOTFIX_URL) == Ci.nsIPrefBranch.PREF_STRING)
- url = Services.prefs.getCharPref(PREF_EM_HOTFIX_URL);
- else
- url = Services.prefs.getCharPref(PREF_EM_UPDATE_BACKGROUND_URL);
-
- // Build the URI from a fake add-on data.
- url = AddonManager.escapeAddonURI({
- id: hotfixID,
- version: hotfixVersion,
- userDisabled: false,
- appDisabled: false
- }, url);
-
- Components.utils.import("resource://gre/modules/addons/AddonUpdateChecker.jsm");
- let update = null;
- try {
- let foundUpdates = yield new Promise((resolve, reject) => {
- AddonUpdateChecker.checkForUpdates(hotfixID, null, url, {
- onUpdateCheckComplete: resolve,
- onUpdateCheckError: reject
- });
- });
- update = AddonUpdateChecker.getNewestCompatibleUpdate(foundUpdates);
- } catch (e) {
- // AUC.checkForUpdates already logged the error
- }
-
- // Check that we have a hotfix update, and it's newer than the one we already
- // have installed (if any)
- if (update) {
- if (Services.vc.compare(hotfixVersion, update.version) < 0) {
- logger.debug("Downloading hotfix version " + update.version);
- let aInstall = yield new Promise((resolve, reject) =>
- AddonManager.getInstallForURL(update.updateURL, resolve,
- "application/x-xpinstall", update.updateHash, null,
- null, update.version));
-
- aInstall.addListener({
- onDownloadEnded: function(aInstall) {
- if (aInstall.addon.id != hotfixID) {
- logger.warn("The downloaded hotfix add-on did not have the " +
- "expected ID and so will not be installed.");
- aInstall.cancel();
- return;
- }
-
- // If XPIProvider has reported the hotfix as properly signed then
- // there is nothing more to do here
- if (aInstall.addon.signedState == AddonManager.SIGNEDSTATE_SIGNED)
- return;
-
- try {
- if (!Services.prefs.getBoolPref(PREF_EM_CERT_CHECKATTRIBUTES))
- return;
- }
- catch (e) {
- // By default don't do certificate checks.
- return;
- }
-
- try {
- CertUtils.validateCert(aInstall.certificate,
- CertUtils.readCertPrefs(PREF_EM_HOTFIX_CERTS));
- }
- catch (e) {
- logger.warn("The hotfix add-on was not signed by the expected " +
- "certificate and so will not be installed.", e);
- aInstall.cancel();
- }
- },
-
- onInstallEnded: function(aInstall) {
- // Remember the last successfully installed version.
- Services.prefs.setCharPref(PREF_EM_HOTFIX_LASTVERSION,
- aInstall.version);
- },
-
- onInstallCancelled: function(aInstall) {
- // Revert to the previous version if the installation was
- // cancelled.
- Services.prefs.setCharPref(PREF_EM_HOTFIX_LASTVERSION,
- hotfixVersion);
- }
- });
-
- aInstall.install();
- }
- }
- }
-
- if (appUpdateEnabled) {
- try {
- yield AddonManagerInternal._getProviderByName("XPIProvider").updateSystemAddons();
- }
- catch (e) {
- logger.warn("Failed to update system addons", e);
- }
- }
-
- logger.debug("Background update check complete");
- Services.obs.notifyObservers(null,
- "addons-background-update-complete",
- null);
- }.bind(this));
- // Fork the promise chain so we can log the error and let our caller see it too.
- buPromise.then(null, e => logger.warn("Error in background update", e));
- return buPromise;
- },
-
- /**
- * Adds a add-on to the list of detected changes for this startup. If
- * addStartupChange is called multiple times for the same add-on in the same
- * startup then only the most recent change will be remembered.
- *
- * @param aType
- * The type of change as a string. Providers can define their own
- * types of changes or use the existing defined STARTUP_CHANGE_*
- * constants
- * @param aID
- * The ID of the add-on
- */
- addStartupChange: function(aType, aID) {
- if (!aType || typeof aType != "string")
- throw Components.Exception("aType must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!aID || typeof aID != "string")
- throw Components.Exception("aID must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (gStartupComplete)
- return;
- logger.debug("Registering startup change '" + aType + "' for " + aID);
-
- // Ensure that an ID is only listed in one type of change
- for (let type in this.startupChanges)
- this.removeStartupChange(type, aID);
-
- if (!(aType in this.startupChanges))
- this.startupChanges[aType] = [];
- this.startupChanges[aType].push(aID);
- },
-
- /**
- * Removes a startup change for an add-on.
- *
- * @param aType
- * The type of change
- * @param aID
- * The ID of the add-on
- */
- removeStartupChange: function(aType, aID) {
- if (!aType || typeof aType != "string")
- throw Components.Exception("aType must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!aID || typeof aID != "string")
- throw Components.Exception("aID must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (gStartupComplete)
- return;
-
- if (!(aType in this.startupChanges))
- return;
-
- this.startupChanges[aType] = this.startupChanges[aType].filter(aItem => aItem != aID);
- },
-
- /**
- * Calls all registered AddonManagerListeners with an event. Any parameters
- * after the method parameter are passed to the listener.
- *
- * @param aMethod
- * The method on the listeners to call
- */
- callManagerListeners: function(aMethod, ...aArgs) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!aMethod || typeof aMethod != "string")
- throw Components.Exception("aMethod must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- let managerListeners = this.managerListeners.slice(0);
- for (let listener of managerListeners) {
- try {
- if (aMethod in listener)
- listener[aMethod].apply(listener, aArgs);
- }
- catch (e) {
- logger.warn("AddonManagerListener threw exception when calling " + aMethod, e);
- }
- }
- },
-
- /**
- * Calls all registered InstallListeners with an event. Any parameters after
- * the extraListeners parameter are passed to the listener.
- *
- * @param aMethod
- * The method on the listeners to call
- * @param aExtraListeners
- * An optional array of extra InstallListeners to also call
- * @return false if any of the listeners returned false, true otherwise
- */
- callInstallListeners: function(aMethod,
- aExtraListeners, ...aArgs) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!aMethod || typeof aMethod != "string")
- throw Components.Exception("aMethod must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (aExtraListeners && !Array.isArray(aExtraListeners))
- throw Components.Exception("aExtraListeners must be an array or null",
- Cr.NS_ERROR_INVALID_ARG);
-
- let result = true;
- let listeners;
- if (aExtraListeners)
- listeners = aExtraListeners.concat(this.installListeners);
- else
- listeners = this.installListeners.slice(0);
-
- for (let listener of listeners) {
- try {
- if (aMethod in listener) {
- if (listener[aMethod].apply(listener, aArgs) === false)
- result = false;
- }
- }
- catch (e) {
- logger.warn("InstallListener threw exception when calling " + aMethod, e);
- }
- }
- return result;
- },
-
- /**
- * Calls all registered AddonListeners with an event. Any parameters after
- * the method parameter are passed to the listener.
- *
- * @param aMethod
- * The method on the listeners to call
- */
- callAddonListeners: function(aMethod, ...aArgs) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!aMethod || typeof aMethod != "string")
- throw Components.Exception("aMethod must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- let addonListeners = this.addonListeners.slice(0);
- for (let listener of addonListeners) {
- try {
- if (aMethod in listener)
- listener[aMethod].apply(listener, aArgs);
- }
- catch (e) {
- logger.warn("AddonListener threw exception when calling " + aMethod, e);
- }
- }
- },
-
- /**
- * Notifies all providers that an add-on has been enabled when that type of
- * add-on only supports a single add-on being enabled at a time. This allows
- * the providers to disable theirs if necessary.
- *
- * @param aID
- * The ID of the enabled add-on
- * @param aType
- * The type of the enabled add-on
- * @param aPendingRestart
- * A boolean indicating if the change will only take place the next
- * time the application is restarted
- */
- notifyAddonChanged: function(aID, aType, aPendingRestart) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (aID && typeof aID != "string")
- throw Components.Exception("aID must be a string or null",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!aType || typeof aType != "string")
- throw Components.Exception("aType must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- // Temporary hack until bug 520124 lands.
- // We can get here during synchronous startup, at which point it's
- // considered unsafe (and therefore disallowed by AddonManager.jsm) to
- // access providers that haven't been initialized yet. Since this is when
- // XPIProvider is starting up, XPIProvider can't access itself via APIs
- // going through AddonManager.jsm. Furthermore, LightweightThemeManager may
- // not be initialized until after XPIProvider is, and therefore would also
- // be unaccessible during XPIProvider startup. Thankfully, these are the
- // only two uses of this API, and we know it's safe to use this API with
- // both providers; so we have this hack to allow bypassing the normal
- // safetey guard.
- // The notifyAddonChanged/addonChanged API will be unneeded and therefore
- // removed by bug 520124, so this is a temporary quick'n'dirty hack.
- let providers = [...this.providers, ...this.pendingProviders];
- for (let provider of providers) {
- callProvider(provider, "addonChanged", null, aID, aType, aPendingRestart);
- }
- },
-
- /**
- * Notifies all providers they need to update the appDisabled property for
- * their add-ons in response to an application change such as a blocklist
- * update.
- */
- updateAddonAppDisabledStates: function() {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- this.callProviders("updateAddonAppDisabledStates");
- },
-
- /**
- * Notifies all providers that the repository has updated its data for
- * installed add-ons.
- *
- * @param aCallback
- * Function to call when operation is complete.
- */
- updateAddonRepositoryData: function(aCallback) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (typeof aCallback != "function")
- throw Components.Exception("aCallback must be a function",
- Cr.NS_ERROR_INVALID_ARG);
-
- new AsyncObjectCaller(this.providers, "updateAddonRepositoryData", {
- nextObject: function(aCaller, aProvider) {
- callProviderAsync(aProvider, "updateAddonRepositoryData",
- aCaller.callNext.bind(aCaller));
- },
- noMoreObjects: function(aCaller) {
- safeCall(aCallback);
- // only tests should care about this
- Services.obs.notifyObservers(null, "TEST:addon-repository-data-updated", null);
- }
- });
- },
-
- /**
- * Asynchronously gets an AddonInstall for a URL.
- *
- * @param aUrl
- * The string represenation of the URL the add-on is located at
- * @param aCallback
- * A callback to pass the AddonInstall to
- * @param aMimetype
- * The mimetype of the add-on
- * @param aHash
- * An optional hash of the add-on
- * @param aName
- * An optional placeholder name while the add-on is being downloaded
- * @param aIcons
- * Optional placeholder icons while the add-on is being downloaded
- * @param aVersion
- * An optional placeholder version while the add-on is being downloaded
- * @param aLoadGroup
- * An optional nsILoadGroup to associate any network requests with
- * @throws if the aUrl, aCallback or aMimetype arguments are not specified
- */
- getInstallForURL: function(aUrl, aCallback, aMimetype,
- aHash, aName, aIcons,
- aVersion, aBrowser) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!aUrl || typeof aUrl != "string")
- throw Components.Exception("aURL must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (typeof aCallback != "function")
- throw Components.Exception("aCallback must be a function",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!aMimetype || typeof aMimetype != "string")
- throw Components.Exception("aMimetype must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (aHash && typeof aHash != "string")
- throw Components.Exception("aHash must be a string or null",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (aName && typeof aName != "string")
- throw Components.Exception("aName must be a string or null",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (aIcons) {
- if (typeof aIcons == "string")
- aIcons = { "32": aIcons };
- else if (typeof aIcons != "object")
- throw Components.Exception("aIcons must be a string, an object or null",
- Cr.NS_ERROR_INVALID_ARG);
- } else {
- aIcons = {};
- }
-
- if (aVersion && typeof aVersion != "string")
- throw Components.Exception("aVersion must be a string or null",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (aBrowser && (!(aBrowser instanceof Ci.nsIDOMElement)))
- throw Components.Exception("aBrowser must be a nsIDOMElement or null",
- Cr.NS_ERROR_INVALID_ARG);
-
- let providers = [...this.providers];
- for (let provider of providers) {
- if (callProvider(provider, "supportsMimetype", false, aMimetype)) {
- callProviderAsync(provider, "getInstallForURL",
- aUrl, aHash, aName, aIcons, aVersion, aBrowser,
- function getInstallForURL_safeCall(aInstall) {
- safeCall(aCallback, aInstall);
- });
- return;
- }
- }
- safeCall(aCallback, null);
- },
-
- /**
- * Asynchronously gets an AddonInstall for an nsIFile.
- *
- * @param aFile
- * The nsIFile where the add-on is located
- * @param aCallback
- * A callback to pass the AddonInstall to
- * @param aMimetype
- * An optional mimetype hint for the add-on
- * @throws if the aFile or aCallback arguments are not specified
- */
- getInstallForFile: function(aFile, aCallback, aMimetype) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!(aFile instanceof Ci.nsIFile))
- throw Components.Exception("aFile must be a nsIFile",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (typeof aCallback != "function")
- throw Components.Exception("aCallback must be a function",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (aMimetype && typeof aMimetype != "string")
- throw Components.Exception("aMimetype must be a string or null",
- Cr.NS_ERROR_INVALID_ARG);
-
- new AsyncObjectCaller(this.providers, "getInstallForFile", {
- nextObject: function(aCaller, aProvider) {
- callProviderAsync(aProvider, "getInstallForFile", aFile,
- function(aInstall) {
- if (aInstall)
- safeCall(aCallback, aInstall);
- else
- aCaller.callNext();
- });
- },
-
- noMoreObjects: function(aCaller) {
- safeCall(aCallback, null);
- }
- });
- },
-
- /**
- * Asynchronously gets all current AddonInstalls optionally limiting to a list
- * of types.
- *
- * @param aTypes
- * An optional array of types to retrieve. Each type is a string name
- * @param aCallback
- * A callback which will be passed an array of AddonInstalls
- * @throws If the aCallback argument is not specified
- */
- getInstallsByTypes: function(aTypes, aCallback) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (aTypes && !Array.isArray(aTypes))
- throw Components.Exception("aTypes must be an array or null",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (typeof aCallback != "function")
- throw Components.Exception("aCallback must be a function",
- Cr.NS_ERROR_INVALID_ARG);
-
- let installs = [];
-
- new AsyncObjectCaller(this.providers, "getInstallsByTypes", {
- nextObject: function(aCaller, aProvider) {
- callProviderAsync(aProvider, "getInstallsByTypes", aTypes,
- function(aProviderInstalls) {
- if (aProviderInstalls) {
- installs = installs.concat(aProviderInstalls);
- }
- aCaller.callNext();
- });
- },
-
- noMoreObjects: function(aCaller) {
- safeCall(aCallback, installs);
- }
- });
- },
-
- /**
- * Asynchronously gets all current AddonInstalls.
- *
- * @param aCallback
- * A callback which will be passed an array of AddonInstalls
- */
- getAllInstalls: function(aCallback) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- this.getInstallsByTypes(null, aCallback);
- },
-
- /**
- * Synchronously map a URI to the corresponding Addon ID.
- *
- * Mappable URIs are limited to in-application resources belonging to the
- * add-on, such as Javascript compartments, XUL windows, XBL bindings, etc.
- * but do not include URIs from meta data, such as the add-on homepage.
- *
- * @param aURI
- * nsIURI to map to an addon id
- * @return string containing the Addon ID or null
- * @see amIAddonManager.mapURIToAddonID
- */
- mapURIToAddonID: function(aURI) {
- if (!(aURI instanceof Ci.nsIURI)) {
- throw Components.Exception("aURI is not a nsIURI",
- Cr.NS_ERROR_INVALID_ARG);
- }
-
- // Try all providers
- let providers = [...this.providers];
- for (let provider of providers) {
- var id = callProvider(provider, "mapURIToAddonID", null, aURI);
- if (id !== null) {
- return id;
- }
- }
-
- return null;
- },
-
- /**
- * Checks whether installation is enabled for a particular mimetype.
- *
- * @param aMimetype
- * The mimetype to check
- * @return true if installation is enabled for the mimetype
- */
- isInstallEnabled: function(aMimetype) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!aMimetype || typeof aMimetype != "string")
- throw Components.Exception("aMimetype must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- let providers = [...this.providers];
- for (let provider of providers) {
- if (callProvider(provider, "supportsMimetype", false, aMimetype) &&
- callProvider(provider, "isInstallEnabled"))
- return true;
- }
- return false;
- },
-
- /**
- * Checks whether a particular source is allowed to install add-ons of a
- * given mimetype.
- *
- * @param aMimetype
- * The mimetype of the add-on
- * @param aInstallingPrincipal
- * The nsIPrincipal that initiated the install
- * @return true if the source is allowed to install this mimetype
- */
- isInstallAllowed: function(aMimetype, aInstallingPrincipal) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!aMimetype || typeof aMimetype != "string")
- throw Components.Exception("aMimetype must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!aInstallingPrincipal || !(aInstallingPrincipal instanceof Ci.nsIPrincipal))
- throw Components.Exception("aInstallingPrincipal must be a nsIPrincipal",
- Cr.NS_ERROR_INVALID_ARG);
-
- let providers = [...this.providers];
- for (let provider of providers) {
- if (callProvider(provider, "supportsMimetype", false, aMimetype) &&
- callProvider(provider, "isInstallAllowed", null, aInstallingPrincipal))
- return true;
- }
- return false;
- },
-
- /**
- * Starts installation of an array of AddonInstalls notifying the registered
- * web install listener of blocked or started installs.
- *
- * @param aMimetype
- * The mimetype of add-ons being installed
- * @param aBrowser
- * The optional browser element that started the installs
- * @param aInstallingPrincipal
- * The nsIPrincipal that initiated the install
- * @param aInstalls
- * The array of AddonInstalls to be installed
- */
- installAddonsFromWebpage: function(aMimetype, aBrowser,
- aInstallingPrincipal, aInstalls) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!aMimetype || typeof aMimetype != "string")
- throw Components.Exception("aMimetype must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (aBrowser && !(aBrowser instanceof Ci.nsIDOMElement))
- throw Components.Exception("aSource must be a nsIDOMElement, or null",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!aInstallingPrincipal || !(aInstallingPrincipal instanceof Ci.nsIPrincipal))
- throw Components.Exception("aInstallingPrincipal must be a nsIPrincipal",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!Array.isArray(aInstalls))
- throw Components.Exception("aInstalls must be an array",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!("@mozilla.org/addons/web-install-listener;1" in Cc)) {
- logger.warn("No web installer available, cancelling all installs");
- for (let install of aInstalls)
- install.cancel();
- return;
- }
-
- // When a chrome in-content UI has loaded a <browser> inside to host a
- // website we want to do our security checks on the inner-browser but
- // notify front-end that install events came from the outer-browser (the
- // main tab's browser). Check this by seeing if the browser we've been
- // passed is in a content type docshell and if so get the outer-browser.
- let topBrowser = aBrowser;
- let docShell = aBrowser.ownerDocument.defaultView
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDocShell)
- .QueryInterface(Ci.nsIDocShellTreeItem);
- if (docShell.itemType == Ci.nsIDocShellTreeItem.typeContent)
- topBrowser = docShell.chromeEventHandler;
-
- try {
- let weblistener = Cc["@mozilla.org/addons/web-install-listener;1"].
- getService(Ci.amIWebInstallListener);
-
- if (!this.isInstallEnabled(aMimetype)) {
- for (let install of aInstalls)
- install.cancel();
-
- weblistener.onWebInstallDisabled(topBrowser, aInstallingPrincipal.URI,
- aInstalls, aInstalls.length);
- return;
- }
- else if (!aBrowser.contentPrincipal || !aInstallingPrincipal.subsumes(aBrowser.contentPrincipal)) {
- for (let install of aInstalls)
- install.cancel();
-
- if (weblistener instanceof Ci.amIWebInstallListener2) {
- weblistener.onWebInstallOriginBlocked(topBrowser, aInstallingPrincipal.URI,
- aInstalls, aInstalls.length);
- }
- return;
- }
-
- // The installs may start now depending on the web install listener,
- // listen for the browser navigating to a new origin and cancel the
- // installs in that case.
- new BrowserListener(aBrowser, aInstallingPrincipal, aInstalls);
-
- if (!this.isInstallAllowed(aMimetype, aInstallingPrincipal)) {
- if (weblistener.onWebInstallBlocked(topBrowser, aInstallingPrincipal.URI,
- aInstalls, aInstalls.length)) {
- for (let install of aInstalls)
- install.install();
- }
- }
- else if (weblistener.onWebInstallRequested(topBrowser, aInstallingPrincipal.URI,
- aInstalls, aInstalls.length)) {
- for (let install of aInstalls)
- install.install();
- }
- }
- catch (e) {
- // In the event that the weblistener throws during instantiation or when
- // calling onWebInstallBlocked or onWebInstallRequested all of the
- // installs should get cancelled.
- logger.warn("Failure calling web installer", e);
- for (let install of aInstalls)
- install.cancel();
- }
- },
-
- /**
- * Adds a new InstallListener if the listener is not already registered.
- *
- * @param aListener
- * The InstallListener to add
- */
- addInstallListener: function(aListener) {
- if (!aListener || typeof aListener != "object")
- throw Components.Exception("aListener must be a InstallListener object",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!this.installListeners.some(function(i) {
- return i == aListener; }))
- this.installListeners.push(aListener);
- },
-
- /**
- * Removes an InstallListener if the listener is registered.
- *
- * @param aListener
- * The InstallListener to remove
- */
- removeInstallListener: function(aListener) {
- if (!aListener || typeof aListener != "object")
- throw Components.Exception("aListener must be a InstallListener object",
- Cr.NS_ERROR_INVALID_ARG);
-
- let pos = 0;
- while (pos < this.installListeners.length) {
- if (this.installListeners[pos] == aListener)
- this.installListeners.splice(pos, 1);
- else
- pos++;
- }
- },
- /*
- * Adds new or overrides existing UpgradeListener.
- *
- * @param aInstanceID
- * The instance ID of an addon to register a listener for.
- * @param aCallback
- * The callback to invoke when updates are available for this addon.
- * @throws if there is no addon matching the instanceID
- */
- addUpgradeListener: function(aInstanceID, aCallback) {
- if (!aInstanceID || typeof aInstanceID != "symbol")
- throw Components.Exception("aInstanceID must be a symbol",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!aCallback || typeof aCallback != "function")
- throw Components.Exception("aCallback must be a function",
- Cr.NS_ERROR_INVALID_ARG);
-
- this.getAddonByInstanceID(aInstanceID).then(wrapper => {
- if (!wrapper) {
- throw Error("No addon matching instanceID:", aInstanceID.toString());
- }
- let addonId = wrapper.addonId();
- logger.debug(`Registering upgrade listener for ${addonId}`);
- this.upgradeListeners.set(addonId, aCallback);
- });
- },
-
- /**
- * Removes an UpgradeListener if the listener is registered.
- *
- * @param aInstanceID
- * The instance ID of the addon to remove
- */
- removeUpgradeListener: function(aInstanceID) {
- if (!aInstanceID || typeof aInstanceID != "symbol")
- throw Components.Exception("aInstanceID must be a symbol",
- Cr.NS_ERROR_INVALID_ARG);
-
- this.getAddonByInstanceID(aInstanceID).then(addon => {
- if (!addon) {
- throw Error("No addon for instanceID:", aInstanceID.toString());
- }
- if (this.upgradeListeners.has(addon.id)) {
- this.upgradeListeners.delete(addon.id);
- } else {
- throw Error("No upgrade listener registered for addon ID:", addon.id);
- }
- });
- },
-
- /**
- * Installs a temporary add-on from a local file or directory.
- * @param aFile
- * An nsIFile for the file or directory of the add-on to be
- * temporarily installed.
- * @return a Promise that rejects if the add-on is not a valid restartless
- * add-on or if the same ID is already temporarily installed.
- */
- installTemporaryAddon: function(aFile) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!(aFile instanceof Ci.nsIFile))
- throw Components.Exception("aFile must be a nsIFile",
- Cr.NS_ERROR_INVALID_ARG);
-
- return AddonManagerInternal._getProviderByName("XPIProvider")
- .installTemporaryAddon(aFile);
- },
-
- installAddonFromSources: function(aFile) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!(aFile instanceof Ci.nsIFile))
- throw Components.Exception("aFile must be a nsIFile",
- Cr.NS_ERROR_INVALID_ARG);
-
- return AddonManagerInternal._getProviderByName("XPIProvider")
- .installAddonFromSources(aFile);
- },
-
- /**
- * Returns an Addon corresponding to an instance ID.
- * @param aInstanceID
- * An Addon Instance ID symbol
- * @return {Promise}
- * @resolves The found Addon or null if no such add-on exists.
- * @rejects Never
- * @throws if the aInstanceID argument is not specified
- * or the AddonManager is not initialized
- */
- getAddonByInstanceID: function(aInstanceID) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!aInstanceID || typeof aInstanceID != "symbol")
- throw Components.Exception("aInstanceID must be a Symbol()",
- Cr.NS_ERROR_INVALID_ARG);
-
- return AddonManagerInternal._getProviderByName("XPIProvider")
- .getAddonByInstanceID(aInstanceID);
- },
-
- /**
- * Gets an icon from the icon set provided by the add-on
- * that is closest to the specified size.
- *
- * The optional window parameter will be used to determine
- * the screen resolution and select a more appropriate icon.
- * Calling this method with 48px on retina screens will try to
- * match an icon of size 96px.
- *
- * @param aAddon
- * An addon object, meaning:
- * An object with either an icons property that is a key-value
- * list of icon size and icon URL, or an object having an iconURL
- * and icon64URL property.
- * @param aSize
- * Ideal icon size in pixels
- * @param aWindow
- * Optional window object for determining the correct scale.
- * @return {String} The absolute URL of the icon or null if the addon doesn't have icons
- */
- getPreferredIconURL: function(aAddon, aSize, aWindow = undefined) {
- if (aWindow && aWindow.devicePixelRatio) {
- aSize *= aWindow.devicePixelRatio;
- }
-
- let icons = aAddon.icons;
-
- // certain addon-types only have iconURLs
- if (!icons) {
- icons = {};
- if (aAddon.iconURL) {
- icons[32] = aAddon.iconURL;
- icons[48] = aAddon.iconURL;
- }
- if (aAddon.icon64URL) {
- icons[64] = aAddon.icon64URL;
- }
- }
-
- // quick return if the exact size was found
- if (icons[aSize]) {
- return icons[aSize];
- }
-
- let bestSize = null;
-
- for (let size of Object.keys(icons)) {
- if (!INTEGER.test(size)) {
- throw Components.Exception("Invalid icon size, must be an integer",
- Cr.NS_ERROR_ILLEGAL_VALUE);
- }
-
- size = parseInt(size, 10);
-
- if (!bestSize) {
- bestSize = size;
- continue;
- }
-
- if (size > aSize && bestSize > aSize) {
- // If both best size and current size are larger than the wanted size then choose
- // the one closest to the wanted size
- bestSize = Math.min(bestSize, size);
- }
- else {
- // Otherwise choose the largest of the two so we'll prefer sizes as close to below aSize
- // or above aSize
- bestSize = Math.max(bestSize, size);
- }
- }
-
- return icons[bestSize] || null;
- },
-
- /**
- * Asynchronously gets an add-on with a specific ID.
- *
- * @param aID
- * The ID of the add-on to retrieve
- * @return {Promise}
- * @resolves The found Addon or null if no such add-on exists.
- * @rejects Never
- * @throws if the aID argument is not specified
- */
- getAddonByID: function(aID) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!aID || typeof aID != "string")
- throw Components.Exception("aID must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- let promises = Array.from(this.providers,
- p => promiseCallProvider(p, "getAddonByID", aID));
- return Promise.all(promises).then(aAddons => {
- return aAddons.find(a => !!a) || null;
- });
- },
-
- /**
- * Asynchronously get an add-on with a specific Sync GUID.
- *
- * @param aGUID
- * String GUID of add-on to retrieve
- * @param aCallback
- * The callback to pass the retrieved add-on to.
- * @throws if the aGUID or aCallback arguments are not specified
- */
- getAddonBySyncGUID: function(aGUID, aCallback) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!aGUID || typeof aGUID != "string")
- throw Components.Exception("aGUID must be a non-empty string",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (typeof aCallback != "function")
- throw Components.Exception("aCallback must be a function",
- Cr.NS_ERROR_INVALID_ARG);
-
- new AsyncObjectCaller(this.providers, "getAddonBySyncGUID", {
- nextObject: function(aCaller, aProvider) {
- callProviderAsync(aProvider, "getAddonBySyncGUID", aGUID,
- function(aAddon) {
- if (aAddon) {
- safeCall(aCallback, aAddon);
- } else {
- aCaller.callNext();
- }
- });
- },
-
- noMoreObjects: function(aCaller) {
- safeCall(aCallback, null);
- }
- });
- },
-
- /**
- * Asynchronously gets an array of add-ons.
- *
- * @param aIDs
- * The array of IDs to retrieve
- * @return {Promise}
- * @resolves The array of found add-ons.
- * @rejects Never
- * @throws if the aIDs argument is not specified
- */
- getAddonsByIDs: function(aIDs) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (!Array.isArray(aIDs))
- throw Components.Exception("aIDs must be an array",
- Cr.NS_ERROR_INVALID_ARG);
-
- let promises = aIDs.map(a => AddonManagerInternal.getAddonByID(a));
- return Promise.all(promises);
- },
-
- /**
- * Asynchronously gets add-ons of specific types.
- *
- * @param aTypes
- * An optional array of types to retrieve. Each type is a string name
- * @param aCallback
- * The callback to pass an array of Addons to.
- * @throws if the aCallback argument is not specified
- */
- getAddonsByTypes: function(aTypes, aCallback) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (aTypes && !Array.isArray(aTypes))
- throw Components.Exception("aTypes must be an array or null",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (typeof aCallback != "function")
- throw Components.Exception("aCallback must be a function",
- Cr.NS_ERROR_INVALID_ARG);
-
- let addons = [];
-
- new AsyncObjectCaller(this.providers, "getAddonsByTypes", {
- nextObject: function(aCaller, aProvider) {
- callProviderAsync(aProvider, "getAddonsByTypes", aTypes,
- function(aProviderAddons) {
- if (aProviderAddons) {
- addons = addons.concat(aProviderAddons);
- }
- aCaller.callNext();
- });
- },
-
- noMoreObjects: function(aCaller) {
- safeCall(aCallback, addons);
- }
- });
- },
-
- /**
- * Asynchronously gets all installed add-ons.
- *
- * @param aCallback
- * A callback which will be passed an array of Addons
- */
- getAllAddons: function(aCallback) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (typeof aCallback != "function")
- throw Components.Exception("aCallback must be a function",
- Cr.NS_ERROR_INVALID_ARG);
-
- this.getAddonsByTypes(null, aCallback);
- },
-
- /**
- * Asynchronously gets add-ons that have operations waiting for an application
- * restart to complete.
- *
- * @param aTypes
- * An optional array of types to retrieve. Each type is a string name
- * @param aCallback
- * The callback to pass the array of Addons to
- * @throws if the aCallback argument is not specified
- */
- getAddonsWithOperationsByTypes: function(aTypes, aCallback) {
- if (!gStarted)
- throw Components.Exception("AddonManager is not initialized",
- Cr.NS_ERROR_NOT_INITIALIZED);
-
- if (aTypes && !Array.isArray(aTypes))
- throw Components.Exception("aTypes must be an array or null",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (typeof aCallback != "function")
- throw Components.Exception("aCallback must be a function",
- Cr.NS_ERROR_INVALID_ARG);
-
- let addons = [];
-
- new AsyncObjectCaller(this.providers, "getAddonsWithOperationsByTypes", {
- nextObject: function getAddonsWithOperationsByTypes_nextObject
- (aCaller, aProvider) {
- callProviderAsync(aProvider, "getAddonsWithOperationsByTypes", aTypes,
- function getAddonsWithOperationsByTypes_concatAddons
- (aProviderAddons) {
- if (aProviderAddons) {
- addons = addons.concat(aProviderAddons);
- }
- aCaller.callNext();
- });
- },
-
- noMoreObjects: function(caller) {
- safeCall(aCallback, addons);
- }
- });
- },
-
- /**
- * Adds a new AddonManagerListener if the listener is not already registered.
- *
- * @param aListener
- * The listener to add
- */
- addManagerListener: function(aListener) {
- if (!aListener || typeof aListener != "object")
- throw Components.Exception("aListener must be an AddonManagerListener object",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!this.managerListeners.some(i => i == aListener))
- this.managerListeners.push(aListener);
- },
-
- /**
- * Removes an AddonManagerListener if the listener is registered.
- *
- * @param aListener
- * The listener to remove
- */
- removeManagerListener: function(aListener) {
- if (!aListener || typeof aListener != "object")
- throw Components.Exception("aListener must be an AddonManagerListener object",
- Cr.NS_ERROR_INVALID_ARG);
-
- let pos = 0;
- while (pos < this.managerListeners.length) {
- if (this.managerListeners[pos] == aListener)
- this.managerListeners.splice(pos, 1);
- else
- pos++;
- }
- },
-
- /**
- * Adds a new AddonListener if the listener is not already registered.
- *
- * @param aListener
- * The AddonListener to add
- */
- addAddonListener: function(aListener) {
- if (!aListener || typeof aListener != "object")
- throw Components.Exception("aListener must be an AddonListener object",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!this.addonListeners.some(i => i == aListener))
- this.addonListeners.push(aListener);
- },
-
- /**
- * Removes an AddonListener if the listener is registered.
- *
- * @param aListener
- * The AddonListener to remove
- */
- removeAddonListener: function(aListener) {
- if (!aListener || typeof aListener != "object")
- throw Components.Exception("aListener must be an AddonListener object",
- Cr.NS_ERROR_INVALID_ARG);
-
- let pos = 0;
- while (pos < this.addonListeners.length) {
- if (this.addonListeners[pos] == aListener)
- this.addonListeners.splice(pos, 1);
- else
- pos++;
- }
- },
-
- /**
- * Adds a new TypeListener if the listener is not already registered.
- *
- * @param aListener
- * The TypeListener to add
- */
- addTypeListener: function(aListener) {
- if (!aListener || typeof aListener != "object")
- throw Components.Exception("aListener must be a TypeListener object",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!this.typeListeners.some(i => i == aListener))
- this.typeListeners.push(aListener);
- },
-
- /**
- * Removes an TypeListener if the listener is registered.
- *
- * @param aListener
- * The TypeListener to remove
- */
- removeTypeListener: function(aListener) {
- if (!aListener || typeof aListener != "object")
- throw Components.Exception("aListener must be a TypeListener object",
- Cr.NS_ERROR_INVALID_ARG);
-
- let pos = 0;
- while (pos < this.typeListeners.length) {
- if (this.typeListeners[pos] == aListener)
- this.typeListeners.splice(pos, 1);
- else
- pos++;
- }
- },
-
- get addonTypes() {
- // A read-only wrapper around the types dictionary
- return new Proxy(this.types, {
- defineProperty(target, property, descriptor) {
- // Not allowed to define properties
- return false;
- },
-
- deleteProperty(target, property) {
- // Not allowed to delete properties
- return false;
- },
-
- get(target, property, receiver) {
- if (!target.hasOwnProperty(property))
- return undefined;
-
- return target[property].type;
- },
-
- getOwnPropertyDescriptor(target, property) {
- if (!target.hasOwnProperty(property))
- return undefined;
-
- return {
- value: target[property].type,
- writable: false,
- // Claim configurability to maintain the proxy invariants.
- configurable: true,
- enumerable: true
- }
- },
-
- preventExtensions(target) {
- // Not allowed to prevent adding new properties
- return false;
- },
-
- set(target, property, value, receiver) {
- // Not allowed to set properties
- return false;
- },
-
- setPrototypeOf(target, prototype) {
- // Not allowed to change prototype
- return false;
- }
- });
- },
-
- get autoUpdateDefault() {
- return gAutoUpdateDefault;
- },
-
- set autoUpdateDefault(aValue) {
- aValue = !!aValue;
- if (aValue != gAutoUpdateDefault)
- Services.prefs.setBoolPref(PREF_EM_AUTOUPDATE_DEFAULT, aValue);
- return aValue;
- },
-
- get checkCompatibility() {
- return gCheckCompatibility;
- },
-
- set checkCompatibility(aValue) {
- aValue = !!aValue;
- if (aValue != gCheckCompatibility) {
- if (!aValue)
- Services.prefs.setBoolPref(PREF_EM_CHECK_COMPATIBILITY, false);
- else
- Services.prefs.clearUserPref(PREF_EM_CHECK_COMPATIBILITY);
- }
- return aValue;
- },
-
- get strictCompatibility() {
- return gStrictCompatibility;
- },
-
- set strictCompatibility(aValue) {
- aValue = !!aValue;
- if (aValue != gStrictCompatibility)
- Services.prefs.setBoolPref(PREF_EM_STRICT_COMPATIBILITY, aValue);
- return aValue;
- },
-
- get checkUpdateSecurityDefault() {
- return gCheckUpdateSecurityDefault;
- },
-
- get checkUpdateSecurity() {
- return gCheckUpdateSecurity;
- },
-
- set checkUpdateSecurity(aValue) {
- aValue = !!aValue;
- if (aValue != gCheckUpdateSecurity) {
- if (aValue != gCheckUpdateSecurityDefault)
- Services.prefs.setBoolPref(PREF_EM_CHECK_UPDATE_SECURITY, aValue);
- else
- Services.prefs.clearUserPref(PREF_EM_CHECK_UPDATE_SECURITY);
- }
- return aValue;
- },
-
- get updateEnabled() {
- return gUpdateEnabled;
- },
-
- set updateEnabled(aValue) {
- aValue = !!aValue;
- if (aValue != gUpdateEnabled)
- Services.prefs.setBoolPref(PREF_EM_UPDATE_ENABLED, aValue);
- return aValue;
- },
-
- get hotfixID() {
- return gHotfixID;
- },
-
- webAPI: {
- // installs maps integer ids to AddonInstall instances.
- installs: new Map(),
- nextInstall: 0,
-
- sendEvent: null,
- setEventHandler(fn) {
- this.sendEvent = fn;
- },
-
- getAddonByID(target, id) {
- return new Promise(resolve => {
- AddonManager.getAddonByID(id, (addon) => {
- resolve(webAPIForAddon(addon));
- });
- });
- },
-
- // helper to copy (and convert) the properties we care about
- copyProps(install, obj) {
- obj.state = AddonManager.stateToString(install.state);
- obj.error = AddonManager.errorToString(install.error);
- obj.progress = install.progress;
- obj.maxProgress = install.maxProgress;
- },
-
- makeListener(id, mm) {
- const events = [
- "onDownloadStarted",
- "onDownloadProgress",
- "onDownloadEnded",
- "onDownloadCancelled",
- "onDownloadFailed",
- "onInstallStarted",
- "onInstallEnded",
- "onInstallCancelled",
- "onInstallFailed",
- ];
-
- let listener = {};
- events.forEach(event => {
- listener[event] = (install) => {
- let data = {event, id};
- AddonManager.webAPI.copyProps(install, data);
- this.sendEvent(mm, data);
- }
- });
- return listener;
- },
-
- forgetInstall(id) {
- let info = this.installs.get(id);
- if (!info) {
- throw new Error(`forgetInstall cannot find ${id}`);
- }
- info.install.removeListener(info.listener);
- this.installs.delete(id);
- },
-
- createInstall(target, options) {
- // Throw an appropriate error if the given URL is not valid
- // as an installation source. Return silently if it is okay.
- function checkInstallUrl(url) {
- let host = Services.io.newURI(options.url, null, null).host;
- if (WEBAPI_INSTALL_HOSTS.includes(host)) {
- return;
- }
- if (Services.prefs.getBoolPref(PREF_WEBAPI_TESTING)
- && WEBAPI_TEST_INSTALL_HOSTS.includes(host)) {
- return;
- }
-
- throw new Error(`Install from ${host} not permitted`);
- }
-
- return new Promise((resolve, reject) => {
- try {
- checkInstallUrl(options.url);
- } catch (err) {
- reject({message: err.message});
- return;
- }
-
- let newInstall = install => {
- let id = this.nextInstall++;
- let listener = this.makeListener(id, target.messageManager);
- install.addListener(listener);
-
- this.installs.set(id, {install, target, listener});
-
- let result = {id};
- this.copyProps(install, result);
- resolve(result);
- };
- AddonManager.getInstallForURL(options.url, newInstall, "application/x-xpinstall", options.hash);
- });
- },
-
- addonUninstall(target, id) {
- return new Promise(resolve => {
- AddonManager.getAddonByID(id, addon => {
- if (!addon) {
- resolve(false);
- }
-
- try {
- addon.uninstall();
- resolve(true);
- } catch (err) {
- Cu.reportError(err);
- resolve(false);
- }
- });
- });
- },
-
- addonSetEnabled(target, id, value) {
- return new Promise((resolve, reject) => {
- AddonManager.getAddonByID(id, addon => {
- if (!addon) {
- reject({message: `No such addon ${id}`});
- }
- addon.userDisabled = !value;
- resolve();
- });
- });
- },
-
- addonInstallDoInstall(target, id) {
- let state = this.installs.get(id);
- if (!state) {
- return Promise.reject(`invalid id ${id}`);
- }
- return Promise.resolve(state.install.install());
- },
-
- addonInstallCancel(target, id) {
- let state = this.installs.get(id);
- if (!state) {
- return Promise.reject(`invalid id ${id}`);
- }
- return Promise.resolve(state.install.cancel());
- },
-
- clearInstalls(ids) {
- for (let id of ids) {
- this.forgetInstall(id);
- }
- },
-
- clearInstallsFrom(mm) {
- for (let [id, info] of this.installs) {
- if (info.target.messageManager == mm) {
- this.forgetInstall(id);
- }
- }
- },
- },
-};
-
-/**
- * Should not be used outside of core Mozilla code. This is a private API for
- * the startup and platform integration code to use. Refer to the methods on
- * AddonManagerInternal for documentation however note that these methods are
- * subject to change at any time.
- */
-this.AddonManagerPrivate = {
- startup: function() {
- AddonManagerInternal.startup();
- },
-
- registerProvider: function(aProvider, aTypes) {
- AddonManagerInternal.registerProvider(aProvider, aTypes);
- },
-
- unregisterProvider: function(aProvider) {
- AddonManagerInternal.unregisterProvider(aProvider);
- },
-
- markProviderSafe: function(aProvider) {
- AddonManagerInternal.markProviderSafe(aProvider);
- },
-
- backgroundUpdateCheck: function() {
- return AddonManagerInternal.backgroundUpdateCheck();
- },
-
- backgroundUpdateTimerHandler() {
- // Don't call through to the real update check if no checks are enabled.
- let checkHotfix = AddonManagerInternal.hotfixID &&
- Services.prefs.getBoolPref(PREF_APP_UPDATE_ENABLED) &&
- Services.prefs.getBoolPref(PREF_APP_UPDATE_AUTO);
-
- if (!AddonManagerInternal.updateEnabled && !checkHotfix) {
- logger.info("Skipping background update check");
- return;
- }
- // Don't return the promise here, since the caller doesn't care.
- AddonManagerInternal.backgroundUpdateCheck();
- },
-
- addStartupChange: function(aType, aID) {
- AddonManagerInternal.addStartupChange(aType, aID);
- },
-
- removeStartupChange: function(aType, aID) {
- AddonManagerInternal.removeStartupChange(aType, aID);
- },
-
- notifyAddonChanged: function(aID, aType, aPendingRestart) {
- AddonManagerInternal.notifyAddonChanged(aID, aType, aPendingRestart);
- },
-
- updateAddonAppDisabledStates: function() {
- AddonManagerInternal.updateAddonAppDisabledStates();
- },
-
- updateAddonRepositoryData: function(aCallback) {
- AddonManagerInternal.updateAddonRepositoryData(aCallback);
- },
-
- callInstallListeners: function(...aArgs) {
- return AddonManagerInternal.callInstallListeners.apply(AddonManagerInternal,
- aArgs);
- },
-
- callAddonListeners: function(...aArgs) {
- AddonManagerInternal.callAddonListeners.apply(AddonManagerInternal, aArgs);
- },
-
- AddonAuthor: AddonAuthor,
-
- AddonScreenshot: AddonScreenshot,
-
- AddonCompatibilityOverride: AddonCompatibilityOverride,
-
- AddonType: AddonType,
-
- recordTimestamp: function(name, value) {
- AddonManagerInternal.recordTimestamp(name, value);
- },
-
- _simpleMeasures: {},
- recordSimpleMeasure: function(name, value) {
- this._simpleMeasures[name] = value;
- },
-
- recordException: function(aModule, aContext, aException) {
- let report = {
- module: aModule,
- context: aContext
- };
-
- if (typeof aException == "number") {
- report.message = Components.Exception("", aException).name;
- }
- else {
- report.message = aException.toString();
- if (aException.fileName) {
- report.file = aException.fileName;
- report.line = aException.lineNumber;
- }
- }
-
- this._simpleMeasures.exception = report;
- },
-
- getSimpleMeasures: function() {
- return this._simpleMeasures;
- },
-
- getTelemetryDetails: function() {
- return AddonManagerInternal.telemetryDetails;
- },
-
- setTelemetryDetails: function(aProvider, aDetails) {
- AddonManagerInternal.telemetryDetails[aProvider] = aDetails;
- },
-
- // Start a timer, record a simple measure of the time interval when
- // timer.done() is called
- simpleTimer: function(aName) {
- let startTime = Cu.now();
- return {
- done: () => this.recordSimpleMeasure(aName, Math.round(Cu.now() - startTime))
- };
- },
-
- /**
- * Helper to call update listeners when no update is available.
- *
- * This can be used as an implementation for Addon.findUpdates() when
- * no update mechanism is available.
- */
- callNoUpdateListeners: function(addon, listener, reason, appVersion, platformVersion) {
- if ("onNoCompatibilityUpdateAvailable" in listener) {
- safeCall(listener.onNoCompatibilityUpdateAvailable.bind(listener), addon);
- }
- if ("onNoUpdateAvailable" in listener) {
- safeCall(listener.onNoUpdateAvailable.bind(listener), addon);
- }
- if ("onUpdateFinished" in listener) {
- safeCall(listener.onUpdateFinished.bind(listener), addon);
- }
- },
-
- get webExtensionsMinPlatformVersion() {
- return gWebExtensionsMinPlatformVersion;
- },
-
- hasUpgradeListener: function(aId) {
- return AddonManagerInternal.upgradeListeners.has(aId);
- },
-
- getUpgradeListener: function(aId) {
- return AddonManagerInternal.upgradeListeners.get(aId);
- },
-};
-
-/**
- * This is the public API that UI and developers should be calling. All methods
- * just forward to AddonManagerInternal.
- */
-this.AddonManager = {
- // Constants for the AddonInstall.state property
- // These will show up as AddonManager.STATE_* (eg, STATE_AVAILABLE)
- _states: new Map([
- // The install is available for download.
- ["STATE_AVAILABLE", 0],
- // The install is being downloaded.
- ["STATE_DOWNLOADING", 1],
- // The install is checking for compatibility information.
- ["STATE_CHECKING", 2],
- // The install is downloaded and ready to install.
- ["STATE_DOWNLOADED", 3],
- // The download failed.
- ["STATE_DOWNLOAD_FAILED", 4],
- // The install has been postponed.
- ["STATE_POSTPONED", 5],
- // The add-on is being installed.
- ["STATE_INSTALLING", 6],
- // The add-on has been installed.
- ["STATE_INSTALLED", 7],
- // The install failed.
- ["STATE_INSTALL_FAILED", 8],
- // The install has been cancelled.
- ["STATE_CANCELLED", 9],
- ]),
-
- // Constants representing different types of errors while downloading an
- // add-on.
- // These will show up as AddonManager.ERROR_* (eg, ERROR_NETWORK_FAILURE)
- _errors: new Map([
- // The download failed due to network problems.
- ["ERROR_NETWORK_FAILURE", -1],
- // The downloaded file did not match the provided hash.
- ["ERROR_INCORRECT_HASH", -2],
- // The downloaded file seems to be corrupted in some way.
- ["ERROR_CORRUPT_FILE", -3],
- // An error occured trying to write to the filesystem.
- ["ERROR_FILE_ACCESS", -4],
- // The add-on must be signed and isn't.
- ["ERROR_SIGNEDSTATE_REQUIRED", -5],
- // The downloaded add-on had a different type than expected.
- ["ERROR_UNEXPECTED_ADDON_TYPE", -6],
- // The addon did not have the expected ID
- ["ERROR_INCORRECT_ID", -7],
- ]),
-
- // These must be kept in sync with AddonUpdateChecker.
- // No error was encountered.
- UPDATE_STATUS_NO_ERROR: 0,
- // The update check timed out
- UPDATE_STATUS_TIMEOUT: -1,
- // There was an error while downloading the update information.
- UPDATE_STATUS_DOWNLOAD_ERROR: -2,
- // The update information was malformed in some way.
- UPDATE_STATUS_PARSE_ERROR: -3,
- // The update information was not in any known format.
- UPDATE_STATUS_UNKNOWN_FORMAT: -4,
- // The update information was not correctly signed or there was an SSL error.
- UPDATE_STATUS_SECURITY_ERROR: -5,
- // The update was cancelled.
- UPDATE_STATUS_CANCELLED: -6,
-
- // Constants to indicate why an update check is being performed
- // Update check has been requested by the user.
- UPDATE_WHEN_USER_REQUESTED: 1,
- // Update check is necessary to see if the Addon is compatibile with a new
- // version of the application.
- UPDATE_WHEN_NEW_APP_DETECTED: 2,
- // Update check is necessary because a new application has been installed.
- UPDATE_WHEN_NEW_APP_INSTALLED: 3,
- // Update check is a regular background update check.
- UPDATE_WHEN_PERIODIC_UPDATE: 16,
- // Update check is needed to check an Addon that is being installed.
- UPDATE_WHEN_ADDON_INSTALLED: 17,
-
- // Constants for operations in Addon.pendingOperations
- // Indicates that the Addon has no pending operations.
- PENDING_NONE: 0,
- // Indicates that the Addon will be enabled after the application restarts.
- PENDING_ENABLE: 1,
- // Indicates that the Addon will be disabled after the application restarts.
- PENDING_DISABLE: 2,
- // Indicates that the Addon will be uninstalled after the application restarts.
- PENDING_UNINSTALL: 4,
- // Indicates that the Addon will be installed after the application restarts.
- PENDING_INSTALL: 8,
- PENDING_UPGRADE: 16,
-
- // Constants for operations in Addon.operationsRequiringRestart
- // Indicates that restart isn't required for any operation.
- OP_NEEDS_RESTART_NONE: 0,
- // Indicates that restart is required for enabling the addon.
- OP_NEEDS_RESTART_ENABLE: 1,
- // Indicates that restart is required for disabling the addon.
- OP_NEEDS_RESTART_DISABLE: 2,
- // Indicates that restart is required for uninstalling the addon.
- OP_NEEDS_RESTART_UNINSTALL: 4,
- // Indicates that restart is required for installing the addon.
- OP_NEEDS_RESTART_INSTALL: 8,
-
- // Constants for permissions in Addon.permissions.
- // Indicates that the Addon can be uninstalled.
- PERM_CAN_UNINSTALL: 1,
- // Indicates that the Addon can be enabled by the user.
- PERM_CAN_ENABLE: 2,
- // Indicates that the Addon can be disabled by the user.
- PERM_CAN_DISABLE: 4,
- // Indicates that the Addon can be upgraded.
- PERM_CAN_UPGRADE: 8,
- // Indicates that the Addon can be set to be optionally enabled
- // on a case-by-case basis.
- PERM_CAN_ASK_TO_ACTIVATE: 16,
-
- // General descriptions of where items are installed.
- // Installed in this profile.
- SCOPE_PROFILE: 1,
- // Installed for all of this user's profiles.
- SCOPE_USER: 2,
- // Installed and owned by the application.
- SCOPE_APPLICATION: 4,
- // Installed for all users of the computer.
- SCOPE_SYSTEM: 8,
- // Installed temporarily
- SCOPE_TEMPORARY: 16,
- // The combination of all scopes.
- SCOPE_ALL: 31,
-
- // Add-on type is expected to be displayed in the UI in a list.
- VIEW_TYPE_LIST: "list",
-
- // Constants describing how add-on types behave.
-
- // If no add-ons of a type are installed, then the category for that add-on
- // type should be hidden in the UI.
- TYPE_UI_HIDE_EMPTY: 16,
- // Indicates that this add-on type supports the ask-to-activate state.
- // That is, add-ons of this type can be set to be optionally enabled
- // on a case-by-case basis.
- TYPE_SUPPORTS_ASK_TO_ACTIVATE: 32,
- // The add-on type natively supports undo for restartless uninstalls.
- // If this flag is not specified, the UI is expected to handle this via
- // disabling the add-on, and performing the actual uninstall at a later time.
- TYPE_SUPPORTS_UNDO_RESTARTLESS_UNINSTALL: 64,
-
- // Constants for Addon.applyBackgroundUpdates.
- // Indicates that the Addon should not update automatically.
- AUTOUPDATE_DISABLE: 0,
- // Indicates that the Addon should update automatically only if
- // that's the global default.
- AUTOUPDATE_DEFAULT: 1,
- // Indicates that the Addon should update automatically.
- AUTOUPDATE_ENABLE: 2,
-
- // Constants for how Addon options should be shown.
- // Options will be opened in a new window
- OPTIONS_TYPE_DIALOG: 1,
- // Options will be displayed within the AM detail view
- OPTIONS_TYPE_INLINE: 2,
- // Options will be displayed in a new tab, if possible
- OPTIONS_TYPE_TAB: 3,
- // Same as OPTIONS_TYPE_INLINE, but no Preferences button will be shown.
- // Used to indicate that only non-interactive information will be shown.
- OPTIONS_TYPE_INLINE_INFO: 4,
- // Similar to OPTIONS_TYPE_INLINE, but rather than generating inline
- // options from a specially-formatted XUL file, the contents of the
- // file are simply displayed in an inline <browser> element.
- OPTIONS_TYPE_INLINE_BROWSER: 5,
-
- // Constants for displayed or hidden options notifications
- // Options notification will be displayed
- OPTIONS_NOTIFICATION_DISPLAYED: "addon-options-displayed",
- // Options notification will be hidden
- OPTIONS_NOTIFICATION_HIDDEN: "addon-options-hidden",
-
- // Constants for getStartupChanges, addStartupChange and removeStartupChange
- // Add-ons that were detected as installed during startup. Doesn't include
- // add-ons that were pending installation the last time the application ran.
- STARTUP_CHANGE_INSTALLED: "installed",
- // Add-ons that were detected as changed during startup. This includes an
- // add-on moving to a different location, changing version or just having
- // been detected as possibly changed.
- STARTUP_CHANGE_CHANGED: "changed",
- // Add-ons that were detected as uninstalled during startup. Doesn't include
- // add-ons that were pending uninstallation the last time the application ran.
- STARTUP_CHANGE_UNINSTALLED: "uninstalled",
- // Add-ons that were detected as disabled during startup, normally because of
- // an application change making an add-on incompatible. Doesn't include
- // add-ons that were pending being disabled the last time the application ran.
- STARTUP_CHANGE_DISABLED: "disabled",
- // Add-ons that were detected as enabled during startup, normally because of
- // an application change making an add-on compatible. Doesn't include
- // add-ons that were pending being enabled the last time the application ran.
- STARTUP_CHANGE_ENABLED: "enabled",
-
- // Constants for Addon.signedState. Any states that should cause an add-on
- // to be unusable in builds that require signing should have negative values.
- // Add-on signing is not required, e.g. because the pref is disabled.
- SIGNEDSTATE_NOT_REQUIRED: undefined,
- // Add-on is signed but signature verification has failed.
- SIGNEDSTATE_BROKEN: -2,
- // Add-on may be signed but by an certificate that doesn't chain to our
- // our trusted certificate.
- SIGNEDSTATE_UNKNOWN: -1,
- // Add-on is unsigned.
- SIGNEDSTATE_MISSING: 0,
- // Add-on is preliminarily reviewed.
- SIGNEDSTATE_PRELIMINARY: 1,
- // Add-on is fully reviewed.
- SIGNEDSTATE_SIGNED: 2,
- // Add-on is system add-on.
- SIGNEDSTATE_SYSTEM: 3,
-
- // Constants for the Addon.userDisabled property
- // Indicates that the userDisabled state of this add-on is currently
- // ask-to-activate. That is, it can be conditionally enabled on a
- // case-by-case basis.
- STATE_ASK_TO_ACTIVATE: "askToActivate",
-
- get __AddonManagerInternal__() {
- return AppConstants.DEBUG ? AddonManagerInternal : undefined;
- },
-
- get isReady() {
- return gStartupComplete && !gShutdownInProgress;
- },
-
- init() {
- this._stateToString = new Map();
- for (let [name, value] of this._states) {
- this[name] = value;
- this._stateToString.set(value, name);
- }
- this._errorToString = new Map();
- for (let [name, value] of this._errors) {
- this[name] = value;
- this._errorToString.set(value, name);
- }
- },
-
- stateToString(state) {
- return this._stateToString.get(state);
- },
-
- errorToString(err) {
- return err ? this._errorToString.get(err) : null;
- },
-
- getInstallForURL: function(aUrl, aCallback, aMimetype,
- aHash, aName, aIcons,
- aVersion, aBrowser) {
- AddonManagerInternal.getInstallForURL(aUrl, aCallback, aMimetype, aHash,
- aName, aIcons, aVersion, aBrowser);
- },
-
- getInstallForFile: function(aFile, aCallback, aMimetype) {
- AddonManagerInternal.getInstallForFile(aFile, aCallback, aMimetype);
- },
-
- /**
- * Gets an array of add-on IDs that changed during the most recent startup.
- *
- * @param aType
- * The type of startup change to get
- * @return An array of add-on IDs
- */
- getStartupChanges: function(aType) {
- if (!(aType in AddonManagerInternal.startupChanges))
- return [];
- return AddonManagerInternal.startupChanges[aType].slice(0);
- },
-
- getAddonByID: function(aID, aCallback) {
- if (typeof aCallback != "function")
- throw Components.Exception("aCallback must be a function",
- Cr.NS_ERROR_INVALID_ARG);
-
- AddonManagerInternal.getAddonByID(aID)
- .then(makeSafe(aCallback))
- .catch(logger.error);
- },
-
- getAddonBySyncGUID: function(aGUID, aCallback) {
- AddonManagerInternal.getAddonBySyncGUID(aGUID, aCallback);
- },
-
- getAddonsByIDs: function(aIDs, aCallback) {
- if (typeof aCallback != "function")
- throw Components.Exception("aCallback must be a function",
- Cr.NS_ERROR_INVALID_ARG);
-
- AddonManagerInternal.getAddonsByIDs(aIDs)
- .then(makeSafe(aCallback))
- .catch(logger.error);
- },
-
- getAddonsWithOperationsByTypes: function(aTypes, aCallback) {
- AddonManagerInternal.getAddonsWithOperationsByTypes(aTypes, aCallback);
- },
-
- getAddonsByTypes: function(aTypes, aCallback) {
- AddonManagerInternal.getAddonsByTypes(aTypes, aCallback);
- },
-
- getAllAddons: function(aCallback) {
- AddonManagerInternal.getAllAddons(aCallback);
- },
-
- getInstallsByTypes: function(aTypes, aCallback) {
- AddonManagerInternal.getInstallsByTypes(aTypes, aCallback);
- },
-
- getAllInstalls: function(aCallback) {
- AddonManagerInternal.getAllInstalls(aCallback);
- },
-
- mapURIToAddonID: function(aURI) {
- return AddonManagerInternal.mapURIToAddonID(aURI);
- },
-
- isInstallEnabled: function(aType) {
- return AddonManagerInternal.isInstallEnabled(aType);
- },
-
- isInstallAllowed: function(aType, aInstallingPrincipal) {
- return AddonManagerInternal.isInstallAllowed(aType, aInstallingPrincipal);
- },
-
- installAddonsFromWebpage: function(aType, aBrowser, aInstallingPrincipal,
- aInstalls) {
- AddonManagerInternal.installAddonsFromWebpage(aType, aBrowser,
- aInstallingPrincipal,
- aInstalls);
- },
-
- installTemporaryAddon: function(aDirectory) {
- return AddonManagerInternal.installTemporaryAddon(aDirectory);
- },
-
- installAddonFromSources: function(aDirectory) {
- return AddonManagerInternal.installAddonFromSources(aDirectory);
- },
-
- getAddonByInstanceID: function(aInstanceID) {
- return AddonManagerInternal.getAddonByInstanceID(aInstanceID);
- },
-
- addManagerListener: function(aListener) {
- AddonManagerInternal.addManagerListener(aListener);
- },
-
- removeManagerListener: function(aListener) {
- AddonManagerInternal.removeManagerListener(aListener);
- },
-
- addInstallListener: function(aListener) {
- AddonManagerInternal.addInstallListener(aListener);
- },
-
- removeInstallListener: function(aListener) {
- AddonManagerInternal.removeInstallListener(aListener);
- },
-
- getUpgradeListener: function(aId) {
- return AddonManagerInternal.upgradeListeners.get(aId);
- },
-
- addUpgradeListener: function(aInstanceID, aCallback) {
- AddonManagerInternal.addUpgradeListener(aInstanceID, aCallback);
- },
-
- removeUpgradeListener: function(aInstanceID) {
- AddonManagerInternal.removeUpgradeListener(aInstanceID);
- },
-
- addAddonListener: function(aListener) {
- AddonManagerInternal.addAddonListener(aListener);
- },
-
- removeAddonListener: function(aListener) {
- AddonManagerInternal.removeAddonListener(aListener);
- },
-
- addTypeListener: function(aListener) {
- AddonManagerInternal.addTypeListener(aListener);
- },
-
- removeTypeListener: function(aListener) {
- AddonManagerInternal.removeTypeListener(aListener);
- },
-
- get addonTypes() {
- return AddonManagerInternal.addonTypes;
- },
-
- /**
- * Determines whether an Addon should auto-update or not.
- *
- * @param aAddon
- * The Addon representing the add-on
- * @return true if the addon should auto-update, false otherwise.
- */
- shouldAutoUpdate: function(aAddon) {
- if (!aAddon || typeof aAddon != "object")
- throw Components.Exception("aAddon must be specified",
- Cr.NS_ERROR_INVALID_ARG);
-
- if (!("applyBackgroundUpdates" in aAddon))
- return false;
- if (aAddon.applyBackgroundUpdates == AddonManager.AUTOUPDATE_ENABLE)
- return true;
- if (aAddon.applyBackgroundUpdates == AddonManager.AUTOUPDATE_DISABLE)
- return false;
- return this.autoUpdateDefault;
- },
-
- get checkCompatibility() {
- return AddonManagerInternal.checkCompatibility;
- },
-
- set checkCompatibility(aValue) {
- AddonManagerInternal.checkCompatibility = aValue;
- },
-
- get strictCompatibility() {
- return AddonManagerInternal.strictCompatibility;
- },
-
- set strictCompatibility(aValue) {
- AddonManagerInternal.strictCompatibility = aValue;
- },
-
- get checkUpdateSecurityDefault() {
- return AddonManagerInternal.checkUpdateSecurityDefault;
- },
-
- get checkUpdateSecurity() {
- return AddonManagerInternal.checkUpdateSecurity;
- },
-
- set checkUpdateSecurity(aValue) {
- AddonManagerInternal.checkUpdateSecurity = aValue;
- },
-
- get updateEnabled() {
- return AddonManagerInternal.updateEnabled;
- },
-
- set updateEnabled(aValue) {
- AddonManagerInternal.updateEnabled = aValue;
- },
-
- get autoUpdateDefault() {
- return AddonManagerInternal.autoUpdateDefault;
- },
-
- set autoUpdateDefault(aValue) {
- AddonManagerInternal.autoUpdateDefault = aValue;
- },
-
- get hotfixID() {
- return AddonManagerInternal.hotfixID;
- },
-
- escapeAddonURI: function(aAddon, aUri, aAppVersion) {
- return AddonManagerInternal.escapeAddonURI(aAddon, aUri, aAppVersion);
- },
-
- getPreferredIconURL: function(aAddon, aSize, aWindow = undefined) {
- return AddonManagerInternal.getPreferredIconURL(aAddon, aSize, aWindow);
- },
-
- get webAPI() {
- return AddonManagerInternal.webAPI;
- },
-
- get shutdown() {
- return gShutdownBarrier.client;
- },
-};
-
-this.AddonManager.init();
-
-// load the timestamps module into AddonManagerInternal
-Cu.import("resource://gre/modules/TelemetryTimestamps.jsm", AddonManagerInternal);
-Object.freeze(AddonManagerInternal);
-Object.freeze(AddonManagerPrivate);
-Object.freeze(AddonManager);
diff --git a/toolkit/mozapps/webextensions/AddonManagerWebAPI.cpp b/toolkit/mozapps/webextensions/AddonManagerWebAPI.cpp
deleted file mode 100644
index 3f2a7a529..000000000
--- a/toolkit/mozapps/webextensions/AddonManagerWebAPI.cpp
+++ /dev/null
@@ -1,171 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#include "AddonManagerWebAPI.h"
-
-#include "mozilla/dom/Navigator.h"
-#include "mozilla/dom/NavigatorBinding.h"
-
-#include "mozilla/Preferences.h"
-#include "nsGlobalWindow.h"
-
-#include "nsIDocShell.h"
-#include "nsIScriptObjectPrincipal.h"
-
-namespace mozilla {
-using namespace mozilla::dom;
-
-static bool
-IsValidHost(const nsACString& host) {
- // This is ugly, but Preferences.h doesn't have support
- // for default prefs or locked prefs
- nsCOMPtr<nsIPrefService> prefService (do_GetService(NS_PREFSERVICE_CONTRACTID));
- nsCOMPtr<nsIPrefBranch> prefs;
- if (prefService) {
- prefService->GetDefaultBranch(nullptr, getter_AddRefs(prefs));
- bool isEnabled;
- if (NS_SUCCEEDED(prefs->GetBoolPref("xpinstall.enabled", &isEnabled)) && !isEnabled) {
- bool isLocked;
- prefs->PrefIsLocked("xpinstall.enabled", &isLocked);
- if (isLocked) {
- return false;
- }
- }
- }
-
- if (host.Equals("addons.mozilla.org") ||
- host.Equals("discovery.addons.mozilla.org") ||
- host.Equals("testpilot.firefox.com")) {
- return true;
- }
-
- // When testing allow access to the developer sites.
- if (Preferences::GetBool("extensions.webapi.testing", false)) {
- if (host.LowerCaseEqualsLiteral("addons.allizom.org") ||
- host.LowerCaseEqualsLiteral("discovery.addons.allizom.org") ||
- host.LowerCaseEqualsLiteral("addons-dev.allizom.org") ||
- host.LowerCaseEqualsLiteral("discovery.addons-dev.allizom.org") ||
- host.LowerCaseEqualsLiteral("testpilot.stage.mozaws.net") ||
- host.LowerCaseEqualsLiteral("testpilot.dev.mozaws.net") ||
- host.LowerCaseEqualsLiteral("example.com")) {
- return true;
- }
- }
-
- return false;
-}
-
-// Checks if the given uri is secure and matches one of the hosts allowed to
-// access the API.
-bool
-AddonManagerWebAPI::IsValidSite(nsIURI* uri)
-{
- if (!uri) {
- return false;
- }
-
- bool isSecure;
- nsresult rv = uri->SchemeIs("https", &isSecure);
- if (NS_FAILED(rv) || !isSecure) {
- return false;
- }
-
- nsAutoCString host;
- rv = uri->GetHost(host);
- if (NS_FAILED(rv)) {
- return false;
- }
-
- return IsValidHost(host);
-}
-
-bool
-AddonManagerWebAPI::IsAPIEnabled(JSContext* cx, JSObject* obj)
-{
- nsGlobalWindow* global = xpc::WindowGlobalOrNull(obj);
- if (!global) {
- return false;
- }
-
- nsCOMPtr<nsPIDOMWindowInner> win = global->AsInner();
- if (!win) {
- return false;
- }
-
- // Check that the current window and all parent frames are allowed access to
- // the API.
- while (win) {
- nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(win);
- if (!sop) {
- return false;
- }
-
- nsCOMPtr<nsIPrincipal> principal = sop->GetPrincipal();
- if (!principal) {
- return false;
- }
-
- // Reaching a window with a system principal means we have reached
- // privileged UI of some kind so stop at this point and allow access.
- if (principal->GetIsSystemPrincipal()) {
- return true;
- }
-
- nsCOMPtr<nsIDocShell> docShell = win->GetDocShell();
- if (!docShell) {
- // This window has been torn down so don't allow access to the API.
- return false;
- }
-
- if (!IsValidSite(win->GetDocumentURI())) {
- return false;
- }
-
- // Checks whether there is a parent frame of the same type. This won't cross
- // mozbrowser or chrome boundaries.
- nsCOMPtr<nsIDocShellTreeItem> parent;
- nsresult rv = docShell->GetSameTypeParent(getter_AddRefs(parent));
- if (NS_FAILED(rv)) {
- return false;
- }
-
- if (!parent) {
- // No parent means we've hit a mozbrowser or chrome boundary so allow
- // access to the API.
- return true;
- }
-
- nsIDocument* doc = win->GetDoc();
- if (!doc) {
- return false;
- }
-
- doc = doc->GetParentDocument();
- if (!doc) {
- // Getting here means something has been torn down so fail safe.
- return false;
- }
-
-
- win = doc->GetInnerWindow();
- }
-
- // Found a document with no inner window, don't grant access to the API.
- return false;
-}
-
-namespace dom {
-
-bool
-AddonManagerPermissions::IsHostPermitted(const GlobalObject& /*unused*/, const nsAString& host)
-{
- return IsValidHost(NS_ConvertUTF16toUTF8(host));
-}
-
-} // namespace mozilla::dom
-
-
-} // namespace mozilla
diff --git a/toolkit/mozapps/webextensions/AddonManagerWebAPI.h b/toolkit/mozapps/webextensions/AddonManagerWebAPI.h
deleted file mode 100644
index 6830bc91f..000000000
--- a/toolkit/mozapps/webextensions/AddonManagerWebAPI.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#ifndef addonmanagerwebapi_h_
-#define addonmanagerwebapi_h_
-
-#include "nsPIDOMWindow.h"
-
-namespace mozilla {
-
-class AddonManagerWebAPI {
-public:
- static bool IsAPIEnabled(JSContext* cx, JSObject* obj);
-
-private:
- static bool IsValidSite(nsIURI* uri);
-};
-
-namespace dom {
-
-class AddonManagerPermissions {
-public:
- static bool IsHostPermitted(const GlobalObject&, const nsAString& host);
-};
-
-} // namespace mozilla::dom
-
-} // namespace mozilla
-
-#endif // addonmanagerwebapi_h_
diff --git a/toolkit/mozapps/webextensions/AddonPathService.cpp b/toolkit/mozapps/webextensions/AddonPathService.cpp
deleted file mode 100644
index 8a405c0ea..000000000
--- a/toolkit/mozapps/webextensions/AddonPathService.cpp
+++ /dev/null
@@ -1,258 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 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/. */
-
-#include "AddonPathService.h"
-
-#include "amIAddonManager.h"
-#include "nsIURI.h"
-#include "nsXULAppAPI.h"
-#include "jsapi.h"
-#include "nsServiceManagerUtils.h"
-#include "nsLiteralString.h"
-#include "nsThreadUtils.h"
-#include "nsIIOService.h"
-#include "nsNetUtil.h"
-#include "nsIAddonPolicyService.h"
-#include "nsIFileURL.h"
-#include "nsIResProtocolHandler.h"
-#include "nsIChromeRegistry.h"
-#include "nsIJARURI.h"
-#include "nsJSUtils.h"
-#include "mozilla/dom/ScriptSettings.h"
-#include "mozilla/dom/ToJSValue.h"
-#include "mozilla/AddonPathService.h"
-#include "mozilla/Omnijar.h"
-
-#include <algorithm>
-
-namespace mozilla {
-
-struct PathEntryComparator
-{
- typedef AddonPathService::PathEntry PathEntry;
-
- bool Equals(const PathEntry& entry1, const PathEntry& entry2) const
- {
- return entry1.mPath == entry2.mPath;
- }
-
- bool LessThan(const PathEntry& entry1, const PathEntry& entry2) const
- {
- return entry1.mPath < entry2.mPath;
- }
-};
-
-AddonPathService::AddonPathService()
-{
-}
-
-AddonPathService::~AddonPathService()
-{
- sInstance = nullptr;
-}
-
-NS_IMPL_ISUPPORTS(AddonPathService, amIAddonPathService)
-
-AddonPathService *AddonPathService::sInstance;
-
-/* static */ AddonPathService*
-AddonPathService::GetInstance()
-{
- if (!sInstance) {
- sInstance = new AddonPathService();
- }
- NS_ADDREF(sInstance);
- return sInstance;
-}
-
-static JSAddonId*
-ConvertAddonId(const nsAString& addonIdString)
-{
- AutoSafeJSContext cx;
- JS::RootedValue strv(cx);
- if (!mozilla::dom::ToJSValue(cx, addonIdString, &strv)) {
- return nullptr;
- }
- JS::RootedString str(cx, strv.toString());
- return JS::NewAddonId(cx, str);
-}
-
-JSAddonId*
-AddonPathService::Find(const nsAString& path)
-{
- // Use binary search to find the nearest entry that is <= |path|.
- PathEntryComparator comparator;
- unsigned index = mPaths.IndexOfFirstElementGt(PathEntry(path, nullptr), comparator);
- if (index == 0) {
- return nullptr;
- }
- const PathEntry& entry = mPaths[index - 1];
-
- // Return the entry's addon if its path is a prefix of |path|.
- if (StringBeginsWith(path, entry.mPath)) {
- return entry.mAddonId;
- }
- return nullptr;
-}
-
-NS_IMETHODIMP
-AddonPathService::FindAddonId(const nsAString& path, nsAString& addonIdString)
-{
- if (JSAddonId* id = Find(path)) {
- JSFlatString* flat = JS_ASSERT_STRING_IS_FLAT(JS::StringOfAddonId(id));
- AssignJSFlatString(addonIdString, flat);
- }
- return NS_OK;
-}
-
-/* static */ JSAddonId*
-AddonPathService::FindAddonId(const nsAString& path)
-{
- // If no service has been created, then we're not going to find anything.
- if (!sInstance) {
- return nullptr;
- }
-
- return sInstance->Find(path);
-}
-
-NS_IMETHODIMP
-AddonPathService::InsertPath(const nsAString& path, const nsAString& addonIdString)
-{
- JSAddonId* addonId = ConvertAddonId(addonIdString);
-
- // Add the new path in sorted order.
- PathEntryComparator comparator;
- mPaths.InsertElementSorted(PathEntry(path, addonId), comparator);
- return NS_OK;
-}
-
-NS_IMETHODIMP
-AddonPathService::MapURIToAddonId(nsIURI* aURI, nsAString& addonIdString)
-{
- if (JSAddonId* id = MapURIToAddonID(aURI)) {
- JSFlatString* flat = JS_ASSERT_STRING_IS_FLAT(JS::StringOfAddonId(id));
- AssignJSFlatString(addonIdString, flat);
- }
- return NS_OK;
-}
-
-static nsresult
-ResolveURI(nsIURI* aURI, nsAString& out)
-{
- bool equals;
- nsresult rv;
- nsCOMPtr<nsIURI> uri;
- nsAutoCString spec;
-
- // Resolve resource:// URIs. At the end of this if/else block, we
- // have both spec and uri variables identifying the same URI.
- if (NS_SUCCEEDED(aURI->SchemeIs("resource", &equals)) && equals) {
- nsCOMPtr<nsIIOService> ioService = do_GetIOService(&rv);
- if (NS_WARN_IF(NS_FAILED(rv)))
- return rv;
-
- nsCOMPtr<nsIProtocolHandler> ph;
- rv = ioService->GetProtocolHandler("resource", getter_AddRefs(ph));
- if (NS_WARN_IF(NS_FAILED(rv)))
- return rv;
-
- nsCOMPtr<nsIResProtocolHandler> irph(do_QueryInterface(ph, &rv));
- if (NS_WARN_IF(NS_FAILED(rv)))
- return rv;
-
- rv = irph->ResolveURI(aURI, spec);
- if (NS_WARN_IF(NS_FAILED(rv)))
- return rv;
-
- rv = ioService->NewURI(spec, nullptr, nullptr, getter_AddRefs(uri));
- if (NS_WARN_IF(NS_FAILED(rv)))
- return rv;
- } else if (NS_SUCCEEDED(aURI->SchemeIs("chrome", &equals)) && equals) {
- nsCOMPtr<nsIChromeRegistry> chromeReg =
- mozilla::services::GetChromeRegistryService();
- if (NS_WARN_IF(!chromeReg))
- return NS_ERROR_UNEXPECTED;
-
- rv = chromeReg->ConvertChromeURL(aURI, getter_AddRefs(uri));
- if (NS_WARN_IF(NS_FAILED(rv)))
- return rv;
- } else {
- uri = aURI;
- }
-
- if (NS_SUCCEEDED(uri->SchemeIs("jar", &equals)) && equals) {
- nsCOMPtr<nsIJARURI> jarURI = do_QueryInterface(uri, &rv);
- if (NS_WARN_IF(NS_FAILED(rv)))
- return rv;
-
- nsCOMPtr<nsIURI> jarFileURI;
- rv = jarURI->GetJARFile(getter_AddRefs(jarFileURI));
- if (NS_WARN_IF(NS_FAILED(rv)))
- return rv;
-
- return ResolveURI(jarFileURI, out);
- }
-
- if (NS_SUCCEEDED(uri->SchemeIs("file", &equals)) && equals) {
- nsCOMPtr<nsIFileURL> baseFileURL = do_QueryInterface(uri, &rv);
- if (NS_WARN_IF(NS_FAILED(rv)))
- return rv;
-
- nsCOMPtr<nsIFile> file;
- rv = baseFileURL->GetFile(getter_AddRefs(file));
- if (NS_WARN_IF(NS_FAILED(rv)))
- return rv;
-
- return file->GetPath(out);
- }
- return NS_ERROR_FAILURE;
-}
-
-JSAddonId*
-MapURIToAddonID(nsIURI* aURI)
-{
- if (!NS_IsMainThread() || !XRE_IsParentProcess()) {
- return nullptr;
- }
-
- bool equals;
- nsresult rv;
- if (NS_SUCCEEDED(aURI->SchemeIs("moz-extension", &equals)) && equals) {
- nsCOMPtr<nsIAddonPolicyService> service = do_GetService("@mozilla.org/addons/policy-service;1");
- if (service) {
- nsString addonId;
- rv = service->ExtensionURIToAddonId(aURI, addonId);
- if (NS_FAILED(rv))
- return nullptr;
-
- return ConvertAddonId(addonId);
- }
- }
-
- nsAutoString filePath;
- rv = ResolveURI(aURI, filePath);
- if (NS_FAILED(rv))
- return nullptr;
-
- nsCOMPtr<nsIFile> greJar = Omnijar::GetPath(Omnijar::GRE);
- nsCOMPtr<nsIFile> appJar = Omnijar::GetPath(Omnijar::APP);
- if (greJar && appJar) {
- nsAutoString greJarString, appJarString;
- if (NS_FAILED(greJar->GetPath(greJarString)) || NS_FAILED(appJar->GetPath(appJarString)))
- return nullptr;
-
- // If |aURI| is part of either Omnijar, then it can't be part of an
- // add-on. This catches pretty much all URLs for Firefox content.
- if (filePath.Equals(greJarString) || filePath.Equals(appJarString))
- return nullptr;
- }
-
- // If it's not part of Firefox, we resort to binary searching through the
- // add-on paths.
- return AddonPathService::FindAddonId(filePath);
-}
-
-} // namespace mozilla
diff --git a/toolkit/mozapps/webextensions/AddonPathService.h b/toolkit/mozapps/webextensions/AddonPathService.h
deleted file mode 100644
index f739b018f..000000000
--- a/toolkit/mozapps/webextensions/AddonPathService.h
+++ /dev/null
@@ -1,55 +0,0 @@
-//* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 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/. */
-
-#ifndef AddonPathService_h
-#define AddonPathService_h
-
-#include "amIAddonPathService.h"
-#include "nsString.h"
-#include "nsTArray.h"
-
-class nsIURI;
-class JSAddonId;
-
-namespace mozilla {
-
-JSAddonId*
-MapURIToAddonID(nsIURI* aURI);
-
-class AddonPathService final : public amIAddonPathService
-{
-public:
- AddonPathService();
-
- static AddonPathService* GetInstance();
-
- JSAddonId* Find(const nsAString& path);
- static JSAddonId* FindAddonId(const nsAString& path);
-
- NS_DECL_ISUPPORTS
- NS_DECL_AMIADDONPATHSERVICE
-
- struct PathEntry
- {
- nsString mPath;
- JSAddonId* mAddonId;
-
- PathEntry(const nsAString& aPath, JSAddonId* aAddonId)
- : mPath(aPath), mAddonId(aAddonId)
- {}
- };
-
-private:
- virtual ~AddonPathService();
-
- // Paths are stored sorted in order of their mPath.
- nsTArray<PathEntry> mPaths;
-
- static AddonPathService* sInstance;
-};
-
-} // namespace mozilla
-
-#endif
diff --git a/toolkit/mozapps/webextensions/GMPInstallManager.jsm b/toolkit/mozapps/webextensions/GMPInstallManager.jsm
deleted file mode 100644
index b5987ca55..000000000
--- a/toolkit/mozapps/webextensions/GMPInstallManager.jsm
+++ /dev/null
@@ -1,523 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-this.EXPORTED_SYMBOLS = [];
-
-const {classes: Cc, interfaces: Ci, results: Cr, utils: Cu, manager: Cm} =
- Components;
-// 1 day default
-const DEFAULT_SECONDS_BETWEEN_CHECKS = 60 * 60 * 24;
-
-var GMPInstallFailureReason = {
- GMP_INVALID: 1,
- GMP_HIDDEN: 2,
- GMP_DISABLED: 3,
- GMP_UPDATE_DISABLED: 4,
-};
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/FileUtils.jsm");
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/Preferences.jsm");
-Cu.import("resource://gre/modules/Log.jsm");
-Cu.import("resource://gre/modules/osfile.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/GMPUtils.jsm");
-Cu.import("resource://gre/modules/addons/ProductAddonChecker.jsm");
-
-this.EXPORTED_SYMBOLS = ["GMPInstallManager", "GMPExtractor", "GMPDownloader",
- "GMPAddon"];
-
-// Shared code for suppressing bad cert dialogs
-XPCOMUtils.defineLazyGetter(this, "gCertUtils", function() {
- let temp = { };
- Cu.import("resource://gre/modules/CertUtils.jsm", temp);
- return temp;
-});
-
-XPCOMUtils.defineLazyModuleGetter(this, "UpdateUtils",
- "resource://gre/modules/UpdateUtils.jsm");
-
-function getScopedLogger(prefix) {
- // `PARENT_LOGGER_ID.` being passed here effectively links this logger
- // to the parentLogger.
- return Log.repository.getLoggerWithMessagePrefix("Toolkit.GMP", prefix + " ");
-}
-
-/**
- * Provides an easy API for downloading and installing GMP Addons
- */
-function GMPInstallManager() {
-}
-/**
- * Temp file name used for downloading
- */
-GMPInstallManager.prototype = {
- /**
- * Obtains a URL with replacement of vars
- */
- _getURL: function() {
- let log = getScopedLogger("GMPInstallManager._getURL");
- // Use the override URL if it is specified. The override URL is just like
- // the normal URL but it does not check the cert.
- let url = GMPPrefs.get(GMPPrefs.KEY_URL_OVERRIDE);
- if (url) {
- log.info("Using override url: " + url);
- } else {
- url = GMPPrefs.get(GMPPrefs.KEY_URL);
- log.info("Using url: " + url);
- }
-
- url = UpdateUtils.formatUpdateURL(url);
-
- log.info("Using url (with replacement): " + url);
- return url;
- },
- /**
- * Performs an addon check.
- * @return a promise which will be resolved or rejected.
- * The promise is resolved with an object with properties:
- * gmpAddons: array of GMPAddons
- * usedFallback: whether the data was collected from online or
- * from fallback data within the build
- * The promise is rejected with an object with properties:
- * target: The XHR request object
- * status: The HTTP status code
- * type: Sometimes specifies type of rejection
- */
- checkForAddons: function() {
- let log = getScopedLogger("GMPInstallManager.checkForAddons");
- if (this._deferred) {
- log.error("checkForAddons already called");
- return Promise.reject({type: "alreadycalled"});
- }
- this._deferred = Promise.defer();
- let url = this._getURL();
-
- let allowNonBuiltIn = true;
- let certs = null;
- if (!Services.prefs.prefHasUserValue(GMPPrefs.KEY_URL_OVERRIDE)) {
- allowNonBuiltIn = !GMPPrefs.get(GMPPrefs.KEY_CERT_REQUIREBUILTIN, true);
- if (GMPPrefs.get(GMPPrefs.KEY_CERT_CHECKATTRS, true)) {
- certs = gCertUtils.readCertPrefs(GMPPrefs.KEY_CERTS_BRANCH);
- }
- }
-
- let addonPromise = ProductAddonChecker
- .getProductAddonList(url, allowNonBuiltIn, certs);
-
- addonPromise.then(res => {
- if (!res || !res.gmpAddons) {
- this._deferred.resolve({gmpAddons: []});
- }
- else {
- res.gmpAddons = res.gmpAddons.map(a => new GMPAddon(a));
- this._deferred.resolve(res);
- }
- delete this._deferred;
- }, (ex) => {
- this._deferred.reject(ex);
- delete this._deferred;
- });
-
- return this._deferred.promise;
- },
- /**
- * Installs the specified addon and calls a callback when done.
- * @param gmpAddon The GMPAddon object to install
- * @return a promise which will be resolved or rejected
- * The promise will resolve with an array of paths that were extracted
- * The promise will reject with an error object:
- * target: The XHR request object
- * status: The HTTP status code
- * type: A string to represent the type of error
- * downloaderr, verifyerr or previouserrorencountered
- */
- installAddon: function(gmpAddon) {
- if (this._deferred) {
- log.error("previous error encountered");
- return Promise.reject({type: "previouserrorencountered"});
- }
- this.gmpDownloader = new GMPDownloader(gmpAddon);
- return this.gmpDownloader.start();
- },
- _getTimeSinceLastCheck: function() {
- let now = Math.round(Date.now() / 1000);
- // Default to 0 here because `now - 0` will be returned later if that case
- // is hit. We want a large value so a check will occur.
- let lastCheck = GMPPrefs.get(GMPPrefs.KEY_UPDATE_LAST_CHECK, 0);
- // Handle clock jumps, return now since we want it to represent
- // a lot of time has passed since the last check.
- if (now < lastCheck) {
- return now;
- }
- return now - lastCheck;
- },
- get _isEMEEnabled() {
- return GMPPrefs.get(GMPPrefs.KEY_EME_ENABLED, true);
- },
- _isAddonEnabled: function(aAddon) {
- return GMPPrefs.get(GMPPrefs.KEY_PLUGIN_ENABLED, true, aAddon);
- },
- _isAddonUpdateEnabled: function(aAddon) {
- return this._isAddonEnabled(aAddon) &&
- GMPPrefs.get(GMPPrefs.KEY_PLUGIN_AUTOUPDATE, true, aAddon);
- },
- _updateLastCheck: function() {
- let now = Math.round(Date.now() / 1000);
- GMPPrefs.set(GMPPrefs.KEY_UPDATE_LAST_CHECK, now);
- },
- _versionchangeOccurred: function() {
- let savedBuildID = GMPPrefs.get(GMPPrefs.KEY_BUILDID, null);
- let buildID = Services.appinfo.platformBuildID;
- if (savedBuildID == buildID) {
- return false;
- }
- GMPPrefs.set(GMPPrefs.KEY_BUILDID, buildID);
- return true;
- },
- /**
- * Wrapper for checkForAddons and installAddon.
- * Will only install if not already installed and will log the results.
- * This will only install/update the OpenH264 and EME plugins
- * @return a promise which will be resolved if all addons could be installed
- * successfully, rejected otherwise.
- */
- simpleCheckAndInstall: Task.async(function*() {
- let log = getScopedLogger("GMPInstallManager.simpleCheckAndInstall");
-
- if (this._versionchangeOccurred()) {
- log.info("A version change occurred. Ignoring " +
- "media.gmp-manager.lastCheck to check immediately for " +
- "new or updated GMPs.");
- } else {
- let secondsBetweenChecks =
- GMPPrefs.get(GMPPrefs.KEY_SECONDS_BETWEEN_CHECKS,
- DEFAULT_SECONDS_BETWEEN_CHECKS)
- let secondsSinceLast = this._getTimeSinceLastCheck();
- log.info("Last check was: " + secondsSinceLast +
- " seconds ago, minimum seconds: " + secondsBetweenChecks);
- if (secondsBetweenChecks > secondsSinceLast) {
- log.info("Will not check for updates.");
- return {status: "too-frequent-no-check"};
- }
- }
-
- try {
- let {usedFallback, gmpAddons} = yield this.checkForAddons();
- this._updateLastCheck();
- log.info("Found " + gmpAddons.length + " addons advertised.");
- let addonsToInstall = gmpAddons.filter(function(gmpAddon) {
- log.info("Found addon: " + gmpAddon.toString());
-
- if (!gmpAddon.isValid) {
- log.info("Addon |" + gmpAddon.id + "| is invalid.");
- return false;
- }
-
- if (GMPUtils.isPluginHidden(gmpAddon)) {
- log.info("Addon |" + gmpAddon.id + "| has been hidden.");
- return false;
- }
-
- if (gmpAddon.isInstalled) {
- log.info("Addon |" + gmpAddon.id + "| already installed.");
- return false;
- }
-
- // Do not install from fallback if already installed as it
- // may be a downgrade
- if (usedFallback && gmpAddon.isUpdate) {
- log.info("Addon |" + gmpAddon.id + "| not installing updates based " +
- "on fallback.");
- return false;
- }
-
- let addonUpdateEnabled = false;
- if (GMP_PLUGIN_IDS.indexOf(gmpAddon.id) >= 0) {
- if (!this._isAddonEnabled(gmpAddon.id)) {
- log.info("GMP |" + gmpAddon.id + "| has been disabled; skipping check.");
- } else if (!this._isAddonUpdateEnabled(gmpAddon.id)) {
- log.info("Auto-update is off for " + gmpAddon.id +
- ", skipping check.");
- } else {
- addonUpdateEnabled = true;
- }
- } else {
- // Currently, we only support installs of OpenH264 and EME plugins.
- log.info("Auto-update is off for unknown plugin '" + gmpAddon.id +
- "', skipping check.");
- }
-
- return addonUpdateEnabled;
- }, this);
-
- if (!addonsToInstall.length) {
- log.info("No new addons to install, returning");
- return {status: "nothing-new-to-install"};
- }
-
- let installResults = [];
- let failureEncountered = false;
- for (let addon of addonsToInstall) {
- try {
- yield this.installAddon(addon);
- installResults.push({
- id: addon.id,
- result: "succeeded",
- });
- } catch (e) {
- failureEncountered = true;
- installResults.push({
- id: addon.id,
- result: "failed",
- });
- }
- }
- if (failureEncountered) {
- throw {status: "failed",
- results: installResults};
- }
- return {status: "succeeded",
- results: installResults};
- } catch (e) {
- log.error("Could not check for addons", e);
- throw e;
- }
- }),
-
- /**
- * Makes sure everything is cleaned up
- */
- uninit: function() {
- let log = getScopedLogger("GMPInstallManager.uninit");
- if (this._request) {
- log.info("Aborting request");
- this._request.abort();
- }
- if (this._deferred) {
- log.info("Rejecting deferred");
- this._deferred.reject({type: "uninitialized"});
- }
- log.info("Done cleanup");
- },
-
- /**
- * If set to true, specifies to leave the temporary downloaded zip file.
- * This is useful for tests.
- */
- overrideLeaveDownloadedZip: false,
-};
-
-/**
- * Used to construct a single GMP addon
- * GMPAddon objects are returns from GMPInstallManager.checkForAddons
- * GMPAddon objects can also be used in calls to GMPInstallManager.installAddon
- *
- * @param addon The ProductAddonChecker `addon` object
- */
-function GMPAddon(addon) {
- let log = getScopedLogger("GMPAddon.constructor");
- for (let name of Object.keys(addon)) {
- this[name] = addon[name];
- }
- log.info ("Created new addon: " + this.toString());
-}
-
-GMPAddon.prototype = {
- /**
- * Returns a string representation of the addon
- */
- toString: function() {
- return this.id + " (" +
- "isValid: " + this.isValid +
- ", isInstalled: " + this.isInstalled +
- ", hashFunction: " + this.hashFunction+
- ", hashValue: " + this.hashValue +
- (this.size !== undefined ? ", size: " + this.size : "" ) +
- ")";
- },
- /**
- * If all the fields aren't specified don't consider this addon valid
- * @return true if the addon is parsed and valid
- */
- get isValid() {
- return this.id && this.URL && this.version &&
- this.hashFunction && !!this.hashValue;
- },
- get isInstalled() {
- return this.version &&
- GMPPrefs.get(GMPPrefs.KEY_PLUGIN_VERSION, "", this.id) === this.version;
- },
- get isEME() {
- return this.id == "gmp-widevinecdm" || this.id.indexOf("gmp-eme-") == 0;
- },
- /**
- * @return true if the addon has been previously installed and this is
- * a new version, if this is a fresh install return false
- */
- get isUpdate() {
- return this.version &&
- GMPPrefs.get(GMPPrefs.KEY_PLUGIN_VERSION, false, this.id);
- },
-};
-/**
- * Constructs a GMPExtractor object which is used to extract a GMP zip
- * into the specified location. (Which typically leties per platform)
- * @param zipPath The path on disk of the zip file to extract
- */
-function GMPExtractor(zipPath, installToDirPath) {
- this.zipPath = zipPath;
- this.installToDirPath = installToDirPath;
-}
-GMPExtractor.prototype = {
- /**
- * Obtains a list of all the entries in a zipfile in the format of *.*.
- * This also includes files inside directories.
- *
- * @param zipReader the nsIZipReader to check
- * @return An array of string name entries which can be used
- * in nsIZipReader.extract
- */
- _getZipEntries: function(zipReader) {
- let entries = [];
- let enumerator = zipReader.findEntries("*.*");
- while (enumerator.hasMore()) {
- entries.push(enumerator.getNext());
- }
- return entries;
- },
- /**
- * Installs the this.zipPath contents into the directory used to store GMP
- * addons for the current platform.
- *
- * @return a promise which will be resolved or rejected
- * See GMPInstallManager.installAddon for resolve/rejected info
- */
- install: function() {
- try {
- let log = getScopedLogger("GMPExtractor.install");
- this._deferred = Promise.defer();
- log.info("Installing " + this.zipPath + "...");
- // Get the input zip file
- let zipFile = Cc["@mozilla.org/file/local;1"].
- createInstance(Ci.nsIFile);
- zipFile.initWithPath(this.zipPath);
-
- // Initialize a zipReader and obtain the entries
- var zipReader = Cc["@mozilla.org/libjar/zip-reader;1"].
- createInstance(Ci.nsIZipReader);
- zipReader.open(zipFile)
- let entries = this._getZipEntries(zipReader);
- let extractedPaths = [];
-
- let destDir = Cc["@mozilla.org/file/local;1"].
- createInstance(Ci.nsILocalFile);
- destDir.initWithPath(this.installToDirPath);
- // Make sure the destination exists
- if (!destDir.exists()) {
- destDir.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt("0755", 8));
- }
-
- // Extract each of the entries
- entries.forEach(entry => {
- // We don't need these types of files
- if (entry.includes("__MACOSX") ||
- entry == "_metadata/verified_contents.json" ||
- entry == "imgs/icon-128x128.png") {
- return;
- }
- let outFile = destDir.clone();
- // Do not extract into directories. Extract all files to the same
- // directory. DO NOT use |OS.Path.basename()| here, as in Windows it
- // does not work properly with forward slashes (which we must use here).
- let outBaseName = entry.slice(entry.lastIndexOf("/") + 1);
- outFile.appendRelativePath(outBaseName);
-
- zipReader.extract(entry, outFile);
- extractedPaths.push(outFile.path);
- // Ensure files are writable and executable. Otherwise we may be unable to
- // execute or uninstall them.
- outFile.permissions |= parseInt("0700", 8);
- log.info(entry + " was successfully extracted to: " +
- outFile.path);
- });
- zipReader.close();
- if (!GMPInstallManager.overrideLeaveDownloadedZip) {
- zipFile.remove(false);
- }
-
- log.info(this.zipPath + " was installed successfully");
- this._deferred.resolve(extractedPaths);
- } catch (e) {
- if (zipReader) {
- zipReader.close();
- }
- this._deferred.reject({
- target: this,
- status: e,
- type: "exception"
- });
- }
- return this._deferred.promise;
- }
-};
-
-
-/**
- * Constructs an object which downloads and initiates an install of
- * the specified GMPAddon object.
- * @param gmpAddon The addon to install.
- */
-function GMPDownloader(gmpAddon)
-{
- this._gmpAddon = gmpAddon;
-}
-
-GMPDownloader.prototype = {
- /**
- * Starts the download process for an addon.
- * @return a promise which will be resolved or rejected
- * See GMPInstallManager.installAddon for resolve/rejected info
- */
- start: function() {
- let log = getScopedLogger("GMPDownloader");
- let gmpAddon = this._gmpAddon;
-
- if (!gmpAddon.isValid) {
- log.info("gmpAddon is not valid, will not continue");
- return Promise.reject({
- target: this,
- status: status,
- type: "downloaderr"
- });
- }
-
- return ProductAddonChecker.downloadAddon(gmpAddon).then((zipPath) => {
- let path = OS.Path.join(OS.Constants.Path.profileDir,
- gmpAddon.id,
- gmpAddon.version);
- log.info("install to directory path: " + path);
- let gmpInstaller = new GMPExtractor(zipPath, path);
- let installPromise = gmpInstaller.install();
- return installPromise.then(extractedPaths => {
- // Success, set the prefs
- let now = Math.round(Date.now() / 1000);
- GMPPrefs.set(GMPPrefs.KEY_PLUGIN_LAST_UPDATE, now, gmpAddon.id);
- // Remember our ABI, so that if the profile is migrated to another
- // platform or from 32 -> 64 bit, we notice and don't try to load the
- // unexecutable plugin library.
- GMPPrefs.set(GMPPrefs.KEY_PLUGIN_ABI, UpdateUtils.ABI, gmpAddon.id);
- // Setting the version pref signals installation completion to consumers,
- // if you need to set other prefs etc. do it before this.
- GMPPrefs.set(GMPPrefs.KEY_PLUGIN_VERSION, gmpAddon.version,
- gmpAddon.id);
- return extractedPaths;
- });
- });
- },
-};
diff --git a/toolkit/mozapps/webextensions/LightweightThemeManager.jsm b/toolkit/mozapps/webextensions/LightweightThemeManager.jsm
deleted file mode 100644
index 5dd41831d..000000000
--- a/toolkit/mozapps/webextensions/LightweightThemeManager.jsm
+++ /dev/null
@@ -1,909 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-this.EXPORTED_SYMBOLS = ["LightweightThemeManager"];
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-Components.utils.import("resource://gre/modules/AddonManager.jsm");
-/* globals AddonManagerPrivate*/
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-const ID_SUFFIX = "@personas.mozilla.org";
-const PREF_LWTHEME_TO_SELECT = "extensions.lwThemeToSelect";
-const PREF_GENERAL_SKINS_SELECTEDSKIN = "general.skins.selectedSkin";
-const PREF_EM_DSS_ENABLED = "extensions.dss.enabled";
-const ADDON_TYPE = "theme";
-
-const URI_EXTENSION_STRINGS = "chrome://mozapps/locale/extensions/extensions.properties";
-
-const STRING_TYPE_NAME = "type.%ID%.name";
-
-const DEFAULT_MAX_USED_THEMES_COUNT = 30;
-
-const MAX_PREVIEW_SECONDS = 30;
-
-const MANDATORY = ["id", "name", "headerURL"];
-const OPTIONAL = ["footerURL", "textcolor", "accentcolor", "iconURL",
- "previewURL", "author", "description", "homepageURL",
- "updateURL", "version"];
-
-const PERSIST_ENABLED = true;
-const PERSIST_BYPASS_CACHE = false;
-const PERSIST_FILES = {
- headerURL: "lightweighttheme-header",
- footerURL: "lightweighttheme-footer"
-};
-
-XPCOMUtils.defineLazyModuleGetter(this, "LightweightThemeImageOptimizer",
- "resource://gre/modules/addons/LightweightThemeImageOptimizer.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ServiceRequest",
- "resource://gre/modules/ServiceRequest.jsm");
-
-
-XPCOMUtils.defineLazyGetter(this, "_prefs", () => {
- return Services.prefs.getBranch("lightweightThemes.");
-});
-
-Object.defineProperty(this, "_maxUsedThemes", {
- get: function() {
- delete this._maxUsedThemes;
- try {
- this._maxUsedThemes = _prefs.getIntPref("maxUsedThemes");
- }
- catch (e) {
- this._maxUsedThemes = DEFAULT_MAX_USED_THEMES_COUNT;
- }
- return this._maxUsedThemes;
- },
-
- set: function(val) {
- delete this._maxUsedThemes;
- return this._maxUsedThemes = val;
- },
- configurable: true,
-});
-
-// Holds the ID of the theme being enabled or disabled while sending out the
-// events so cached AddonWrapper instances can return correct values for
-// permissions and pendingOperations
-var _themeIDBeingEnabled = null;
-var _themeIDBeingDisabled = null;
-
-// Convert from the old storage format (in which the order of usedThemes
-// was combined with isThemeSelected to determine which theme was selected)
-// to the new one (where a selectedThemeID determines which theme is selected).
-(function() {
- let wasThemeSelected = false;
- try {
- wasThemeSelected = _prefs.getBoolPref("isThemeSelected");
- } catch (e) { }
-
- if (wasThemeSelected) {
- _prefs.clearUserPref("isThemeSelected");
- let themes = [];
- try {
- themes = JSON.parse(_prefs.getComplexValue("usedThemes",
- Ci.nsISupportsString).data);
- } catch (e) { }
-
- if (Array.isArray(themes) && themes[0]) {
- _prefs.setCharPref("selectedThemeID", themes[0].id);
- }
- }
-})();
-
-this.LightweightThemeManager = {
- get name() {
- return "LightweightThemeManager";
- },
-
- // Themes that can be added for an application. They can't be removed, and
- // will always show up at the top of the list.
- _builtInThemes: new Map(),
-
- get usedThemes () {
- let themes = [];
- try {
- themes = JSON.parse(_prefs.getComplexValue("usedThemes",
- Ci.nsISupportsString).data);
- } catch (e) { }
-
- themes.push(...this._builtInThemes.values());
- return themes;
- },
-
- get currentTheme () {
- let selectedThemeID = null;
- try {
- selectedThemeID = _prefs.getCharPref("selectedThemeID");
- } catch (e) {}
-
- let data = null;
- if (selectedThemeID) {
- data = this.getUsedTheme(selectedThemeID);
- }
- return data;
- },
-
- get currentThemeForDisplay () {
- var data = this.currentTheme;
-
- if (data && PERSIST_ENABLED) {
- for (let key in PERSIST_FILES) {
- try {
- if (data[key] && _prefs.getBoolPref("persisted." + key))
- data[key] = _getLocalImageURI(PERSIST_FILES[key]).spec
- + "?" + data.id + ";" + _version(data);
- } catch (e) {}
- }
- }
-
- return data;
- },
-
- set currentTheme (aData) {
- return _setCurrentTheme(aData, false);
- },
-
- setLocalTheme: function(aData) {
- _setCurrentTheme(aData, true);
- },
-
- getUsedTheme: function(aId) {
- var usedThemes = this.usedThemes;
- for (let usedTheme of usedThemes) {
- if (usedTheme.id == aId)
- return usedTheme;
- }
- return null;
- },
-
- forgetUsedTheme: function(aId) {
- let theme = this.getUsedTheme(aId);
- if (!theme || LightweightThemeManager._builtInThemes.has(theme.id))
- return;
-
- let wrapper = new AddonWrapper(theme);
- AddonManagerPrivate.callAddonListeners("onUninstalling", wrapper, false);
-
- var currentTheme = this.currentTheme;
- if (currentTheme && currentTheme.id == aId) {
- this.themeChanged(null);
- AddonManagerPrivate.notifyAddonChanged(null, ADDON_TYPE, false);
- }
-
- _updateUsedThemes(_usedThemesExceptId(aId));
- AddonManagerPrivate.callAddonListeners("onUninstalled", wrapper);
- },
-
- addBuiltInTheme: function(theme) {
- if (!theme || !theme.id || this.usedThemes.some(t => t.id == theme.id)) {
- throw new Error("Trying to add invalid builtIn theme");
- }
-
- this._builtInThemes.set(theme.id, theme);
-
- if (_prefs.getCharPref("selectedThemeID") == theme.id) {
- this.currentTheme = theme;
- }
- },
-
- forgetBuiltInTheme: function(id) {
- if (!this._builtInThemes.has(id)) {
- let currentTheme = this.currentTheme;
- if (currentTheme && currentTheme.id == id) {
- this.currentTheme = null;
- }
- }
- return this._builtInThemes.delete(id);
- },
-
- clearBuiltInThemes: function() {
- for (let id of this._builtInThemes.keys()) {
- this.forgetBuiltInTheme(id);
- }
- },
-
- previewTheme: function(aData) {
- let cancel = Cc["@mozilla.org/supports-PRBool;1"].createInstance(Ci.nsISupportsPRBool);
- cancel.data = false;
- Services.obs.notifyObservers(cancel, "lightweight-theme-preview-requested",
- JSON.stringify(aData));
- if (cancel.data)
- return;
-
- if (_previewTimer)
- _previewTimer.cancel();
- else
- _previewTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- _previewTimer.initWithCallback(_previewTimerCallback,
- MAX_PREVIEW_SECONDS * 1000,
- _previewTimer.TYPE_ONE_SHOT);
-
- _notifyWindows(aData);
- },
-
- resetPreview: function() {
- if (_previewTimer) {
- _previewTimer.cancel();
- _previewTimer = null;
- _notifyWindows(this.currentThemeForDisplay);
- }
- },
-
- parseTheme: function(aString, aBaseURI) {
- try {
- return _sanitizeTheme(JSON.parse(aString), aBaseURI, false);
- } catch (e) {
- return null;
- }
- },
-
- updateCurrentTheme: function() {
- try {
- if (!_prefs.getBoolPref("update.enabled"))
- return;
- } catch (e) {
- return;
- }
-
- var theme = this.currentTheme;
- if (!theme || !theme.updateURL)
- return;
-
- var req = new ServiceRequest();
-
- req.mozBackgroundRequest = true;
- req.overrideMimeType("text/plain");
- req.open("GET", theme.updateURL, true);
- // Prevent the request from reading from the cache.
- req.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
- // Prevent the request from writing to the cache.
- req.channel.loadFlags |= Ci.nsIRequest.INHIBIT_CACHING;
-
- req.addEventListener("load", () => {
- if (req.status != 200)
- return;
-
- let newData = this.parseTheme(req.responseText, theme.updateURL);
- if (!newData ||
- newData.id != theme.id ||
- _version(newData) == _version(theme))
- return;
-
- var currentTheme = this.currentTheme;
- if (currentTheme && currentTheme.id == theme.id)
- this.currentTheme = newData;
- }, false);
-
- req.send(null);
- },
-
- /**
- * Switches to a new lightweight theme.
- *
- * @param aData
- * The lightweight theme to switch to
- */
- themeChanged: function(aData) {
- if (_previewTimer) {
- _previewTimer.cancel();
- _previewTimer = null;
- }
-
- if (aData) {
- let usedThemes = _usedThemesExceptId(aData.id);
- usedThemes.unshift(aData);
- _updateUsedThemes(usedThemes);
- if (PERSIST_ENABLED) {
- LightweightThemeImageOptimizer.purge();
- _persistImages(aData, function() {
- _notifyWindows(this.currentThemeForDisplay);
- }.bind(this));
- }
- }
-
- if (aData)
- _prefs.setCharPref("selectedThemeID", aData.id);
- else
- _prefs.setCharPref("selectedThemeID", "");
-
- _notifyWindows(aData);
- Services.obs.notifyObservers(null, "lightweight-theme-changed", null);
- },
-
- /**
- * Starts the Addons provider and enables the new lightweight theme if
- * necessary.
- */
- startup: function() {
- if (Services.prefs.prefHasUserValue(PREF_LWTHEME_TO_SELECT)) {
- let id = Services.prefs.getCharPref(PREF_LWTHEME_TO_SELECT);
- if (id)
- this.themeChanged(this.getUsedTheme(id));
- else
- this.themeChanged(null);
- Services.prefs.clearUserPref(PREF_LWTHEME_TO_SELECT);
- }
-
- _prefs.addObserver("", _prefObserver, false);
- },
-
- /**
- * Shuts down the provider.
- */
- shutdown: function() {
- _prefs.removeObserver("", _prefObserver);
- },
-
- /**
- * Called when a new add-on has been enabled when only one add-on of that type
- * can be enabled.
- *
- * @param aId
- * The ID of the newly enabled add-on
- * @param aType
- * The type of the newly enabled add-on
- * @param aPendingRestart
- * true if the newly enabled add-on will only become enabled after a
- * restart
- */
- addonChanged: function(aId, aType, aPendingRestart) {
- if (aType != ADDON_TYPE)
- return;
-
- let id = _getInternalID(aId);
- let current = this.currentTheme;
-
- try {
- let next = Services.prefs.getCharPref(PREF_LWTHEME_TO_SELECT);
- if (id == next && aPendingRestart)
- return;
-
- Services.prefs.clearUserPref(PREF_LWTHEME_TO_SELECT);
- if (next) {
- AddonManagerPrivate.callAddonListeners("onOperationCancelled",
- new AddonWrapper(this.getUsedTheme(next)));
- }
- else if (id == current.id) {
- AddonManagerPrivate.callAddonListeners("onOperationCancelled",
- new AddonWrapper(current));
- return;
- }
- }
- catch (e) {
- }
-
- if (current) {
- if (current.id == id)
- return;
- _themeIDBeingDisabled = current.id;
- let wrapper = new AddonWrapper(current);
- if (aPendingRestart) {
- Services.prefs.setCharPref(PREF_LWTHEME_TO_SELECT, "");
- AddonManagerPrivate.callAddonListeners("onDisabling", wrapper, true);
- }
- else {
- AddonManagerPrivate.callAddonListeners("onDisabling", wrapper, false);
- this.themeChanged(null);
- AddonManagerPrivate.callAddonListeners("onDisabled", wrapper);
- }
- _themeIDBeingDisabled = null;
- }
-
- if (id) {
- let theme = this.getUsedTheme(id);
- _themeIDBeingEnabled = id;
- let wrapper = new AddonWrapper(theme);
- if (aPendingRestart) {
- AddonManagerPrivate.callAddonListeners("onEnabling", wrapper, true);
- Services.prefs.setCharPref(PREF_LWTHEME_TO_SELECT, id);
-
- // Flush the preferences to disk so they survive any crash
- Services.prefs.savePrefFile(null);
- }
- else {
- AddonManagerPrivate.callAddonListeners("onEnabling", wrapper, false);
- this.themeChanged(theme);
- AddonManagerPrivate.callAddonListeners("onEnabled", wrapper);
- }
- _themeIDBeingEnabled = null;
- }
- },
-
- /**
- * Called to get an Addon with a particular ID.
- *
- * @param aId
- * The ID of the add-on to retrieve
- * @param aCallback
- * A callback to pass the Addon to
- */
- getAddonByID: function(aId, aCallback) {
- let id = _getInternalID(aId);
- if (!id) {
- aCallback(null);
- return;
- }
-
- let theme = this.getUsedTheme(id);
- if (!theme) {
- aCallback(null);
- return;
- }
-
- aCallback(new AddonWrapper(theme));
- },
-
- /**
- * Called to get Addons of a particular type.
- *
- * @param aTypes
- * An array of types to fetch. Can be null to get all types.
- * @param aCallback
- * A callback to pass an array of Addons to
- */
- getAddonsByTypes: function(aTypes, aCallback) {
- if (aTypes && aTypes.indexOf(ADDON_TYPE) == -1) {
- aCallback([]);
- return;
- }
-
- aCallback(this.usedThemes.map(a => new AddonWrapper(a)));
- },
-};
-
-const wrapperMap = new WeakMap();
-let themeFor = wrapper => wrapperMap.get(wrapper);
-
-/**
- * The AddonWrapper wraps lightweight theme to provide the data visible to
- * consumers of the AddonManager API.
- */
-function AddonWrapper(aTheme) {
- wrapperMap.set(this, aTheme);
-}
-
-AddonWrapper.prototype = {
- get id() {
- return themeFor(this).id + ID_SUFFIX;
- },
-
- get type() {
- return ADDON_TYPE;
- },
-
- get isActive() {
- let current = LightweightThemeManager.currentTheme;
- if (current)
- return themeFor(this).id == current.id;
- return false;
- },
-
- get name() {
- return themeFor(this).name;
- },
-
- get version() {
- let theme = themeFor(this);
- return "version" in theme ? theme.version : "";
- },
-
- get creator() {
- let theme = themeFor(this);
- return "author" in theme ? new AddonManagerPrivate.AddonAuthor(theme.author) : null;
- },
-
- get screenshots() {
- let url = themeFor(this).previewURL;
- return [new AddonManagerPrivate.AddonScreenshot(url)];
- },
-
- get pendingOperations() {
- let pending = AddonManager.PENDING_NONE;
- if (this.isActive == this.userDisabled)
- pending |= this.isActive ? AddonManager.PENDING_DISABLE : AddonManager.PENDING_ENABLE;
- return pending;
- },
-
- get operationsRequiringRestart() {
- // If a non-default theme is in use then a restart will be required to
- // enable lightweight themes unless dynamic theme switching is enabled
- if (Services.prefs.prefHasUserValue(PREF_GENERAL_SKINS_SELECTEDSKIN)) {
- try {
- if (Services.prefs.getBoolPref(PREF_EM_DSS_ENABLED))
- return AddonManager.OP_NEEDS_RESTART_NONE;
- }
- catch (e) {
- }
- return AddonManager.OP_NEEDS_RESTART_ENABLE;
- }
-
- return AddonManager.OP_NEEDS_RESTART_NONE;
- },
-
- get size() {
- // The size changes depending on whether the theme is in use or not, this is
- // probably not worth exposing.
- return null;
- },
-
- get permissions() {
- let permissions = 0;
-
- // Do not allow uninstall of builtIn themes.
- if (!LightweightThemeManager._builtInThemes.has(themeFor(this).id))
- permissions = AddonManager.PERM_CAN_UNINSTALL;
- if (this.userDisabled)
- permissions |= AddonManager.PERM_CAN_ENABLE;
- else
- permissions |= AddonManager.PERM_CAN_DISABLE;
- return permissions;
- },
-
- get userDisabled() {
- let id = themeFor(this).id;
- if (_themeIDBeingEnabled == id)
- return false;
- if (_themeIDBeingDisabled == id)
- return true;
-
- try {
- let toSelect = Services.prefs.getCharPref(PREF_LWTHEME_TO_SELECT);
- return id != toSelect;
- }
- catch (e) {
- let current = LightweightThemeManager.currentTheme;
- return !current || current.id != id;
- }
- },
-
- set userDisabled(val) {
- if (val == this.userDisabled)
- return val;
-
- if (val)
- LightweightThemeManager.currentTheme = null;
- else
- LightweightThemeManager.currentTheme = themeFor(this);
-
- return val;
- },
-
- // Lightweight themes are never disabled by the application
- get appDisabled() {
- return false;
- },
-
- // Lightweight themes are always compatible
- get isCompatible() {
- return true;
- },
-
- get isPlatformCompatible() {
- return true;
- },
-
- get scope() {
- return AddonManager.SCOPE_PROFILE;
- },
-
- get foreignInstall() {
- return false;
- },
-
- uninstall: function() {
- LightweightThemeManager.forgetUsedTheme(themeFor(this).id);
- },
-
- cancelUninstall: function() {
- throw new Error("Theme is not marked to be uninstalled");
- },
-
- findUpdates: function(listener, reason, appVersion, platformVersion) {
- AddonManagerPrivate.callNoUpdateListeners(this, listener, reason, appVersion, platformVersion);
- },
-
- // Lightweight themes are always compatible
- isCompatibleWith: function(appVersion, platformVersion) {
- return true;
- },
-
- // Lightweight themes are always securely updated
- get providesUpdatesSecurely() {
- return true;
- },
-
- // Lightweight themes are never blocklisted
- get blocklistState() {
- return Ci.nsIBlocklistService.STATE_NOT_BLOCKED;
- }
-};
-
-["description", "homepageURL", "iconURL"].forEach(function(prop) {
- Object.defineProperty(AddonWrapper.prototype, prop, {
- get: function() {
- let theme = themeFor(this);
- return prop in theme ? theme[prop] : null;
- },
- enumarable: true,
- });
-});
-
-["installDate", "updateDate"].forEach(function(prop) {
- Object.defineProperty(AddonWrapper.prototype, prop, {
- get: function() {
- let theme = themeFor(this);
- return prop in theme ? new Date(theme[prop]) : null;
- },
- enumarable: true,
- });
-});
-
-/**
- * Converts the ID used by the public AddonManager API to an lightweight theme
- * ID.
- *
- * @param id
- * The ID to be converted
- *
- * @return the lightweight theme ID or null if the ID was not for a lightweight
- * theme.
- */
-function _getInternalID(id) {
- if (!id)
- return null;
- let len = id.length - ID_SUFFIX.length;
- if (len > 0 && id.substring(len) == ID_SUFFIX)
- return id.substring(0, len);
- return null;
-}
-
-function _setCurrentTheme(aData, aLocal) {
- aData = _sanitizeTheme(aData, null, aLocal);
-
- let needsRestart = (ADDON_TYPE == "theme") &&
- Services.prefs.prefHasUserValue(PREF_GENERAL_SKINS_SELECTEDSKIN);
-
- let cancel = Cc["@mozilla.org/supports-PRBool;1"].createInstance(Ci.nsISupportsPRBool);
- cancel.data = false;
- Services.obs.notifyObservers(cancel, "lightweight-theme-change-requested",
- JSON.stringify(aData));
-
- if (aData) {
- let theme = LightweightThemeManager.getUsedTheme(aData.id);
- let isInstall = !theme || theme.version != aData.version;
- if (isInstall) {
- aData.updateDate = Date.now();
- if (theme && "installDate" in theme)
- aData.installDate = theme.installDate;
- else
- aData.installDate = aData.updateDate;
-
- var oldWrapper = theme ? new AddonWrapper(theme) : null;
- var wrapper = new AddonWrapper(aData);
- AddonManagerPrivate.callInstallListeners("onExternalInstall", null,
- wrapper, oldWrapper, false);
- AddonManagerPrivate.callAddonListeners("onInstalling", wrapper, false);
- }
-
- let current = LightweightThemeManager.currentTheme;
- let usedThemes = _usedThemesExceptId(aData.id);
- if (current && current.id != aData.id)
- usedThemes.splice(1, 0, aData);
- else
- usedThemes.unshift(aData);
- _updateUsedThemes(usedThemes);
-
- if (isInstall)
- AddonManagerPrivate.callAddonListeners("onInstalled", wrapper);
- }
-
- if (cancel.data)
- return null;
-
- AddonManagerPrivate.notifyAddonChanged(aData ? aData.id + ID_SUFFIX : null,
- ADDON_TYPE, needsRestart);
-
- return LightweightThemeManager.currentTheme;
-}
-
-function _sanitizeTheme(aData, aBaseURI, aLocal) {
- if (!aData || typeof aData != "object")
- return null;
-
- var resourceProtocols = ["http", "https", "resource"];
- if (aLocal)
- resourceProtocols.push("file");
- var resourceProtocolExp = new RegExp("^(" + resourceProtocols.join("|") + "):");
-
- function sanitizeProperty(prop) {
- if (!(prop in aData))
- return null;
- if (typeof aData[prop] != "string")
- return null;
- let val = aData[prop].trim();
- if (!val)
- return null;
-
- if (!/URL$/.test(prop))
- return val;
-
- try {
- val = _makeURI(val, aBaseURI ? _makeURI(aBaseURI) : null).spec;
- if ((prop == "updateURL" ? /^https:/ : resourceProtocolExp).test(val))
- return val;
- return null;
- }
- catch (e) {
- return null;
- }
- }
-
- let result = {};
- for (let mandatoryProperty of MANDATORY) {
- let val = sanitizeProperty(mandatoryProperty);
- if (!val)
- throw Components.results.NS_ERROR_INVALID_ARG;
- result[mandatoryProperty] = val;
- }
-
- for (let optionalProperty of OPTIONAL) {
- let val = sanitizeProperty(optionalProperty);
- if (!val)
- continue;
- result[optionalProperty] = val;
- }
-
- return result;
-}
-
-function _usedThemesExceptId(aId) {
- return LightweightThemeManager.usedThemes.filter(function(t) {
- return "id" in t && t.id != aId;
- });
-}
-
-function _version(aThemeData) {
- return aThemeData.version || "";
-}
-
-function _makeURI(aURL, aBaseURI) {
- return Services.io.newURI(aURL, null, aBaseURI);
-}
-
-function _updateUsedThemes(aList) {
- // Remove app-specific themes before saving them to the usedThemes pref.
- aList = aList.filter(theme => !LightweightThemeManager._builtInThemes.has(theme.id));
-
- // Send uninstall events for all themes that need to be removed.
- while (aList.length > _maxUsedThemes) {
- let wrapper = new AddonWrapper(aList[aList.length - 1]);
- AddonManagerPrivate.callAddonListeners("onUninstalling", wrapper, false);
- aList.pop();
- AddonManagerPrivate.callAddonListeners("onUninstalled", wrapper);
- }
-
- var str = Cc["@mozilla.org/supports-string;1"]
- .createInstance(Ci.nsISupportsString);
- str.data = JSON.stringify(aList);
- _prefs.setComplexValue("usedThemes", Ci.nsISupportsString, str);
-
- Services.obs.notifyObservers(null, "lightweight-theme-list-changed", null);
-}
-
-function _notifyWindows(aThemeData) {
- Services.obs.notifyObservers(null, "lightweight-theme-styling-update",
- JSON.stringify(aThemeData));
-}
-
-var _previewTimer;
-var _previewTimerCallback = {
- notify: function() {
- LightweightThemeManager.resetPreview();
- }
-};
-
-/**
- * Called when any of the lightweightThemes preferences are changed.
- */
-function _prefObserver(aSubject, aTopic, aData) {
- switch (aData) {
- case "maxUsedThemes":
- try {
- _maxUsedThemes = _prefs.getIntPref(aData);
- }
- catch (e) {
- _maxUsedThemes = DEFAULT_MAX_USED_THEMES_COUNT;
- }
- // Update the theme list to remove any themes over the number we keep
- _updateUsedThemes(LightweightThemeManager.usedThemes);
- break;
- }
-}
-
-function _persistImages(aData, aCallback) {
- function onSuccess(key) {
- return function () {
- let current = LightweightThemeManager.currentTheme;
- if (current && current.id == aData.id) {
- _prefs.setBoolPref("persisted." + key, true);
- }
- if (--numFilesToPersist == 0 && aCallback) {
- aCallback();
- }
- };
- }
-
- let numFilesToPersist = 0;
- for (let key in PERSIST_FILES) {
- _prefs.setBoolPref("persisted." + key, false);
- if (aData[key]) {
- numFilesToPersist++;
- _persistImage(aData[key], PERSIST_FILES[key], onSuccess(key));
- }
- }
-}
-
-function _getLocalImageURI(localFileName) {
- var localFile = Services.dirsvc.get("ProfD", Ci.nsIFile);
- localFile.append(localFileName);
- return Services.io.newFileURI(localFile);
-}
-
-function _persistImage(sourceURL, localFileName, successCallback) {
- if (/^(file|resource):/.test(sourceURL))
- return;
-
- var targetURI = _getLocalImageURI(localFileName);
- var sourceURI = _makeURI(sourceURL);
-
- var persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
- .createInstance(Ci.nsIWebBrowserPersist);
-
- persist.persistFlags =
- Ci.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES |
- Ci.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION |
- (PERSIST_BYPASS_CACHE ?
- Ci.nsIWebBrowserPersist.PERSIST_FLAGS_BYPASS_CACHE :
- Ci.nsIWebBrowserPersist.PERSIST_FLAGS_FROM_CACHE);
-
- persist.progressListener = new _persistProgressListener(successCallback);
-
- persist.saveURI(sourceURI, null,
- null, Ci.nsIHttpChannel.REFERRER_POLICY_NO_REFERRER_WHEN_DOWNGRADE,
- null, null, targetURI, null);
-}
-
-function _persistProgressListener(successCallback) {
- this.onLocationChange = function() {};
- this.onProgressChange = function() {};
- this.onStatusChange = function() {};
- this.onSecurityChange = function() {};
- this.onStateChange = function(aWebProgress, aRequest, aStateFlags, aStatus) {
- if (aRequest &&
- aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK &&
- aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) {
- try {
- if (aRequest.QueryInterface(Ci.nsIHttpChannel).requestSucceeded) {
- // success
- successCallback();
- return;
- }
- } catch (e) { }
- // failure
- }
- };
-}
-
-AddonManagerPrivate.registerProvider(LightweightThemeManager, [
- new AddonManagerPrivate.AddonType("theme", URI_EXTENSION_STRINGS,
- STRING_TYPE_NAME,
- AddonManager.VIEW_TYPE_LIST, 5000)
-]);
diff --git a/toolkit/mozapps/webextensions/addonManager.js b/toolkit/mozapps/webextensions/addonManager.js
deleted file mode 100644
index d34cbaf62..000000000
--- a/toolkit/mozapps/webextensions/addonManager.js
+++ /dev/null
@@ -1,296 +0,0 @@
-/* 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/. */
-
-/**
- * This component serves as integration between the platform and AddonManager.
- * It is responsible for initializing and shutting down the AddonManager as well
- * as passing new installs from webpages to the AddonManager.
- */
-
-"use strict";
-
-const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
-
-// The old XPInstall error codes
-const EXECUTION_ERROR = -203;
-const CANT_READ_ARCHIVE = -207;
-const USER_CANCELLED = -210;
-const DOWNLOAD_ERROR = -228;
-const UNSUPPORTED_TYPE = -244;
-const SUCCESS = 0;
-
-const MSG_INSTALL_ENABLED = "WebInstallerIsInstallEnabled";
-const MSG_INSTALL_ADDONS = "WebInstallerInstallAddonsFromWebpage";
-const MSG_INSTALL_CALLBACK = "WebInstallerInstallCallback";
-
-const MSG_PROMISE_REQUEST = "WebAPIPromiseRequest";
-const MSG_PROMISE_RESULT = "WebAPIPromiseResult";
-const MSG_INSTALL_EVENT = "WebAPIInstallEvent";
-const MSG_INSTALL_CLEANUP = "WebAPICleanup";
-const MSG_ADDON_EVENT_REQ = "WebAPIAddonEventRequest";
-const MSG_ADDON_EVENT = "WebAPIAddonEvent";
-
-const CHILD_SCRIPT = "resource://gre/modules/addons/Content.js";
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-var gSingleton = null;
-
-function amManager() {
- Cu.import("resource://gre/modules/AddonManager.jsm");
- /* globals AddonManagerPrivate*/
-
- Services.mm.loadFrameScript(CHILD_SCRIPT, true);
- Services.mm.addMessageListener(MSG_INSTALL_ENABLED, this);
- Services.mm.addMessageListener(MSG_INSTALL_ADDONS, this);
- Services.mm.addMessageListener(MSG_PROMISE_REQUEST, this);
- Services.mm.addMessageListener(MSG_INSTALL_CLEANUP, this);
- Services.mm.addMessageListener(MSG_ADDON_EVENT_REQ, this);
-
- Services.obs.addObserver(this, "message-manager-close", false);
- Services.obs.addObserver(this, "message-manager-disconnect", false);
-
- AddonManager.webAPI.setEventHandler(this.sendEvent);
-
- // Needed so receiveMessage can be called directly by JS callers
- this.wrappedJSObject = this;
-}
-
-amManager.prototype = {
- observe: function(aSubject, aTopic, aData) {
- switch (aTopic) {
- case "addons-startup":
- AddonManagerPrivate.startup();
- break;
-
- case "message-manager-close":
- case "message-manager-disconnect":
- this.childClosed(aSubject);
- break;
- }
- },
-
- /**
- * @see amIAddonManager.idl
- */
- mapURIToAddonID: function(uri, id) {
- id.value = AddonManager.mapURIToAddonID(uri);
- return !!id.value;
- },
-
- /**
- * @see amIWebInstaller.idl
- */
- isInstallEnabled: function(aMimetype, aReferer) {
- return AddonManager.isInstallEnabled(aMimetype);
- },
-
- /**
- * @see amIWebInstaller.idl
- */
- installAddonsFromWebpage: function(aMimetype, aBrowser, aInstallingPrincipal,
- aUris, aHashes, aNames, aIcons, aCallback) {
- if (aUris.length == 0)
- return false;
-
- let retval = true;
- if (!AddonManager.isInstallAllowed(aMimetype, aInstallingPrincipal)) {
- aCallback = null;
- retval = false;
- }
-
- let installs = [];
- function buildNextInstall() {
- if (aUris.length == 0) {
- AddonManager.installAddonsFromWebpage(aMimetype, aBrowser, aInstallingPrincipal, installs);
- return;
- }
- let uri = aUris.shift();
- AddonManager.getInstallForURL(uri, function(aInstall) {
- function callCallback(aUri, aStatus) {
- try {
- aCallback.onInstallEnded(aUri, aStatus);
- }
- catch (e) {
- Components.utils.reportError(e);
- }
- }
-
- if (aInstall) {
- installs.push(aInstall);
- if (aCallback) {
- aInstall.addListener({
- onDownloadCancelled: function(aInstall) {
- callCallback(uri, USER_CANCELLED);
- },
-
- onDownloadFailed: function(aInstall) {
- if (aInstall.error == AddonManager.ERROR_CORRUPT_FILE)
- callCallback(uri, CANT_READ_ARCHIVE);
- else
- callCallback(uri, DOWNLOAD_ERROR);
- },
-
- onInstallFailed: function(aInstall) {
- callCallback(uri, EXECUTION_ERROR);
- },
-
- onInstallEnded: function(aInstall, aStatus) {
- callCallback(uri, SUCCESS);
- }
- });
- }
- }
- else if (aCallback) {
- aCallback.onInstallEnded(uri, UNSUPPORTED_TYPE);
- }
- buildNextInstall();
- }, aMimetype, aHashes.shift(), aNames.shift(), aIcons.shift(), null, aBrowser);
- }
- buildNextInstall();
-
- return retval;
- },
-
- notify: function(aTimer) {
- AddonManagerPrivate.backgroundUpdateTimerHandler();
- },
-
- // Maps message manager instances for content processes to the associated
- // AddonListener instances.
- addonListeners: new Map(),
-
- _addAddonListener(target) {
- if (!this.addonListeners.has(target)) {
- let handler = (event, id, needsRestart) => {
- target.sendAsyncMessage(MSG_ADDON_EVENT, {event, id, needsRestart});
- };
- let listener = {
- onEnabling: (addon, needsRestart) => handler("onEnabling", addon.id, needsRestart),
- onEnabled: (addon) => handler("onEnabled", addon.id, false),
- onDisabling: (addon, needsRestart) => handler("onDisabling", addon.id, needsRestart),
- onDisabled: (addon) => handler("onDisabled", addon.id, false),
- onInstalling: (addon, needsRestart) => handler("onInstalling", addon.id, needsRestart),
- onInstalled: (addon) => handler("onInstalled", addon.id, false),
- onUninstalling: (addon, needsRestart) => handler("onUninstalling", addon.id, needsRestart),
- onUninstalled: (addon) => handler("onUninstalled", addon.id, false),
- onOperationCancelled: (addon) => handler("onOperationCancelled", addon.id, false),
- };
- this.addonListeners.set(target, listener);
- AddonManager.addAddonListener(listener);
- }
- },
-
- _removeAddonListener(target) {
- if (this.addonListeners.has(target)) {
- AddonManager.removeAddonListener(this.addonListeners.get(target));
- this.addonListeners.delete(target);
- }
- },
-
- /**
- * messageManager callback function.
- *
- * Listens to requests from child processes for InstallTrigger
- * activity, and sends back callbacks.
- */
- receiveMessage: function(aMessage) {
- let payload = aMessage.data;
-
- switch (aMessage.name) {
- case MSG_INSTALL_ENABLED:
- return AddonManager.isInstallEnabled(payload.mimetype);
-
- case MSG_INSTALL_ADDONS: {
- let callback = null;
- if (payload.callbackID != -1) {
- let mm = aMessage.target.messageManager;
- callback = {
- onInstallEnded: function(url, status) {
- mm.sendAsyncMessage(MSG_INSTALL_CALLBACK, {
- callbackID: payload.callbackID,
- url: url,
- status: status
- });
- },
- };
- }
-
- return this.installAddonsFromWebpage(payload.mimetype,
- aMessage.target, payload.triggeringPrincipal, payload.uris,
- payload.hashes, payload.names, payload.icons, callback);
- }
-
- case MSG_PROMISE_REQUEST: {
- let mm = aMessage.target.messageManager;
- let resolve = (value) => {
- mm.sendAsyncMessage(MSG_PROMISE_RESULT, {
- callbackID: payload.callbackID,
- resolve: value
- });
- }
- let reject = (value) => {
- mm.sendAsyncMessage(MSG_PROMISE_RESULT, {
- callbackID: payload.callbackID,
- reject: value
- });
- }
-
- let API = AddonManager.webAPI;
- if (payload.type in API) {
- API[payload.type](aMessage.target, ...payload.args).then(resolve, reject);
- }
- else {
- reject("Unknown Add-on API request.");
- }
- break;
- }
-
- case MSG_INSTALL_CLEANUP: {
- AddonManager.webAPI.clearInstalls(payload.ids);
- break;
- }
-
- case MSG_ADDON_EVENT_REQ: {
- let target = aMessage.target.messageManager;
- if (payload.enabled) {
- this._addAddonListener(target);
- } else {
- this._removeAddonListener(target);
- }
- }
- }
- return undefined;
- },
-
- childClosed(target) {
- AddonManager.webAPI.clearInstallsFrom(target);
- this._removeAddonListener(target);
- },
-
- sendEvent(mm, data) {
- mm.sendAsyncMessage(MSG_INSTALL_EVENT, data);
- },
-
- classID: Components.ID("{4399533d-08d1-458c-a87a-235f74451cfa}"),
- _xpcom_factory: {
- createInstance: function(aOuter, aIid) {
- if (aOuter != null)
- throw Components.Exception("Component does not support aggregation",
- Cr.NS_ERROR_NO_AGGREGATION);
-
- if (!gSingleton)
- gSingleton = new amManager();
- return gSingleton.QueryInterface(aIid);
- }
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.amIAddonManager,
- Ci.amIWebInstaller,
- Ci.nsITimerCallback,
- Ci.nsIObserver,
- Ci.nsIMessageListener])
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([amManager]);
diff --git a/toolkit/mozapps/webextensions/amInstallTrigger.js b/toolkit/mozapps/webextensions/amInstallTrigger.js
deleted file mode 100644
index 382791d32..000000000
--- a/toolkit/mozapps/webextensions/amInstallTrigger.js
+++ /dev/null
@@ -1,240 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Preferences.jsm");
-Cu.import("resource://gre/modules/Log.jsm");
-
-const XPINSTALL_MIMETYPE = "application/x-xpinstall";
-
-const MSG_INSTALL_ENABLED = "WebInstallerIsInstallEnabled";
-const MSG_INSTALL_ADDONS = "WebInstallerInstallAddonsFromWebpage";
-const MSG_INSTALL_CALLBACK = "WebInstallerInstallCallback";
-
-
-var log = Log.repository.getLogger("AddonManager.InstallTrigger");
-log.level = Log.Level[Preferences.get("extensions.logging.enabled", false) ? "Warn" : "Trace"];
-
-function CallbackObject(id, callback, urls, mediator) {
- this.id = id;
- this.callback = callback;
- this.urls = new Set(urls);
- this.callCallback = function(url, status) {
- try {
- this.callback(url, status);
- }
- catch (e) {
- log.warn("InstallTrigger callback threw an exception: " + e);
- }
-
- this.urls.delete(url);
- if (this.urls.size == 0)
- mediator._callbacks.delete(id);
- };
-}
-
-function RemoteMediator(window) {
- window.QueryInterface(Ci.nsIInterfaceRequestor);
- let utils = window.getInterface(Ci.nsIDOMWindowUtils);
- this._windowID = utils.currentInnerWindowID;
-
- this.mm = window
- .getInterface(Ci.nsIDocShell)
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIContentFrameMessageManager);
- this.mm.addWeakMessageListener(MSG_INSTALL_CALLBACK, this);
-
- this._lastCallbackID = 0;
- this._callbacks = new Map();
-}
-
-RemoteMediator.prototype = {
- receiveMessage: function(message) {
- if (message.name == MSG_INSTALL_CALLBACK) {
- let payload = message.data;
- let callbackHandler = this._callbacks.get(payload.callbackID);
- if (callbackHandler) {
- callbackHandler.callCallback(payload.url, payload.status);
- }
- }
- },
-
- enabled: function(url) {
- let params = {
- mimetype: XPINSTALL_MIMETYPE
- };
- return this.mm.sendSyncMessage(MSG_INSTALL_ENABLED, params)[0];
- },
-
- install: function(installs, principal, callback, window) {
- let callbackID = this._addCallback(callback, installs.uris);
-
- installs.mimetype = XPINSTALL_MIMETYPE;
- installs.triggeringPrincipal = principal;
- installs.callbackID = callbackID;
-
- if (Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) {
- // When running in the main process this might be a frame inside an
- // in-content UI page, walk up to find the first frame element in a chrome
- // privileged document
- let element = window.frameElement;
- let ssm = Services.scriptSecurityManager;
- while (element && !ssm.isSystemPrincipal(element.ownerDocument.nodePrincipal))
- element = element.ownerDocument.defaultView.frameElement;
-
- if (element) {
- let listener = Cc["@mozilla.org/addons/integration;1"].
- getService(Ci.nsIMessageListener);
- return listener.wrappedJSObject.receiveMessage({
- name: MSG_INSTALL_ADDONS,
- target: element,
- data: installs,
- });
- }
- }
-
- // Fall back to sending through the message manager
- let messageManager = window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .QueryInterface(Ci.nsIDocShell)
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIContentFrameMessageManager);
-
- return messageManager.sendSyncMessage(MSG_INSTALL_ADDONS, installs)[0];
- },
-
- _addCallback: function(callback, urls) {
- if (!callback || typeof callback != "function")
- return -1;
-
- let callbackID = this._windowID + "-" + ++this._lastCallbackID;
- let callbackObject = new CallbackObject(callbackID, callback, urls, this);
- this._callbacks.set(callbackID, callbackObject);
- return callbackID;
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupportsWeakReference])
-};
-
-
-function InstallTrigger() {
-}
-
-InstallTrigger.prototype = {
- // Here be magic. We've declared ourselves as providing the
- // nsIDOMGlobalPropertyInitializer interface, and are registered in the
- // "JavaScript-global-property" category in the XPCOM category manager. This
- // means that for newly created windows, XPCOM will createinstance this
- // object, and then call init, passing in the window for which we need to
- // provide an instance. We then initialize ourselves and return the webidl
- // version of this object using the webidl-provided _create method, which
- // XPCOM will then duly expose as a property value on the window. All this
- // indirection is necessary because webidl does not (yet) support statics
- // (bug 863952). See bug 926712 for more details about this implementation.
- init: function(window) {
- this._window = window;
- this._principal = window.document.nodePrincipal;
- this._url = window.document.documentURIObject;
-
- try {
- this._mediator = new RemoteMediator(window);
- } catch (ex) {
- // If we can't set up IPC (e.g., because this is a top-level window
- // or something), then don't expose InstallTrigger.
- return null;
- }
-
- return window.InstallTriggerImpl._create(window, this);
- },
-
- enabled: function() {
- return this._mediator.enabled(this._url.spec);
- },
-
- updateEnabled: function() {
- return this.enabled();
- },
-
- install: function(installs, callback) {
- let installData = {
- uris: [],
- hashes: [],
- names: [],
- icons: [],
- };
-
- for (let name of Object.keys(installs)) {
- let item = installs[name];
- if (typeof item === "string") {
- item = { URL: item };
- }
- if (!item.URL) {
- throw new this._window.Error("Missing URL property for '" + name + "'");
- }
-
- let url = this._resolveURL(item.URL);
- if (!this._checkLoadURIFromScript(url)) {
- throw new this._window.Error("Insufficient permissions to install: " + url.spec);
- }
-
- let iconUrl = null;
- if (item.IconURL) {
- iconUrl = this._resolveURL(item.IconURL);
- if (!this._checkLoadURIFromScript(iconUrl)) {
- iconUrl = null; // If page can't load the icon, just ignore it
- }
- }
-
- installData.uris.push(url.spec);
- installData.hashes.push(item.Hash || null);
- installData.names.push(name);
- installData.icons.push(iconUrl ? iconUrl.spec : null);
- }
-
- return this._mediator.install(installData, this._principal, callback, this._window);
- },
-
- startSoftwareUpdate: function(url, flags) {
- let filename = Services.io.newURI(url, null, null)
- .QueryInterface(Ci.nsIURL)
- .filename;
- let args = {};
- args[filename] = { "URL": url };
- return this.install(args);
- },
-
- installChrome: function(type, url, skin) {
- return this.startSoftwareUpdate(url);
- },
-
- _resolveURL: function(url) {
- return Services.io.newURI(url, null, this._url);
- },
-
- _checkLoadURIFromScript: function(uri) {
- let secman = Services.scriptSecurityManager;
- try {
- secman.checkLoadURIWithPrincipal(this._principal,
- uri,
- secman.DISALLOW_INHERIT_PRINCIPAL);
- return true;
- }
- catch (e) {
- return false;
- }
- },
-
- classID: Components.ID("{9df8ef2b-94da-45c9-ab9f-132eb55fddf1}"),
- contractID: "@mozilla.org/addons/installtrigger;1",
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports, Ci.nsIDOMGlobalPropertyInitializer])
-};
-
-
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([InstallTrigger]);
diff --git a/toolkit/mozapps/webextensions/amWebAPI.js b/toolkit/mozapps/webextensions/amWebAPI.js
deleted file mode 100644
index 5ad0d23f1..000000000
--- a/toolkit/mozapps/webextensions/amWebAPI.js
+++ /dev/null
@@ -1,269 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-
-const MSG_PROMISE_REQUEST = "WebAPIPromiseRequest";
-const MSG_PROMISE_RESULT = "WebAPIPromiseResult";
-const MSG_INSTALL_EVENT = "WebAPIInstallEvent";
-const MSG_INSTALL_CLEANUP = "WebAPICleanup";
-const MSG_ADDON_EVENT_REQ = "WebAPIAddonEventRequest";
-const MSG_ADDON_EVENT = "WebAPIAddonEvent";
-
-class APIBroker {
- constructor(mm) {
- this.mm = mm;
-
- this._promises = new Map();
-
- // _installMap maps integer ids to DOM AddonInstall instances
- this._installMap = new Map();
-
- this.mm.addMessageListener(MSG_PROMISE_RESULT, this);
- this.mm.addMessageListener(MSG_INSTALL_EVENT, this);
-
- this._eventListener = null;
- }
-
- receiveMessage(message) {
- let payload = message.data;
-
- switch (message.name) {
- case MSG_PROMISE_RESULT: {
- if (!this._promises.has(payload.callbackID)) {
- return;
- }
-
- let resolve = this._promises.get(payload.callbackID);
- this._promises.delete(payload.callbackID);
- resolve(payload);
- break;
- }
-
- case MSG_INSTALL_EVENT: {
- let install = this._installMap.get(payload.id);
- if (!install) {
- let err = new Error(`Got install event for unknown install ${payload.id}`);
- Cu.reportError(err);
- return;
- }
- install._dispatch(payload);
- break;
- }
-
- case MSG_ADDON_EVENT: {
- if (this._eventListener) {
- this._eventListener(payload);
- }
- }
- }
- }
-
- sendRequest(type, ...args) {
- return new Promise(resolve => {
- let callbackID = APIBroker._nextID++;
-
- this._promises.set(callbackID, resolve);
- this.mm.sendAsyncMessage(MSG_PROMISE_REQUEST, { type, callbackID, args });
- });
- }
-
- setAddonListener(callback) {
- this._eventListener = callback;
- if (callback) {
- this.mm.addMessageListener(MSG_ADDON_EVENT, this);
- this.mm.sendAsyncMessage(MSG_ADDON_EVENT_REQ, {enabled: true});
- } else {
- this.mm.removeMessageListener(MSG_ADDON_EVENT, this);
- this.mm.sendAsyncMessage(MSG_ADDON_EVENT_REQ, {enabled: false});
- }
- }
-
- sendCleanup(ids) {
- this.setAddonListener(null);
- this.mm.sendAsyncMessage(MSG_INSTALL_CLEANUP, { ids });
- }
-}
-
-APIBroker._nextID = 0;
-
-// Base class for building classes to back content-exposed interfaces.
-class APIObject {
- init(window, broker, properties) {
- this.window = window;
- this.broker = broker;
-
- // Copy any provided properties onto this object, webidl bindings
- // will only expose to content what should be exposed.
- for (let key of Object.keys(properties)) {
- this[key] = properties[key];
- }
- }
-
- /**
- * Helper to implement an asychronous method visible to content, where
- * the method is implemented by sending a message to the parent process
- * and then wrapping the returned object or error in an appropriate object.
- * This helper method ensures that:
- * - Returned Promise objects are from the content window
- * - Rejected Promises have Error objects from the content window
- * - Only non-internal errors are exposed to the caller
- *
- * @param {string} apiRequest The command to invoke in the parent process.
- * @param {array<cloneable>} apiArgs The arguments to include with the
- * request to the parent process.
- * @param {function} resultConvert If provided, a function called with the
- * result from the parent process as an
- * argument. Used to convert the result
- * into something appropriate for content.
- * @returns {Promise<any>} A Promise suitable for passing directly to content.
- */
- _apiTask(apiRequest, apiArgs, resultConverter) {
- let win = this.window;
- let broker = this.broker;
- return new win.Promise((resolve, reject) => {
- Task.spawn(function*() {
- let result = yield broker.sendRequest(apiRequest, ...apiArgs);
- if ("reject" in result) {
- let err = new win.Error(result.reject.message);
- // We don't currently put any other properties onto Errors
- // generated by mozAddonManager. If/when we do, they will
- // need to get copied here.
- reject(err);
- return;
- }
-
- let obj = result.resolve;
- if (resultConverter) {
- obj = resultConverter(obj);
- }
- resolve(obj);
- }).catch(err => {
- Cu.reportError(err);
- reject(new win.Error("Unexpected internal error"));
- });
- });
- }
-}
-
-class Addon extends APIObject {
- constructor(...args) {
- super();
- this.init(...args);
- }
-
- uninstall() {
- return this._apiTask("addonUninstall", [this.id]);
- }
-
- setEnabled(value) {
- return this._apiTask("addonSetEnabled", [this.id, value]);
- }
-}
-
-class AddonInstall extends APIObject {
- constructor(window, broker, properties) {
- super();
- this.init(window, broker, properties);
-
- broker._installMap.set(properties.id, this);
- }
-
- _dispatch(data) {
- // The message for the event includes updated copies of all install
- // properties. Use the usual "let webidl filter visible properties" trick.
- for (let key of Object.keys(data)) {
- this[key] = data[key];
- }
-
- let event = new this.window.Event(data.event);
- this.__DOM_IMPL__.dispatchEvent(event);
- }
-
- install() {
- return this._apiTask("addonInstallDoInstall", [this.id]);
- }
-
- cancel() {
- return this._apiTask("addonInstallCancel", [this.id]);
- }
-}
-
-class WebAPI extends APIObject {
- constructor() {
- super();
- this.allInstalls = [];
- this.listenerCount = 0;
- }
-
- init(window) {
- let mm = window
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDocShell)
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIContentFrameMessageManager);
- let broker = new APIBroker(mm);
-
- super.init(window, broker, {});
-
- window.addEventListener("unload", event => {
- this.broker.sendCleanup(this.allInstalls);
- });
- }
-
- getAddonByID(id) {
- return this._apiTask("getAddonByID", [id], addonInfo => {
- if (!addonInfo) {
- return null;
- }
- let addon = new Addon(this.window, this.broker, addonInfo);
- return this.window.Addon._create(this.window, addon);
- });
- }
-
- createInstall(options) {
- return this._apiTask("createInstall", [options], installInfo => {
- if (!installInfo) {
- return null;
- }
- let install = new AddonInstall(this.window, this.broker, installInfo);
- this.allInstalls.push(installInfo.id);
- return this.window.AddonInstall._create(this.window, install);
- });
- }
-
- eventListenerWasAdded(type) {
- if (this.listenerCount == 0) {
- this.broker.setAddonListener(data => {
- let event = new this.window.AddonEvent(data.event, data);
- this.__DOM_IMPL__.dispatchEvent(event);
- });
- }
- this.listenerCount++;
- }
-
- eventListenerWasRemoved(type) {
- this.listenerCount--;
- if (this.listenerCount == 0) {
- this.broker.setAddonListener(null);
- }
- }
-
- QueryInterface(iid) {
- if (iid.equals(WebAPI.classID) || iid.equals(Ci.nsISupports)
- || iid.equals(Ci.nsIDOMGlobalPropertyInitializer)) {
- return this;
- }
- return Cr.NS_ERROR_NO_INTERFACE;
- }
-}
-
-WebAPI.prototype.classID = Components.ID("{8866d8e3-4ea5-48b7-a891-13ba0ac15235}");
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([WebAPI]);
diff --git a/toolkit/mozapps/webextensions/amWebInstallListener.js b/toolkit/mozapps/webextensions/amWebInstallListener.js
deleted file mode 100644
index 0bcc345e8..000000000
--- a/toolkit/mozapps/webextensions/amWebInstallListener.js
+++ /dev/null
@@ -1,348 +0,0 @@
-/* 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/. */
-
-/**
- * This is a default implementation of amIWebInstallListener that should work
- * for most applications but can be overriden. It notifies the observer service
- * about blocked installs. For normal installs it pops up an install
- * confirmation when all the add-ons have been downloaded.
- */
-
-"use strict";
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cr = Components.results;
-const Cu = Components.utils;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/AddonManager.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Preferences.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "PromptUtils", "resource://gre/modules/SharedPromptUtils.jsm");
-
-const URI_XPINSTALL_DIALOG = "chrome://mozapps/content/xpinstall/xpinstallConfirm.xul";
-
-// Installation can begin from any of these states
-const READY_STATES = [
- AddonManager.STATE_AVAILABLE,
- AddonManager.STATE_DOWNLOAD_FAILED,
- AddonManager.STATE_INSTALL_FAILED,
- AddonManager.STATE_CANCELLED
-];
-
-Cu.import("resource://gre/modules/Log.jsm");
-const LOGGER_ID = "addons.weblistener";
-
-// Create a new logger for use by the Addons Web Listener
-// (Requires AddonManager.jsm)
-var logger = Log.repository.getLogger(LOGGER_ID);
-
-function notifyObservers(aTopic, aBrowser, aUri, aInstalls) {
- let info = {
- browser: aBrowser,
- originatingURI: aUri,
- installs: aInstalls,
-
- QueryInterface: XPCOMUtils.generateQI([Ci.amIWebInstallInfo])
- };
- Services.obs.notifyObservers(info, aTopic, null);
-}
-
-/**
- * Creates a new installer to monitor downloads and prompt to install when
- * ready
- *
- * @param aBrowser
- * The browser that started the installations
- * @param aUrl
- * The URL that started the installations
- * @param aInstalls
- * An array of AddonInstalls
- */
-function Installer(aBrowser, aUrl, aInstalls) {
- this.browser = aBrowser;
- this.url = aUrl;
- this.downloads = aInstalls;
- this.installed = [];
-
- notifyObservers("addon-install-started", aBrowser, aUrl, aInstalls);
-
- for (let install of aInstalls) {
- install.addListener(this);
-
- // Start downloading if it hasn't already begun
- if (READY_STATES.indexOf(install.state) != -1)
- install.install();
- }
-
- this.checkAllDownloaded();
-}
-
-Installer.prototype = {
- browser: null,
- downloads: null,
- installed: null,
- isDownloading: true,
-
- /**
- * Checks if all downloads are now complete and if so prompts to install.
- */
- checkAllDownloaded: function() {
- // Prevent re-entrancy caused by the confirmation dialog cancelling unwanted
- // installs.
- if (!this.isDownloading)
- return;
-
- var failed = [];
- var installs = [];
-
- for (let install of this.downloads) {
- switch (install.state) {
- case AddonManager.STATE_AVAILABLE:
- case AddonManager.STATE_DOWNLOADING:
- // Exit early if any add-ons haven't started downloading yet or are
- // still downloading
- return;
- case AddonManager.STATE_DOWNLOAD_FAILED:
- failed.push(install);
- break;
- case AddonManager.STATE_DOWNLOADED:
- // App disabled items are not compatible and so fail to install
- if (install.addon.appDisabled)
- failed.push(install);
- else
- installs.push(install);
-
- if (install.linkedInstalls) {
- for (let linkedInstall of install.linkedInstalls) {
- linkedInstall.addListener(this);
- // Corrupt or incompatible items fail to install
- if (linkedInstall.state == AddonManager.STATE_DOWNLOAD_FAILED || linkedInstall.addon.appDisabled)
- failed.push(linkedInstall);
- else
- installs.push(linkedInstall);
- }
- }
- break;
- case AddonManager.STATE_CANCELLED:
- // Just ignore cancelled downloads
- break;
- default:
- logger.warn("Download of " + install.sourceURI.spec + " in unexpected state " +
- install.state);
- }
- }
-
- this.isDownloading = false;
- this.downloads = installs;
-
- if (failed.length > 0) {
- // Stop listening and cancel any installs that are failed because of
- // compatibility reasons.
- for (let install of failed) {
- if (install.state == AddonManager.STATE_DOWNLOADED) {
- install.removeListener(this);
- install.cancel();
- }
- }
- notifyObservers("addon-install-failed", this.browser, this.url, failed);
- }
-
- // If none of the downloads were successful then exit early
- if (this.downloads.length == 0)
- return;
-
- // Check for a custom installation prompt that may be provided by the
- // applicaton
- if ("@mozilla.org/addons/web-install-prompt;1" in Cc) {
- try {
- let prompt = Cc["@mozilla.org/addons/web-install-prompt;1"].
- getService(Ci.amIWebInstallPrompt);
- prompt.confirm(this.browser, this.url, this.downloads, this.downloads.length);
- return;
- }
- catch (e) {}
- }
-
- if (Preferences.get("xpinstall.customConfirmationUI", false)) {
- notifyObservers("addon-install-confirmation", this.browser, this.url, this.downloads);
- return;
- }
-
- let args = {};
- args.url = this.url;
- args.installs = this.downloads;
- args.wrappedJSObject = args;
-
- try {
- Cc["@mozilla.org/base/telemetry;1"].
- getService(Ci.nsITelemetry).
- getHistogramById("SECURITY_UI").
- add(Ci.nsISecurityUITelemetry.WARNING_CONFIRM_ADDON_INSTALL);
- let parentWindow = null;
- if (this.browser) {
- parentWindow = this.browser.ownerDocument.defaultView;
- PromptUtils.fireDialogEvent(parentWindow, "DOMWillOpenModalDialog", this.browser);
- }
- Services.ww.openWindow(parentWindow, URI_XPINSTALL_DIALOG,
- null, "chrome,modal,centerscreen", args);
- } catch (e) {
- logger.warn("Exception showing install confirmation dialog", e);
- for (let install of this.downloads) {
- install.removeListener(this);
- // Cancel the installs, as currently there is no way to make them fail
- // from here.
- install.cancel();
- }
- notifyObservers("addon-install-cancelled", this.browser, this.url,
- this.downloads);
- }
- },
-
- /**
- * Checks if all installs are now complete and if so notifies observers.
- */
- checkAllInstalled: function() {
- var failed = [];
-
- for (let install of this.downloads) {
- switch (install.state) {
- case AddonManager.STATE_DOWNLOADED:
- case AddonManager.STATE_INSTALLING:
- // Exit early if any add-ons haven't started installing yet or are
- // still installing
- return;
- case AddonManager.STATE_INSTALL_FAILED:
- failed.push(install);
- break;
- }
- }
-
- this.downloads = null;
-
- if (failed.length > 0)
- notifyObservers("addon-install-failed", this.browser, this.url, failed);
-
- if (this.installed.length > 0)
- notifyObservers("addon-install-complete", this.browser, this.url, this.installed);
- this.installed = null;
- },
-
- onDownloadCancelled: function(aInstall) {
- aInstall.removeListener(this);
- this.checkAllDownloaded();
- },
-
- onDownloadFailed: function(aInstall) {
- aInstall.removeListener(this);
- this.checkAllDownloaded();
- },
-
- onDownloadEnded: function(aInstall) {
- this.checkAllDownloaded();
- return false;
- },
-
- onInstallCancelled: function(aInstall) {
- aInstall.removeListener(this);
- this.checkAllInstalled();
- },
-
- onInstallFailed: function(aInstall) {
- aInstall.removeListener(this);
- this.checkAllInstalled();
- },
-
- onInstallEnded: function(aInstall) {
- aInstall.removeListener(this);
- this.installed.push(aInstall);
-
- // If installing a theme that is disabled and can be enabled then enable it
- if (aInstall.addon.type == "theme" &&
- aInstall.addon.userDisabled == true &&
- aInstall.addon.appDisabled == false) {
- aInstall.addon.userDisabled = false;
- }
-
- this.checkAllInstalled();
- }
-};
-
-function extWebInstallListener() {
-}
-
-extWebInstallListener.prototype = {
- /**
- * @see amIWebInstallListener.idl
- */
- onWebInstallDisabled: function(aBrowser, aUri, aInstalls) {
- let info = {
- browser: aBrowser,
- originatingURI: aUri,
- installs: aInstalls,
-
- QueryInterface: XPCOMUtils.generateQI([Ci.amIWebInstallInfo])
- };
- Services.obs.notifyObservers(info, "addon-install-disabled", null);
- },
-
- /**
- * @see amIWebInstallListener.idl
- */
- onWebInstallOriginBlocked: function(aBrowser, aUri, aInstalls) {
- let info = {
- browser: aBrowser,
- originatingURI: aUri,
- installs: aInstalls,
-
- install: function() {
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.amIWebInstallInfo])
- };
- Services.obs.notifyObservers(info, "addon-install-origin-blocked", null);
-
- return false;
- },
-
- /**
- * @see amIWebInstallListener.idl
- */
- onWebInstallBlocked: function(aBrowser, aUri, aInstalls) {
- let info = {
- browser: aBrowser,
- originatingURI: aUri,
- installs: aInstalls,
-
- install: function() {
- new Installer(this.browser, this.originatingURI, this.installs);
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.amIWebInstallInfo])
- };
- Services.obs.notifyObservers(info, "addon-install-blocked", null);
-
- return false;
- },
-
- /**
- * @see amIWebInstallListener.idl
- */
- onWebInstallRequested: function(aBrowser, aUri, aInstalls) {
- new Installer(aBrowser, aUri, aInstalls);
-
- // We start the installs ourself
- return false;
- },
-
- classDescription: "XPI Install Handler",
- contractID: "@mozilla.org/addons/web-install-listener;1",
- classID: Components.ID("{0f38e086-89a3-40a5-8ffc-9b694de1d04a}"),
- QueryInterface: XPCOMUtils.generateQI([Ci.amIWebInstallListener,
- Ci.amIWebInstallListener2])
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([extWebInstallListener]);
diff --git a/toolkit/mozapps/webextensions/content/about.js b/toolkit/mozapps/webextensions/content/about.js
deleted file mode 100644
index 4f8fb353e..000000000
--- a/toolkit/mozapps/webextensions/content/about.js
+++ /dev/null
@@ -1,103 +0,0 @@
-// -*- 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/. */
-
-"use strict";
-
-/* import-globals-from ../../../content/contentAreaUtils.js */
-
-var Cu = Components.utils;
-Cu.import("resource://gre/modules/AddonManager.jsm");
-
-function init() {
- var addon = window.arguments[0];
- var extensionsStrings = document.getElementById("extensionsStrings");
-
- document.documentElement.setAttribute("addontype", addon.type);
-
- var iconURL = AddonManager.getPreferredIconURL(addon, 48, window);
- if (iconURL) {
- var extensionIcon = document.getElementById("extensionIcon");
- extensionIcon.src = iconURL;
- }
-
- document.title = extensionsStrings.getFormattedString("aboutWindowTitle", [addon.name]);
- var extensionName = document.getElementById("extensionName");
- extensionName.textContent = addon.name;
-
- var extensionVersion = document.getElementById("extensionVersion");
- if (addon.version)
- extensionVersion.setAttribute("value", extensionsStrings.getFormattedString("aboutWindowVersionString", [addon.version]));
- else
- extensionVersion.hidden = true;
-
- var extensionDescription = document.getElementById("extensionDescription");
- if (addon.description)
- extensionDescription.textContent = addon.description;
- else
- extensionDescription.hidden = true;
-
- var numDetails = 0;
-
- var extensionCreator = document.getElementById("extensionCreator");
- if (addon.creator) {
- extensionCreator.setAttribute("value", addon.creator);
- numDetails++;
- } else {
- extensionCreator.hidden = true;
- var extensionCreatorLabel = document.getElementById("extensionCreatorLabel");
- extensionCreatorLabel.hidden = true;
- }
-
- var extensionHomepage = document.getElementById("extensionHomepage");
- var homepageURL = addon.homepageURL;
- if (homepageURL) {
- extensionHomepage.setAttribute("homepageURL", homepageURL);
- extensionHomepage.setAttribute("tooltiptext", homepageURL);
- numDetails++;
- } else {
- extensionHomepage.hidden = true;
- }
-
- numDetails += appendToList("extensionDevelopers", "developersBox", addon.developers);
- numDetails += appendToList("extensionTranslators", "translatorsBox", addon.translators);
- numDetails += appendToList("extensionContributors", "contributorsBox", addon.contributors);
-
- if (numDetails == 0) {
- var groove = document.getElementById("groove");
- groove.hidden = true;
- var extensionDetailsBox = document.getElementById("extensionDetailsBox");
- extensionDetailsBox.hidden = true;
- }
-
- var acceptButton = document.documentElement.getButton("accept");
- acceptButton.label = extensionsStrings.getString("aboutWindowCloseButton");
-
- setTimeout(sizeToContent, 0);
-}
-
-function appendToList(aHeaderId, aNodeId, aItems) {
- var header = document.getElementById(aHeaderId);
- var node = document.getElementById(aNodeId);
-
- if (!aItems || aItems.length == 0) {
- header.hidden = true;
- return 0;
- }
-
- for (let currentItem of aItems) {
- var label = document.createElement("label");
- label.textContent = currentItem;
- label.setAttribute("class", "contributor");
- node.appendChild(label);
- }
-
- return aItems.length;
-}
-
-function loadHomepage(aEvent) {
- window.close();
- openURL(aEvent.target.getAttribute("homepageURL"));
-}
diff --git a/toolkit/mozapps/webextensions/content/eula.js b/toolkit/mozapps/webextensions/content/eula.js
deleted file mode 100644
index 537ee7284..000000000
--- a/toolkit/mozapps/webextensions/content/eula.js
+++ /dev/null
@@ -1,25 +0,0 @@
-// -*- 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/. */
-
-"use strict";
-
-var Cu = Components.utils;
-Cu.import("resource://gre/modules/AddonManager.jsm");
-
-function Startup() {
- var bundle = document.getElementById("extensionsStrings");
- var addon = window.arguments[0].addon;
-
- document.documentElement.setAttribute("addontype", addon.type);
-
- var iconURL = AddonManager.getPreferredIconURL(addon, 48, window);
- if (iconURL)
- document.getElementById("icon").src = iconURL;
-
- var label = document.createTextNode(bundle.getFormattedString("eulaHeader", [addon.name]));
- document.getElementById("heading").appendChild(label);
- document.getElementById("eula").value = addon.eula;
-}
diff --git a/toolkit/mozapps/webextensions/content/extensions.css b/toolkit/mozapps/webextensions/content/extensions.css
deleted file mode 100644
index cb5313365..000000000
--- a/toolkit/mozapps/webextensions/content/extensions.css
+++ /dev/null
@@ -1,270 +0,0 @@
-/* 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/. */
-
-@namespace xhtml "http://www.w3.org/1999/xhtml";
-
-/* HTML link elements do weird things to the layout if they are not hidden */
-xhtml|link {
- display: none;
-}
-
-#categories {
- -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#categories-list");
-}
-
-.category {
- -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#category");
-}
-
-.sort-controls {
- -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#sorters");
-}
-
-.addon[status="installed"] {
- -moz-box-orient: vertical;
- -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#addon-generic");
-}
-
-.addon[status="installing"] {
- -moz-box-orient: vertical;
- -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#addon-installing");
-}
-
-.addon[pending="uninstall"] {
- -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#addon-uninstalled");
-}
-
-.creator {
- -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#creator-link");
-}
-
-.meta-rating {
- -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#rating");
-}
-
-.download-progress, .download-progress[mode="undetermined"] {
- -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#download-progress");
-}
-
-.install-status {
- -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#install-status");
-}
-
-.detail-row {
- -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#detail-row");
-}
-
-.text-list {
- white-space: pre-line;
- -moz-user-select: element;
-}
-
-setting, row[unsupported="true"] {
- display: none;
-}
-
-setting[type="bool"] {
- display: -moz-grid-line;
- -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-bool");
-}
-
-setting[type="bool"][localized="true"] {
- display: -moz-grid-line;
- -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-localized-bool");
-}
-
-setting[type="bool"]:not([learnmore]) .preferences-learnmore,
-setting[type="boolint"]:not([learnmore]) .preferences-learnmore {
- visibility: collapse;
-}
-
-setting[type="boolint"] {
- display: -moz-grid-line;
- -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-boolint");
-}
-
-setting[type="integer"] {
- display: -moz-grid-line;
- -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-integer");
-}
-
-setting[type="integer"]:not([size]) textbox {
- -moz-box-flex: 1;
-}
-
-setting[type="control"] {
- display: -moz-grid-line;
- -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-control");
-}
-
-setting[type="string"] {
- display: -moz-grid-line;
- -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-string");
-}
-
-setting[type="color"] {
- display: -moz-grid-line;
- -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-color");
-}
-
-setting[type="file"],
-setting[type="directory"] {
- display: -moz-grid-line;
- -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-path");
-}
-
-setting[type="radio"],
-setting[type="menulist"] {
- display: -moz-grid-line;
- -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-multi");
-}
-
-#addonitem-popup > menuitem[disabled="true"] {
- display: none;
-}
-
-#addonitem-popup[addontype="theme"] > #menuitem_enableItem,
-#addonitem-popup[addontype="theme"] > #menuitem_disableItem,
-#addonitem-popup:not([addontype="theme"]) > #menuitem_enableTheme,
-#addonitem-popup:not([addontype="theme"]) > #menuitem_disableTheme {
- display: none;
-}
-
-#show-disabled-unsigned-extensions .button-text {
- margin-inline-start: 3px !important;
- margin-inline-end: 2px !important;
-}
-
-#header-searching:not([active]) {
- visibility: hidden;
-}
-
-#search-list[local="false"] > .addon[remote="false"],
-#search-list[remote="false"] > .addon[remote="true"] {
- visibility: collapse;
-}
-
-#detail-view {
- overflow: auto;
-}
-
-.addon:not([notification="warning"]) .warning,
-.addon:not([notification="error"]) .error,
-.addon:not([notification="info"]) .info,
-.addon:not([pending]) .pending,
-.addon:not([upgrade="true"]) .update-postfix,
-.addon[active="true"] .disabled-postfix,
-.addon[pending="install"] .update-postfix,
-.addon[pending="install"] .disabled-postfix,
-#detail-view:not([notification="warning"]) .warning,
-#detail-view:not([notification="error"]) .error,
-#detail-view:not([notification="info"]) .info,
-#detail-view:not([pending]) .pending,
-#detail-view:not([upgrade="true"]) .update-postfix,
-#detail-view[active="true"] .disabled-postfix,
-#detail-view[loading] .detail-view-container,
-#detail-view:not([loading]) .alert-container,
-.detail-row:not([value]),
-#search-list[remote="false"] #search-allresults-link {
- display: none;
-}
-
-#addons-page:not([warning]) #list-view > .global-warning-container {
- display: none;
-}
-#addon-list .date-updated {
- display: none;
-}
-
-.view-pane:not(#updates-view) .addon .relnotes-toggle,
-.view-pane:not(#updates-view) .addon .include-update,
-#updates-view:not([updatetype="available"]) .addon .include-update,
-#updates-view[updatetype="available"] .addon .update-available-notice {
- display: none;
-}
-
-#addons-page:not([warning]) .global-warning,
-#addons-page:not([warning="safemode"]) .global-warning-safemode,
-#addons-page:not([warning="checkcompatibility"]) .global-warning-checkcompatibility,
-#addons-page:not([warning="updatesecurity"]) .global-warning-updatesecurity {
- display: none;
-}
-
-/* Plugins aren't yet disabled by safemode (bug 342333),
- so don't show that warning when viewing plugins. */
-#addons-page[warning="safemode"] .view-pane[type="plugin"] .global-warning-container,
-#addons-page[warning="safemode"] #detail-view[loading="true"] .global-warning {
- display: none;
-}
-
-#addons-page .view-pane:not([type="plugin"]) #plugindeprecation-notice {
- display: none;
-}
-
-#addons-page .view-pane:not([type="experiment"]) .experiment-info-container {
- display: none;
-}
-
-.addon .relnotes {
- -moz-user-select: text;
-}
-#detail-name, #detail-desc, #detail-fulldesc {
- -moz-user-select: text;
-}
-
-/* Make sure we're not animating hidden images. See bug 623739. */
-#view-port:not([selectedIndex="0"]) #discover-view .loading,
-#discover-view:not([selectedIndex="0"]) .loading {
- display: none;
-}
-
-/* Elements in unselected richlistitems cannot be focused */
-richlistitem:not([selected]) * {
- -moz-user-focus: ignore;
-}
-
-#header-search {
- width: 22em;
-}
-
-#header-utils-btn {
- -moz-user-focus: normal;
-}
-
-.discover-button[disabled="true"] {
- display: none;
-}
-
-#experiments-learn-more[disabled="true"] {
- display: none;
-}
-
-#experiments-change-telemetry[disabled="true"] {
- display: none;
-}
-
-.view-pane[type="experiment"] .error,
-.view-pane[type="experiment"] .warning,
-.view-pane[type="experiment"] .addon:not([pending="uninstall"]) .pending,
-.view-pane[type="experiment"] .disabled-postfix,
-.view-pane[type="experiment"] .update-postfix,
-.view-pane[type="experiment"] .addon-control.enable,
-.view-pane[type="experiment"] .addon-control.disable,
-#detail-view[type="experiment"] .alert-container,
-#detail-view[type="experiment"] #detail-version,
-#detail-view[type="experiment"] #detail-creator,
-#detail-view[type="experiment"] #detail-enable-btn,
-#detail-view[type="experiment"] #detail-disable-btn {
- display: none;
-}
-
-.view-pane:not([type="experiment"]) .experiment-container,
-.view-pane:not([type="experiment"]) #detail-experiment-container {
- display: none;
-}
-
-.addon[type="experiment"][status="installing"] .experiment-time,
-.addon[type="experiment"][status="installing"] .experiment-state {
- display: none;
-}
diff --git a/toolkit/mozapps/webextensions/content/extensions.js b/toolkit/mozapps/webextensions/content/extensions.js
deleted file mode 100644
index 3159eb1e1..000000000
--- a/toolkit/mozapps/webextensions/content/extensions.js
+++ /dev/null
@@ -1,3827 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-/* import-globals-from ../../../content/contentAreaUtils.js */
-/* globals XMLStylesheetProcessingInstruction*/
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cu = Components.utils;
-var Cr = Components.results;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/DownloadUtils.jsm");
-Cu.import("resource://gre/modules/AddonManager.jsm");
-Cu.import("resource://gre/modules/addons/AddonRepository.jsm");
-
-const CONSTANTS = {};
-Cu.import("resource://gre/modules/addons/AddonConstants.jsm", CONSTANTS);
-const SIGNING_REQUIRED = CONSTANTS.REQUIRE_SIGNING ?
- true :
- Services.prefs.getBoolPref("xpinstall.signatures.required");
-
-XPCOMUtils.defineLazyModuleGetter(this, "PluralForm",
- "resource://gre/modules/PluralForm.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Preferences",
- "resource://gre/modules/Preferences.jsm");
-
-const PREF_DISCOVERURL = "extensions.webservice.discoverURL";
-const PREF_DISCOVER_ENABLED = "extensions.getAddons.showPane";
-const PREF_XPI_ENABLED = "xpinstall.enabled";
-const PREF_MAXRESULTS = "extensions.getAddons.maxResults";
-const PREF_GETADDONS_CACHE_ENABLED = "extensions.getAddons.cache.enabled";
-const PREF_GETADDONS_CACHE_ID_ENABLED = "extensions.%ID%.getAddons.cache.enabled";
-const PREF_UI_TYPE_HIDDEN = "extensions.ui.%TYPE%.hidden";
-const PREF_UI_LASTCATEGORY = "extensions.ui.lastCategory";
-
-const LOADING_MSG_DELAY = 100;
-
-const SEARCH_SCORE_MULTIPLIER_NAME = 2;
-const SEARCH_SCORE_MULTIPLIER_DESCRIPTION = 2;
-
-// Use integers so search scores are sortable by nsIXULSortService
-const SEARCH_SCORE_MATCH_WHOLEWORD = 10;
-const SEARCH_SCORE_MATCH_WORDBOUNDRY = 6;
-const SEARCH_SCORE_MATCH_SUBSTRING = 3;
-
-const UPDATES_RECENT_TIMESPAN = 2 * 24 * 3600000; // 2 days (in milliseconds)
-const UPDATES_RELEASENOTES_TRANSFORMFILE = "chrome://mozapps/content/extensions/updateinfo.xsl";
-
-const XMLURI_PARSE_ERROR = "http://www.mozilla.org/newlayout/xml/parsererror.xml"
-
-var gViewDefault = "addons://discover/";
-
-var gStrings = {};
-XPCOMUtils.defineLazyServiceGetter(gStrings, "bundleSvc",
- "@mozilla.org/intl/stringbundle;1",
- "nsIStringBundleService");
-
-XPCOMUtils.defineLazyGetter(gStrings, "brand", function() {
- return this.bundleSvc.createBundle("chrome://branding/locale/brand.properties");
-});
-XPCOMUtils.defineLazyGetter(gStrings, "ext", function() {
- return this.bundleSvc.createBundle("chrome://mozapps/locale/extensions/extensions.properties");
-});
-XPCOMUtils.defineLazyGetter(gStrings, "dl", function() {
- return this.bundleSvc.createBundle("chrome://mozapps/locale/downloads/downloads.properties");
-});
-
-XPCOMUtils.defineLazyGetter(gStrings, "brandShortName", function() {
- return this.brand.GetStringFromName("brandShortName");
-});
-XPCOMUtils.defineLazyGetter(gStrings, "appVersion", function() {
- return Services.appinfo.version;
-});
-
-document.addEventListener("load", initialize, true);
-window.addEventListener("unload", shutdown, false);
-
-class MessageDispatcher {
- constructor(target) {
- this.listeners = new Map();
- this.target = target;
- }
-
- addMessageListener(name, handler) {
- if (!this.listeners.has(name)) {
- this.listeners.set(name, new Set());
- }
-
- this.listeners.get(name).add(handler);
- }
-
- removeMessageListener(name, handler) {
- if (this.listeners.has(name)) {
- this.listeners.get(name).delete(handler);
- }
- }
-
- sendAsyncMessage(name, data) {
- for (let handler of this.listeners.get(name) || new Set()) {
- Promise.resolve().then(() => {
- handler.receiveMessage({
- name,
- data,
- target: this.target,
- });
- });
- }
- }
-}
-
-/**
- * A mock FrameMessageManager global to allow frame scripts to run in
- * non-top-level, non-remote <browser>s as if they were top-level or
- * remote.
- *
- * @param {Element} browser
- * A XUL <browser> element.
- */
-class FakeFrameMessageManager {
- constructor(browser) {
- let dispatcher = new MessageDispatcher(browser);
- let frameDispatcher = new MessageDispatcher(null);
-
- this.sendAsyncMessage = frameDispatcher.sendAsyncMessage.bind(frameDispatcher);
- this.addMessageListener = dispatcher.addMessageListener.bind(dispatcher);
- this.removeMessageListener = dispatcher.removeMessageListener.bind(dispatcher);
-
- this.frame = {
- get content() {
- return browser.contentWindow;
- },
-
- get docShell() {
- return browser.docShell;
- },
-
- addEventListener: browser.addEventListener.bind(browser),
- removeEventListener: browser.removeEventListener.bind(browser),
-
- sendAsyncMessage: dispatcher.sendAsyncMessage.bind(dispatcher),
- addMessageListener: frameDispatcher.addMessageListener.bind(frameDispatcher),
- removeMessageListener: frameDispatcher.removeMessageListener.bind(frameDispatcher),
- }
- }
-
- loadFrameScript(url) {
- Services.scriptloader.loadSubScript(url, Object.create(this.frame));
- }
-}
-
-var gPendingInitializations = 1;
-Object.defineProperty(this, "gIsInitializing", {
- get: () => gPendingInitializations > 0
-});
-
-function initialize(event) {
- // XXXbz this listener gets _all_ load events for all nodes in the
- // document... but relies on not being called "too early".
- if (event.target instanceof XMLStylesheetProcessingInstruction) {
- return;
- }
- document.removeEventListener("load", initialize, true);
-
- let globalCommandSet = document.getElementById("globalCommandSet");
- globalCommandSet.addEventListener("command", function(event) {
- gViewController.doCommand(event.target.id);
- });
-
- let viewCommandSet = document.getElementById("viewCommandSet");
- viewCommandSet.addEventListener("commandupdate", function(event) {
- gViewController.updateCommands();
- });
- viewCommandSet.addEventListener("command", function(event) {
- gViewController.doCommand(event.target.id);
- });
-
- let detailScreenshot = document.getElementById("detail-screenshot");
- detailScreenshot.addEventListener("load", function(event) {
- this.removeAttribute("loading");
- });
- detailScreenshot.addEventListener("error", function(event) {
- this.setAttribute("loading", "error");
- });
-
- let addonPage = document.getElementById("addons-page");
- addonPage.addEventListener("dragenter", function(event) {
- gDragDrop.onDragOver(event);
- });
- addonPage.addEventListener("dragover", function(event) {
- gDragDrop.onDragOver(event);
- });
- addonPage.addEventListener("drop", function(event) {
- gDragDrop.onDrop(event);
- });
- addonPage.addEventListener("keypress", function(event) {
- gHeader.onKeyPress(event);
- });
-
- if (!isDiscoverEnabled()) {
- gViewDefault = "addons://list/extension";
- }
-
- gViewController.initialize();
- gCategories.initialize();
- gHeader.initialize();
- gEventManager.initialize();
- Services.obs.addObserver(sendEMPong, "EM-ping", false);
- Services.obs.notifyObservers(window, "EM-loaded", "");
-
- // If the initial view has already been selected (by a call to loadView from
- // the above notifications) then bail out now
- if (gViewController.initialViewSelected)
- return;
-
- // If there is a history state to restore then use that
- if (window.history.state) {
- gViewController.updateState(window.history.state);
- return;
- }
-
- // Default to the last selected category
- var view = gCategories.node.value;
-
- // Allow passing in a view through the window arguments
- if ("arguments" in window && window.arguments.length > 0 &&
- window.arguments[0] !== null && "view" in window.arguments[0]) {
- view = window.arguments[0].view;
- }
-
- gViewController.loadInitialView(view);
-}
-
-function notifyInitialized() {
- if (!gIsInitializing)
- return;
-
- gPendingInitializations--;
- if (!gIsInitializing) {
- var event = document.createEvent("Events");
- event.initEvent("Initialized", true, true);
- document.dispatchEvent(event);
- }
-}
-
-function shutdown() {
- gCategories.shutdown();
- gSearchView.shutdown();
- gEventManager.shutdown();
- gViewController.shutdown();
- Services.obs.removeObserver(sendEMPong, "EM-ping");
-}
-
-function sendEMPong(aSubject, aTopic, aData) {
- Services.obs.notifyObservers(window, "EM-pong", "");
-}
-
-// Used by external callers to load a specific view into the manager
-function loadView(aViewId) {
- if (!gViewController.initialViewSelected) {
- // The caller opened the window and immediately loaded the view so it
- // should be the initial history entry
-
- gViewController.loadInitialView(aViewId);
- } else {
- gViewController.loadView(aViewId);
- }
-}
-
-function isCorrectlySigned(aAddon) {
- // Add-ons without an "isCorrectlySigned" property are correctly signed as
- // they aren't the correct type for signing.
- return aAddon.isCorrectlySigned !== false;
-}
-
-function isDiscoverEnabled() {
- if (Services.prefs.getPrefType(PREF_DISCOVERURL) == Services.prefs.PREF_INVALID)
- return false;
-
- try {
- if (!Services.prefs.getBoolPref(PREF_DISCOVER_ENABLED))
- return false;
- } catch (e) {}
-
- try {
- if (!Services.prefs.getBoolPref(PREF_XPI_ENABLED))
- return false;
- } catch (e) {}
-
- return true;
-}
-
-/**
- * Obtain the main DOMWindow for the current context.
- */
-function getMainWindow() {
- return window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .QueryInterface(Ci.nsIDocShellTreeItem)
- .rootTreeItem
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
-}
-
-function getBrowserElement() {
- return window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDocShell)
- .chromeEventHandler;
-}
-
-/**
- * Obtain the DOMWindow that can open a preferences pane.
- *
- * This is essentially "get the browser chrome window" with the added check
- * that the supposed browser chrome window is capable of opening a preferences
- * pane.
- *
- * This may return null if we can't find the browser chrome window.
- */
-function getMainWindowWithPreferencesPane() {
- let mainWindow = getMainWindow();
- if (mainWindow && "openAdvancedPreferences" in mainWindow) {
- return mainWindow;
- }
- return null;
-}
-
-/**
- * A wrapper around the HTML5 session history service that allows the browser
- * back/forward controls to work within the manager
- */
-var HTML5History = {
- get index() {
- return window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .sessionHistory.index;
- },
-
- get canGoBack() {
- return window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .canGoBack;
- },
-
- get canGoForward() {
- return window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .canGoForward;
- },
-
- back: function() {
- window.history.back();
- gViewController.updateCommand("cmd_back");
- gViewController.updateCommand("cmd_forward");
- },
-
- forward: function() {
- window.history.forward();
- gViewController.updateCommand("cmd_back");
- gViewController.updateCommand("cmd_forward");
- },
-
- pushState: function(aState) {
- window.history.pushState(aState, document.title);
- },
-
- replaceState: function(aState) {
- window.history.replaceState(aState, document.title);
- },
-
- popState: function() {
- function onStatePopped(aEvent) {
- window.removeEventListener("popstate", onStatePopped, true);
- // TODO To ensure we can't go forward again we put an additional entry
- // for the current state into the history. Ideally we would just strip
- // the history but there doesn't seem to be a way to do that. Bug 590661
- window.history.pushState(aEvent.state, document.title);
- }
- window.addEventListener("popstate", onStatePopped, true);
- window.history.back();
- gViewController.updateCommand("cmd_back");
- gViewController.updateCommand("cmd_forward");
- }
-};
-
-/**
- * A wrapper around a fake history service
- */
-var FakeHistory = {
- pos: 0,
- states: [null],
-
- get index() {
- return this.pos;
- },
-
- get canGoBack() {
- return this.pos > 0;
- },
-
- get canGoForward() {
- return (this.pos + 1) < this.states.length;
- },
-
- back: function() {
- if (this.pos == 0)
- throw Components.Exception("Cannot go back from this point");
-
- this.pos--;
- gViewController.updateState(this.states[this.pos]);
- gViewController.updateCommand("cmd_back");
- gViewController.updateCommand("cmd_forward");
- },
-
- forward: function() {
- if ((this.pos + 1) >= this.states.length)
- throw Components.Exception("Cannot go forward from this point");
-
- this.pos++;
- gViewController.updateState(this.states[this.pos]);
- gViewController.updateCommand("cmd_back");
- gViewController.updateCommand("cmd_forward");
- },
-
- pushState: function(aState) {
- this.pos++;
- this.states.splice(this.pos, this.states.length);
- this.states.push(aState);
- },
-
- replaceState: function(aState) {
- this.states[this.pos] = aState;
- },
-
- popState: function() {
- if (this.pos == 0)
- throw Components.Exception("Cannot popState from this view");
-
- this.states.splice(this.pos, this.states.length);
- this.pos--;
-
- gViewController.updateState(this.states[this.pos]);
- gViewController.updateCommand("cmd_back");
- gViewController.updateCommand("cmd_forward");
- }
-};
-
-// If the window has a session history then use the HTML5 History wrapper
-// otherwise use our fake history implementation
-if (window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .sessionHistory) {
- var gHistory = HTML5History;
-}
-else {
- gHistory = FakeHistory;
-}
-
-var gEventManager = {
- _listeners: {},
- _installListeners: [],
-
- initialize: function() {
- const ADDON_EVENTS = ["onEnabling", "onEnabled", "onDisabling",
- "onDisabled", "onUninstalling", "onUninstalled",
- "onInstalled", "onOperationCancelled",
- "onUpdateAvailable", "onUpdateFinished",
- "onCompatibilityUpdateAvailable",
- "onPropertyChanged"];
- for (let evt of ADDON_EVENTS) {
- let event = evt;
- this[event] = (...aArgs) => this.delegateAddonEvent(event, aArgs);
- }
-
- const INSTALL_EVENTS = ["onNewInstall", "onDownloadStarted",
- "onDownloadEnded", "onDownloadFailed",
- "onDownloadProgress", "onDownloadCancelled",
- "onInstallStarted", "onInstallEnded",
- "onInstallFailed", "onInstallCancelled",
- "onExternalInstall"];
- for (let evt of INSTALL_EVENTS) {
- let event = evt;
- this[event] = (...aArgs) => this.delegateInstallEvent(event, aArgs);
- }
-
- AddonManager.addManagerListener(this);
- AddonManager.addInstallListener(this);
- AddonManager.addAddonListener(this);
-
- this.refreshGlobalWarning();
- this.refreshAutoUpdateDefault();
-
- var contextMenu = document.getElementById("addonitem-popup");
- contextMenu.addEventListener("popupshowing", function() {
- var addon = gViewController.currentViewObj.getSelectedAddon();
- contextMenu.setAttribute("addontype", addon.type);
-
- var menuSep = document.getElementById("addonitem-menuseparator");
- var countMenuItemsBeforeSep = 0;
- for (let child of contextMenu.children) {
- if (child == menuSep) {
- break;
- }
- if (child.nodeName == "menuitem" &&
- gViewController.isCommandEnabled(child.command)) {
- countMenuItemsBeforeSep++;
- }
- }
-
- // Hide the separator if there are no visible menu items before it
- menuSep.hidden = (countMenuItemsBeforeSep == 0);
-
- }, false);
-
- let addonTooltip = document.getElementById("addonitem-tooltip");
- addonTooltip.addEventListener("popupshowing", function() {
- let addonItem = addonTooltip.triggerNode;
- // The way the test triggers the tooltip the richlistitem is the
- // tooltipNode but in normal use it is the anonymous node. This allows
- // any case
- if (addonItem.localName != "richlistitem")
- addonItem = document.getBindingParent(addonItem);
-
- let tiptext = addonItem.getAttribute("name");
-
- if (addonItem.mAddon) {
- if (shouldShowVersionNumber(addonItem.mAddon)) {
- tiptext += " " + (addonItem.hasAttribute("upgrade") ? addonItem.mManualUpdate.version
- : addonItem.mAddon.version);
- }
- }
- else if (shouldShowVersionNumber(addonItem.mInstall)) {
- tiptext += " " + addonItem.mInstall.version;
- }
-
- addonTooltip.label = tiptext;
- }, false);
- },
-
- shutdown: function() {
- AddonManager.removeManagerListener(this);
- AddonManager.removeInstallListener(this);
- AddonManager.removeAddonListener(this);
- },
-
- registerAddonListener: function(aListener, aAddonId) {
- if (!(aAddonId in this._listeners))
- this._listeners[aAddonId] = [];
- else if (this._listeners[aAddonId].indexOf(aListener) != -1)
- return;
- this._listeners[aAddonId].push(aListener);
- },
-
- unregisterAddonListener: function(aListener, aAddonId) {
- if (!(aAddonId in this._listeners))
- return;
- var index = this._listeners[aAddonId].indexOf(aListener);
- if (index == -1)
- return;
- this._listeners[aAddonId].splice(index, 1);
- },
-
- registerInstallListener: function(aListener) {
- if (this._installListeners.indexOf(aListener) != -1)
- return;
- this._installListeners.push(aListener);
- },
-
- unregisterInstallListener: function(aListener) {
- var i = this._installListeners.indexOf(aListener);
- if (i == -1)
- return;
- this._installListeners.splice(i, 1);
- },
-
- delegateAddonEvent: function(aEvent, aParams) {
- var addon = aParams.shift();
- if (!(addon.id in this._listeners))
- return;
-
- var listeners = this._listeners[addon.id];
- for (let listener of listeners) {
- if (!(aEvent in listener))
- continue;
- try {
- listener[aEvent].apply(listener, aParams);
- } catch (e) {
- // this shouldn't be fatal
- Cu.reportError(e);
- }
- }
- },
-
- delegateInstallEvent: function(aEvent, aParams) {
- var existingAddon = aEvent == "onExternalInstall" ? aParams[1] : aParams[0].existingAddon;
- // If the install is an update then send the event to all listeners
- // registered for the existing add-on
- if (existingAddon)
- this.delegateAddonEvent(aEvent, [existingAddon].concat(aParams));
-
- for (let listener of this._installListeners) {
- if (!(aEvent in listener))
- continue;
- try {
- listener[aEvent].apply(listener, aParams);
- } catch (e) {
- // this shouldn't be fatal
- Cu.reportError(e);
- }
- }
- },
-
- refreshGlobalWarning: function() {
- var page = document.getElementById("addons-page");
-
- if (Services.appinfo.inSafeMode) {
- page.setAttribute("warning", "safemode");
- return;
- }
-
- if (AddonManager.checkUpdateSecurityDefault &&
- !AddonManager.checkUpdateSecurity) {
- page.setAttribute("warning", "updatesecurity");
- return;
- }
-
- if (!AddonManager.checkCompatibility) {
- page.setAttribute("warning", "checkcompatibility");
- return;
- }
-
- page.removeAttribute("warning");
- },
-
- refreshAutoUpdateDefault: function() {
- var updateEnabled = AddonManager.updateEnabled;
- var autoUpdateDefault = AddonManager.autoUpdateDefault;
-
- // The checkbox needs to reflect that both prefs need to be true
- // for updates to be checked for and applied automatically
- document.getElementById("utils-autoUpdateDefault")
- .setAttribute("checked", updateEnabled && autoUpdateDefault);
-
- document.getElementById("utils-resetAddonUpdatesToAutomatic").hidden = !autoUpdateDefault;
- document.getElementById("utils-resetAddonUpdatesToManual").hidden = autoUpdateDefault;
- },
-
- onCompatibilityModeChanged: function() {
- this.refreshGlobalWarning();
- },
-
- onCheckUpdateSecurityChanged: function() {
- this.refreshGlobalWarning();
- },
-
- onUpdateModeChanged: function() {
- this.refreshAutoUpdateDefault();
- }
-};
-
-
-var gViewController = {
- viewPort: null,
- currentViewId: "",
- currentViewObj: null,
- currentViewRequest: 0,
- viewObjects: {},
- viewChangeCallback: null,
- initialViewSelected: false,
- lastHistoryIndex: -1,
-
- initialize: function() {
- this.viewPort = document.getElementById("view-port");
- this.headeredViews = document.getElementById("headered-views");
- this.headeredViewsDeck = document.getElementById("headered-views-content");
-
- this.viewObjects["search"] = gSearchView;
- this.viewObjects["discover"] = gDiscoverView;
- this.viewObjects["list"] = gListView;
- this.viewObjects["detail"] = gDetailView;
- this.viewObjects["updates"] = gUpdatesView;
-
- for (let type in this.viewObjects) {
- let view = this.viewObjects[type];
- view.initialize();
- }
-
- window.controllers.appendController(this);
-
- window.addEventListener("popstate", function(e) {
- gViewController.updateState(e.state);
- },
- false);
- },
-
- shutdown: function() {
- if (this.currentViewObj)
- this.currentViewObj.hide();
- this.currentViewRequest = 0;
-
- for (let type in this.viewObjects) {
- let view = this.viewObjects[type];
- if ("shutdown" in view) {
- try {
- view.shutdown();
- } catch (e) {
- // this shouldn't be fatal
- Cu.reportError(e);
- }
- }
- }
-
- window.controllers.removeController(this);
- },
-
- updateState: function(state) {
- try {
- this.loadViewInternal(state.view, state.previousView, state);
- this.lastHistoryIndex = gHistory.index;
- }
- catch (e) {
- // The attempt to load the view failed, try moving further along history
- if (this.lastHistoryIndex > gHistory.index) {
- if (gHistory.canGoBack)
- gHistory.back();
- else
- gViewController.replaceView(gViewDefault);
- } else if (gHistory.canGoForward) {
- gHistory.forward();
- } else {
- gViewController.replaceView(gViewDefault);
- }
- }
- },
-
- parseViewId: function(aViewId) {
- var matchRegex = /^addons:\/\/([^\/]+)\/(.*)$/;
- var [, viewType, viewParam] = aViewId.match(matchRegex) || [];
- return {type: viewType, param: decodeURIComponent(viewParam)};
- },
-
- get isLoading() {
- return !this.currentViewObj || this.currentViewObj.node.hasAttribute("loading");
- },
-
- loadView: function(aViewId) {
- var isRefresh = false;
- if (aViewId == this.currentViewId) {
- if (this.isLoading)
- return;
- if (!("refresh" in this.currentViewObj))
- return;
- if (!this.currentViewObj.canRefresh())
- return;
- isRefresh = true;
- }
-
- var state = {
- view: aViewId,
- previousView: this.currentViewId
- };
- if (!isRefresh) {
- gHistory.pushState(state);
- this.lastHistoryIndex = gHistory.index;
- }
- this.loadViewInternal(aViewId, this.currentViewId, state);
- },
-
- // Replaces the existing view with a new one, rewriting the current history
- // entry to match.
- replaceView: function(aViewId) {
- if (aViewId == this.currentViewId)
- return;
-
- var state = {
- view: aViewId,
- previousView: null
- };
- gHistory.replaceState(state);
- this.loadViewInternal(aViewId, null, state);
- },
-
- loadInitialView: function(aViewId) {
- var state = {
- view: aViewId,
- previousView: null
- };
- gHistory.replaceState(state);
-
- this.loadViewInternal(aViewId, null, state);
- this.initialViewSelected = true;
- notifyInitialized();
- },
-
- get displayedView() {
- if (this.viewPort.selectedPanel == this.headeredViews) {
- return this.headeredViewsDeck.selectedPanel;
- }
- return this.viewPort.selectedPanel;
- },
-
- set displayedView(view) {
- let node = view.node;
- if (node.parentNode == this.headeredViewsDeck) {
- this.headeredViewsDeck.selectedPanel = node;
- this.viewPort.selectedPanel = this.headeredViews;
- } else {
- this.viewPort.selectedPanel = node;
- }
- },
-
- loadViewInternal: function(aViewId, aPreviousView, aState) {
- var view = this.parseViewId(aViewId);
-
- if (!view.type || !(view.type in this.viewObjects))
- throw Components.Exception("Invalid view: " + view.type);
-
- var viewObj = this.viewObjects[view.type];
- if (!viewObj.node)
- throw Components.Exception("Root node doesn't exist for '" + view.type + "' view");
-
- if (this.currentViewObj && aViewId != aPreviousView) {
- try {
- let canHide = this.currentViewObj.hide();
- if (canHide === false)
- return;
- this.displayedView.removeAttribute("loading");
- } catch (e) {
- // this shouldn't be fatal
- Cu.reportError(e);
- }
- }
-
- gCategories.select(aViewId, aPreviousView);
-
- this.currentViewId = aViewId;
- this.currentViewObj = viewObj;
-
- this.displayedView = this.currentViewObj;
- this.currentViewObj.node.setAttribute("loading", "true");
- this.currentViewObj.node.focus();
-
- if (aViewId == aPreviousView)
- this.currentViewObj.refresh(view.param, ++this.currentViewRequest, aState);
- else
- this.currentViewObj.show(view.param, ++this.currentViewRequest, aState);
- },
-
- // Moves back in the document history and removes the current history entry
- popState: function(aCallback) {
- this.viewChangeCallback = aCallback;
- gHistory.popState();
- },
-
- notifyViewChanged: function() {
- this.displayedView.removeAttribute("loading");
-
- if (this.viewChangeCallback) {
- this.viewChangeCallback();
- this.viewChangeCallback = null;
- }
-
- var event = document.createEvent("Events");
- event.initEvent("ViewChanged", true, true);
- this.currentViewObj.node.dispatchEvent(event);
- },
-
- commands: {
- cmd_back: {
- isEnabled: function() {
- return gHistory.canGoBack;
- },
- doCommand: function() {
- gHistory.back();
- }
- },
-
- cmd_forward: {
- isEnabled: function() {
- return gHistory.canGoForward;
- },
- doCommand: function() {
- gHistory.forward();
- }
- },
-
- cmd_focusSearch: {
- isEnabled: () => true,
- doCommand: function() {
- gHeader.focusSearchBox();
- }
- },
-
- cmd_restartApp: {
- isEnabled: function() {
- return true;
- },
- doCommand: function() {
- let cancelQuit = Cc["@mozilla.org/supports-PRBool;1"].
- createInstance(Ci.nsISupportsPRBool);
- Services.obs.notifyObservers(cancelQuit, "quit-application-requested",
- "restart");
- if (cancelQuit.data)
- return; // somebody canceled our quit request
-
- let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"].
- getService(Ci.nsIAppStartup);
- appStartup.quit(Ci.nsIAppStartup.eAttemptQuit | Ci.nsIAppStartup.eRestart);
- }
- },
-
- cmd_enableCheckCompatibility: {
- isEnabled: function() {
- return true;
- },
- doCommand: function() {
- AddonManager.checkCompatibility = true;
- }
- },
-
- cmd_enableUpdateSecurity: {
- isEnabled: function() {
- return true;
- },
- doCommand: function() {
- AddonManager.checkUpdateSecurity = true;
- }
- },
-
- cmd_toggleAutoUpdateDefault: {
- isEnabled: function() {
- return true;
- },
- doCommand: function() {
- if (!AddonManager.updateEnabled || !AddonManager.autoUpdateDefault) {
- // One or both of the prefs is false, i.e. the checkbox is not checked.
- // Now toggle both to true. If the user wants us to auto-update
- // add-ons, we also need to auto-check for updates.
- AddonManager.updateEnabled = true;
- AddonManager.autoUpdateDefault = true;
- } else {
- // Both prefs are true, i.e. the checkbox is checked.
- // Toggle the auto pref to false, but don't touch the enabled check.
- AddonManager.autoUpdateDefault = false;
- }
- }
- },
-
- cmd_resetAddonAutoUpdate: {
- isEnabled: function() {
- return true;
- },
- doCommand: function() {
- AddonManager.getAllAddons(function(aAddonList) {
- for (let addon of aAddonList) {
- if ("applyBackgroundUpdates" in addon)
- addon.applyBackgroundUpdates = AddonManager.AUTOUPDATE_DEFAULT;
- }
- });
- }
- },
-
- cmd_goToDiscoverPane: {
- isEnabled: function() {
- return gDiscoverView.enabled;
- },
- doCommand: function() {
- gViewController.loadView("addons://discover/");
- }
- },
-
- cmd_goToRecentUpdates: {
- isEnabled: function() {
- return true;
- },
- doCommand: function() {
- gViewController.loadView("addons://updates/recent");
- }
- },
-
- cmd_goToAvailableUpdates: {
- isEnabled: function() {
- return true;
- },
- doCommand: function() {
- gViewController.loadView("addons://updates/available");
- }
- },
-
- cmd_showItemDetails: {
- isEnabled: function(aAddon) {
- return !!aAddon && (gViewController.currentViewObj != gDetailView);
- },
- doCommand: function(aAddon, aScrollToPreferences) {
- gViewController.loadView("addons://detail/" +
- encodeURIComponent(aAddon.id) +
- (aScrollToPreferences ? "/preferences" : ""));
- }
- },
-
- cmd_findAllUpdates: {
- inProgress: false,
- isEnabled: function() {
- return !this.inProgress;
- },
- doCommand: function() {
- this.inProgress = true;
- gViewController.updateCommand("cmd_findAllUpdates");
- document.getElementById("updates-noneFound").hidden = true;
- document.getElementById("updates-progress").hidden = false;
- document.getElementById("updates-manualUpdatesFound-btn").hidden = true;
-
- var pendingChecks = 0;
- var numUpdated = 0;
- var numManualUpdates = 0;
- var restartNeeded = false;
-
- let updateStatus = () => {
- if (pendingChecks > 0)
- return;
-
- this.inProgress = false;
- gViewController.updateCommand("cmd_findAllUpdates");
- document.getElementById("updates-progress").hidden = true;
- gUpdatesView.maybeRefresh();
-
- if (numManualUpdates > 0 && numUpdated == 0) {
- document.getElementById("updates-manualUpdatesFound-btn").hidden = false;
- return;
- }
-
- if (numUpdated == 0) {
- document.getElementById("updates-noneFound").hidden = false;
- return;
- }
-
- if (restartNeeded) {
- document.getElementById("updates-downloaded").hidden = false;
- document.getElementById("updates-restart-btn").hidden = false;
- } else {
- document.getElementById("updates-installed").hidden = false;
- }
- }
-
- var updateInstallListener = {
- onDownloadFailed: function() {
- pendingChecks--;
- updateStatus();
- },
- onInstallFailed: function() {
- pendingChecks--;
- updateStatus();
- },
- onInstallEnded: function(aInstall, aAddon) {
- pendingChecks--;
- numUpdated++;
- if (isPending(aInstall.existingAddon, "upgrade"))
- restartNeeded = true;
- updateStatus();
- }
- };
-
- var updateCheckListener = {
- onUpdateAvailable: function(aAddon, aInstall) {
- gEventManager.delegateAddonEvent("onUpdateAvailable",
- [aAddon, aInstall]);
- if (AddonManager.shouldAutoUpdate(aAddon)) {
- aInstall.addListener(updateInstallListener);
- aInstall.install();
- } else {
- pendingChecks--;
- numManualUpdates++;
- updateStatus();
- }
- },
- onNoUpdateAvailable: function(aAddon) {
- pendingChecks--;
- updateStatus();
- },
- onUpdateFinished: function(aAddon, aError) {
- gEventManager.delegateAddonEvent("onUpdateFinished",
- [aAddon, aError]);
- }
- };
-
- AddonManager.getAddonsByTypes(null, function(aAddonList) {
- for (let addon of aAddonList) {
- if (addon.permissions & AddonManager.PERM_CAN_UPGRADE) {
- pendingChecks++;
- addon.findUpdates(updateCheckListener,
- AddonManager.UPDATE_WHEN_USER_REQUESTED);
- }
- }
-
- if (pendingChecks == 0)
- updateStatus();
- });
- }
- },
-
- cmd_findItemUpdates: {
- isEnabled: function(aAddon) {
- if (!aAddon)
- return false;
- return hasPermission(aAddon, "upgrade");
- },
- doCommand: function(aAddon) {
- var listener = {
- onUpdateAvailable: function(aAddon, aInstall) {
- gEventManager.delegateAddonEvent("onUpdateAvailable",
- [aAddon, aInstall]);
- if (AddonManager.shouldAutoUpdate(aAddon))
- aInstall.install();
- },
- onNoUpdateAvailable: function(aAddon) {
- gEventManager.delegateAddonEvent("onNoUpdateAvailable",
- [aAddon]);
- }
- };
- gEventManager.delegateAddonEvent("onCheckingUpdate", [aAddon]);
- aAddon.findUpdates(listener, AddonManager.UPDATE_WHEN_USER_REQUESTED);
- }
- },
-
- cmd_showItemPreferences: {
- isEnabled: function(aAddon) {
- if (!aAddon ||
- (!aAddon.isActive && !aAddon.isGMPlugin) ||
- !aAddon.optionsURL) {
- return false;
- }
- if (gViewController.currentViewObj == gDetailView &&
- (aAddon.optionsType == AddonManager.OPTIONS_TYPE_INLINE ||
- aAddon.optionsType == AddonManager.OPTIONS_TYPE_INLINE_BROWSER)) {
- return false;
- }
- if (aAddon.optionsType == AddonManager.OPTIONS_TYPE_INLINE_INFO)
- return false;
- return true;
- },
- doCommand: function(aAddon) {
- if (hasInlineOptions(aAddon)) {
- gViewController.commands.cmd_showItemDetails.doCommand(aAddon, true);
- return;
- }
- var optionsURL = aAddon.optionsURL;
- if (aAddon.optionsType == AddonManager.OPTIONS_TYPE_TAB &&
- openOptionsInTab(optionsURL)) {
- return;
- }
- var windows = Services.wm.getEnumerator(null);
- while (windows.hasMoreElements()) {
- var win = windows.getNext();
- if (win.closed) {
- continue;
- }
- if (win.document.documentURI == optionsURL) {
- win.focus();
- return;
- }
- }
- var features = "chrome,titlebar,toolbar,centerscreen";
- try {
- var instantApply = Services.prefs.getBoolPref("browser.preferences.instantApply");
- features += instantApply ? ",dialog=no" : ",modal";
- } catch (e) {
- features += ",modal";
- }
- openDialog(optionsURL, "", features);
- }
- },
-
- cmd_showItemAbout: {
- isEnabled: function(aAddon) {
- // XXXunf This may be applicable to install items too. See bug 561260
- return !!aAddon;
- },
- doCommand: function(aAddon) {
- var aboutURL = aAddon.aboutURL;
- if (aboutURL)
- openDialog(aboutURL, "", "chrome,centerscreen,modal", aAddon);
- else
- openDialog("chrome://mozapps/content/extensions/about.xul",
- "", "chrome,centerscreen,modal", aAddon);
- }
- },
-
- cmd_enableItem: {
- isEnabled: function(aAddon) {
- if (!aAddon)
- return false;
- let addonType = AddonManager.addonTypes[aAddon.type];
- return (!(addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) &&
- hasPermission(aAddon, "enable"));
- },
- doCommand: function(aAddon) {
- aAddon.userDisabled = false;
- },
- getTooltip: function(aAddon) {
- if (!aAddon)
- return "";
- if (aAddon.operationsRequiringRestart & AddonManager.OP_NEEDS_RESTART_ENABLE)
- return gStrings.ext.GetStringFromName("enableAddonRestartRequiredTooltip");
- return gStrings.ext.GetStringFromName("enableAddonTooltip");
- }
- },
-
- cmd_disableItem: {
- isEnabled: function(aAddon) {
- if (!aAddon)
- return false;
- let addonType = AddonManager.addonTypes[aAddon.type];
- return (!(addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) &&
- hasPermission(aAddon, "disable"));
- },
- doCommand: function(aAddon) {
- aAddon.userDisabled = true;
- },
- getTooltip: function(aAddon) {
- if (!aAddon)
- return "";
- if (aAddon.operationsRequiringRestart & AddonManager.OP_NEEDS_RESTART_DISABLE)
- return gStrings.ext.GetStringFromName("disableAddonRestartRequiredTooltip");
- return gStrings.ext.GetStringFromName("disableAddonTooltip");
- }
- },
-
- cmd_installItem: {
- isEnabled: function(aAddon) {
- if (!aAddon)
- return false;
- return aAddon.install && aAddon.install.state == AddonManager.STATE_AVAILABLE;
- },
- doCommand: function(aAddon) {
- function doInstall() {
- gViewController.currentViewObj.getListItemForID(aAddon.id)._installStatus.installRemote();
- }
-
- if (gViewController.currentViewObj == gDetailView)
- gViewController.popState(doInstall);
- else
- doInstall();
- }
- },
-
- cmd_purchaseItem: {
- isEnabled: function(aAddon) {
- if (!aAddon)
- return false;
- return !!aAddon.purchaseURL;
- },
- doCommand: function(aAddon) {
- openURL(aAddon.purchaseURL);
- }
- },
-
- cmd_uninstallItem: {
- isEnabled: function(aAddon) {
- if (!aAddon)
- return false;
- return hasPermission(aAddon, "uninstall");
- },
- doCommand: function(aAddon) {
- if (gViewController.currentViewObj != gDetailView) {
- aAddon.uninstall();
- return;
- }
-
- gViewController.popState(function() {
- gViewController.currentViewObj.getListItemForID(aAddon.id).uninstall();
- });
- },
- getTooltip: function(aAddon) {
- if (!aAddon)
- return "";
- if (aAddon.operationsRequiringRestart & AddonManager.OP_NEEDS_RESTART_UNINSTALL)
- return gStrings.ext.GetStringFromName("uninstallAddonRestartRequiredTooltip");
- return gStrings.ext.GetStringFromName("uninstallAddonTooltip");
- }
- },
-
- cmd_cancelUninstallItem: {
- isEnabled: function(aAddon) {
- if (!aAddon)
- return false;
- return isPending(aAddon, "uninstall");
- },
- doCommand: function(aAddon) {
- aAddon.cancelUninstall();
- }
- },
-
- cmd_installFromFile: {
- isEnabled: function() {
- return true;
- },
- doCommand: function() {
- const nsIFilePicker = Ci.nsIFilePicker;
- var fp = Cc["@mozilla.org/filepicker;1"]
- .createInstance(nsIFilePicker);
- fp.init(window,
- gStrings.ext.GetStringFromName("installFromFile.dialogTitle"),
- nsIFilePicker.modeOpenMultiple);
- try {
- fp.appendFilter(gStrings.ext.GetStringFromName("installFromFile.filterName"),
- "*.xpi;*.jar");
- fp.appendFilters(nsIFilePicker.filterAll);
- } catch (e) { }
-
- if (fp.show() != nsIFilePicker.returnOK)
- return;
-
- var files = fp.files;
- var installs = [];
-
- function buildNextInstall() {
- if (!files.hasMoreElements()) {
- if (installs.length > 0) {
- // Display the normal install confirmation for the installs
- let webInstaller = Cc["@mozilla.org/addons/web-install-listener;1"].
- getService(Ci.amIWebInstallListener);
- webInstaller.onWebInstallRequested(getBrowserElement(),
- document.documentURIObject,
- installs);
- }
- return;
- }
-
- var file = files.getNext();
- AddonManager.getInstallForFile(file, function(aInstall) {
- installs.push(aInstall);
- buildNextInstall();
- });
- }
-
- buildNextInstall();
- }
- },
-
- cmd_debugAddons: {
- isEnabled: function() {
- return true;
- },
- doCommand: function() {
- let mainWindow = getMainWindow();
- if ("switchToTabHavingURI" in mainWindow) {
- mainWindow.switchToTabHavingURI("about:debugging#addons", true);
- }
- },
- },
-
- cmd_cancelOperation: {
- isEnabled: function(aAddon) {
- if (!aAddon)
- return false;
- return aAddon.pendingOperations != AddonManager.PENDING_NONE;
- },
- doCommand: function(aAddon) {
- if (isPending(aAddon, "install")) {
- aAddon.install.cancel();
- } else if (isPending(aAddon, "upgrade")) {
- aAddon.pendingUpgrade.install.cancel();
- } else if (isPending(aAddon, "uninstall")) {
- aAddon.cancelUninstall();
- } else if (isPending(aAddon, "enable")) {
- aAddon.userDisabled = true;
- } else if (isPending(aAddon, "disable")) {
- aAddon.userDisabled = false;
- }
- }
- },
-
- cmd_contribute: {
- isEnabled: function(aAddon) {
- if (!aAddon)
- return false;
- return ("contributionURL" in aAddon && aAddon.contributionURL);
- },
- doCommand: function(aAddon) {
- openURL(aAddon.contributionURL);
- }
- },
-
- cmd_askToActivateItem: {
- isEnabled: function(aAddon) {
- if (!aAddon)
- return false;
- let addonType = AddonManager.addonTypes[aAddon.type];
- return ((addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) &&
- hasPermission(aAddon, "ask_to_activate"));
- },
- doCommand: function(aAddon) {
- aAddon.userDisabled = AddonManager.STATE_ASK_TO_ACTIVATE;
- }
- },
-
- cmd_alwaysActivateItem: {
- isEnabled: function(aAddon) {
- if (!aAddon)
- return false;
- let addonType = AddonManager.addonTypes[aAddon.type];
- return ((addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) &&
- hasPermission(aAddon, "enable"));
- },
- doCommand: function(aAddon) {
- aAddon.userDisabled = false;
- }
- },
-
- cmd_neverActivateItem: {
- isEnabled: function(aAddon) {
- if (!aAddon)
- return false;
- let addonType = AddonManager.addonTypes[aAddon.type];
- return ((addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) &&
- hasPermission(aAddon, "disable"));
- },
- doCommand: function(aAddon) {
- aAddon.userDisabled = true;
- }
- },
-
- cmd_showUnsignedExtensions: {
- isEnabled: function() {
- return true;
- },
- doCommand: function() {
- gViewController.loadView("addons://list/extension?unsigned=true");
- },
- },
-
- cmd_showAllExtensions: {
- isEnabled: function() {
- return true;
- },
- doCommand: function() {
- gViewController.loadView("addons://list/extension");
- },
- },
- },
-
- supportsCommand: function(aCommand) {
- return (aCommand in this.commands);
- },
-
- isCommandEnabled: function(aCommand) {
- if (!this.supportsCommand(aCommand))
- return false;
- var addon = this.currentViewObj.getSelectedAddon();
- return this.commands[aCommand].isEnabled(addon);
- },
-
- updateCommands: function() {
- // wait until the view is initialized
- if (!this.currentViewObj)
- return;
- var addon = this.currentViewObj.getSelectedAddon();
- for (let commandId in this.commands)
- this.updateCommand(commandId, addon);
- },
-
- updateCommand: function(aCommandId, aAddon) {
- if (typeof aAddon == "undefined")
- aAddon = this.currentViewObj.getSelectedAddon();
- var cmd = this.commands[aCommandId];
- var cmdElt = document.getElementById(aCommandId);
- cmdElt.setAttribute("disabled", !cmd.isEnabled(aAddon));
- if ("getTooltip" in cmd) {
- let tooltip = cmd.getTooltip(aAddon);
- if (tooltip)
- cmdElt.setAttribute("tooltiptext", tooltip);
- else
- cmdElt.removeAttribute("tooltiptext");
- }
- },
-
- doCommand: function(aCommand, aAddon) {
- if (!this.supportsCommand(aCommand))
- return;
- var cmd = this.commands[aCommand];
- if (!aAddon)
- aAddon = this.currentViewObj.getSelectedAddon();
- if (!cmd.isEnabled(aAddon))
- return;
- cmd.doCommand(aAddon);
- },
-
- onEvent: function() {}
-};
-
-function hasInlineOptions(aAddon) {
- return (aAddon.optionsType == AddonManager.OPTIONS_TYPE_INLINE ||
- aAddon.optionsType == AddonManager.OPTIONS_TYPE_INLINE_BROWSER ||
- aAddon.optionsType == AddonManager.OPTIONS_TYPE_INLINE_INFO);
-}
-
-function openOptionsInTab(optionsURL) {
- let mainWindow = getMainWindow();
- if ("switchToTabHavingURI" in mainWindow) {
- mainWindow.switchToTabHavingURI(optionsURL, true);
- return true;
- }
- return false;
-}
-
-function formatDate(aDate) {
- const locale = Cc["@mozilla.org/chrome/chrome-registry;1"]
- .getService(Ci.nsIXULChromeRegistry)
- .getSelectedLocale("global", true);
- const dtOptions = { year: 'numeric', month: 'long', day: 'numeric' };
- return aDate.toLocaleDateString(locale, dtOptions);
-}
-
-
-function hasPermission(aAddon, aPerm) {
- var perm = AddonManager["PERM_CAN_" + aPerm.toUpperCase()];
- return !!(aAddon.permissions & perm);
-}
-
-
-function isPending(aAddon, aAction) {
- var action = AddonManager["PENDING_" + aAction.toUpperCase()];
- return !!(aAddon.pendingOperations & action);
-}
-
-function isInState(aInstall, aState) {
- var state = AddonManager["STATE_" + aState.toUpperCase()];
- return aInstall.state == state;
-}
-
-function shouldShowVersionNumber(aAddon) {
- if (!aAddon.version)
- return false;
-
- // The version number is hidden for lightweight themes.
- if (aAddon.type == "theme")
- return !/@personas\.mozilla\.org$/.test(aAddon.id);
-
- return true;
-}
-
-function createItem(aObj, aIsInstall, aIsRemote) {
- let item = document.createElement("richlistitem");
-
- item.setAttribute("class", "addon addon-view");
- item.setAttribute("name", aObj.name);
- item.setAttribute("type", aObj.type);
- item.setAttribute("remote", !!aIsRemote);
-
- if (aIsInstall) {
- item.mInstall = aObj;
-
- if (aObj.state != AddonManager.STATE_INSTALLED) {
- item.setAttribute("status", "installing");
- return item;
- }
- aObj = aObj.addon;
- }
-
- item.mAddon = aObj;
-
- item.setAttribute("status", "installed");
-
- // set only attributes needed for sorting and XBL binding,
- // the binding handles the rest
- item.setAttribute("value", aObj.id);
-
- return item;
-}
-
-function sortElements(aElements, aSortBy, aAscending) {
- // aSortBy is an Array of attributes to sort by, in decending
- // order of priority.
-
- const DATE_FIELDS = ["updateDate"];
- const NUMERIC_FIELDS = ["size", "relevancescore", "purchaseAmount"];
-
- // We're going to group add-ons into the following buckets:
- //
- // enabledInstalled
- // * Enabled
- // * Incompatible but enabled because compatibility checking is off
- // * Waiting to be installed
- // * Waiting to be enabled
- //
- // pendingDisable
- // * Waiting to be disabled
- //
- // pendingUninstall
- // * Waiting to be removed
- //
- // disabledIncompatibleBlocked
- // * Disabled
- // * Incompatible
- // * Blocklisted
-
- const UISTATE_ORDER = ["enabled", "askToActivate", "pendingDisable",
- "pendingUninstall", "disabled"];
-
- function dateCompare(a, b) {
- var aTime = a.getTime();
- var bTime = b.getTime();
- if (aTime < bTime)
- return -1;
- if (aTime > bTime)
- return 1;
- return 0;
- }
-
- function numberCompare(a, b) {
- return a - b;
- }
-
- function stringCompare(a, b) {
- return a.localeCompare(b);
- }
-
- function uiStateCompare(a, b) {
- // If we're in descending order, swap a and b, because
- // we don't ever want to have descending uiStates
- if (!aAscending)
- [a, b] = [b, a];
-
- return (UISTATE_ORDER.indexOf(a) - UISTATE_ORDER.indexOf(b));
- }
-
- function getValue(aObj, aKey) {
- if (!aObj)
- return null;
-
- if (aObj.hasAttribute(aKey))
- return aObj.getAttribute(aKey);
-
- var addon = aObj.mAddon || aObj.mInstall;
- var addonType = aObj.mAddon && AddonManager.addonTypes[aObj.mAddon.type];
-
- if (!addon)
- return null;
-
- if (aKey == "uiState") {
- if (addon.pendingOperations == AddonManager.PENDING_DISABLE)
- return "pendingDisable";
- if (addon.pendingOperations == AddonManager.PENDING_UNINSTALL)
- return "pendingUninstall";
- if (!addon.isActive &&
- (addon.pendingOperations != AddonManager.PENDING_ENABLE &&
- addon.pendingOperations != AddonManager.PENDING_INSTALL))
- return "disabled";
- if (addonType && (addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) &&
- addon.userDisabled == AddonManager.STATE_ASK_TO_ACTIVATE)
- return "askToActivate";
- return "enabled";
- }
-
- return addon[aKey];
- }
-
- // aSortFuncs will hold the sorting functions that we'll
- // use per element, in the correct order.
- var aSortFuncs = [];
-
- for (let i = 0; i < aSortBy.length; i++) {
- var sortBy = aSortBy[i];
-
- aSortFuncs[i] = stringCompare;
-
- if (sortBy == "uiState")
- aSortFuncs[i] = uiStateCompare;
- else if (DATE_FIELDS.indexOf(sortBy) != -1)
- aSortFuncs[i] = dateCompare;
- else if (NUMERIC_FIELDS.indexOf(sortBy) != -1)
- aSortFuncs[i] = numberCompare;
- }
-
-
- aElements.sort(function(a, b) {
- if (!aAscending)
- [a, b] = [b, a];
-
- for (let i = 0; i < aSortFuncs.length; i++) {
- var sortBy = aSortBy[i];
- var aValue = getValue(a, sortBy);
- var bValue = getValue(b, sortBy);
-
- if (!aValue && !bValue)
- return 0;
- if (!aValue)
- return -1;
- if (!bValue)
- return 1;
- if (aValue != bValue) {
- var result = aSortFuncs[i](aValue, bValue);
-
- if (result != 0)
- return result;
- }
- }
-
- // If we got here, then all values of a and b
- // must have been equal.
- return 0;
-
- });
-}
-
-function sortList(aList, aSortBy, aAscending) {
- var elements = Array.slice(aList.childNodes, 0);
- sortElements(elements, [aSortBy], aAscending);
-
- while (aList.listChild)
- aList.removeChild(aList.lastChild);
-
- for (let element of elements)
- aList.appendChild(element);
-}
-
-function getAddonsAndInstalls(aType, aCallback) {
- let addons = null, installs = null;
- let types = (aType != null) ? [aType] : null;
-
- AddonManager.getAddonsByTypes(types, function(aAddonsList) {
- addons = aAddonsList.filter(a => !a.hidden);
- if (installs != null)
- aCallback(addons, installs);
- });
-
- AddonManager.getInstallsByTypes(types, function(aInstallsList) {
- // skip over upgrade installs and non-active installs
- installs = aInstallsList.filter(function(aInstall) {
- return !(aInstall.existingAddon ||
- aInstall.state == AddonManager.STATE_AVAILABLE);
- });
-
- if (addons != null)
- aCallback(addons, installs)
- });
-}
-
-function doPendingUninstalls(aListBox) {
- // Uninstalling add-ons can mutate the list so find the add-ons first then
- // uninstall them
- var items = [];
- var listitem = aListBox.firstChild;
- while (listitem) {
- if (listitem.getAttribute("pending") == "uninstall" &&
- !(listitem.opRequiresRestart("UNINSTALL")))
- items.push(listitem.mAddon);
- listitem = listitem.nextSibling;
- }
-
- for (let addon of items)
- addon.uninstall();
-}
-
-var gCategories = {
- node: null,
- _search: null,
-
- initialize: function() {
- this.node = document.getElementById("categories");
- this._search = this.get("addons://search/");
-
- var types = AddonManager.addonTypes;
- for (var type in types)
- this.onTypeAdded(types[type]);
-
- AddonManager.addTypeListener(this);
-
- try {
- this.node.value = Services.prefs.getCharPref(PREF_UI_LASTCATEGORY);
- } catch (e) { }
-
- // If there was no last view or no existing category matched the last view
- // then the list will default to selecting the search category and we never
- // want to show that as the first view so switch to the default category
- if (!this.node.selectedItem || this.node.selectedItem == this._search)
- this.node.value = gViewDefault;
-
- this.node.addEventListener("select", () => {
- this.maybeHideSearch();
- gViewController.loadView(this.node.selectedItem.value);
- }, false);
-
- this.node.addEventListener("click", (aEvent) => {
- var selectedItem = this.node.selectedItem;
- if (aEvent.target.localName == "richlistitem" &&
- aEvent.target == selectedItem) {
- var viewId = selectedItem.value;
-
- if (gViewController.parseViewId(viewId).type == "search") {
- viewId += encodeURIComponent(gHeader.searchQuery);
- }
-
- gViewController.loadView(viewId);
- }
- }, false);
- },
-
- shutdown: function() {
- AddonManager.removeTypeListener(this);
- },
-
- _insertCategory: function(aId, aName, aView, aPriority, aStartHidden) {
- // If this category already exists then don't re-add it
- if (document.getElementById("category-" + aId))
- return;
-
- var category = document.createElement("richlistitem");
- category.setAttribute("id", "category-" + aId);
- category.setAttribute("value", aView);
- category.setAttribute("class", "category");
- category.setAttribute("name", aName);
- category.setAttribute("tooltiptext", aName);
- category.setAttribute("priority", aPriority);
- category.setAttribute("hidden", aStartHidden);
-
- var node;
- for (node of this.node.children) {
- var nodePriority = parseInt(node.getAttribute("priority"));
- // If the new type's priority is higher than this one then this is the
- // insertion point
- if (aPriority < nodePriority)
- break;
- // If the new type's priority is lower than this one then this is isn't
- // the insertion point
- if (aPriority > nodePriority)
- continue;
- // If the priorities are equal and the new type's name is earlier
- // alphabetically then this is the insertion point
- if (String.localeCompare(aName, node.getAttribute("name")) < 0)
- break;
- }
-
- this.node.insertBefore(category, node);
- },
-
- _removeCategory: function(aId) {
- var category = document.getElementById("category-" + aId);
- if (!category)
- return;
-
- // If this category is currently selected then switch to the default view
- if (this.node.selectedItem == category)
- gViewController.replaceView(gViewDefault);
-
- this.node.removeChild(category);
- },
-
- onTypeAdded: function(aType) {
- // Ignore types that we don't have a view object for
- if (!(aType.viewType in gViewController.viewObjects))
- return;
-
- var aViewId = "addons://" + aType.viewType + "/" + aType.id;
-
- var startHidden = false;
- if (aType.flags & AddonManager.TYPE_UI_HIDE_EMPTY) {
- var prefName = PREF_UI_TYPE_HIDDEN.replace("%TYPE%", aType.id);
- try {
- startHidden = Services.prefs.getBoolPref(prefName);
- }
- catch (e) {
- // Default to hidden
- startHidden = true;
- }
-
- gPendingInitializations++;
- getAddonsAndInstalls(aType.id, (aAddonsList, aInstallsList) => {
- var hidden = (aAddonsList.length == 0 && aInstallsList.length == 0);
- var item = this.get(aViewId);
-
- // Don't load view that is becoming hidden
- if (hidden && aViewId == gViewController.currentViewId)
- gViewController.loadView(gViewDefault);
-
- item.hidden = hidden;
- Services.prefs.setBoolPref(prefName, hidden);
-
- if (aAddonsList.length > 0 || aInstallsList.length > 0) {
- notifyInitialized();
- return;
- }
-
- gEventManager.registerInstallListener({
- onDownloadStarted: function(aInstall) {
- this._maybeShowCategory(aInstall);
- },
-
- onInstallStarted: function(aInstall) {
- this._maybeShowCategory(aInstall);
- },
-
- onInstallEnded: function(aInstall, aAddon) {
- this._maybeShowCategory(aAddon);
- },
-
- onExternalInstall: function(aAddon, aExistingAddon, aRequiresRestart) {
- this._maybeShowCategory(aAddon);
- },
-
- _maybeShowCategory: aAddon => {
- if (aType.id == aAddon.type) {
- this.get(aViewId).hidden = false;
- Services.prefs.setBoolPref(prefName, false);
- gEventManager.unregisterInstallListener(this);
- }
- }
- });
-
- notifyInitialized();
- });
- }
-
- this._insertCategory(aType.id, aType.name, aViewId, aType.uiPriority,
- startHidden);
- },
-
- onTypeRemoved: function(aType) {
- this._removeCategory(aType.id);
- },
-
- get selected() {
- return this.node.selectedItem ? this.node.selectedItem.value : null;
- },
-
- select: function(aId, aPreviousView) {
- var view = gViewController.parseViewId(aId);
- if (view.type == "detail" && aPreviousView) {
- aId = aPreviousView;
- view = gViewController.parseViewId(aPreviousView);
- }
- aId = aId.replace(/\?.*/, "");
-
- Services.prefs.setCharPref(PREF_UI_LASTCATEGORY, aId);
-
- if (this.node.selectedItem &&
- this.node.selectedItem.value == aId) {
- this.node.selectedItem.hidden = false;
- this.node.selectedItem.disabled = false;
- return;
- }
-
- var item;
- if (view.type == "search")
- item = this._search;
- else
- item = this.get(aId);
-
- if (item) {
- item.hidden = false;
- item.disabled = false;
- this.node.suppressOnSelect = true;
- this.node.selectedItem = item;
- this.node.suppressOnSelect = false;
- this.node.ensureElementIsVisible(item);
-
- this.maybeHideSearch();
- }
- },
-
- get: function(aId) {
- var items = document.getElementsByAttribute("value", aId);
- if (items.length)
- return items[0];
- return null;
- },
-
- setBadge: function(aId, aCount) {
- let item = this.get(aId);
- if (item)
- item.badgeCount = aCount;
- },
-
- maybeHideSearch: function() {
- var view = gViewController.parseViewId(this.node.selectedItem.value);
- this._search.disabled = view.type != "search";
- }
-};
-
-
-var gHeader = {
- _search: null,
- _dest: "",
-
- initialize: function() {
- this._search = document.getElementById("header-search");
-
- this._search.addEventListener("command", function(aEvent) {
- var query = aEvent.target.value;
- if (query.length == 0)
- return;
-
- gViewController.loadView("addons://search/" + encodeURIComponent(query));
- }, false);
-
- function updateNavButtonVisibility() {
- var shouldShow = gHeader.shouldShowNavButtons;
- document.getElementById("back-btn").hidden = !shouldShow;
- document.getElementById("forward-btn").hidden = !shouldShow;
- }
-
- window.addEventListener("focus", function(aEvent) {
- if (aEvent.target == window)
- updateNavButtonVisibility();
- }, false);
-
- updateNavButtonVisibility();
- },
-
- focusSearchBox: function() {
- this._search.focus();
- },
-
- onKeyPress: function(aEvent) {
- if (String.fromCharCode(aEvent.charCode) == "/") {
- this.focusSearchBox();
- return;
- }
- },
-
- get shouldShowNavButtons() {
- var docshellItem = window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .QueryInterface(Ci.nsIDocShellTreeItem);
-
- // If there is no outer frame then make the buttons visible
- if (docshellItem.rootTreeItem == docshellItem)
- return true;
-
- var outerWin = docshellItem.rootTreeItem.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
- var outerDoc = outerWin.document;
- var node = outerDoc.getElementById("back-button");
- // If the outer frame has no back-button then make the buttons visible
- if (!node)
- return true;
-
- // If the back-button or any of its parents are hidden then make the buttons
- // visible
- while (node != outerDoc) {
- var style = outerWin.getComputedStyle(node, "");
- if (style.display == "none")
- return true;
- if (style.visibility != "visible")
- return true;
- node = node.parentNode;
- }
-
- return false;
- },
-
- get searchQuery() {
- return this._search.value;
- },
-
- set searchQuery(aQuery) {
- this._search.value = aQuery;
- },
-};
-
-
-var gDiscoverView = {
- node: null,
- enabled: true,
- // Set to true after the view is first shown. If initialization completes
- // after this then it must also load the discover homepage
- loaded: false,
- _browser: null,
- _loading: null,
- _error: null,
- homepageURL: null,
- _loadListeners: [],
- hideHeader: true,
-
- initialize: function() {
- this.enabled = isDiscoverEnabled();
- if (!this.enabled) {
- gCategories.get("addons://discover/").hidden = true;
- return;
- }
-
- this.node = document.getElementById("discover-view");
- this._loading = document.getElementById("discover-loading");
- this._error = document.getElementById("discover-error");
- this._browser = document.getElementById("discover-browser");
-
- let compatMode = "normal";
- if (!AddonManager.checkCompatibility)
- compatMode = "ignore";
- else if (AddonManager.strictCompatibility)
- compatMode = "strict";
-
- var url = Services.prefs.getCharPref(PREF_DISCOVERURL);
- url = url.replace("%COMPATIBILITY_MODE%", compatMode);
- url = Services.urlFormatter.formatURL(url);
-
- let setURL = (aURL) => {
- try {
- this.homepageURL = Services.io.newURI(aURL, null, null);
- } catch (e) {
- this.showError();
- notifyInitialized();
- return;
- }
-
- this._browser.homePage = this.homepageURL.spec;
- this._browser.addProgressListener(this);
-
- if (this.loaded)
- this._loadURL(this.homepageURL.spec, false, notifyInitialized);
- else
- notifyInitialized();
- }
-
- if (Services.prefs.getBoolPref(PREF_GETADDONS_CACHE_ENABLED) == false) {
- setURL(url);
- return;
- }
-
- gPendingInitializations++;
- AddonManager.getAllAddons(function(aAddons) {
- var list = {};
- for (let addon of aAddons) {
- var prefName = PREF_GETADDONS_CACHE_ID_ENABLED.replace("%ID%",
- addon.id);
- try {
- if (!Services.prefs.getBoolPref(prefName))
- continue;
- } catch (e) { }
- list[addon.id] = {
- name: addon.name,
- version: addon.version,
- type: addon.type,
- userDisabled: addon.userDisabled,
- isCompatible: addon.isCompatible,
- isBlocklisted: addon.blocklistState == Ci.nsIBlocklistService.STATE_BLOCKED
- }
- }
-
- setURL(url + "#" + JSON.stringify(list));
- });
- },
-
- destroy: function() {
- try {
- this._browser.removeProgressListener(this);
- }
- catch (e) {
- // Ignore the case when the listener wasn't already registered
- }
- },
-
- show: function(aParam, aRequest, aState, aIsRefresh) {
- gViewController.updateCommands();
-
- // If we're being told to load a specific URL then just do that
- if (aState && "url" in aState) {
- this.loaded = true;
- this._loadURL(aState.url);
- }
-
- // If the view has loaded before and still at the homepage (if refreshing),
- // and the error page is not visible then there is nothing else to do
- if (this.loaded && this.node.selectedPanel != this._error &&
- (!aIsRefresh || (this._browser.currentURI &&
- this._browser.currentURI.spec == this._browser.homePage))) {
- gViewController.notifyViewChanged();
- return;
- }
-
- this.loaded = true;
-
- // No homepage means initialization isn't complete, the browser will get
- // loaded once initialization is complete
- if (!this.homepageURL) {
- this._loadListeners.push(gViewController.notifyViewChanged.bind(gViewController));
- return;
- }
-
- this._loadURL(this.homepageURL.spec, aIsRefresh,
- gViewController.notifyViewChanged.bind(gViewController));
- },
-
- canRefresh: function() {
- if (this._browser.currentURI &&
- this._browser.currentURI.spec == this._browser.homePage)
- return false;
- return true;
- },
-
- refresh: function(aParam, aRequest, aState) {
- this.show(aParam, aRequest, aState, true);
- },
-
- hide: function() { },
-
- showError: function() {
- this.node.selectedPanel = this._error;
- },
-
- _loadURL: function(aURL, aKeepHistory, aCallback) {
- if (this._browser.currentURI.spec == aURL) {
- if (aCallback)
- aCallback();
- return;
- }
-
- if (aCallback)
- this._loadListeners.push(aCallback);
-
- var flags = 0;
- if (!aKeepHistory)
- flags |= Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY;
-
- this._browser.loadURIWithFlags(aURL, flags);
- },
-
- onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) {
- // Ignore the about:blank load
- if (aLocation.spec == "about:blank")
- return;
-
- // When using the real session history the inner-frame will update the
- // session history automatically, if using the fake history though it must
- // be manually updated
- if (gHistory == FakeHistory) {
- var docshell = aWebProgress.QueryInterface(Ci.nsIDocShell);
-
- var state = {
- view: "addons://discover/",
- url: aLocation.spec
- };
-
- var replaceHistory = Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY << 16;
- if (docshell.loadType & replaceHistory)
- gHistory.replaceState(state);
- else
- gHistory.pushState(state);
- gViewController.lastHistoryIndex = gHistory.index;
- }
-
- gViewController.updateCommands();
-
- // If the hostname is the same as the new location's host and either the
- // default scheme is insecure or the new location is secure then continue
- // with the load
- if (aLocation.host == this.homepageURL.host &&
- (!this.homepageURL.schemeIs("https") || aLocation.schemeIs("https")))
- return;
-
- // Canceling the request will send an error to onStateChange which will show
- // the error page
- aRequest.cancel(Components.results.NS_BINDING_ABORTED);
- },
-
- onSecurityChange: function(aWebProgress, aRequest, aState) {
- // Don't care about security if the page is not https
- if (!this.homepageURL.schemeIs("https"))
- return;
-
- // If the request was secure then it is ok
- if (aState & Ci.nsIWebProgressListener.STATE_IS_SECURE)
- return;
-
- // Canceling the request will send an error to onStateChange which will show
- // the error page
- aRequest.cancel(Components.results.NS_BINDING_ABORTED);
- },
-
- onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) {
- let transferStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT |
- Ci.nsIWebProgressListener.STATE_IS_REQUEST |
- Ci.nsIWebProgressListener.STATE_TRANSFERRING;
- // Once transferring begins show the content
- if ((aStateFlags & transferStart) === transferStart)
- this.node.selectedPanel = this._browser;
-
- // Only care about the network events
- if (!(aStateFlags & (Ci.nsIWebProgressListener.STATE_IS_NETWORK)))
- return;
-
- // If this is the start of network activity then show the loading page
- if (aStateFlags & (Ci.nsIWebProgressListener.STATE_START))
- this.node.selectedPanel = this._loading;
-
- // Ignore anything except stop events
- if (!(aStateFlags & (Ci.nsIWebProgressListener.STATE_STOP)))
- return;
-
- // Consider the successful load of about:blank as still loading
- if (aRequest instanceof Ci.nsIChannel && aRequest.URI.spec == "about:blank")
- return;
-
- // If there was an error loading the page or the new hostname is not the
- // same as the default hostname or the default scheme is secure and the new
- // scheme is insecure then show the error page
- const NS_ERROR_PARSED_DATA_CACHED = 0x805D0021;
- if (!(Components.isSuccessCode(aStatus) || aStatus == NS_ERROR_PARSED_DATA_CACHED) ||
- (aRequest && aRequest instanceof Ci.nsIHttpChannel && !aRequest.requestSucceeded)) {
- this.showError();
- } else {
- // Got a successful load, make sure the browser is visible
- this.node.selectedPanel = this._browser;
- gViewController.updateCommands();
- }
-
- var listeners = this._loadListeners;
- this._loadListeners = [];
-
- for (let listener of listeners)
- listener();
- },
-
- onProgressChange: function() { },
- onStatusChange: function() { },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
- Ci.nsISupportsWeakReference]),
-
- getSelectedAddon: function() {
- return null;
- }
-};
-
-
-var gCachedAddons = {};
-
-var gSearchView = {
- node: null,
- _filter: null,
- _sorters: null,
- _loading: null,
- _listBox: null,
- _emptyNotice: null,
- _allResultsLink: null,
- _lastQuery: null,
- _lastRemoteTotal: 0,
- _pendingSearches: 0,
-
- initialize: function() {
- this.node = document.getElementById("search-view");
- this._filter = document.getElementById("search-filter-radiogroup");
- this._sorters = document.getElementById("search-sorters");
- this._sorters.handler = this;
- this._loading = document.getElementById("search-loading");
- this._listBox = document.getElementById("search-list");
- this._emptyNotice = document.getElementById("search-list-empty");
- this._allResultsLink = document.getElementById("search-allresults-link");
-
- if (!AddonManager.isInstallEnabled("application/x-xpinstall"))
- this._filter.hidden = true;
-
- this._listBox.addEventListener("keydown", aEvent => {
- if (aEvent.keyCode == aEvent.DOM_VK_RETURN) {
- var item = this._listBox.selectedItem;
- if (item)
- item.showInDetailView();
- }
- }, false);
-
- this._filter.addEventListener("command", () => this.updateView(), false);
- },
-
- shutdown: function() {
- if (AddonRepository.isSearching)
- AddonRepository.cancelSearch();
- },
-
- get isSearching() {
- return this._pendingSearches > 0;
- },
-
- show: function(aQuery, aRequest) {
- gEventManager.registerInstallListener(this);
-
- this.showEmptyNotice(false);
- this.showAllResultsLink(0);
- this.showLoading(true);
- this._sorters.showprice = false;
-
- gHeader.searchQuery = aQuery;
- aQuery = aQuery.trim().toLocaleLowerCase();
- if (this._lastQuery == aQuery) {
- this.updateView();
- gViewController.notifyViewChanged();
- return;
- }
- this._lastQuery = aQuery;
-
- if (AddonRepository.isSearching)
- AddonRepository.cancelSearch();
-
- while (this._listBox.firstChild.localName == "richlistitem")
- this._listBox.removeChild(this._listBox.firstChild);
-
- gCachedAddons = {};
- this._pendingSearches = 2;
- this._sorters.setSort("relevancescore", false);
-
- var elements = [];
-
- let createSearchResults = (aObjsList, aIsInstall, aIsRemote) => {
- for (let index in aObjsList) {
- let obj = aObjsList[index];
- let score = aObjsList.length - index;
- if (!aIsRemote && aQuery.length > 0) {
- score = this.getMatchScore(obj, aQuery);
- if (score == 0)
- continue;
- }
-
- let item = createItem(obj, aIsInstall, aIsRemote);
- item.setAttribute("relevancescore", score);
- if (aIsRemote) {
- gCachedAddons[obj.id] = obj;
- if (obj.purchaseURL)
- this._sorters.showprice = true;
- }
-
- elements.push(item);
- }
- }
-
- let finishSearch = (createdCount) => {
- if (elements.length > 0) {
- sortElements(elements, [this._sorters.sortBy], this._sorters.ascending);
- for (let element of elements)
- this._listBox.insertBefore(element, this._listBox.lastChild);
- this.updateListAttributes();
- }
-
- this._pendingSearches--;
- this.updateView();
-
- if (!this.isSearching)
- gViewController.notifyViewChanged();
- }
-
- getAddonsAndInstalls(null, function(aAddons, aInstalls) {
- if (gViewController && aRequest != gViewController.currentViewRequest)
- return;
-
- createSearchResults(aAddons, false, false);
- createSearchResults(aInstalls, true, false);
- finishSearch();
- });
-
- var maxRemoteResults = 0;
- try {
- maxRemoteResults = Services.prefs.getIntPref(PREF_MAXRESULTS);
- } catch (e) {}
-
- if (maxRemoteResults <= 0) {
- finishSearch(0);
- return;
- }
-
- AddonRepository.searchAddons(aQuery, maxRemoteResults, {
- searchFailed: () => {
- if (gViewController && aRequest != gViewController.currentViewRequest)
- return;
-
- this._lastRemoteTotal = 0;
-
- // XXXunf Better handling of AMO search failure. See bug 579502
- finishSearch(0); // Silently fail
- },
-
- searchSucceeded: (aAddonsList, aAddonCount, aTotalResults) => {
- if (gViewController && aRequest != gViewController.currentViewRequest)
- return;
-
- if (aTotalResults > maxRemoteResults)
- this._lastRemoteTotal = aTotalResults;
- else
- this._lastRemoteTotal = 0;
-
- var createdCount = createSearchResults(aAddonsList, false, true);
- finishSearch(createdCount);
- }
- });
- },
-
- showLoading: function(aLoading) {
- this._loading.hidden = !aLoading;
- this._listBox.hidden = aLoading;
- },
-
- updateView: function() {
- var showLocal = this._filter.value == "local";
-
- if (!showLocal && !AddonManager.isInstallEnabled("application/x-xpinstall"))
- showLocal = true;
-
- this._listBox.setAttribute("local", showLocal);
- this._listBox.setAttribute("remote", !showLocal);
-
- this.showLoading(this.isSearching && !showLocal);
- if (!this.isSearching) {
- var isEmpty = true;
- var results = this._listBox.getElementsByTagName("richlistitem");
- for (let result of results) {
- var isRemote = (result.getAttribute("remote") == "true");
- if ((isRemote && !showLocal) || (!isRemote && showLocal)) {
- isEmpty = false;
- break;
- }
- }
-
- this.showEmptyNotice(isEmpty);
- this.showAllResultsLink(this._lastRemoteTotal);
- }
-
- gViewController.updateCommands();
- },
-
- hide: function() {
- gEventManager.unregisterInstallListener(this);
- doPendingUninstalls(this._listBox);
- },
-
- getMatchScore: function(aObj, aQuery) {
- var score = 0;
- score += this.calculateMatchScore(aObj.name, aQuery,
- SEARCH_SCORE_MULTIPLIER_NAME);
- score += this.calculateMatchScore(aObj.description, aQuery,
- SEARCH_SCORE_MULTIPLIER_DESCRIPTION);
- return score;
- },
-
- calculateMatchScore: function(aStr, aQuery, aMultiplier) {
- var score = 0;
- if (!aStr || aQuery.length == 0)
- return score;
-
- aStr = aStr.trim().toLocaleLowerCase();
- var haystack = aStr.split(/\s+/);
- var needles = aQuery.split(/\s+/);
-
- for (let needle of needles) {
- for (let hay of haystack) {
- if (hay == needle) {
- // matching whole words is best
- score += SEARCH_SCORE_MATCH_WHOLEWORD;
- } else {
- let i = hay.indexOf(needle);
- if (i == 0) // matching on word boundries is also good
- score += SEARCH_SCORE_MATCH_WORDBOUNDRY;
- else if (i > 0) // substring matches not so good
- score += SEARCH_SCORE_MATCH_SUBSTRING;
- }
- }
- }
-
- // give progressively higher score for longer queries, since longer queries
- // are more likely to be unique and therefore more relevant.
- if (needles.length > 1 && aStr.indexOf(aQuery) != -1)
- score += needles.length;
-
- return score * aMultiplier;
- },
-
- showEmptyNotice: function(aShow) {
- this._emptyNotice.hidden = !aShow;
- this._listBox.hidden = aShow;
- },
-
- showAllResultsLink: function(aTotalResults) {
- if (aTotalResults == 0) {
- this._allResultsLink.hidden = true;
- return;
- }
-
- var linkStr = gStrings.ext.GetStringFromName("showAllSearchResults");
- linkStr = PluralForm.get(aTotalResults, linkStr);
- linkStr = linkStr.replace("#1", aTotalResults);
- this._allResultsLink.setAttribute("value", linkStr);
-
- this._allResultsLink.setAttribute("href",
- AddonRepository.getSearchURL(this._lastQuery));
- this._allResultsLink.hidden = false;
- },
-
- updateListAttributes: function() {
- var item = this._listBox.querySelector("richlistitem[remote='true'][first]");
- if (item)
- item.removeAttribute("first");
- item = this._listBox.querySelector("richlistitem[remote='true'][last]");
- if (item)
- item.removeAttribute("last");
- var items = this._listBox.querySelectorAll("richlistitem[remote='true']");
- if (items.length > 0) {
- items[0].setAttribute("first", true);
- items[items.length - 1].setAttribute("last", true);
- }
-
- item = this._listBox.querySelector("richlistitem:not([remote='true'])[first]");
- if (item)
- item.removeAttribute("first");
- item = this._listBox.querySelector("richlistitem:not([remote='true'])[last]");
- if (item)
- item.removeAttribute("last");
- items = this._listBox.querySelectorAll("richlistitem:not([remote='true'])");
- if (items.length > 0) {
- items[0].setAttribute("first", true);
- items[items.length - 1].setAttribute("last", true);
- }
-
- },
-
- onSortChanged: function(aSortBy, aAscending) {
- var footer = this._listBox.lastChild;
- this._listBox.removeChild(footer);
-
- sortList(this._listBox, aSortBy, aAscending);
- this.updateListAttributes();
-
- this._listBox.appendChild(footer);
- },
-
- onDownloadCancelled: function(aInstall) {
- this.removeInstall(aInstall);
- },
-
- onInstallCancelled: function(aInstall) {
- this.removeInstall(aInstall);
- },
-
- removeInstall: function(aInstall) {
- for (let item of this._listBox.childNodes) {
- if (item.mInstall == aInstall) {
- this._listBox.removeChild(item);
- return;
- }
- }
- },
-
- getSelectedAddon: function() {
- var item = this._listBox.selectedItem;
- if (item)
- return item.mAddon;
- return null;
- },
-
- getListItemForID: function(aId) {
- var listitem = this._listBox.firstChild;
- while (listitem) {
- if (listitem.getAttribute("status") == "installed" && listitem.mAddon.id == aId)
- return listitem;
- listitem = listitem.nextSibling;
- }
- return null;
- }
-};
-
-
-var gListView = {
- node: null,
- _listBox: null,
- _emptyNotice: null,
- _type: null,
-
- initialize: function() {
- this.node = document.getElementById("list-view");
- this._listBox = document.getElementById("addon-list");
- this._emptyNotice = document.getElementById("addon-list-empty");
-
- this._listBox.addEventListener("keydown", (aEvent) => {
- if (aEvent.keyCode == aEvent.DOM_VK_RETURN) {
- var item = this._listBox.selectedItem;
- if (item)
- item.showInDetailView();
- }
- }, false);
-
- document.getElementById("signing-learn-more").setAttribute("href",
- Services.urlFormatter.formatURLPref("app.support.baseURL") + "unsigned-addons");
-
- let findSignedAddonsLink = document.getElementById("find-alternative-addons");
- try {
- findSignedAddonsLink.setAttribute("href",
- Services.urlFormatter.formatURLPref("extensions.getAddons.link.url"));
- } catch (e) {
- findSignedAddonsLink.classList.remove("text-link");
- }
-
- try {
- document.getElementById("signing-dev-manual-link").setAttribute("href",
- Services.prefs.getCharPref("xpinstall.signatures.devInfoURL"));
- } catch (e) {
- document.getElementById("signing-dev-info").hidden = true;
- }
-
- // To-Do: remove deprecation notice content.
- document.getElementById("plugindeprecation-notice").hidden = true;
- },
-
- show: function(aType, aRequest) {
- let showOnlyDisabledUnsigned = false;
- if (aType.endsWith("?unsigned=true")) {
- aType = aType.replace(/\?.*/, "");
- showOnlyDisabledUnsigned = true;
- }
-
- if (!(aType in AddonManager.addonTypes))
- throw Components.Exception("Attempting to show unknown type " + aType, Cr.NS_ERROR_INVALID_ARG);
-
- this._type = aType;
- this.node.setAttribute("type", aType);
- this.showEmptyNotice(false);
-
- while (this._listBox.itemCount > 0)
- this._listBox.removeItemAt(0);
-
- if (aType == "plugin") {
- navigator.plugins.refresh(false);
- }
-
- getAddonsAndInstalls(aType, (aAddonsList, aInstallsList) => {
- if (gViewController && aRequest != gViewController.currentViewRequest)
- return;
-
- var elements = [];
-
- for (let addonItem of aAddonsList)
- elements.push(createItem(addonItem));
-
- for (let installItem of aInstallsList)
- elements.push(createItem(installItem, true));
-
- this.showEmptyNotice(elements.length == 0);
- if (elements.length > 0) {
- sortElements(elements, ["uiState", "name"], true);
- for (let element of elements)
- this._listBox.appendChild(element);
- }
-
- this.filterDisabledUnsigned(showOnlyDisabledUnsigned);
-
- gEventManager.registerInstallListener(this);
- gViewController.updateCommands();
- gViewController.notifyViewChanged();
- });
- },
-
- hide: function() {
- gEventManager.unregisterInstallListener(this);
- doPendingUninstalls(this._listBox);
- },
-
- filterDisabledUnsigned: function(aFilter = true) {
- let foundDisabledUnsigned = false;
-
- if (SIGNING_REQUIRED) {
- for (let item of this._listBox.childNodes) {
- if (!isCorrectlySigned(item.mAddon))
- foundDisabledUnsigned = true;
- else
- item.hidden = aFilter;
- }
- }
-
- document.getElementById("show-disabled-unsigned-extensions").hidden =
- aFilter || !foundDisabledUnsigned;
-
- document.getElementById("show-all-extensions").hidden = !aFilter;
- document.getElementById("disabled-unsigned-addons-info").hidden = !aFilter;
- },
-
- showEmptyNotice: function(aShow) {
- this._emptyNotice.hidden = !aShow;
- this._listBox.hidden = aShow;
- },
-
- onSortChanged: function(aSortBy, aAscending) {
- sortList(this._listBox, aSortBy, aAscending);
- },
-
- onExternalInstall: function(aAddon, aExistingAddon, aRequiresRestart) {
- // The existing list item will take care of upgrade installs
- if (aExistingAddon)
- return;
-
- if (aAddon.hidden)
- return;
-
- this.addItem(aAddon);
- },
-
- onDownloadStarted: function(aInstall) {
- this.addItem(aInstall, true);
- },
-
- onInstallStarted: function(aInstall) {
- this.addItem(aInstall, true);
- },
-
- onDownloadCancelled: function(aInstall) {
- this.removeItem(aInstall, true);
- },
-
- onInstallCancelled: function(aInstall) {
- this.removeItem(aInstall, true);
- },
-
- onInstallEnded: function(aInstall) {
- // Remove any install entries for upgrades, their status will appear against
- // the existing item
- if (aInstall.existingAddon)
- this.removeItem(aInstall, true);
- },
-
- addItem: function(aObj, aIsInstall) {
- if (aObj.type != this._type)
- return;
-
- if (aIsInstall && aObj.existingAddon)
- return;
-
- let prop = aIsInstall ? "mInstall" : "mAddon";
- for (let item of this._listBox.childNodes) {
- if (item[prop] == aObj)
- return;
- }
-
- let item = createItem(aObj, aIsInstall);
- this._listBox.insertBefore(item, this._listBox.firstChild);
- this.showEmptyNotice(false);
- },
-
- removeItem: function(aObj, aIsInstall) {
- let prop = aIsInstall ? "mInstall" : "mAddon";
-
- for (let item of this._listBox.childNodes) {
- if (item[prop] == aObj) {
- this._listBox.removeChild(item);
- this.showEmptyNotice(this._listBox.itemCount == 0);
- return;
- }
- }
- },
-
- getSelectedAddon: function() {
- var item = this._listBox.selectedItem;
- if (item)
- return item.mAddon;
- return null;
- },
-
- getListItemForID: function(aId) {
- var listitem = this._listBox.firstChild;
- while (listitem) {
- if (listitem.getAttribute("status") == "installed" && listitem.mAddon.id == aId)
- return listitem;
- listitem = listitem.nextSibling;
- }
- return null;
- }
-};
-
-
-var gDetailView = {
- node: null,
- _addon: null,
- _loadingTimer: null,
- _autoUpdate: null,
-
- initialize: function() {
- this.node = document.getElementById("detail-view");
-
- this._autoUpdate = document.getElementById("detail-autoUpdate");
-
- this._autoUpdate.addEventListener("command", () => {
- this._addon.applyBackgroundUpdates = this._autoUpdate.value;
- }, true);
- },
-
- shutdown: function() {
- AddonManager.removeManagerListener(this);
- },
-
- onUpdateModeChanged: function() {
- this.onPropertyChanged(["applyBackgroundUpdates"]);
- },
-
- _updateView: function(aAddon, aIsRemote, aScrollToPreferences) {
- AddonManager.addManagerListener(this);
- this.clearLoading();
-
- this._addon = aAddon;
- gEventManager.registerAddonListener(this, aAddon.id);
- gEventManager.registerInstallListener(this);
-
- this.node.setAttribute("type", aAddon.type);
-
- // If the search category isn't selected then make sure to select the
- // correct category
- if (gCategories.selected != "addons://search/")
- gCategories.select("addons://list/" + aAddon.type);
-
- document.getElementById("detail-name").textContent = aAddon.name;
- var icon = AddonManager.getPreferredIconURL(aAddon, 64, window);
- document.getElementById("detail-icon").src = icon ? icon : "";
- document.getElementById("detail-creator").setCreator(aAddon.creator, aAddon.homepageURL);
-
- var version = document.getElementById("detail-version");
- if (shouldShowVersionNumber(aAddon)) {
- version.hidden = false;
- version.value = aAddon.version;
- } else {
- version.hidden = true;
- }
-
- var screenshotbox = document.getElementById("detail-screenshot-box");
- var screenshot = document.getElementById("detail-screenshot");
- if (aAddon.screenshots && aAddon.screenshots.length > 0) {
- if (aAddon.screenshots[0].thumbnailURL) {
- screenshot.src = aAddon.screenshots[0].thumbnailURL;
- screenshot.width = aAddon.screenshots[0].thumbnailWidth;
- screenshot.height = aAddon.screenshots[0].thumbnailHeight;
- } else {
- screenshot.src = aAddon.screenshots[0].url;
- screenshot.width = aAddon.screenshots[0].width;
- screenshot.height = aAddon.screenshots[0].height;
- }
- screenshot.setAttribute("loading", "true");
- screenshotbox.hidden = false;
- } else {
- screenshotbox.hidden = true;
- }
-
- var desc = document.getElementById("detail-desc");
- desc.textContent = aAddon.description;
-
- var fullDesc = document.getElementById("detail-fulldesc");
- if (aAddon.fullDescription) {
- // The following is part of an awful hack to include the licenses for GMP
- // plugins without having bug 624602 fixed yet, and intentionally ignores
- // localisation.
- if (aAddon.isGMPlugin) {
- fullDesc.innerHTML = aAddon.fullDescription;
- } else {
- fullDesc.textContent = aAddon.fullDescription;
- }
-
- fullDesc.hidden = false;
- } else {
- fullDesc.hidden = true;
- }
-
- var contributions = document.getElementById("detail-contributions");
- if ("contributionURL" in aAddon && aAddon.contributionURL) {
- contributions.hidden = false;
- var amount = document.getElementById("detail-contrib-suggested");
- if (aAddon.contributionAmount) {
- amount.value = gStrings.ext.formatStringFromName("contributionAmount2",
- [aAddon.contributionAmount],
- 1);
- amount.hidden = false;
- } else {
- amount.hidden = true;
- }
- } else {
- contributions.hidden = true;
- }
-
- if ("purchaseURL" in aAddon && aAddon.purchaseURL) {
- var purchase = document.getElementById("detail-purchase-btn");
- purchase.label = gStrings.ext.formatStringFromName("cmd.purchaseAddon.label",
- [aAddon.purchaseDisplayAmount],
- 1);
- purchase.accesskey = gStrings.ext.GetStringFromName("cmd.purchaseAddon.accesskey");
- }
-
- var updateDateRow = document.getElementById("detail-dateUpdated");
- if (aAddon.updateDate) {
- var date = formatDate(aAddon.updateDate);
- updateDateRow.value = date;
- } else {
- updateDateRow.value = null;
- }
-
- // TODO if the add-on was downloaded from releases.mozilla.org link to the
- // AMO profile (bug 590344)
- if (false) {
- document.getElementById("detail-repository-row").hidden = false;
- document.getElementById("detail-homepage-row").hidden = true;
- var repository = document.getElementById("detail-repository");
- repository.value = aAddon.homepageURL;
- repository.href = aAddon.homepageURL;
- } else if (aAddon.homepageURL) {
- document.getElementById("detail-repository-row").hidden = true;
- document.getElementById("detail-homepage-row").hidden = false;
- var homepage = document.getElementById("detail-homepage");
- homepage.value = aAddon.homepageURL;
- homepage.href = aAddon.homepageURL;
- } else {
- document.getElementById("detail-repository-row").hidden = true;
- document.getElementById("detail-homepage-row").hidden = true;
- }
-
- var rating = document.getElementById("detail-rating");
- if (aAddon.averageRating) {
- rating.averageRating = aAddon.averageRating;
- rating.hidden = false;
- } else {
- rating.hidden = true;
- }
-
- var reviews = document.getElementById("detail-reviews");
- if (aAddon.reviewURL) {
- var text = gStrings.ext.GetStringFromName("numReviews");
- text = PluralForm.get(aAddon.reviewCount, text)
- text = text.replace("#1", aAddon.reviewCount);
- reviews.value = text;
- reviews.hidden = false;
- reviews.href = aAddon.reviewURL;
- } else {
- reviews.hidden = true;
- }
-
- document.getElementById("detail-rating-row").hidden = !aAddon.averageRating && !aAddon.reviewURL;
-
- var sizeRow = document.getElementById("detail-size");
- if (aAddon.size && aIsRemote) {
- let [size, unit] = DownloadUtils.convertByteUnits(parseInt(aAddon.size));
- let formatted = gStrings.dl.GetStringFromName("doneSize");
- formatted = formatted.replace("#1", size).replace("#2", unit);
- sizeRow.value = formatted;
- } else {
- sizeRow.value = null;
- }
-
- var downloadsRow = document.getElementById("detail-downloads");
- if (aAddon.totalDownloads && aIsRemote) {
- var downloads = aAddon.totalDownloads;
- downloadsRow.value = downloads;
- } else {
- downloadsRow.value = null;
- }
-
- var canUpdate = !aIsRemote && hasPermission(aAddon, "upgrade") && aAddon.id != AddonManager.hotfixID;
- document.getElementById("detail-updates-row").hidden = !canUpdate;
-
- if ("applyBackgroundUpdates" in aAddon) {
- this._autoUpdate.hidden = false;
- this._autoUpdate.value = aAddon.applyBackgroundUpdates;
- let hideFindUpdates = AddonManager.shouldAutoUpdate(this._addon);
- document.getElementById("detail-findUpdates-btn").hidden = hideFindUpdates;
- } else {
- this._autoUpdate.hidden = true;
- document.getElementById("detail-findUpdates-btn").hidden = false;
- }
-
- document.getElementById("detail-prefs-btn").hidden = !aIsRemote &&
- !gViewController.commands.cmd_showItemPreferences.isEnabled(aAddon);
-
- var gridRows = document.querySelectorAll("#detail-grid rows row");
- let first = true;
- for (let gridRow of gridRows) {
- if (first && window.getComputedStyle(gridRow, null).getPropertyValue("display") != "none") {
- gridRow.setAttribute("first-row", true);
- first = false;
- } else {
- gridRow.removeAttribute("first-row");
- }
- }
-
- this.fillSettingsRows(aScrollToPreferences, (function() {
- this.updateState();
- gViewController.notifyViewChanged();
- }).bind(this));
- },
-
- show: function(aAddonId, aRequest) {
- let index = aAddonId.indexOf("/preferences");
- let scrollToPreferences = false;
- if (index >= 0) {
- aAddonId = aAddonId.substring(0, index);
- scrollToPreferences = true;
- }
-
- this._loadingTimer = setTimeout(() => {
- this.node.setAttribute("loading-extended", true);
- }, LOADING_MSG_DELAY);
-
- var view = gViewController.currentViewId;
-
- AddonManager.getAddonByID(aAddonId, (aAddon) => {
- if (gViewController && aRequest != gViewController.currentViewRequest)
- return;
-
- if (aAddon) {
- this._updateView(aAddon, false, scrollToPreferences);
- return;
- }
-
- // Look for an add-on pending install
- AddonManager.getAllInstalls(aInstalls => {
- for (let install of aInstalls) {
- if (install.state == AddonManager.STATE_INSTALLED &&
- install.addon.id == aAddonId) {
- this._updateView(install.addon, false);
- return;
- }
- }
-
- if (aAddonId in gCachedAddons) {
- this._updateView(gCachedAddons[aAddonId], true);
- return;
- }
-
- // This might happen due to session restore restoring us back to an
- // add-on that doesn't exist but otherwise shouldn't normally happen.
- // Either way just revert to the default view.
- gViewController.replaceView(gViewDefault);
- });
- });
- },
-
- hide: function() {
- AddonManager.removeManagerListener(this);
- this.clearLoading();
- if (this._addon) {
- if (hasInlineOptions(this._addon)) {
- Services.obs.notifyObservers(document,
- AddonManager.OPTIONS_NOTIFICATION_HIDDEN,
- this._addon.id);
- }
-
- gEventManager.unregisterAddonListener(this, this._addon.id);
- gEventManager.unregisterInstallListener(this);
- this._addon = null;
-
- // Flush the preferences to disk so they survive any crash
- if (this.node.getElementsByTagName("setting").length)
- Services.prefs.savePrefFile(null);
- }
- },
-
- updateState: function() {
- gViewController.updateCommands();
-
- var pending = this._addon.pendingOperations;
- if (pending != AddonManager.PENDING_NONE) {
- this.node.removeAttribute("notification");
-
- pending = null;
- const PENDING_OPERATIONS = ["enable", "disable", "install", "uninstall",
- "upgrade"];
- for (let op of PENDING_OPERATIONS) {
- if (isPending(this._addon, op))
- pending = op;
- }
-
- this.node.setAttribute("pending", pending);
- document.getElementById("detail-pending").textContent = gStrings.ext.formatStringFromName(
- "details.notification." + pending,
- [this._addon.name, gStrings.brandShortName], 2
- );
- } else {
- this.node.removeAttribute("pending");
-
- if (this._addon.blocklistState == Ci.nsIBlocklistService.STATE_BLOCKED) {
- this.node.setAttribute("notification", "error");
- document.getElementById("detail-error").textContent = gStrings.ext.formatStringFromName(
- "details.notification.blocked",
- [this._addon.name], 1
- );
- var errorLink = document.getElementById("detail-error-link");
- errorLink.value = gStrings.ext.GetStringFromName("details.notification.blocked.link");
- errorLink.href = this._addon.blocklistURL;
- errorLink.hidden = false;
- } else if (!isCorrectlySigned(this._addon) && SIGNING_REQUIRED) {
- this.node.setAttribute("notification", "error");
- document.getElementById("detail-error").textContent = gStrings.ext.formatStringFromName(
- "details.notification.unsignedAndDisabled", [this._addon.name, gStrings.brandShortName], 2
- );
- let errorLink = document.getElementById("detail-error-link");
- errorLink.value = gStrings.ext.GetStringFromName("details.notification.unsigned.link");
- errorLink.href = Services.urlFormatter.formatURLPref("app.support.baseURL") + "unsigned-addons";
- errorLink.hidden = false;
- } else if (!this._addon.isCompatible && (AddonManager.checkCompatibility ||
- (this._addon.blocklistState != Ci.nsIBlocklistService.STATE_SOFTBLOCKED))) {
- this.node.setAttribute("notification", "warning");
- document.getElementById("detail-warning").textContent = gStrings.ext.formatStringFromName(
- "details.notification.incompatible",
- [this._addon.name, gStrings.brandShortName, gStrings.appVersion], 3
- );
- document.getElementById("detail-warning-link").hidden = true;
- } else if (!isCorrectlySigned(this._addon)) {
- this.node.setAttribute("notification", "warning");
- document.getElementById("detail-warning").textContent = gStrings.ext.formatStringFromName(
- "details.notification.unsigned", [this._addon.name, gStrings.brandShortName], 2
- );
- var warningLink = document.getElementById("detail-warning-link");
- warningLink.value = gStrings.ext.GetStringFromName("details.notification.unsigned.link");
- warningLink.href = Services.urlFormatter.formatURLPref("app.support.baseURL") + "unsigned-addons";
- warningLink.hidden = false;
- } else if (this._addon.blocklistState == Ci.nsIBlocklistService.STATE_SOFTBLOCKED) {
- this.node.setAttribute("notification", "warning");
- document.getElementById("detail-warning").textContent = gStrings.ext.formatStringFromName(
- "details.notification.softblocked",
- [this._addon.name], 1
- );
- let warningLink = document.getElementById("detail-warning-link");
- warningLink.value = gStrings.ext.GetStringFromName("details.notification.softblocked.link");
- warningLink.href = this._addon.blocklistURL;
- warningLink.hidden = false;
- } else if (this._addon.blocklistState == Ci.nsIBlocklistService.STATE_OUTDATED) {
- this.node.setAttribute("notification", "warning");
- document.getElementById("detail-warning").textContent = gStrings.ext.formatStringFromName(
- "details.notification.outdated",
- [this._addon.name], 1
- );
- let warningLink = document.getElementById("detail-warning-link");
- warningLink.value = gStrings.ext.GetStringFromName("details.notification.outdated.link");
- warningLink.href = this._addon.blocklistURL;
- warningLink.hidden = false;
- } else if (this._addon.blocklistState == Ci.nsIBlocklistService.STATE_VULNERABLE_UPDATE_AVAILABLE) {
- this.node.setAttribute("notification", "error");
- document.getElementById("detail-error").textContent = gStrings.ext.formatStringFromName(
- "details.notification.vulnerableUpdatable",
- [this._addon.name], 1
- );
- let errorLink = document.getElementById("detail-error-link");
- errorLink.value = gStrings.ext.GetStringFromName("details.notification.vulnerableUpdatable.link");
- errorLink.href = this._addon.blocklistURL;
- errorLink.hidden = false;
- } else if (this._addon.blocklistState == Ci.nsIBlocklistService.STATE_VULNERABLE_NO_UPDATE) {
- this.node.setAttribute("notification", "error");
- document.getElementById("detail-error").textContent = gStrings.ext.formatStringFromName(
- "details.notification.vulnerableNoUpdate",
- [this._addon.name], 1
- );
- let errorLink = document.getElementById("detail-error-link");
- errorLink.value = gStrings.ext.GetStringFromName("details.notification.vulnerableNoUpdate.link");
- errorLink.href = this._addon.blocklistURL;
- errorLink.hidden = false;
- } else if (this._addon.isGMPlugin && !this._addon.isInstalled &&
- this._addon.isActive) {
- this.node.setAttribute("notification", "warning");
- let warning = document.getElementById("detail-warning");
- warning.textContent =
- gStrings.ext.formatStringFromName("details.notification.gmpPending",
- [this._addon.name], 1);
- } else {
- this.node.removeAttribute("notification");
- }
- }
-
- let menulist = document.getElementById("detail-state-menulist");
- let addonType = AddonManager.addonTypes[this._addon.type];
- if (addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) {
- let askItem = document.getElementById("detail-ask-to-activate-menuitem");
- let alwaysItem = document.getElementById("detail-always-activate-menuitem");
- let neverItem = document.getElementById("detail-never-activate-menuitem");
- let hasActivatePermission =
- ["ask_to_activate", "enable", "disable"].some(perm => hasPermission(this._addon, perm));
-
- if (!this._addon.isActive) {
- menulist.selectedItem = neverItem;
- } else if (this._addon.userDisabled == AddonManager.STATE_ASK_TO_ACTIVATE) {
- menulist.selectedItem = askItem;
- } else {
- menulist.selectedItem = alwaysItem;
- }
-
- menulist.disabled = !hasActivatePermission;
- menulist.hidden = false;
- menulist.classList.add('no-auto-hide');
- } else {
- menulist.hidden = true;
- }
-
- this.node.setAttribute("active", this._addon.isActive);
- },
-
- clearLoading: function() {
- if (this._loadingTimer) {
- clearTimeout(this._loadingTimer);
- this._loadingTimer = null;
- }
-
- this.node.removeAttribute("loading-extended");
- },
-
- emptySettingsRows: function() {
- var lastRow = document.getElementById("detail-downloads");
- var rows = lastRow.parentNode;
- while (lastRow.nextSibling)
- rows.removeChild(rows.lastChild);
- },
-
- fillSettingsRows: function(aScrollToPreferences, aCallback) {
- this.emptySettingsRows();
- if (!hasInlineOptions(this._addon)) {
- if (aCallback)
- aCallback();
- return;
- }
-
- // We can't use a promise for this, since some code (especially in tests)
- // relies on us finishing before the ViewChanged event bubbles up to its
- // listeners, and promises resolve asynchronously.
- let whenViewLoaded = callback => {
- if (gViewController.displayedView.hasAttribute("loading")) {
- gDetailView.node.addEventListener("ViewChanged", function viewChangedEventListener() {
- gDetailView.node.removeEventListener("ViewChanged", viewChangedEventListener);
- callback();
- });
- } else {
- callback();
- }
- };
-
- let finish = (firstSetting) => {
- // Ensure the page has loaded and force the XBL bindings to be synchronously applied,
- // then notify observers.
- whenViewLoaded(() => {
- if (firstSetting)
- firstSetting.clientTop;
- Services.obs.notifyObservers(document,
- AddonManager.OPTIONS_NOTIFICATION_DISPLAYED,
- this._addon.id);
- if (aScrollToPreferences)
- gDetailView.scrollToPreferencesRows();
- });
- }
-
- // This function removes and returns the text content of aNode without
- // removing any child elements. Removing the text nodes ensures any XBL
- // bindings apply properly.
- function stripTextNodes(aNode) {
- var text = '';
- for (var i = 0; i < aNode.childNodes.length; i++) {
- if (aNode.childNodes[i].nodeType != document.ELEMENT_NODE) {
- text += aNode.childNodes[i].textContent;
- aNode.removeChild(aNode.childNodes[i--]);
- } else {
- text += stripTextNodes(aNode.childNodes[i]);
- }
- }
- return text;
- }
-
- var rows = document.getElementById("detail-downloads").parentNode;
-
- try {
- if (this._addon.optionsType == AddonManager.OPTIONS_TYPE_INLINE_BROWSER) {
- whenViewLoaded(() => {
- this.createOptionsBrowser(rows).then(browser => {
- // Make sure the browser is unloaded as soon as we change views,
- // rather than waiting for the next detail view to load.
- document.addEventListener("ViewChanged", function viewChangedEventListener() {
- document.removeEventListener("ViewChanged", viewChangedEventListener);
- browser.remove();
- });
-
- finish(browser);
- });
- });
-
- if (aCallback)
- aCallback();
- } else {
- var xhr = new XMLHttpRequest();
- xhr.open("GET", this._addon.optionsURL, true);
- xhr.responseType = "xml";
- xhr.onload = (function() {
- var xml = xhr.responseXML;
- var settings = xml.querySelectorAll(":root > setting");
-
- var firstSetting = null;
- for (var setting of settings) {
-
- var desc = stripTextNodes(setting).trim();
- if (!setting.hasAttribute("desc"))
- setting.setAttribute("desc", desc);
-
- var type = setting.getAttribute("type");
- if (type == "file" || type == "directory")
- setting.setAttribute("fullpath", "true");
-
- setting = document.importNode(setting, true);
- var style = setting.getAttribute("style");
- if (style) {
- setting.removeAttribute("style");
- setting.setAttribute("style", style);
- }
-
- rows.appendChild(setting);
- var visible = window.getComputedStyle(setting, null).getPropertyValue("display") != "none";
- if (!firstSetting && visible) {
- setting.setAttribute("first-row", true);
- firstSetting = setting;
- }
- }
-
- finish(firstSetting);
-
- if (aCallback)
- aCallback();
- }).bind(this);
- xhr.onerror = function(aEvent) {
- Cu.reportError("Error " + aEvent.target.status +
- " occurred while receiving " + this._addon.optionsURL);
- if (aCallback)
- aCallback();
- };
- xhr.send();
- }
- } catch (e) {
- Cu.reportError(e);
- if (aCallback)
- aCallback();
- }
- },
-
- scrollToPreferencesRows: function() {
- // We find this row, rather than remembering it from above,
- // in case it has been changed by the observers.
- let firstRow = gDetailView.node.querySelector('setting[first-row="true"]');
- if (firstRow) {
- let top = firstRow.boxObject.y;
- top -= parseInt(window.getComputedStyle(firstRow, null).getPropertyValue("margin-top"));
-
- let detailViewBoxObject = gDetailView.node.boxObject;
- top -= detailViewBoxObject.y;
-
- detailViewBoxObject.scrollTo(0, top);
- }
- },
-
- createOptionsBrowser: function(parentNode) {
- let browser = document.createElement("browser");
- browser.setAttribute("type", "content");
- browser.setAttribute("disableglobalhistory", "true");
- browser.setAttribute("class", "inline-options-browser");
-
- return new Promise((resolve, reject) => {
- let messageListener = {
- receiveMessage({name, data}) {
- if (name === "Extension:BrowserResized")
- browser.style.height = `${data.height}px`;
- else if (name === "Extension:BrowserContentLoaded")
- resolve(browser);
- },
- };
-
- let onload = () => {
- browser.removeEventListener("load", onload, true);
-
- let mm = new FakeFrameMessageManager(browser);
- mm.loadFrameScript("chrome://extensions/content/ext-browser-content.js",
- false);
- mm.addMessageListener("Extension:BrowserContentLoaded", messageListener);
- mm.addMessageListener("Extension:BrowserResized", messageListener);
- mm.sendAsyncMessage("Extension:InitBrowser", {fixedWidth: true});
-
- browser.setAttribute("src", this._addon.optionsURL);
- };
- browser.addEventListener("load", onload, true);
- browser.addEventListener("error", reject);
-
- parentNode.appendChild(browser);
- });
- },
-
- getSelectedAddon: function() {
- return this._addon;
- },
-
- onEnabling: function() {
- this.updateState();
- },
-
- onEnabled: function() {
- this.updateState();
- this.fillSettingsRows();
- },
-
- onDisabling: function(aNeedsRestart) {
- this.updateState();
- if (!aNeedsRestart && hasInlineOptions(this._addon)) {
- Services.obs.notifyObservers(document,
- AddonManager.OPTIONS_NOTIFICATION_HIDDEN,
- this._addon.id);
- }
- },
-
- onDisabled: function() {
- this.updateState();
- this.emptySettingsRows();
- },
-
- onUninstalling: function() {
- this.updateState();
- },
-
- onUninstalled: function() {
- gViewController.popState();
- },
-
- onOperationCancelled: function() {
- this.updateState();
- },
-
- onPropertyChanged: function(aProperties) {
- if (aProperties.indexOf("applyBackgroundUpdates") != -1) {
- this._autoUpdate.value = this._addon.applyBackgroundUpdates;
- let hideFindUpdates = AddonManager.shouldAutoUpdate(this._addon);
- document.getElementById("detail-findUpdates-btn").hidden = hideFindUpdates;
- }
-
- if (aProperties.indexOf("appDisabled") != -1 ||
- aProperties.indexOf("signedState") != -1 ||
- aProperties.indexOf("userDisabled") != -1)
- this.updateState();
- },
-
- onExternalInstall: function(aAddon, aExistingAddon, aNeedsRestart) {
- // Only care about upgrades for the currently displayed add-on
- if (!aExistingAddon || aExistingAddon.id != this._addon.id)
- return;
-
- if (!aNeedsRestart)
- this._updateView(aAddon, false);
- else
- this.updateState();
- },
-
- onInstallCancelled: function(aInstall) {
- if (aInstall.addon.id == this._addon.id)
- gViewController.popState();
- }
-};
-
-
-var gUpdatesView = {
- node: null,
- _listBox: null,
- _emptyNotice: null,
- _sorters: null,
- _updateSelected: null,
- _categoryItem: null,
-
- initialize: function() {
- this.node = document.getElementById("updates-view");
- this._listBox = document.getElementById("updates-list");
- this._emptyNotice = document.getElementById("updates-list-empty");
- this._sorters = document.getElementById("updates-sorters");
- this._sorters.handler = this;
-
- this._categoryItem = gCategories.get("addons://updates/available");
-
- this._updateSelected = document.getElementById("update-selected-btn");
- this._updateSelected.addEventListener("command", function() {
- gUpdatesView.installSelected();
- }, false);
-
- this.updateAvailableCount(true);
-
- AddonManager.addAddonListener(this);
- AddonManager.addInstallListener(this);
- },
-
- shutdown: function() {
- AddonManager.removeAddonListener(this);
- AddonManager.removeInstallListener(this);
- },
-
- show: function(aType, aRequest) {
- document.getElementById("empty-availableUpdates-msg").hidden = aType != "available";
- document.getElementById("empty-recentUpdates-msg").hidden = aType != "recent";
- this.showEmptyNotice(false);
-
- while (this._listBox.itemCount > 0)
- this._listBox.removeItemAt(0);
-
- this.node.setAttribute("updatetype", aType);
- if (aType == "recent")
- this._showRecentUpdates(aRequest);
- else
- this._showAvailableUpdates(false, aRequest);
- },
-
- hide: function() {
- this._updateSelected.hidden = true;
- this._categoryItem.disabled = this._categoryItem.badgeCount == 0;
- doPendingUninstalls(this._listBox);
- },
-
- _showRecentUpdates: function(aRequest) {
- AddonManager.getAllAddons((aAddonsList) => {
- if (gViewController && aRequest != gViewController.currentViewRequest)
- return;
-
- var elements = [];
- let threshold = Date.now() - UPDATES_RECENT_TIMESPAN;
- for (let addon of aAddonsList) {
- if (addon.hidden || !addon.updateDate || addon.updateDate.getTime() < threshold)
- continue;
-
- elements.push(createItem(addon));
- }
-
- this.showEmptyNotice(elements.length == 0);
- if (elements.length > 0) {
- sortElements(elements, [this._sorters.sortBy], this._sorters.ascending);
- for (let element of elements)
- this._listBox.appendChild(element);
- }
-
- gViewController.notifyViewChanged();
- });
- },
-
- _showAvailableUpdates: function(aIsRefresh, aRequest) {
- /* Disable the Update Selected button so it can't get clicked
- before everything is initialized asynchronously.
- It will get re-enabled by maybeDisableUpdateSelected(). */
- this._updateSelected.disabled = true;
-
- AddonManager.getAllInstalls((aInstallsList) => {
- if (!aIsRefresh && gViewController && aRequest &&
- aRequest != gViewController.currentViewRequest)
- return;
-
- if (aIsRefresh) {
- this.showEmptyNotice(false);
- this._updateSelected.hidden = true;
-
- while (this._listBox.childNodes.length > 0)
- this._listBox.removeChild(this._listBox.firstChild);
- }
-
- var elements = [];
-
- for (let install of aInstallsList) {
- if (!this.isManualUpdate(install))
- continue;
-
- let item = createItem(install.existingAddon);
- item.setAttribute("upgrade", true);
- item.addEventListener("IncludeUpdateChanged", () => {
- this.maybeDisableUpdateSelected();
- }, false);
- elements.push(item);
- }
-
- this.showEmptyNotice(elements.length == 0);
- if (elements.length > 0) {
- this._updateSelected.hidden = false;
- sortElements(elements, [this._sorters.sortBy], this._sorters.ascending);
- for (let element of elements)
- this._listBox.appendChild(element);
- }
-
- // ensure badge count is in sync
- this._categoryItem.badgeCount = this._listBox.itemCount;
-
- gViewController.notifyViewChanged();
- });
- },
-
- showEmptyNotice: function(aShow) {
- this._emptyNotice.hidden = !aShow;
- this._listBox.hidden = aShow;
- },
-
- isManualUpdate: function(aInstall, aOnlyAvailable) {
- var isManual = aInstall.existingAddon &&
- !AddonManager.shouldAutoUpdate(aInstall.existingAddon);
- if (isManual && aOnlyAvailable)
- return isInState(aInstall, "available");
- return isManual;
- },
-
- maybeRefresh: function() {
- if (gViewController.currentViewId == "addons://updates/available")
- this._showAvailableUpdates(true);
- this.updateAvailableCount();
- },
-
- updateAvailableCount: function(aInitializing) {
- if (aInitializing)
- gPendingInitializations++;
- AddonManager.getAllInstalls((aInstallsList) => {
- var count = aInstallsList.filter(aInstall => {
- return this.isManualUpdate(aInstall, true);
- }).length;
- this._categoryItem.disabled = gViewController.currentViewId != "addons://updates/available" &&
- count == 0;
- this._categoryItem.badgeCount = count;
- if (aInitializing)
- notifyInitialized();
- });
- },
-
- maybeDisableUpdateSelected: function() {
- for (let item of this._listBox.childNodes) {
- if (item.includeUpdate) {
- this._updateSelected.disabled = false;
- return;
- }
- }
- this._updateSelected.disabled = true;
- },
-
- installSelected: function() {
- for (let item of this._listBox.childNodes) {
- if (item.includeUpdate)
- item.upgrade();
- }
-
- this._updateSelected.disabled = true;
- },
-
- getSelectedAddon: function() {
- var item = this._listBox.selectedItem;
- if (item)
- return item.mAddon;
- return null;
- },
-
- getListItemForID: function(aId) {
- var listitem = this._listBox.firstChild;
- while (listitem) {
- if (listitem.mAddon.id == aId)
- return listitem;
- listitem = listitem.nextSibling;
- }
- return null;
- },
-
- onSortChanged: function(aSortBy, aAscending) {
- sortList(this._listBox, aSortBy, aAscending);
- },
-
- onNewInstall: function(aInstall) {
- if (!this.isManualUpdate(aInstall))
- return;
- this.maybeRefresh();
- },
-
- onInstallStarted: function(aInstall) {
- this.updateAvailableCount();
- },
-
- onInstallCancelled: function(aInstall) {
- if (!this.isManualUpdate(aInstall))
- return;
- this.maybeRefresh();
- },
-
- onPropertyChanged: function(aAddon, aProperties) {
- if (aProperties.indexOf("applyBackgroundUpdates") != -1)
- this.updateAvailableCount();
- }
-};
-
-var gDragDrop = {
- onDragOver: function(aEvent) {
- var types = aEvent.dataTransfer.types;
- if (types.includes("text/uri-list") ||
- types.includes("text/x-moz-url") ||
- types.includes("application/x-moz-file"))
- aEvent.preventDefault();
- },
-
- onDrop: function(aEvent) {
- var dataTransfer = aEvent.dataTransfer;
- var urls = [];
-
- // Convert every dropped item into a url
- for (var i = 0; i < dataTransfer.mozItemCount; i++) {
- var url = dataTransfer.mozGetDataAt("text/uri-list", i);
- if (url) {
- urls.push(url);
- continue;
- }
-
- url = dataTransfer.mozGetDataAt("text/x-moz-url", i);
- if (url) {
- urls.push(url.split("\n")[0]);
- continue;
- }
-
- var file = dataTransfer.mozGetDataAt("application/x-moz-file", i);
- if (file) {
- urls.push(Services.io.newFileURI(file).spec);
- continue;
- }
- }
-
- var pos = 0;
- var installs = [];
-
- function buildNextInstall() {
- if (pos == urls.length) {
- if (installs.length > 0) {
- // Display the normal install confirmation for the installs
- let webInstaller = Cc["@mozilla.org/addons/web-install-listener;1"].
- getService(Ci.amIWebInstallListener);
- webInstaller.onWebInstallRequested(getBrowserElement(),
- document.documentURIObject,
- installs);
- }
- return;
- }
-
- AddonManager.getInstallForURL(urls[pos++], function(aInstall) {
- installs.push(aInstall);
- buildNextInstall();
- }, "application/x-xpinstall");
- }
-
- buildNextInstall();
-
- aEvent.preventDefault();
- }
-};
diff --git a/toolkit/mozapps/webextensions/content/extensions.xml b/toolkit/mozapps/webextensions/content/extensions.xml
deleted file mode 100644
index b49645cf0..000000000
--- a/toolkit/mozapps/webextensions/content/extensions.xml
+++ /dev/null
@@ -1,2008 +0,0 @@
-<?xml version="1.0"?>
-<!-- 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/. -->
-
-
-<!DOCTYPE page [
-<!ENTITY % extensionsDTD SYSTEM "chrome://mozapps/locale/extensions/extensions.dtd">
-%extensionsDTD;
-]>
-
-<!-- import-globals-from extensions.js -->
-
-<bindings id="addonBindings"
- xmlns="http://www.mozilla.org/xbl"
- xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- xmlns:xbl="http://www.mozilla.org/xbl">
-
-
- <!-- Rating - displays current/average rating, allows setting user rating -->
- <binding id="rating">
- <content>
- <xul:image class="star"
- onmouseover="document.getBindingParent(this)._hover(1);"
- onclick="document.getBindingParent(this).userRating = 1;"/>
- <xul:image class="star"
- onmouseover="document.getBindingParent(this)._hover(2);"
- onclick="document.getBindingParent(this).userRating = 2;"/>
- <xul:image class="star"
- onmouseover="document.getBindingParent(this)._hover(3);"
- onclick="document.getBindingParent(this).userRating = 3;"/>
- <xul:image class="star"
- onmouseover="document.getBindingParent(this)._hover(4);"
- onclick="document.getBindingParent(this).userRating = 4;"/>
- <xul:image class="star"
- onmouseover="document.getBindingParent(this)._hover(5);"
- onclick="document.getBindingParent(this).userRating = 5;"/>
- </content>
-
- <implementation>
- <constructor><![CDATA[
- this._updateStars();
- ]]></constructor>
-
- <property name="stars" readonly="true">
- <getter><![CDATA[
- return document.getAnonymousNodes(this);
- ]]></getter>
- </property>
-
- <property name="averageRating">
- <getter><![CDATA[
- if (this.hasAttribute("averagerating"))
- return this.getAttribute("averagerating");
- return -1;
- ]]></getter>
- <setter><![CDATA[
- this.setAttribute("averagerating", val);
- if (this.showRating == "average")
- this._updateStars();
- ]]></setter>
- </property>
-
- <property name="userRating">
- <getter><![CDATA[
- if (this.hasAttribute("userrating"))
- return this.getAttribute("userrating");
- return -1;
- ]]></getter>
- <setter><![CDATA[
- if (this.showRating != "user")
- return;
- this.setAttribute("userrating", val);
- if (this.showRating == "user")
- this._updateStars();
- ]]></setter>
- </property>
-
- <property name="showRating">
- <getter><![CDATA[
- if (this.hasAttribute("showrating"))
- return this.getAttribute("showrating");
- return "average";
- ]]></getter>
- <setter><![CDATA[
- if (val != "average" || val != "user")
- throw Components.Exception("Invalid value", Components.results.NS_ERROR_ILLEGAL_VALUE);
- this.setAttribute("showrating", val);
- this._updateStars();
- ]]></setter>
- </property>
-
- <method name="_updateStars">
- <body><![CDATA[
- var stars = this.stars;
- var rating = this[this.showRating + "Rating"];
- // average ratings can be non-whole numbers, round them so they
- // match to their closest star
- rating = Math.round(rating);
- for (let i = 0; i < stars.length; i++)
- stars[i].setAttribute("on", rating > i);
- ]]></body>
- </method>
-
- <method name="_hover">
- <parameter name="aScore"/>
- <body><![CDATA[
- if (this.showRating != "user")
- return;
- var stars = this.stars;
- for (let i = 0; i < stars.length; i++)
- stars[i].setAttribute("on", i <= (aScore -1));
- ]]></body>
- </method>
-
- </implementation>
-
- <handlers>
- <handler event="mouseout">
- this._updateStars();
- </handler>
- </handlers>
- </binding>
-
- <!-- Download progress - shows graphical progress of download and any
- related status message. -->
- <binding id="download-progress">
- <content>
- <xul:stack flex="1">
- <xul:hbox flex="1">
- <xul:hbox class="start-cap"/>
- <xul:progressmeter anonid="progress" class="progress" flex="1"
- min="0" max="100"/>
- <xul:hbox class="end-cap"/>
- </xul:hbox>
- <xul:hbox class="status-container">
- <xul:spacer flex="1"/>
- <xul:label anonid="status" class="status"/>
- <xul:spacer flex="1"/>
- <xul:button anonid="cancel-btn" class="cancel"
- tooltiptext="&progress.cancel.tooltip;"
- oncommand="document.getBindingParent(this).cancel();"/>
- </xul:hbox>
- </xul:stack>
- </content>
-
- <implementation>
- <constructor><![CDATA[
- var progress = 0;
- if (this.hasAttribute("progress"))
- progress = parseInt(this.getAttribute("progress"));
- this.progress = progress;
- ]]></constructor>
-
- <field name="_progress">
- document.getAnonymousElementByAttribute(this, "anonid", "progress");
- </field>
- <field name="_cancel">
- document.getAnonymousElementByAttribute(this, "anonid", "cancel-btn");
- </field>
- <field name="_status">
- document.getAnonymousElementByAttribute(this, "anonid", "status");
- </field>
-
- <property name="progress">
- <getter><![CDATA[
- return this._progress.value;
- ]]></getter>
- <setter><![CDATA[
- this._progress.value = val;
- if (val == this._progress.max)
- this.setAttribute("complete", true);
- else
- this.removeAttribute("complete");
- ]]></setter>
- </property>
-
- <property name="maxProgress">
- <getter><![CDATA[
- return this._progress.max;
- ]]></getter>
- <setter><![CDATA[
- if (val == -1) {
- this._progress.mode = "undetermined";
- } else {
- this._progress.mode = "determined";
- this._progress.max = val;
- }
- this.setAttribute("mode", this._progress.mode);
- ]]></setter>
- </property>
-
- <property name="status">
- <getter><![CDATA[
- return this._status.value;
- ]]></getter>
- <setter><![CDATA[
- this._status.value = val;
- ]]></setter>
- </property>
-
- <method name="cancel">
- <body><![CDATA[
- this.mInstall.cancel();
- ]]></body>
- </method>
- </implementation>
- </binding>
-
-
- <!-- Sorters - displays and controls the sort state of a list. -->
- <binding id="sorters">
- <content orient="horizontal">
- <xul:button anonid="name-btn" class="sorter"
- label="&sort.name.label;" tooltiptext="&sort.name.tooltip;"
- oncommand="this.parentNode._handleChange('name');"/>
- <xul:button anonid="date-btn" class="sorter"
- label="&sort.dateUpdated.label;"
- tooltiptext="&sort.dateUpdated.tooltip;"
- oncommand="this.parentNode._handleChange('updateDate');"/>
- <xul:button anonid="price-btn" class="sorter" hidden="true"
- label="&sort.price.label;"
- tooltiptext="&sort.price.tooltip;"
- oncommand="this.parentNode._handleChange('purchaseAmount');"/>
- <xul:button anonid="relevance-btn" class="sorter" hidden="true"
- label="&sort.relevance.label;"
- tooltiptext="&sort.relevance.tooltip;"
- oncommand="this.parentNode._handleChange('relevancescore');"/>
- </content>
-
- <implementation>
- <constructor><![CDATA[
- if (!this.hasAttribute("sortby"))
- this.setAttribute("sortby", "name");
-
- if (this.getAttribute("showrelevance") == "true")
- this._btnRelevance.hidden = false;
-
- if (this.getAttribute("showprice") == "true")
- this._btnPrice.hidden = false;
-
- this._refreshState();
- ]]></constructor>
-
- <field name="handler">null</field>
- <field name="_btnName">
- document.getAnonymousElementByAttribute(this, "anonid", "name-btn");
- </field>
- <field name="_btnDate">
- document.getAnonymousElementByAttribute(this, "anonid", "date-btn");
- </field>
- <field name="_btnPrice">
- document.getAnonymousElementByAttribute(this, "anonid", "price-btn");
- </field>
- <field name="_btnRelevance">
- document.getAnonymousElementByAttribute(this, "anonid", "relevance-btn");
- </field>
-
- <property name="sortBy">
- <getter><![CDATA[
- return this.getAttribute("sortby");
- ]]></getter>
- <setter><![CDATA[
- if (val != this.sortBy) {
- this.setAttribute("sortBy", val);
- this._refreshState();
- }
- ]]></setter>
- </property>
-
- <property name="ascending">
- <getter><![CDATA[
- return (this.getAttribute("ascending") == "true");
- ]]></getter>
- <setter><![CDATA[
- val = !!val;
- if (val != this.ascending) {
- this.setAttribute("ascending", val);
- this._refreshState();
- }
- ]]></setter>
- </property>
-
- <property name="showrelevance">
- <getter><![CDATA[
- return (this.getAttribute("showrelevance") == "true");
- ]]></getter>
- <setter><![CDATA[
- val = !!val;
- this.setAttribute("showrelevance", val);
- this._btnRelevance.hidden = !val;
- ]]></setter>
- </property>
-
- <property name="showprice">
- <getter><![CDATA[
- return (this.getAttribute("showprice") == "true");
- ]]></getter>
- <setter><![CDATA[
- val = !!val;
- this.setAttribute("showprice", val);
- this._btnPrice.hidden = !val;
- ]]></setter>
- </property>
-
- <method name="setSort">
- <parameter name="aSort"/>
- <parameter name="aAscending"/>
- <body><![CDATA[
- var sortChanged = false;
- if (aSort != this.sortBy) {
- this.setAttribute("sortby", aSort);
- sortChanged = true;
- }
-
- aAscending = !!aAscending;
- if (this.ascending != aAscending) {
- this.setAttribute("ascending", aAscending);
- sortChanged = true;
- }
-
- if (sortChanged)
- this._refreshState();
- ]]></body>
- </method>
-
- <method name="_handleChange">
- <parameter name="aSort"/>
- <body><![CDATA[
- const ASCENDING_SORT_FIELDS = ["name", "purchaseAmount"];
-
- // Toggle ascending if sort by is not changing, otherwise
- // name sorting defaults to ascending, others to descending
- if (aSort == this.sortBy)
- this.ascending = !this.ascending;
- else
- this.setSort(aSort, ASCENDING_SORT_FIELDS.indexOf(aSort) >= 0);
- ]]></body>
- </method>
-
- <method name="_refreshState">
- <body><![CDATA[
- var sortBy = this.sortBy;
- var checkState = this.ascending ? 2 : 1;
-
- if (sortBy == "name") {
- this._btnName.checkState = checkState;
- this._btnName.checked = true;
- } else {
- this._btnName.checkState = 0;
- this._btnName.checked = false;
- }
-
- if (sortBy == "updateDate") {
- this._btnDate.checkState = checkState;
- this._btnDate.checked = true;
- } else {
- this._btnDate.checkState = 0;
- this._btnDate.checked = false;
- }
-
- if (sortBy == "purchaseAmount") {
- this._btnPrice.checkState = checkState;
- this._btnPrice.checked = true;
- } else {
- this._btnPrice.checkState = 0;
- this._btnPrice.checked = false;
- }
-
- if (sortBy == "relevancescore") {
- this._btnRelevance.checkState = checkState;
- this._btnRelevance.checked = true;
- } else {
- this._btnRelevance.checkState = 0;
- this._btnRelevance.checked = false;
- }
-
- if (this.handler && "onSortChanged" in this.handler)
- this.handler.onSortChanged(sortBy, this.ascending);
- ]]></body>
- </method>
- </implementation>
- </binding>
-
-
- <!-- Categories list - displays the list of categories on the left pane. -->
- <binding id="categories-list"
- extends="chrome://global/content/bindings/richlistbox.xml#richlistbox">
- <implementation>
- <!-- This needs to be overridden to allow the fancy animation while not
- allowing that item to be selected when hiding. -->
- <method name="_canUserSelect">
- <parameter name="aItem"/>
- <body>
- <![CDATA[
- if (aItem.hasAttribute("disabled") &&
- aItem.getAttribute("disabled") == "true")
- return false;
- var style = document.defaultView.getComputedStyle(aItem, "");
- return style.display != "none" && style.visibility == "visible";
- ]]>
- </body>
- </method>
- </implementation>
- </binding>
-
-
- <!-- Category item - an item in the category list. -->
- <binding id="category"
- extends="chrome://global/content/bindings/richlistbox.xml#richlistitem">
- <content align="center">
- <xul:image anonid="icon" class="category-icon"/>
- <xul:label anonid="name" class="category-name" flex="1" xbl:inherits="value=name"/>
- <xul:label anonid="badge" class="category-badge" xbl:inherits="value=count"/>
- </content>
-
- <implementation>
- <constructor><![CDATA[
- if (!this.hasAttribute("count"))
- this.setAttribute("count", 0);
- ]]></constructor>
-
- <property name="badgeCount">
- <getter><![CDATA[
- return this.getAttribute("count");
- ]]></getter>
- <setter><![CDATA[
- if (this.getAttribute("count") == val)
- return;
-
- this.setAttribute("count", val);
- var event = document.createEvent("Events");
- event.initEvent("CategoryBadgeUpdated", true, true);
- this.dispatchEvent(event);
- ]]></setter>
- </property>
- </implementation>
- </binding>
-
-
- <!-- Creator link - Name of a user/developer, providing a link if relevant. -->
- <binding id="creator-link">
- <content>
- <xul:label anonid="label" value="&addon.createdBy.label;"/>
- <xul:label anonid="creator-link" class="creator-link text-link"/>
- <xul:label anonid="creator-name" class="creator-name"/>
- </content>
-
- <implementation>
- <constructor><![CDATA[
- if (this.hasAttribute("nameonly") &&
- this.getAttribute("nameonly") == "true") {
- this._label.hidden = true;
- }
- ]]></constructor>
-
- <field name="_label">
- document.getAnonymousElementByAttribute(this, "anonid", "label");
- </field>
- <field name="_creatorLink">
- document.getAnonymousElementByAttribute(this, "anonid", "creator-link");
- </field>
- <field name="_creatorName">
- document.getAnonymousElementByAttribute(this, "anonid", "creator-name");
- </field>
-
- <method name="setCreator">
- <parameter name="aCreator"/>
- <parameter name="aHomepageURL"/>
- <body><![CDATA[
- if (!aCreator) {
- this.collapsed = true;
- return;
- }
- this.collapsed = false;
- var url = aCreator.url || aHomepageURL;
- var showLink = !!url;
- if (showLink) {
- this._creatorLink.value = aCreator.name;
- this._creatorLink.href = url;
- } else {
- this._creatorName.value = aCreator.name;
- }
- this._creatorLink.hidden = !showLink;
- this._creatorName.hidden = showLink;
- ]]></body>
- </method>
- </implementation>
- </binding>
-
-
- <!-- Install status - Displays the status of an install/upgrade. -->
- <binding id="install-status">
- <content>
- <xul:label anonid="message"/>
- <xul:progressmeter anonid="progress" class="download-progress"/>
- <xul:button anonid="purchase-remote-btn" hidden="true"
- class="addon-control"
- oncommand="document.getBindingParent(this).purchaseRemote();"/>
- <xul:button anonid="install-remote-btn" hidden="true"
- class="addon-control install" label="&addon.install.label;"
- tooltiptext="&addon.install.tooltip;"
- oncommand="document.getBindingParent(this).installRemote();"/>
- </content>
-
- <implementation>
- <constructor><![CDATA[
- if (this.mInstall)
- this.initWithInstall(this.mInstall);
- else if (this.mControl.mAddon.install)
- this.initWithInstall(this.mControl.mAddon.install);
- else
- this.refreshState();
- ]]></constructor>
-
- <destructor><![CDATA[
- if (this.mInstall)
- this.mInstall.removeListener(this);
- ]]></destructor>
-
- <field name="_message">
- document.getAnonymousElementByAttribute(this, "anonid", "message");
- </field>
- <field name="_progress">
- document.getAnonymousElementByAttribute(this, "anonid", "progress");
- </field>
- <field name="_purchaseRemote">
- document.getAnonymousElementByAttribute(this, "anonid",
- "purchase-remote-btn");
- </field>
- <field name="_installRemote">
- document.getAnonymousElementByAttribute(this, "anonid",
- "install-remote-btn");
- </field>
- <field name="_restartNeeded">
- document.getAnonymousElementByAttribute(this, "anonid",
- "restart-needed");
- </field>
- <field name="_undo">
- document.getAnonymousElementByAttribute(this, "anonid",
- "undo-btn");
- </field>
-
- <method name="initWithInstall">
- <parameter name="aInstall"/>
- <body><![CDATA[
- if (this.mInstall) {
- this.mInstall.removeListener(this);
- this.mInstall = null;
- }
- this.mInstall = aInstall;
- this._progress.mInstall = aInstall;
- this.refreshState();
- this.mInstall.addListener(this);
- ]]></body>
- </method>
-
- <method name="refreshState">
- <body><![CDATA[
- var showInstallRemote = false;
- var showPurchase = false;
-
- if (this.mInstall) {
-
- switch (this.mInstall.state) {
- case AddonManager.STATE_AVAILABLE:
- if (this.mControl.getAttribute("remote") != "true")
- break;
-
- this._progress.hidden = true;
- showInstallRemote = true;
- break;
- case AddonManager.STATE_DOWNLOADING:
- this.showMessage("installDownloading");
- break;
- case AddonManager.STATE_CHECKING:
- this.showMessage("installVerifying");
- break;
- case AddonManager.STATE_DOWNLOADED:
- this.showMessage("installDownloaded");
- break;
- case AddonManager.STATE_DOWNLOAD_FAILED:
- // XXXunf expose what error occured (bug 553487)
- this.showMessage("installDownloadFailed", true);
- break;
- case AddonManager.STATE_INSTALLING:
- this.showMessage("installInstalling");
- break;
- case AddonManager.STATE_INSTALL_FAILED:
- // XXXunf expose what error occured (bug 553487)
- this.showMessage("installFailed", true);
- break;
- case AddonManager.STATE_CANCELLED:
- this.showMessage("installCancelled", true);
- break;
- }
-
- } else if (this.mControl.mAddon.purchaseURL) {
- this._progress.hidden = true;
- showPurchase = true;
- this._purchaseRemote.label =
- gStrings.ext.formatStringFromName("addon.purchase.label",
- [this.mControl.mAddon.purchaseDisplayAmount], 1);
- this._purchaseRemote.tooltiptext =
- gStrings.ext.GetStringFromName("addon.purchase.tooltip");
- }
-
- this._purchaseRemote.hidden = !showPurchase;
- this._installRemote.hidden = !showInstallRemote;
-
- if ("refreshInfo" in this.mControl)
- this.mControl.refreshInfo();
- ]]></body>
- </method>
-
- <method name="showMessage">
- <parameter name="aMsgId"/>
- <parameter name="aHideProgress"/>
- <body><![CDATA[
- this._message.setAttribute("hidden", !aHideProgress);
- this._progress.setAttribute("hidden", !!aHideProgress);
-
- var msg = gStrings.ext.GetStringFromName(aMsgId);
- if (aHideProgress)
- this._message.value = msg;
- else
- this._progress.status = msg;
- ]]></body>
- </method>
-
- <method name="purchaseRemote">
- <body><![CDATA[
- openURL(this.mControl.mAddon.purchaseURL);
- ]]></body>
- </method>
-
- <method name="installRemote">
- <body><![CDATA[
- if (this.mControl.getAttribute("remote") != "true")
- return;
-
- if (this.mControl.mAddon.eula) {
- var data = {
- addon: this.mControl.mAddon,
- accepted: false
- };
- window.openDialog("chrome://mozapps/content/extensions/eula.xul", "_blank",
- "chrome,dialog,modal,centerscreen,resizable=no", data);
- if (!data.accepted)
- return;
- }
-
- delete this.mControl.mAddon;
- this.mControl.mInstall = this.mInstall;
- this.mControl.setAttribute("status", "installing");
- this.mInstall.install();
- ]]></body>
- </method>
-
- <method name="undoAction">
- <body><![CDATA[
- if (!this.mAddon)
- return;
- var pending = this.mAddon.pendingOperations;
- if (pending & AddonManager.PENDING_ENABLE)
- this.mAddon.userDisabled = true;
- else if (pending & AddonManager.PENDING_DISABLE)
- this.mAddon.userDisabled = false;
- this.refreshState();
- ]]></body>
- </method>
-
- <method name="onDownloadStarted">
- <body><![CDATA[
- this.refreshState();
- ]]></body>
- </method>
-
- <method name="onDownloadEnded">
- <body><![CDATA[
- this.refreshState();
- ]]></body>
- </method>
-
- <method name="onDownloadFailed">
- <body><![CDATA[
- this.refreshState();
- ]]></body>
- </method>
-
- <method name="onDownloadProgress">
- <body><![CDATA[
- this._progress.maxProgress = this.mInstall.maxProgress;
- this._progress.progress = this.mInstall.progress;
- ]]></body>
- </method>
-
- <method name="onInstallStarted">
- <body><![CDATA[
- this._progress.progress = 0;
- this.refreshState();
- ]]></body>
- </method>
-
- <method name="onInstallEnded">
- <body><![CDATA[
- this.refreshState();
- if ("onInstallCompleted" in this.mControl)
- this.mControl.onInstallCompleted();
- ]]></body>
- </method>
-
- <method name="onInstallFailed">
- <body><![CDATA[
- this.refreshState();
- ]]></body>
- </method>
- </implementation>
- </binding>
-
-
- <!-- Addon - base - parent binding of any item representing an addon. -->
- <binding id="addon-base"
- extends="chrome://global/content/bindings/richlistbox.xml#richlistitem">
- <implementation>
- <method name="hasPermission">
- <parameter name="aPerm"/>
- <body><![CDATA[
- var perm = AddonManager["PERM_CAN_" + aPerm.toUpperCase()];
- return !!(this.mAddon.permissions & perm);
- ]]></body>
- </method>
-
- <method name="opRequiresRestart">
- <parameter name="aOperation"/>
- <body><![CDATA[
- var operation = AddonManager["OP_NEEDS_RESTART_" + aOperation.toUpperCase()];
- return !!(this.mAddon.operationsRequiringRestart & operation);
- ]]></body>
- </method>
-
- <method name="isPending">
- <parameter name="aAction"/>
- <body><![CDATA[
- var action = AddonManager["PENDING_" + aAction.toUpperCase()];
- return !!(this.mAddon.pendingOperations & action);
- ]]></body>
- </method>
-
- <method name="typeHasFlag">
- <parameter name="aFlag"/>
- <body><![CDATA[
- let flag = AddonManager["TYPE_" + aFlag];
- let type = AddonManager.addonTypes[this.mAddon.type];
-
- return !!(type.flags & flag);
- ]]></body>
- </method>
-
- <method name="onUninstalled">
- <body><![CDATA[
- this.parentNode.removeChild(this);
- ]]></body>
- </method>
- </implementation>
- </binding>
-
-
- <!-- Addon - generic - A normal addon item, or an update to one -->
- <binding id="addon-generic"
- extends="chrome://mozapps/content/extensions/extensions.xml#addon-base">
- <content>
- <xul:hbox anonid="warning-container"
- class="warning">
- <xul:image class="warning-icon"/>
- <xul:label anonid="warning" flex="1"/>
- <xul:label anonid="warning-link" class="text-link"/>
- <xul:button anonid="warning-btn" class="button-link" hidden="true"/>
- <xul:spacer flex="5000"/> <!-- Necessary to allow the message to wrap -->
- </xul:hbox>
- <xul:hbox anonid="error-container"
- class="error">
- <xul:image class="error-icon"/>
- <xul:label anonid="error" flex="1"/>
- <xul:label anonid="error-link" class="text-link" hidden="true"/>
- <xul:spacer flex="5000"/> <!-- Necessary to allow the message to wrap -->
- </xul:hbox>
- <xul:hbox anonid="pending-container"
- class="pending">
- <xul:image class="pending-icon"/>
- <xul:label anonid="pending" flex="1"/>
- <xul:button anonid="restart-btn" class="button-link"
- label="&addon.restartNow.label;"
- oncommand="document.getBindingParent(this).restart();"/>
- <xul:button anonid="undo-btn" class="button-link"
- label="&addon.undoAction.label;"
- tooltipText="&addon.undoAction.tooltip;"
- oncommand="document.getBindingParent(this).undo();"/>
- <xul:spacer flex="5000"/> <!-- Necessary to allow the message to wrap -->
- </xul:hbox>
-
- <xul:hbox class="content-container" align="center">
- <xul:vbox class="icon-container">
- <xul:image anonid="icon" class="icon"/>
- </xul:vbox>
- <xul:vbox class="content-inner-container" flex="1">
- <xul:hbox class="basicinfo-container">
- <xul:hbox class="name-container">
- <xul:label anonid="name" class="name" crop="end" flex="1"
- tooltip="addonitem-tooltip" xbl:inherits="value=name"/>
- <xul:label class="disabled-postfix" value="&addon.disabled.postfix;"/>
- <xul:label class="update-postfix" value="&addon.update.postfix;"/>
- <xul:spacer flex="5000"/> <!-- Necessary to make the name crop -->
- </xul:hbox>
- <xul:label anonid="date-updated" class="date-updated"
- unknown="&addon.unknownDate;"/>
- </xul:hbox>
- <xul:hbox class="experiment-container">
- <svg width="6" height="6" viewBox="0 0 6 6" version="1.1"
- xmlns="http://www.w3.org/2000/svg"
- class="experiment-bullet-container">
- <circle cx="3" cy="3" r="3" class="experiment-bullet"/>
- </svg>
- <xul:label anonid="experiment-state" class="experiment-state"/>
- <xul:label anonid="experiment-time" class="experiment-time"/>
- </xul:hbox>
-
- <xul:hbox class="advancedinfo-container" flex="1">
- <xul:vbox class="description-outer-container" flex="1">
- <xul:hbox class="description-container">
- <xul:label anonid="description" class="description" crop="end" flex="1"/>
- <xul:button anonid="details-btn" class="details button-link"
- label="&addon.details.label;"
- tooltiptext="&addon.details.tooltip;"
- oncommand="document.getBindingParent(this).showInDetailView();"/>
- <xul:spacer flex="5000"/> <!-- Necessary to make the description crop -->
- </xul:hbox>
- <xul:vbox anonid="relnotes-container" class="relnotes-container">
- <xul:label class="relnotes-header" value="&addon.releaseNotes.label;"/>
- <xul:label anonid="relnotes-loading" value="&addon.loadingReleaseNotes.label;"/>
- <xul:label anonid="relnotes-error" hidden="true"
- value="&addon.errorLoadingReleaseNotes.label;"/>
- <xul:vbox anonid="relnotes" class="relnotes"/>
- </xul:vbox>
- <xul:hbox class="relnotes-toggle-container">
- <xul:button anonid="relnotes-toggle-btn" class="relnotes-toggle"
- hidden="true" label="&cmd.showReleaseNotes.label;"
- tooltiptext="&cmd.showReleaseNotes.tooltip;"
- showlabel="&cmd.showReleaseNotes.label;"
- showtooltip="&cmd.showReleaseNotes.tooltip;"
- hidelabel="&cmd.hideReleaseNotes.label;"
- hidetooltip="&cmd.hideReleaseNotes.tooltip;"
- oncommand="document.getBindingParent(this).toggleReleaseNotes();"/>
- </xul:hbox>
- </xul:vbox>
- </xul:hbox>
- </xul:vbox>
- <xul:vbox class="status-control-wrapper">
- <xul:hbox class="status-container">
- <xul:hbox anonid="checking-update" hidden="true">
- <xul:image class="spinner"/>
- <xul:label value="&addon.checkingForUpdates.label;"/>
- </xul:hbox>
- <xul:vbox anonid="update-available" class="update-available"
- hidden="true">
- <xul:checkbox anonid="include-update" class="include-update"
- label="&addon.includeUpdate.label;" checked="true"
- oncommand="document.getBindingParent(this).onIncludeUpdateChanged();"/>
- <xul:hbox class="update-info-container">
- <xul:label class="update-available-notice"
- value="&addon.updateAvailable.label;"/>
- <xul:button anonid="update-btn" class="addon-control update"
- label="&addon.updateNow.label;"
- tooltiptext="&addon.updateNow.tooltip;"
- oncommand="document.getBindingParent(this).upgrade();"/>
- </xul:hbox>
- </xul:vbox>
- <xul:hbox anonid="install-status" class="install-status"
- hidden="true"/>
- </xul:hbox>
- <xul:hbox anonid="control-container" class="control-container">
- <xul:button anonid="preferences-btn"
- class="addon-control preferences"
-#ifdef XP_WIN
- label="&cmd.showPreferencesWin.label;"
- tooltiptext="&cmd.showPreferencesWin.tooltip;"
-#else
- label="&cmd.showPreferencesUnix.label;"
- tooltiptext="&cmd.showPreferencesUnix.tooltip;"
-#endif
- oncommand="document.getBindingParent(this).showPreferences();"/>
- <xul:button anonid="enable-btn" class="addon-control enable"
- label="&cmd.enableAddon.label;"
- oncommand="document.getBindingParent(this).userDisabled = false;"/>
- <xul:button anonid="disable-btn" class="addon-control disable"
- label="&cmd.disableAddon.label;"
- oncommand="document.getBindingParent(this).userDisabled = true;"/>
- <xul:button anonid="remove-btn" class="addon-control remove"
- label="&cmd.uninstallAddon.label;"
- oncommand="document.getBindingParent(this).uninstall();"/>
- <xul:menulist anonid="state-menulist"
- class="addon-control state"
- tooltiptext="&cmd.stateMenu.tooltip;">
- <xul:menupopup>
- <xul:menuitem anonid="ask-to-activate-menuitem"
- class="addon-control"
- label="&cmd.askToActivate.label;"
- tooltiptext="&cmd.askToActivate.tooltip;"
- oncommand="document.getBindingParent(this).userDisabled = AddonManager.STATE_ASK_TO_ACTIVATE;"/>
- <xul:menuitem anonid="always-activate-menuitem"
- class="addon-control"
- label="&cmd.alwaysActivate.label;"
- tooltiptext="&cmd.alwaysActivate.tooltip;"
- oncommand="document.getBindingParent(this).userDisabled = false;"/>
- <xul:menuitem anonid="never-activate-menuitem"
- class="addon-control"
- label="&cmd.neverActivate.label;"
- tooltiptext="&cmd.neverActivate.tooltip;"
- oncommand="document.getBindingParent(this).userDisabled = true;"/>
- </xul:menupopup>
- </xul:menulist>
- </xul:hbox>
- </xul:vbox>
- </xul:hbox>
- </content>
-
- <implementation>
- <constructor><![CDATA[
- this._installStatus = document.getAnonymousElementByAttribute(this, "anonid", "install-status");
- this._installStatus.mControl = this;
-
- this.setAttribute("contextmenu", "addonitem-popup");
-
- this._showStatus("none");
-
- this._initWithAddon(this.mAddon);
-
- gEventManager.registerAddonListener(this, this.mAddon.id);
- ]]></constructor>
-
- <destructor><![CDATA[
- gEventManager.unregisterAddonListener(this, this.mAddon.id);
- ]]></destructor>
-
- <field name="_warningContainer">
- document.getAnonymousElementByAttribute(this, "anonid",
- "warning-container");
- </field>
- <field name="_warning">
- document.getAnonymousElementByAttribute(this, "anonid",
- "warning");
- </field>
- <field name="_warningLink">
- document.getAnonymousElementByAttribute(this, "anonid",
- "warning-link");
- </field>
- <field name="_warningBtn">
- document.getAnonymousElementByAttribute(this, "anonid",
- "warning-btn");
- </field>
- <field name="_errorContainer">
- document.getAnonymousElementByAttribute(this, "anonid",
- "error-container");
- </field>
- <field name="_error">
- document.getAnonymousElementByAttribute(this, "anonid",
- "error");
- </field>
- <field name="_errorLink">
- document.getAnonymousElementByAttribute(this, "anonid",
- "error-link");
- </field>
- <field name="_pendingContainer">
- document.getAnonymousElementByAttribute(this, "anonid",
- "pending-container");
- </field>
- <field name="_pending">
- document.getAnonymousElementByAttribute(this, "anonid",
- "pending");
- </field>
- <field name="_infoContainer">
- document.getAnonymousElementByAttribute(this, "anonid",
- "info-container");
- </field>
- <field name="_info">
- document.getAnonymousElementByAttribute(this, "anonid",
- "info");
- </field>
- <field name="_experimentState">
- document.getAnonymousElementByAttribute(this, "anonid", "experiment-state");
- </field>
- <field name="_experimentTime">
- document.getAnonymousElementByAttribute(this, "anonid", "experiment-time");
- </field>
- <field name="_icon">
- document.getAnonymousElementByAttribute(this, "anonid", "icon");
- </field>
- <field name="_dateUpdated">
- document.getAnonymousElementByAttribute(this, "anonid",
- "date-updated");
- </field>
- <field name="_description">
- document.getAnonymousElementByAttribute(this, "anonid",
- "description");
- </field>
- <field name="_stateMenulist">
- document.getAnonymousElementByAttribute(this, "anonid",
- "state-menulist");
- </field>
- <field name="_askToActivateMenuitem">
- document.getAnonymousElementByAttribute(this, "anonid",
- "ask-to-activate-menuitem");
- </field>
- <field name="_alwaysActivateMenuitem">
- document.getAnonymousElementByAttribute(this, "anonid",
- "always-activate-menuitem");
- </field>
- <field name="_neverActivateMenuitem">
- document.getAnonymousElementByAttribute(this, "anonid",
- "never-activate-menuitem");
- </field>
- <field name="_preferencesBtn">
- document.getAnonymousElementByAttribute(this, "anonid",
- "preferences-btn");
- </field>
- <field name="_enableBtn">
- document.getAnonymousElementByAttribute(this, "anonid",
- "enable-btn");
- </field>
- <field name="_disableBtn">
- document.getAnonymousElementByAttribute(this, "anonid",
- "disable-btn");
- </field>
- <field name="_removeBtn">
- document.getAnonymousElementByAttribute(this, "anonid",
- "remove-btn");
- </field>
- <field name="_updateBtn">
- document.getAnonymousElementByAttribute(this, "anonid",
- "update-btn");
- </field>
- <field name="_controlContainer">
- document.getAnonymousElementByAttribute(this, "anonid",
- "control-container");
- </field>
- <field name="_installStatus">
- document.getAnonymousElementByAttribute(this, "anonid",
- "install-status");
- </field>
- <field name="_checkingUpdate">
- document.getAnonymousElementByAttribute(this, "anonid",
- "checking-update");
- </field>
- <field name="_updateAvailable">
- document.getAnonymousElementByAttribute(this, "anonid",
- "update-available");
- </field>
- <field name="_includeUpdate">
- document.getAnonymousElementByAttribute(this, "anonid",
- "include-update");
- </field>
- <field name="_relNotesLoaded">false</field>
- <field name="_relNotesToggle">
- document.getAnonymousElementByAttribute(this, "anonid",
- "relnotes-toggle-btn");
- </field>
- <field name="_relNotesLoading">
- document.getAnonymousElementByAttribute(this, "anonid",
- "relnotes-loading");
- </field>
- <field name="_relNotesError">
- document.getAnonymousElementByAttribute(this, "anonid",
- "relnotes-error");
- </field>
- <field name="_relNotesContainer">
- document.getAnonymousElementByAttribute(this, "anonid",
- "relnotes-container");
- </field>
- <field name="_relNotes">
- document.getAnonymousElementByAttribute(this, "anonid",
- "relnotes");
- </field>
-
- <property name="userDisabled">
- <getter><![CDATA[
- return this.mAddon.userDisabled;
- ]]></getter>
- <setter><![CDATA[
- this.mAddon.userDisabled = val;
- ]]></setter>
- </property>
-
- <property name="includeUpdate">
- <getter><![CDATA[
- return this._includeUpdate.checked && !!this.mManualUpdate;
- ]]></getter>
- <setter><![CDATA[
- // XXXunf Eventually, we'll want to persist this for individual
- // updates - see bug 594619.
- this._includeUpdate.checked = !!val;
- ]]></setter>
- </property>
-
- <method name="_initWithAddon">
- <parameter name="aAddon"/>
- <body><![CDATA[
- this.mAddon = aAddon;
-
- this._installStatus.mAddon = this.mAddon;
- this._updateDates();
- this._updateState();
-
- this.setAttribute("name", aAddon.name);
-
- var iconURL = AddonManager.getPreferredIconURL(aAddon, 48, window);
- if (iconURL)
- this._icon.src = iconURL;
- else
- this._icon.src = "";
-
- if (this.mAddon.description)
- this._description.value = this.mAddon.description;
- else
- this._description.hidden = true;
-
- if (!("applyBackgroundUpdates" in this.mAddon) ||
- (this.mAddon.applyBackgroundUpdates == AddonManager.AUTOUPDATE_DISABLE ||
- (this.mAddon.applyBackgroundUpdates == AddonManager.AUTOUPDATE_DEFAULT &&
- !AddonManager.autoUpdateDefault))) {
- AddonManager.getAllInstalls(aInstallsList => {
- // This can return after the binding has been destroyed,
- // so try to detect that and return early
- if (!("onNewInstall" in this))
- return;
- for (let install of aInstallsList) {
- if (install.existingAddon &&
- install.existingAddon.id == this.mAddon.id &&
- install.state == AddonManager.STATE_AVAILABLE) {
- this.onNewInstall(install);
- this.onIncludeUpdateChanged();
- }
- }
- });
- }
- ]]></body>
- </method>
-
- <method name="_showStatus">
- <parameter name="aType"/>
- <body><![CDATA[
- this._controlContainer.hidden = aType != "none" &&
- !(aType == "update-available" && !this.hasAttribute("upgrade"));
-
- this._installStatus.hidden = aType != "progress";
- if (aType == "progress")
- this._installStatus.refreshState();
- this._checkingUpdate.hidden = aType != "checking-update";
- this._updateAvailable.hidden = aType != "update-available";
- this._relNotesToggle.hidden = !(this.mManualUpdate ?
- this.mManualUpdate.releaseNotesURI :
- this.mAddon.releaseNotesURI);
- ]]></body>
- </method>
-
- <method name="_updateDates">
- <body><![CDATA[
- function formatDate(aDate) {
- const locale = Components.classes["@mozilla.org/chrome/chrome-registry;1"]
- .getService(Components.interfaces.nsIXULChromeRegistry)
- .getSelectedLocale("global", true);
- const dtOptions = { year: 'numeric', month: 'long', day: 'numeric' };
- return aDate.toLocaleDateString(locale, dtOptions);
- }
-
- if (this.mAddon.updateDate)
- this._dateUpdated.value = formatDate(this.mAddon.updateDate);
- else
- this._dateUpdated.value = this._dateUpdated.getAttribute("unknown");
- ]]></body>
- </method>
-
- <method name="_updateState">
- <body><![CDATA[
- if (this.parentNode.selectedItem == this)
- gViewController.updateCommands();
-
- var pending = this.mAddon.pendingOperations;
- if (pending != AddonManager.PENDING_NONE) {
- this.removeAttribute("notification");
-
- pending = null;
- const PENDING_OPERATIONS = ["enable", "disable", "install",
- "uninstall", "upgrade"];
- for (let op of PENDING_OPERATIONS) {
- if (this.isPending(op))
- pending = op;
- }
-
- this.setAttribute("pending", pending);
- this._pending.textContent = gStrings.ext.formatStringFromName(
- "notification." + pending,
- [this.mAddon.name, gStrings.brandShortName], 2
- );
- } else {
- this.removeAttribute("pending");
-
- var isUpgrade = this.hasAttribute("upgrade");
- var install = this._installStatus.mInstall;
-
- if (install && install.state == AddonManager.STATE_DOWNLOAD_FAILED) {
- this.setAttribute("notification", "warning");
- this._warning.textContent = gStrings.ext.formatStringFromName(
- "notification.downloadError",
- [this.mAddon.name], 1
- );
- this._warningBtn.label = gStrings.ext.GetStringFromName("notification.downloadError.retry");
- this._warningBtn.tooltipText = gStrings.ext.GetStringFromName("notification.downloadError.retry.tooltip");
- this._warningBtn.setAttribute("oncommand", "document.getBindingParent(this).retryInstall();");
- this._warningBtn.hidden = false;
- this._warningLink.hidden = true;
- } else if (install && install.state == AddonManager.STATE_INSTALL_FAILED) {
- this.setAttribute("notification", "warning");
- this._warning.textContent = gStrings.ext.formatStringFromName(
- "notification.installError",
- [this.mAddon.name], 1
- );
- this._warningBtn.label = gStrings.ext.GetStringFromName("notification.installError.retry");
- this._warningBtn.tooltipText = gStrings.ext.GetStringFromName("notification.downloadError.retry.tooltip");
- this._warningBtn.setAttribute("oncommand", "document.getBindingParent(this).retryInstall();");
- this._warningBtn.hidden = false;
- this._warningLink.hidden = true;
- } else if (!isUpgrade && this.mAddon.blocklistState == Ci.nsIBlocklistService.STATE_BLOCKED) {
- this.setAttribute("notification", "error");
- this._error.textContent = gStrings.ext.formatStringFromName(
- "notification.blocked",
- [this.mAddon.name], 1
- );
- this._errorLink.value = gStrings.ext.GetStringFromName("notification.blocked.link");
- this._errorLink.href = this.mAddon.blocklistURL;
- this._errorLink.hidden = false;
- } else if (!isUpgrade && !isCorrectlySigned(this.mAddon) && SIGNING_REQUIRED) {
- this.setAttribute("notification", "error");
- this._error.textContent = gStrings.ext.formatStringFromName(
- "notification.unsignedAndDisabled", [this.mAddon.name, gStrings.brandShortName], 2
- );
- this._errorLink.value = gStrings.ext.GetStringFromName("notification.unsigned.link");
- this._errorLink.href = Services.urlFormatter.formatURLPref("app.support.baseURL") + "unsigned-addons";
- this._errorLink.hidden = false;
- } else if ((!isUpgrade && !this.mAddon.isCompatible) && (AddonManager.checkCompatibility
- || (this.mAddon.blocklistState != Ci.nsIBlocklistService.STATE_SOFTBLOCKED))) {
- this.setAttribute("notification", "warning");
- this._warning.textContent = gStrings.ext.formatStringFromName(
- "notification.incompatible",
- [this.mAddon.name, gStrings.brandShortName, gStrings.appVersion], 3
- );
- this._warningLink.hidden = true;
- this._warningBtn.hidden = true;
- } else if (!isUpgrade && !isCorrectlySigned(this.mAddon)) {
- this.setAttribute("notification", "warning");
- this._warning.textContent = gStrings.ext.formatStringFromName(
- "notification.unsigned", [this.mAddon.name, gStrings.brandShortName], 2
- );
- this._warningLink.value = gStrings.ext.GetStringFromName("notification.unsigned.link");
- this._warningLink.href = Services.urlFormatter.formatURLPref("app.support.baseURL") + "unsigned-addons";
- this._warningLink.hidden = false;
- } else if (!isUpgrade && this.mAddon.blocklistState == Ci.nsIBlocklistService.STATE_SOFTBLOCKED) {
- this.setAttribute("notification", "warning");
- this._warning.textContent = gStrings.ext.formatStringFromName(
- "notification.softblocked",
- [this.mAddon.name], 1
- );
- this._warningLink.value = gStrings.ext.GetStringFromName("notification.softblocked.link");
- this._warningLink.href = this.mAddon.blocklistURL;
- this._warningLink.hidden = false;
- this._warningBtn.hidden = true;
- } else if (!isUpgrade && this.mAddon.blocklistState == Ci.nsIBlocklistService.STATE_OUTDATED) {
- this.setAttribute("notification", "warning");
- this._warning.textContent = gStrings.ext.formatStringFromName(
- "notification.outdated",
- [this.mAddon.name], 1
- );
- this._warningLink.value = gStrings.ext.GetStringFromName("notification.outdated.link");
- this._warningLink.href = this.mAddon.blocklistURL;
- this._warningLink.hidden = false;
- this._warningBtn.hidden = true;
- } else if (!isUpgrade && this.mAddon.blocklistState == Ci.nsIBlocklistService.STATE_VULNERABLE_UPDATE_AVAILABLE) {
- this.setAttribute("notification", "error");
- this._error.textContent = gStrings.ext.formatStringFromName(
- "notification.vulnerableUpdatable",
- [this.mAddon.name], 1
- );
- this._errorLink.value = gStrings.ext.GetStringFromName("notification.vulnerableUpdatable.link");
- this._errorLink.href = this.mAddon.blocklistURL;
- this._errorLink.hidden = false;
- } else if (!isUpgrade && this.mAddon.blocklistState == Ci.nsIBlocklistService.STATE_VULNERABLE_NO_UPDATE) {
- this.setAttribute("notification", "error");
- this._error.textContent = gStrings.ext.formatStringFromName(
- "notification.vulnerableNoUpdate",
- [this.mAddon.name], 1
- );
- this._errorLink.value = gStrings.ext.GetStringFromName("notification.vulnerableNoUpdate.link");
- this._errorLink.href = this.mAddon.blocklistURL;
- this._errorLink.hidden = false;
- } else if (this.mAddon.isGMPlugin && !this.mAddon.isInstalled &&
- this.mAddon.isActive) {
- this.setAttribute("notification", "warning");
- this._warning.textContent =
- gStrings.ext.formatStringFromName("notification.gmpPending",
- [this.mAddon.name], 1);
- } else {
- this.removeAttribute("notification");
- }
- }
-
- this._preferencesBtn.hidden = (!this.mAddon.optionsURL) ||
- this.mAddon.optionsType == AddonManager.OPTIONS_TYPE_INLINE_INFO;
-
- if (this.typeHasFlag("SUPPORTS_ASK_TO_ACTIVATE")) {
- this._enableBtn.disabled = true;
- this._disableBtn.disabled = true;
- this._askToActivateMenuitem.disabled = !this.hasPermission("ask_to_activate");
- this._alwaysActivateMenuitem.disabled = !this.hasPermission("enable");
- this._neverActivateMenuitem.disabled = !this.hasPermission("disable");
- if (!this.mAddon.isActive) {
- this._stateMenulist.selectedItem = this._neverActivateMenuitem;
- } else if (this.mAddon.userDisabled == AddonManager.STATE_ASK_TO_ACTIVATE) {
- this._stateMenulist.selectedItem = this._askToActivateMenuitem;
- } else {
- this._stateMenulist.selectedItem = this._alwaysActivateMenuitem;
- }
- let hasActivatePermission =
- ["ask_to_activate", "enable", "disable"].some(perm => this.hasPermission(perm));
- this._stateMenulist.disabled = !hasActivatePermission;
- this._stateMenulist.hidden = false;
- this._stateMenulist.classList.add('no-auto-hide');
- } else {
- this._stateMenulist.hidden = true;
-
- let enableTooltip = gViewController.commands["cmd_enableItem"]
- .getTooltip(this.mAddon);
- this._enableBtn.setAttribute("tooltiptext", enableTooltip);
- if (this.hasPermission("enable")) {
- this._enableBtn.hidden = false;
- } else {
- this._enableBtn.hidden = true;
- }
-
- let disableTooltip = gViewController.commands["cmd_disableItem"]
- .getTooltip(this.mAddon);
- this._disableBtn.setAttribute("tooltiptext", disableTooltip);
- if (this.hasPermission("disable")) {
- this._disableBtn.hidden = false;
- } else {
- this._disableBtn.hidden = true;
- }
- }
-
- let uninstallTooltip = gViewController.commands["cmd_uninstallItem"]
- .getTooltip(this.mAddon);
- this._removeBtn.setAttribute("tooltiptext", uninstallTooltip);
- if (this.hasPermission("uninstall")) {
- this._removeBtn.hidden = false;
- } else {
- this._removeBtn.hidden = true;
- }
-
- this.setAttribute("active", this.mAddon.isActive);
-
- var showProgress = this.mAddon.purchaseURL || (this.mAddon.install &&
- this.mAddon.install.state != AddonManager.STATE_INSTALLED);
- this._showStatus(showProgress ? "progress" : "none");
-
- if (this.mAddon.type == "experiment") {
- this.removeAttribute("notification");
- let prefix = "experiment.";
- let active = this.mAddon.isActive;
-
- if (!showProgress) {
- let stateKey = prefix + "state." + (active ? "active" : "complete");
- this._experimentState.value = gStrings.ext.GetStringFromName(stateKey);
-
- let now = Date.now();
- let end = this.endDate;
- let days = Math.abs(end - now) / (24 * 60 * 60 * 1000);
-
- let timeKey = prefix + "time.";
- let timeMessage;
-
- if (days < 1) {
- timeKey += (active ? "endsToday" : "endedToday");
- timeMessage = gStrings.ext.GetStringFromName(timeKey);
- } else {
- timeKey += (active ? "daysRemaining" : "daysPassed");
- days = Math.round(days);
- let timeString = gStrings.ext.GetStringFromName(timeKey);
- timeMessage = PluralForm.get(days, timeString)
- .replace("#1", days);
- }
-
- this._experimentTime.value = timeMessage;
- }
- }
- ]]></body>
- </method>
-
- <method name="_fetchReleaseNotes">
- <parameter name="aURI"/>
- <body><![CDATA[
- if (!aURI || this._relNotesLoaded) {
- sendToggleEvent();
- return;
- }
-
- var relNotesData = null, transformData = null;
-
- this._relNotesLoaded = true;
- this._relNotesLoading.hidden = false;
- this._relNotesError.hidden = true;
-
- let sendToggleEvent = () => {
- var event = document.createEvent("Events");
- event.initEvent("RelNotesToggle", true, true);
- this.dispatchEvent(event);
- }
-
- let showRelNotes = () => {
- if (!relNotesData || !transformData)
- return;
-
- this._relNotesLoading.hidden = true;
-
- var processor = Components.classes["@mozilla.org/document-transformer;1?type=xslt"]
- .createInstance(Components.interfaces.nsIXSLTProcessor);
- processor.flags |= Components.interfaces.nsIXSLTProcessorPrivate.DISABLE_ALL_LOADS;
-
- processor.importStylesheet(transformData);
- var fragment = processor.transformToFragment(relNotesData, document);
- this._relNotes.appendChild(fragment);
- if (this.hasAttribute("show-relnotes")) {
- var container = this._relNotesContainer;
- container.style.height = container.scrollHeight + "px";
- }
- sendToggleEvent();
- }
-
- let handleError = () => {
- dataReq.abort();
- styleReq.abort();
- this._relNotesLoading.hidden = true;
- this._relNotesError.hidden = false;
- this._relNotesLoaded = false; // allow loading to be re-tried
- sendToggleEvent();
- }
-
- function handleResponse(aEvent) {
- var req = aEvent.target;
- var ct = req.getResponseHeader("content-type");
- if ((!ct || ct.indexOf("text/html") < 0) &&
- req.responseXML &&
- req.responseXML.documentElement.namespaceURI != XMLURI_PARSE_ERROR) {
- if (req == dataReq)
- relNotesData = req.responseXML;
- else
- transformData = req.responseXML;
- showRelNotes();
- } else {
- handleError();
- }
- }
-
- var dataReq = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
- .createInstance(Components.interfaces.nsIXMLHttpRequest);
- dataReq.open("GET", aURI.spec, true);
- dataReq.responseType = "document";
- dataReq.addEventListener("load", handleResponse, false);
- dataReq.addEventListener("error", handleError, false);
- dataReq.send(null);
-
- var styleReq = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
- .createInstance(Components.interfaces.nsIXMLHttpRequest);
- styleReq.open("GET", UPDATES_RELEASENOTES_TRANSFORMFILE, true);
- styleReq.responseType = "document";
- styleReq.addEventListener("load", handleResponse, false);
- styleReq.addEventListener("error", handleError, false);
- styleReq.send(null);
- ]]></body>
- </method>
-
- <method name="toggleReleaseNotes">
- <body><![CDATA[
- if (this.hasAttribute("show-relnotes")) {
- this._relNotesContainer.style.height = "0px";
- this.removeAttribute("show-relnotes");
- this._relNotesToggle.setAttribute(
- "label",
- this._relNotesToggle.getAttribute("showlabel")
- );
- this._relNotesToggle.setAttribute(
- "tooltiptext",
- this._relNotesToggle.getAttribute("showtooltip")
- );
- var event = document.createEvent("Events");
- event.initEvent("RelNotesToggle", true, true);
- this.dispatchEvent(event);
- } else {
- this._relNotesContainer.style.height = this._relNotesContainer.scrollHeight +
- "px";
- this.setAttribute("show-relnotes", true);
- this._relNotesToggle.setAttribute(
- "label",
- this._relNotesToggle.getAttribute("hidelabel")
- );
- this._relNotesToggle.setAttribute(
- "tooltiptext",
- this._relNotesToggle.getAttribute("hidetooltip")
- );
- var uri = this.mManualUpdate ?
- this.mManualUpdate.releaseNotesURI :
- this.mAddon.releaseNotesURI;
- this._fetchReleaseNotes(uri);
- }
- ]]></body>
- </method>
-
- <method name="restart">
- <body><![CDATA[
- gViewController.commands["cmd_restartApp"].doCommand();
- ]]></body>
- </method>
-
- <method name="undo">
- <body><![CDATA[
- gViewController.commands["cmd_cancelOperation"].doCommand(this.mAddon);
- ]]></body>
- </method>
-
- <method name="uninstall">
- <body><![CDATA[
- // If uninstalling does not require a restart and the type doesn't
- // support undoing of restartless uninstalls, then we fake it by
- // just disabling it it, and doing the real uninstall later.
- if (!this.opRequiresRestart("uninstall") &&
- !this.typeHasFlag("SUPPORTS_UNDO_RESTARTLESS_UNINSTALL")) {
- this.setAttribute("wasDisabled", this.mAddon.userDisabled);
-
- // We must set userDisabled to true first, this will call
- // _updateState which will clear any pending attribute set.
- this.mAddon.userDisabled = true;
-
- // This won't update any other add-on manager views (bug 582002)
- this.setAttribute("pending", "uninstall");
- } else {
- this.mAddon.uninstall(true);
- }
- ]]></body>
- </method>
-
- <method name="showPreferences">
- <body><![CDATA[
- gViewController.doCommand("cmd_showItemPreferences", this.mAddon);
- ]]></body>
- </method>
-
- <method name="upgrade">
- <body><![CDATA[
- var install = this.mManualUpdate;
- delete this.mManualUpdate;
- install.install();
- ]]></body>
- </method>
-
- <method name="retryInstall">
- <body><![CDATA[
- var install = this._installStatus.mInstall;
- if (!install)
- return;
- if (install.state != AddonManager.STATE_DOWNLOAD_FAILED &&
- install.state != AddonManager.STATE_INSTALL_FAILED)
- return;
- install.install();
- ]]></body>
- </method>
-
- <method name="showInDetailView">
- <body><![CDATA[
- gViewController.loadView("addons://detail/" +
- encodeURIComponent(this.mAddon.id));
- ]]></body>
- </method>
-
- <method name="onIncludeUpdateChanged">
- <body><![CDATA[
- var event = document.createEvent("Events");
- event.initEvent("IncludeUpdateChanged", true, true);
- this.dispatchEvent(event);
- ]]></body>
- </method>
-
- <method name="onEnabling">
- <body><![CDATA[
- this._updateState();
- ]]></body>
- </method>
-
- <method name="onEnabled">
- <body><![CDATA[
- this._updateState();
- ]]></body>
- </method>
-
- <method name="onDisabling">
- <body><![CDATA[
- this._updateState();
- ]]></body>
- </method>
-
- <method name="onDisabled">
- <body><![CDATA[
- this._updateState();
- ]]></body>
- </method>
-
- <method name="onUninstalling">
- <parameter name="aRestartRequired"/>
- <body><![CDATA[
- this._updateState();
- ]]></body>
- </method>
-
- <method name="onOperationCancelled">
- <body><![CDATA[
- this._updateState();
- ]]></body>
- </method>
-
- <method name="onPropertyChanged">
- <parameter name="aProperties"/>
- <body><![CDATA[
- if (aProperties.indexOf("appDisabled") != -1 ||
- aProperties.indexOf("signedState") != -1 ||
- aProperties.indexOf("userDisabled") != -1)
- this._updateState();
- ]]></body>
- </method>
-
- <method name="onNoUpdateAvailable">
- <body><![CDATA[
- this._showStatus("none");
- ]]></body>
- </method>
-
- <method name="onCheckingUpdate">
- <body><![CDATA[
- this._showStatus("checking-update");
- ]]></body>
- </method>
-
- <method name="onCompatibilityUpdateAvailable">
- <body><![CDATA[
- this._updateState();
- ]]></body>
- </method>
-
- <method name="onExternalInstall">
- <parameter name="aAddon"/>
- <parameter name="aExistingAddon"/>
- <parameter name="aNeedsRestart"/>
- <body><![CDATA[
- if (aExistingAddon.id != this.mAddon.id)
- return;
-
- // If the install completed without needing a restart then switch to
- // using the new Addon
- if (!aNeedsRestart)
- this._initWithAddon(aAddon);
- else
- this._updateState();
- ]]></body>
- </method>
-
- <method name="onNewInstall">
- <parameter name="aInstall"/>
- <body><![CDATA[
- if (this.mAddon.applyBackgroundUpdates == AddonManager.AUTOUPDATE_ENABLE)
- return;
- if (this.mAddon.applyBackgroundUpdates == AddonManager.AUTOUPDATE_DEFAULT &&
- AddonManager.autoUpdateDefault)
- return;
-
- this.mManualUpdate = aInstall;
- this._showStatus("update-available");
- ]]></body>
- </method>
-
- <method name="onDownloadStarted">
- <parameter name="aInstall"/>
- <body><![CDATA[
- this._updateState();
- this._showStatus("progress");
- this._installStatus.initWithInstall(aInstall);
- ]]></body>
- </method>
-
- <method name="onInstallStarted">
- <parameter name="aInstall"/>
- <body><![CDATA[
- this._updateState();
- this._showStatus("progress");
- this._installStatus.initWithInstall(aInstall);
- ]]></body>
- </method>
-
- <method name="onInstallEnded">
- <parameter name="aInstall"/>
- <parameter name="aAddon"/>
- <body><![CDATA[
- // If the install completed without needing a restart then switch to
- // using the new Addon
- if (!(aAddon.pendingOperations & AddonManager.PENDING_INSTALL))
- this._initWithAddon(aAddon);
- else
- this._updateState();
- ]]></body>
- </method>
-
- <method name="onDownloadFailed">
- <body><![CDATA[
- this._updateState();
- ]]></body>
- </method>
-
- <method name="onInstallFailed">
- <body><![CDATA[
- this._updateState();
- ]]></body>
- </method>
-
- <method name="onInstallCancelled">
- <body><![CDATA[
- this._updateState();
- ]]></body>
- </method>
- </implementation>
-
- <handlers>
- <handler event="click" button="0"><![CDATA[
- switch (event.detail) {
- case 1:
- // Prevent double-click where the UI changes on the first click
- this._lastClickTarget = event.originalTarget;
- break;
- case 2:
- if (event.originalTarget.localName != 'button' &&
- !event.originalTarget.classList.contains('text-link') &&
- event.originalTarget == this._lastClickTarget) {
- this.showInDetailView();
- }
- break;
- }
- ]]></handler>
- </handlers>
- </binding>
-
-
- <!-- Addon - uninstalled - An uninstalled addon that can be re-installed. -->
- <binding id="addon-uninstalled"
- extends="chrome://mozapps/content/extensions/extensions.xml#addon-base">
- <content>
- <xul:hbox class="pending">
- <xul:image class="pending-icon"/>
- <xul:label anonid="notice" flex="1"/>
- <xul:button anonid="restart-btn" class="button-link"
- label="&addon.restartNow.label;"
- command="cmd_restartApp"/>
- <xul:button anonid="undo-btn" class="button-link"
- label="&addon.undoRemove.label;"
- tooltiptext="&addon.undoRemove.tooltip;"
- oncommand="document.getBindingParent(this).cancelUninstall();"/>
- <xul:spacer flex="5000"/> <!-- Necessary to allow the message to wrap -->
- </xul:hbox>
- </content>
-
- <implementation>
- <constructor><![CDATA[
- this._notice.textContent = gStrings.ext.formatStringFromName("uninstallNotice",
- [this.mAddon.name],
- 1);
-
- if (!this.opRequiresRestart("uninstall"))
- this._restartBtn.setAttribute("hidden", true);
-
- gEventManager.registerAddonListener(this, this.mAddon.id);
- ]]></constructor>
-
- <destructor><![CDATA[
- gEventManager.unregisterAddonListener(this, this.mAddon.id);
- ]]></destructor>
-
- <field name="_notice" readonly="true">
- document.getAnonymousElementByAttribute(this, "anonid", "notice");
- </field>
- <field name="_restartBtn" readonly="true">
- document.getAnonymousElementByAttribute(this, "anonid", "restart-btn");
- </field>
-
- <method name="cancelUninstall">
- <body><![CDATA[
- // This assumes that disabling does not require a restart when
- // uninstalling doesn't. Things will still work if not, the add-on
- // will just still be active until finally getting uninstalled.
-
- if (this.isPending("uninstall"))
- this.mAddon.cancelUninstall();
- else if (this.getAttribute("wasDisabled") != "true")
- this.mAddon.userDisabled = false;
-
- this.removeAttribute("pending");
- ]]></body>
- </method>
-
- <method name="onOperationCancelled">
- <body><![CDATA[
- if (!this.isPending("uninstall"))
- this.removeAttribute("pending");
- ]]></body>
- </method>
-
- <method name="onExternalInstall">
- <parameter name="aAddon"/>
- <parameter name="aExistingAddon"/>
- <parameter name="aNeedsRestart"/>
- <body><![CDATA[
- if (aExistingAddon.id != this.mAddon.id)
- return;
-
- // Make sure any newly installed add-on has the correct disabled state
- if (this.hasAttribute("wasDisabled"))
- aAddon.userDisabled = this.getAttribute("wasDisabled") == "true";
-
- // If the install completed without needing a restart then switch to
- // using the new Addon
- if (!aNeedsRestart)
- this.mAddon = aAddon;
-
- this.removeAttribute("pending");
- ]]></body>
- </method>
-
- <method name="onInstallStarted">
- <parameter name="aInstall"/>
- <body><![CDATA[
- // Make sure any newly installed add-on has the correct disabled state
- if (this.hasAttribute("wasDisabled"))
- aInstall.addon.userDisabled = this.getAttribute("wasDisabled") == "true";
- ]]></body>
- </method>
-
- <method name="onInstallEnded">
- <parameter name="aInstall"/>
- <parameter name="aAddon"/>
- <body><![CDATA[
- // If the install completed without needing a restart then switch to
- // using the new Addon
- if (!(aAddon.pendingOperations & AddonManager.PENDING_INSTALL))
- this.mAddon = aAddon;
-
- this.removeAttribute("pending");
- ]]></body>
- </method>
- </implementation>
- </binding>
-
-
- <!-- Addon - installing - an addon item that is currently being installed -->
- <binding id="addon-installing"
- extends="chrome://mozapps/content/extensions/extensions.xml#addon-base">
- <content>
- <xul:hbox anonid="warning-container" class="warning">
- <xul:image class="warning-icon"/>
- <xul:label anonid="warning" flex="1"/>
- <xul:button anonid="warning-link" class="button-link"
- oncommand="document.getBindingParent(this).retryInstall();"/>
- <xul:spacer flex="5000"/> <!-- Necessary to allow the message to wrap -->
- </xul:hbox>
- <xul:hbox class="content-container">
- <xul:vbox class="icon-outer-container">
- <xul:vbox class="icon-container">
- <xul:image anonid="icon" class="icon"/>
- </xul:vbox>
- </xul:vbox>
- <xul:vbox class="fade name-outer-container" flex="1">
- <xul:hbox class="name-container">
- <xul:label anonid="name" class="name" crop="end" tooltip="addonitem-tooltip"/>
- </xul:hbox>
- </xul:vbox>
- <xul:vbox class="install-status-container">
- <xul:hbox anonid="install-status" class="install-status"/>
- </xul:vbox>
- </xul:hbox>
- </content>
-
- <implementation>
- <constructor><![CDATA[
- this._installStatus.mControl = this;
- this._installStatus.mInstall = this.mInstall;
- this.refreshInfo();
- ]]></constructor>
-
- <field name="_icon">
- document.getAnonymousElementByAttribute(this, "anonid", "icon");
- </field>
- <field name="_name">
- document.getAnonymousElementByAttribute(this, "anonid", "name");
- </field>
- <field name="_warning">
- document.getAnonymousElementByAttribute(this, "anonid", "warning");
- </field>
- <field name="_warningLink">
- document.getAnonymousElementByAttribute(this, "anonid", "warning-link");
- </field>
- <field name="_installStatus">
- document.getAnonymousElementByAttribute(this, "anonid",
- "install-status");
- </field>
-
- <method name="onInstallCompleted">
- <body><![CDATA[
- this.mAddon = this.mInstall.addon;
- this.setAttribute("name", this.mAddon.name);
- this.setAttribute("value", this.mAddon.id);
- this.setAttribute("status", "installed");
- ]]></body>
- </method>
-
- <method name="refreshInfo">
- <body><![CDATA[
- this.mAddon = this.mAddon || this.mInstall.addon;
- if (this.mAddon) {
- this._icon.src = this.mAddon.iconURL ||
- (this.mInstall ? this.mInstall.iconURL : "");
- this._name.value = this.mAddon.name;
- } else {
- this._icon.src = this.mInstall.iconURL;
- // AddonInstall.name isn't always available - fallback to filename
- if (this.mInstall.name) {
- this._name.value = this.mInstall.name;
- } else if (this.mInstall.sourceURI) {
- var url = Components.classes["@mozilla.org/network/standard-url;1"]
- .createInstance(Components.interfaces.nsIStandardURL);
- url.init(url.URLTYPE_STANDARD, 80, this.mInstall.sourceURI.spec,
- null, null);
- url.QueryInterface(Components.interfaces.nsIURL);
- this._name.value = url.fileName;
- }
- }
-
- if (this.mInstall.state == AddonManager.STATE_DOWNLOAD_FAILED) {
- this.setAttribute("notification", "warning");
- this._warning.textContent = gStrings.ext.formatStringFromName(
- "notification.downloadError",
- [this._name.value], 1
- );
- this._warningLink.label = gStrings.ext.GetStringFromName("notification.downloadError.retry");
- this._warningLink.tooltipText = gStrings.ext.GetStringFromName("notification.downloadError.retry.tooltip");
- } else if (this.mInstall.state == AddonManager.STATE_INSTALL_FAILED) {
- this.setAttribute("notification", "warning");
- this._warning.textContent = gStrings.ext.formatStringFromName(
- "notification.installError",
- [this._name.value], 1
- );
- this._warningLink.label = gStrings.ext.GetStringFromName("notification.installError.retry");
- this._warningLink.tooltipText = gStrings.ext.GetStringFromName("notification.downloadError.retry.tooltip");
- } else {
- this.removeAttribute("notification");
- }
- ]]></body>
- </method>
-
- <method name="retryInstall">
- <body><![CDATA[
- this.mInstall.install();
- ]]></body>
- </method>
- </implementation>
- </binding>
-
- <binding id="detail-row">
- <content>
- <xul:label class="detail-row-label" xbl:inherits="value=label"/>
- <xul:label class="detail-row-value" xbl:inherits="value"/>
- </content>
-
- <implementation>
- <property name="value">
- <getter><![CDATA[
- return this.getAttribute("value");
- ]]></getter>
- <setter><![CDATA[
- if (!val)
- this.removeAttribute("value");
- else
- this.setAttribute("value", val);
- ]]></setter>
- </property>
- </implementation>
- </binding>
-
-</bindings>
diff --git a/toolkit/mozapps/webextensions/content/extensions.xul b/toolkit/mozapps/webextensions/content/extensions.xul
deleted file mode 100644
index 70939d024..000000000
--- a/toolkit/mozapps/webextensions/content/extensions.xul
+++ /dev/null
@@ -1,715 +0,0 @@
-<?xml version="1.0"?>
-<!-- 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/. -->
-
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-<?xml-stylesheet href="chrome://mozapps/content/extensions/extensions.css"?>
-<?xml-stylesheet href="chrome://mozapps/skin/extensions/extensions.css"?>
-
-<!DOCTYPE page [
-<!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd" >
-%brandDTD;
-<!ENTITY % extensionsDTD SYSTEM "chrome://mozapps/locale/extensions/extensions.dtd">
-%extensionsDTD;
-]>
-
-<page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- xmlns:xhtml="http://www.w3.org/1999/xhtml"
- id="addons-page" title="&addons.windowTitle;"
- role="application" windowtype="Addons:Manager"
- disablefastfind="true">
-
- <xhtml:link rel="shortcut icon"
- href="chrome://mozapps/skin/extensions/extensionGeneric-16.png"/>
-
- <script type="application/javascript"
- src="chrome://mozapps/content/extensions/extensions.js"/>
- <script type="application/javascript"
- src="chrome://global/content/contentAreaUtils.js"/>
-
- <popupset>
- <!-- menu for an addon item -->
- <menupopup id="addonitem-popup">
- <menuitem id="menuitem_showDetails" command="cmd_showItemDetails"
- default="true" label="&cmd.showDetails.label;"
- accesskey="&cmd.showDetails.accesskey;"/>
- <menuitem id="menuitem_enableItem" command="cmd_enableItem"
- label="&cmd.enableAddon.label;"
- accesskey="&cmd.enableAddon.accesskey;"/>
- <menuitem id="menuitem_disableItem" command="cmd_disableItem"
- label="&cmd.disableAddon.label;"
- accesskey="&cmd.disableAddon.accesskey;"/>
- <menuitem id="menuitem_enableTheme" command="cmd_enableItem"
- label="&cmd.enableTheme.label;"
- accesskey="&cmd.enableTheme.accesskey;"/>
- <menuitem id="menuitem_disableTheme" command="cmd_disableItem"
- label="&cmd.disableTheme.label;"
- accesskey="&cmd.disableTheme.accesskey;"/>
- <menuitem id="menuitem_installItem" command="cmd_installItem"
- label="&cmd.installAddon.label;"
- accesskey="&cmd.installAddon.accesskey;"/>
- <menuitem id="menuitem_uninstallItem" command="cmd_uninstallItem"
- label="&cmd.uninstallAddon.label;"
- accesskey="&cmd.uninstallAddon.accesskey;"/>
- <menuseparator id="addonitem-menuseparator" />
- <menuitem id="menuitem_preferences" command="cmd_showItemPreferences"
-#ifdef XP_WIN
- label="&cmd.preferencesWin.label;"
- accesskey="&cmd.preferencesWin.accesskey;"/>
-#else
- label="&cmd.preferencesUnix.label;"
- accesskey="&cmd.preferencesUnix.accesskey;"/>
-#endif
- <menuitem id="menuitem_findUpdates" command="cmd_findItemUpdates"
- label="&cmd.findUpdates.label;"
- accesskey="&cmd.findUpdates.accesskey;"/>
- <menuitem id="menuitem_about" command="cmd_showItemAbout"
- label="&cmd.about.label;"
- accesskey="&cmd.about.accesskey;"/>
- </menupopup>
-
- <tooltip id="addonitem-tooltip"/>
- </popupset>
-
- <!-- global commands - these act on all addons, or affect the addons manager
- in some other way -->
- <commandset id="globalCommandSet">
- <!-- XXXsw remove useless oncommand attribute once bug 371900 is fixed -->
- <command id="cmd_focusSearch" oncommand=";"/>
- <command id="cmd_findAllUpdates"/>
- <command id="cmd_restartApp"/>
- <command id="cmd_goToDiscoverPane"/>
- <command id="cmd_goToRecentUpdates"/>
- <command id="cmd_goToAvailableUpdates"/>
- <command id="cmd_installFromFile"/>
- <command id="cmd_debugAddons"/>
- <command id="cmd_back"/>
- <command id="cmd_forward"/>
- <command id="cmd_enableCheckCompatibility"/>
- <command id="cmd_enableUpdateSecurity"/>
- <command id="cmd_toggleAutoUpdateDefault"/>
- <command id="cmd_resetAddonAutoUpdate"/>
- <command id="cmd_experimentsLearnMore"/>
- <command id="cmd_experimentsOpenTelemetryPreferences"/>
- <command id="cmd_showUnsignedExtensions"/>
- <command id="cmd_showAllExtensions"/>
- </commandset>
-
- <!-- view commands - these act on the selected addon -->
- <commandset id="viewCommandSet"
- events="richlistbox-select" commandupdater="true">
- <command id="cmd_showItemDetails"/>
- <command id="cmd_findItemUpdates"/>
- <command id="cmd_showItemPreferences"/>
- <command id="cmd_showItemAbout"/>
- <command id="cmd_enableItem"/>
- <command id="cmd_disableItem"/>
- <command id="cmd_installItem"/>
- <command id="cmd_purchaseItem"/>
- <command id="cmd_uninstallItem"/>
- <command id="cmd_cancelUninstallItem"/>
- <command id="cmd_cancelOperation"/>
- <command id="cmd_contribute"/>
- <command id="cmd_askToActivateItem"/>
- <command id="cmd_alwaysActivateItem"/>
- <command id="cmd_neverActivateItem"/>
- </commandset>
-
- <keyset>
- <key id="focusSearch" key="&search.commandkey;" modifiers="accel"
- command="cmd_focusSearch"/>
- </keyset>
- <hbox flex="1">
- <vbox>
- <hbox id="nav-header"
- align="center"
- pack="center">
- <toolbarbutton id="back-btn"
- class="nav-button header-button"
- command="cmd_back"
- tooltiptext="&cmd.back.tooltip;"
- hidden="true"
- disabled="true"/>
- <toolbarbutton id="forward-btn"
- class="nav-button header-button"
- command="cmd_forward"
- tooltiptext="&cmd.forward.tooltip;"
- hidden="true"
- disabled="true"/>
- </hbox>
- <!-- category list -->
- <richlistbox id="categories" flex="1">
- <richlistitem id="category-search" value="addons://search/"
- class="category"
- name="&view.search.label;" priority="0"
- tooltiptext="&view.search.label;" disabled="true"/>
- <richlistitem id="category-discover" value="addons://discover/"
- class="category"
- name="&view.discover.label;" priority="1000"
- tooltiptext="&view.discover.label;"/>
- <richlistitem id="category-availableUpdates" value="addons://updates/available"
- class="category"
- name="&view.availableUpdates.label;" priority="100000"
- tooltiptext="&view.availableUpdates.label;"
- disabled="true"/>
- <richlistitem id="category-recentUpdates" value="addons://updates/recent"
- class="category"
- name="&view.recentUpdates.label;" priority="101000"
- tooltiptext="&view.recentUpdates.label;" disabled="true"/>
- </richlistbox>
- </vbox>
- <vbox class="main-content" flex="1">
- <!-- view port -->
- <deck id="view-port" flex="1" selectedIndex="0">
- <!-- discover view -->
- <deck id="discover-view" flex="1" class="view-pane" selectedIndex="0" tabindex="0">
- <vbox id="discover-loading" align="center" pack="stretch" flex="1" class="alert-container">
- <spacer class="alert-spacer-before"/>
- <hbox class="alert loading" align="center">
- <image/>
- <label value="&loading.label;"/>
- </hbox>
- <spacer class="alert-spacer-after"/>
- </vbox>
- <vbox id="discover-error" align="center" pack="stretch" flex="1" class="alert-container">
- <spacer class="alert-spacer-before"/>
- <hbox>
- <spacer class="discover-spacer-before"/>
- <hbox class="alert" align="center">
- <image class="discover-logo"/>
- <vbox flex="1" align="stretch">
- <label class="discover-title">&discover.title;</label>
- <description class="discover-description">&discover.description2;</description>
- <description class="discover-footer">&discover.footer;</description>
- </vbox>
- </hbox>
- <spacer class="discover-spacer-after"/>
- </hbox>
- <spacer class="alert-spacer-after"/>
- </vbox>
- <browser id="discover-browser" type="content" flex="1"
- disablehistory="true" homepage="about:blank"/>
- </deck>
-
- <!-- container for views with the search/tools header -->
- <vbox id="headered-views" flex="1">
- <!-- main header -->
- <hbox id="header" align="center">
- <button id="show-all-extensions" hidden="true"
- label="&showAllExtensions.button.label;"
- command="cmd_showAllExtensions"/>
- <spacer flex="1"/>
- <hbox id="updates-container" align="center">
- <image class="spinner"/>
- <label id="updates-noneFound" hidden="true"
- value="&updates.noneFound.label;"/>
- <button id="updates-manualUpdatesFound-btn" class="button-link"
- hidden="true" label="&updates.manualUpdatesFound.label;"
- command="cmd_goToAvailableUpdates"/>
- <label id="updates-progress" hidden="true"
- value="&updates.updating.label;"/>
- <label id="updates-installed" hidden="true"
- value="&updates.installed.label;"/>
- <label id="updates-downloaded" hidden="true"
- value="&updates.downloaded.label;"/>
- <button id="updates-restart-btn" class="button-link" hidden="true"
- label="&updates.restart.label;"
- command="cmd_restartApp"/>
- </hbox>
- <button id="show-disabled-unsigned-extensions" hidden="true"
- class="warning"
- label="&showUnsignedExtensions.button.label;"
- command="cmd_showUnsignedExtensions"/>
- <toolbarbutton id="header-utils-btn" class="header-button" type="menu"
- tooltiptext="&toolsMenu.tooltip;">
- <menupopup id="utils-menu">
- <menuitem id="utils-updateNow"
- label="&updates.checkForUpdates.label;"
- accesskey="&updates.checkForUpdates.accesskey;"
- command="cmd_findAllUpdates"/>
- <menuitem id="utils-viewUpdates"
- label="&updates.viewUpdates.label;"
- accesskey="&updates.viewUpdates.accesskey;"
- command="cmd_goToRecentUpdates"/>
- <menuseparator id="utils-installFromFile-separator"/>
- <menuitem id="utils-installFromFile"
- label="&installAddonFromFile.label;"
- accesskey="&installAddonFromFile.accesskey;"
- command="cmd_installFromFile"/>
- <menuitem id="utils-debugAddons"
- label="&debugAddons.label;"
- accesskey="&debugAddons.accesskey;"
- command="cmd_debugAddons"/>
- <menuseparator/>
- <menuitem id="utils-autoUpdateDefault"
- label="&updates.updateAddonsAutomatically.label;"
- accesskey="&updates.updateAddonsAutomatically.accesskey;"
- type="checkbox" autocheck="false"
- command="cmd_toggleAutoUpdateDefault"/>
- <menuitem id="utils-resetAddonUpdatesToAutomatic"
- label="&updates.resetUpdatesToAutomatic.label;"
- accesskey="&updates.resetUpdatesToAutomatic.accesskey;"
- command="cmd_resetAddonAutoUpdate"/>
- <menuitem id="utils-resetAddonUpdatesToManual"
- label="&updates.resetUpdatesToManual.label;"
- accesskey="&updates.resetUpdatesToManual.accesskey;"
- command="cmd_resetAddonAutoUpdate"/>
- </menupopup>
- </toolbarbutton>
- <textbox id="header-search" type="search" searchbutton="true"
- searchbuttonlabel="&search.buttonlabel;"
- placeholder="&search.placeholder;"/>
- </hbox>
-
- <deck id="headered-views-content" flex="1" selectedIndex="0">
- <!-- search view -->
- <vbox id="search-view" flex="1" class="view-pane" tabindex="0">
- <hbox class="view-header global-warning-container" align="center">
- <!-- global warnings -->
- <hbox class="global-warning" flex="1">
- <hbox class="global-warning-safemode" flex="1" align="center"
- tooltiptext="&warning.safemode.label;">
- <image class="warning-icon"/>
- <label class="global-warning-text" flex="1" crop="end"
- value="&warning.safemode.label;"/>
- </hbox>
- <hbox class="global-warning-checkcompatibility" flex="1" align="center"
- tooltiptext="&warning.checkcompatibility.label;">
- <image class="warning-icon"/>
- <label class="global-warning-text" flex="1" crop="end"
- value="&warning.checkcompatibility.label;"/>
- </hbox>
- <button class="button-link global-warning-checkcompatibility"
- label="&warning.checkcompatibility.enable.label;"
- tooltiptext="&warning.checkcompatibility.enable.tooltip;"
- command="cmd_enableCheckCompatibility"/>
- <hbox class="global-warning-updatesecurity" flex="1" align="center"
- tooltiptext="&warning.updatesecurity.label;">
- <image class="warning-icon"/>
- <label class="global-warning-text" flex="1" crop="end"
- value="&warning.updatesecurity.label;"/>
- </hbox>
- <button class="button-link global-warning-updatesecurity"
- label="&warning.updatesecurity.enable.label;"
- tooltiptext="&warning.updatesecurity.enable.tooltip;"
- command="cmd_enableUpdateSecurity"/>
- <spacer flex="5000"/> <!-- Necessary to allow the message to wrap -->
- </hbox>
- <spacer flex="1"/>
- <hbox id="search-sorters" class="sort-controls"
- showrelevance="true" sortby="relevancescore" ascending="false"/>
- </hbox>
- <hbox id="search-filter" align="center">
- <label id="search-filter-label" value="&search.filter2.label;"/>
- <radiogroup id="search-filter-radiogroup" orient="horizontal"
- align="center" persist="value" value="remote">
- <radio id="search-filter-local" class="search-filter-radio"
- label="&search.filter2.installed.label;" value="local"
- tooltiptext="&search.filter2.installed.tooltip;"/>
- <radio id="search-filter-remote" class="search-filter-radio"
- label="&search.filter2.available.label;" value="remote"
- tooltiptext="&search.filter2.available.tooltip;"/>
- </radiogroup>
- </hbox>
- <vbox id="search-loading" class="alert-container"
- flex="1" hidden="true">
- <spacer class="alert-spacer-before"/>
- <hbox class="alert loading" align="center">
- <image/>
- <label value="&loading.label;"/>
- </hbox>
- <spacer class="alert-spacer-after"/>
- </vbox>
- <vbox id="search-list-empty" class="alert-container"
- flex="1" hidden="true">
- <spacer class="alert-spacer-before"/>
- <vbox class="alert">
- <label value="&listEmpty.search.label;"/>
- <button class="discover-button"
- id="discover-button-search"
- label="&listEmpty.button.label;"
- command="cmd_goToDiscoverPane"/>
- </vbox>
- <spacer class="alert-spacer-after"/>
- </vbox>
- <richlistbox id="search-list" class="list" flex="1">
- <hbox pack="center">
- <label id="search-allresults-link" class="text-link"/>
- </hbox>
- </richlistbox>
- </vbox>
-
- <!-- list view -->
- <vbox id="list-view" flex="1" class="view-pane" align="stretch" tabindex="0">
- <!-- info UI for add-ons that have been disabled for being unsigned -->
- <vbox id="disabled-unsigned-addons-info" hidden="true">
- <label id="disabled-unsigned-addons-heading" value="&disabledUnsigned.heading;"/>
- <description>
- &disabledUnsigned.description.start;<label class="text-link plain" id="find-alternative-addons">&disabledUnsigned.description.findAddonsLink;</label>&disabledUnsigned.description.end;
- </description>
- <hbox pack="start"><label class="text-link" id="signing-learn-more">&disabledUnsigned.learnMore;</label></hbox>
- <description id="signing-dev-info">
- &disabledUnsigned.devInfo.start;<label class="text-link plain" id="signing-dev-manual-link">&disabledUnsigned.devInfo.linkToManual;</label>&disabledUnsigned.devInfo.end;
- </description>
- </vbox>
- <vbox id="plugindeprecation-notice" class="alert-container">
- <hbox class="alert">
- <description>&pluginDeprecation.description; &#160;
- <label class="text-link plain" id="plugindeprecation-learnmore-link">&pluginDeprecation.learnMore;</label>
- </description>
- </hbox>
- </vbox>
- <hbox class="view-header global-warning-container">
- <!-- global warnings -->
- <hbox class="global-warning" flex="1">
- <hbox class="global-warning-safemode" flex="1" align="center"
- tooltiptext="&warning.safemode.label;">
- <image class="warning-icon"/>
- <label class="global-warning-text" flex="1" crop="end"
- value="&warning.safemode.label;"/>
- </hbox>
- <hbox class="global-warning-checkcompatibility" flex="1" align="center"
- tooltiptext="&warning.checkcompatibility.label;">
- <image class="warning-icon"/>
- <label class="global-warning-text" flex="1" crop="end"
- value="&warning.checkcompatibility.label;"/>
- </hbox>
- <button class="button-link global-warning-checkcompatibility"
- label="&warning.checkcompatibility.enable.label;"
- tooltiptext="&warning.checkcompatibility.enable.tooltip;"
- command="cmd_enableCheckCompatibility"/>
- <hbox class="global-warning-updatesecurity" flex="1" align="center"
- tooltiptext="&warning.updatesecurity.label;">
- <image class="warning-icon"/>
- <label class="global-warning-text" flex="1" crop="end"
- value="&warning.updatesecurity.label;"/>
- </hbox>
- <button class="button-link global-warning-updatesecurity"
- label="&warning.updatesecurity.enable.label;"
- tooltiptext="&warning.updatesecurity.enable.tooltip;"
- command="cmd_enableUpdateSecurity"/>
- <spacer flex="5000"/> <!-- Necessary to allow the message to wrap -->
- </hbox>
- </hbox>
- <hbox class="view-header global-info-container experiment-info-container">
- <hbox class="global-info" flex="1" align="center">
- <label value="&experiment.info.label;"/>
- <button id="experiments-learn-more"
- label="&experiment.info.learnmore;"
- tooltiptext="&experiment.info.learnmore;"
- accesskey="&experiment.info.learnmore.accesskey;"
- command="cmd_experimentsLearnMore"/>
- <button id="experiments-change-telemetry"
- label="&experiment.info.changetelemetry;"
- tooltiptext="&experiment.info.changetelemetry;"
- accesskey="&experiment.info.changetelemetry.accesskey;"
- command="cmd_experimentsOpenTelemetryPreferences"/>
- <spacer flex="5000"/> <!-- Necessary to allow the message to wrap. -->
- </hbox>
- </hbox>
- <vbox id="addon-list-empty" class="alert-container"
- flex="1" hidden="true">
- <spacer class="alert-spacer-before"/>
- <vbox class="alert">
- <label value="&listEmpty.installed.label;"/>
- <button class="discover-button"
- id="discover-button-install"
- label="&listEmpty.button.label;"
- command="cmd_goToDiscoverPane"/>
- </vbox>
- <spacer class="alert-spacer-after"/>
- </vbox>
- <richlistbox id="addon-list" class="list" flex="1"/>
- </vbox>
- <!-- updates view -->
- <vbox id="updates-view" flex="1" class="view-pane" tabindex="0">
- <hbox class="view-header global-warning-container" align="center">
- <!-- global warnings -->
- <hbox class="global-warning" flex="1">
- <hbox class="global-warning-safemode" flex="1" align="center"
- tooltiptext="&warning.safemode.label;">
- <image class="warning-icon"/>
- <label class="global-warning-text" flex="1" crop="end"
- value="&warning.safemode.label;"/>
- </hbox>
- <hbox class="global-warning-checkcompatibility" flex="1" align="center"
- tooltiptext="&warning.checkcompatibility.label;">
- <image class="warning-icon"/>
- <label class="global-warning-text" flex="1" crop="end"
- value="&warning.checkcompatibility.label;"/>
- </hbox>
- <button class="button-link global-warning-checkcompatibility"
- label="&warning.checkcompatibility.enable.label;"
- tooltiptext="&warning.checkcompatibility.enable.tooltip;"
- command="cmd_enableCheckCompatibility"/>
- <hbox class="global-warning-updatesecurity" flex="1" align="center"
- tooltiptext="&warning.updatesecurity.label;">
- <image class="warning-icon"/>
- <label class="global-warning-text" flex="1" crop="end"
- value="&warning.updatesecurity.label;"/>
- </hbox>
- <button class="button-link global-warning-updatesecurity"
- label="&warning.updatesecurity.enable.label;"
- tooltiptext="&warning.updatesecurity.enable.tooltip;"
- command="cmd_enableUpdateSecurity"/>
- <spacer flex="5000"/> <!-- Necessary to allow the message to wrap -->
- </hbox>
- <spacer flex="1"/>
- <hbox id="updates-sorters" class="sort-controls" sortby="updateDate"
- ascending="false"/>
- </hbox>
- <vbox id="updates-list-empty" class="alert-container"
- flex="1" hidden="true">
- <spacer class="alert-spacer-before"/>
- <vbox class="alert">
- <label id="empty-availableUpdates-msg" value="&listEmpty.availableUpdates.label;"/>
- <label id="empty-recentUpdates-msg" value="&listEmpty.recentUpdates.label;"/>
- <button label="&listEmpty.findUpdates.label;"
- command="cmd_findAllUpdates"/>
- </vbox>
- <spacer class="alert-spacer-after"/>
- </vbox>
- <hbox id="update-actions" pack="center">
- <button id="update-selected-btn" hidden="true"
- label="&updates.updateSelected.label;"
- tooltiptext="&updates.updateSelected.tooltip;"/>
- </hbox>
- <richlistbox id="updates-list" class="list" flex="1"/>
- </vbox>
-
- <!-- detail view -->
- <scrollbox id="detail-view" flex="1" class="view-pane addon-view" orient="vertical" tabindex="0"
- role="document">
- <!-- global warnings -->
- <hbox class="global-warning-container global-warning">
- <hbox class="global-warning-safemode" flex="1" align="center"
- tooltiptext="&warning.safemode.label;">
- <image class="warning-icon"/>
- <label class="global-warning-text" flex="1" crop="end"
- value="&warning.safemode.label;"/>
- </hbox>
- <hbox class="global-warning-checkcompatibility" flex="1" align="center"
- tooltiptext="&warning.checkcompatibility.label;">
- <image class="warning-icon"/>
- <label class="global-warning-text" flex="1" crop="end"
- value="&warning.checkcompatibility.label;"/>
- </hbox>
- <button class="button-link global-warning-checkcompatibility"
- label="&warning.checkcompatibility.enable.label;"
- tooltiptext="&warning.checkcompatibility.enable.tooltip;"
- command="cmd_enableCheckCompatibility"/>
- <hbox class="global-warning-updatesecurity" flex="1" align="center"
- tooltiptext="&warning.updatesecurity.label;">
- <image class="warning-icon"/>
- <label class="global-warning-text" flex="1" crop="end"
- value="&warning.updatesecurity.label;"/>
- </hbox>
- <button class="button-link global-warning-updatesecurity"
- label="&warning.updatesecurity.enable.label;"
- tooltiptext="&warning.updatesecurity.enable.tooltip;"
- command="cmd_enableUpdateSecurity"/>
- <spacer flex="5000"/> <!-- Necessary to allow the message to wrap -->
- </hbox>
- <hbox flex="1">
- <spacer flex="1"/>
- <!-- "loading" splash screen -->
- <vbox class="alert-container">
- <spacer class="alert-spacer-before"/>
- <hbox class="alert loading">
- <image/>
- <label value="&loading.label;"/>
- </hbox>
- <spacer class="alert-spacer-after"/>
- </vbox>
- <!-- actual detail view -->
- <vbox class="detail-view-container" flex="3" contextmenu="addonitem-popup">
- <vbox id="detail-notifications">
- <hbox id="warning-container" align="center" class="warning">
- <image class="warning-icon"/>
- <label id="detail-warning" flex="1"/>
- <label id="detail-warning-link" class="text-link"/>
- <spacer flex="5000"/> <!-- Necessary to allow the message to wrap -->
- </hbox>
- <hbox id="error-container" align="center" class="error">
- <image class="error-icon"/>
- <label id="detail-error" flex="1"/>
- <label id="detail-error-link" class="text-link"/>
- <spacer flex="5000"/> <!-- Necessary to allow the message to wrap -->
- </hbox>
- <hbox id="pending-container" align="center" class="pending">
- <image class="pending-icon"/>
- <label id="detail-pending" flex="1"/>
- <button id="detail-restart-btn" class="button-link"
- label="&addon.restartNow.label;"
- command="cmd_restartApp"/>
- <button id="detail-undo-btn" class="button-link"
- label="&addon.undoAction.label;"
- tooltipText="&addon.undoAction.tooltip;"
- command="cmd_cancelOperation"/>
- <spacer flex="5000"/> <!-- Necessary to allow the message to wrap -->
- </hbox>
- </vbox>
- <hbox align="start">
- <vbox id="detail-icon-container" align="end">
- <image id="detail-icon" class="icon"/>
- </vbox>
- <vbox flex="1">
- <vbox id="detail-summary">
- <hbox id="detail-name-container" class="name-container"
- align="start">
- <label id="detail-name" flex="1"/>
- <label id="detail-version"/>
- <label class="disabled-postfix" value="&addon.disabled.postfix;"/>
- <label class="update-postfix" value="&addon.update.postfix;"/>
- <spacer flex="5000"/> <!-- Necessary to allow the name to wrap -->
- </hbox>
- <label id="detail-creator" class="creator"/>
- </vbox>
- <hbox id="detail-experiment-container">
- <svg width="8" height="8" viewBox="0 0 8 8" version="1.1"
- xmlns="http://www.w3.org/2000/svg"
- id="detail-experiment-bullet-container">
- <circle cx="4" cy="4" r="4" id="detail-experiment-bullet"/>
- </svg>
- <label id="detail-experiment-state"/>
- <label id="detail-experiment-time"/>
- </hbox>
- <hbox id="detail-desc-container" align="start">
- <vbox id="detail-screenshot-box" pack="center" hidden="true"> <!-- Necessary to work around bug 394738 -->
- <image id="detail-screenshot"/>
- </vbox>
- <vbox flex="1">
- <description id="detail-desc"/>
- <description id="detail-fulldesc"/>
- </vbox>
- </hbox>
- <vbox id="detail-contributions">
- <description id="detail-contrib-description">
- &detail.contributions.description;
- </description>
- <hbox align="center">
- <label id="detail-contrib-suggested"/>
- <spacer flex="1"/>
- <button id="detail-contrib-btn"
- label="&cmd.contribute.label;"
- accesskey="&cmd.contribute.accesskey;"
- tooltiptext="&cmd.contribute.tooltip;"
- command="cmd_contribute"/>
- </hbox>
- </vbox>
- <grid id="detail-grid">
- <columns>
- <column flex="1"/>
- <column flex="2"/>
- </columns>
- <rows id="detail-rows">
- <row class="detail-row-complex" id="detail-updates-row">
- <label class="detail-row-label" value="&detail.updateType;"/>
- <hbox align="center">
- <radiogroup id="detail-autoUpdate" orient="horizontal">
- <!-- The values here need to match the values of
- AddonManager.AUTOUPDATE_* -->
- <radio label="&detail.updateDefault.label;"
- tooltiptext="&detail.updateDefault.tooltip;"
- value="1"/>
- <radio label="&detail.updateAutomatic.label;"
- tooltiptext="&detail.updateAutomatic.tooltip;"
- value="2"/>
- <radio label="&detail.updateManual.label;"
- tooltiptext="&detail.updateManual.tooltip;"
- value="0"/>
- </radiogroup>
- <button id="detail-findUpdates-btn" class="button-link"
- label="&detail.checkForUpdates.label;"
- accesskey="&detail.checkForUpdates.accesskey;"
- tooltiptext="&detail.checkForUpdates.tooltip;"
- command="cmd_findItemUpdates"/>
- </hbox>
- </row>
- <row class="detail-row" id="detail-dateUpdated" label="&detail.lastupdated.label;"/>
- <row class="detail-row-complex" id="detail-homepage-row" label="&detail.home;">
- <label class="detail-row-label" value="&detail.home;"/>
- <label id="detail-homepage" class="detail-row-value text-link" crop="end"/>
- </row>
- <row class="detail-row-complex" id="detail-repository-row" label="&detail.repository;">
- <label class="detail-row-label" value="&detail.repository;"/>
- <label id="detail-repository" class="detail-row-value text-link"/>
- </row>
- <row class="detail-row" id="detail-size" label="&detail.size;"/>
- <row class="detail-row-complex" id="detail-rating-row">
- <label class="detail-row-label" value="&rating2.label;"/>
- <hbox>
- <label id="detail-rating" class="meta-value meta-rating"
- showrating="average"/>
- <label id="detail-reviews" class="text-link"/>
- </hbox>
- </row>
- <row class="detail-row" id="detail-downloads" label="&detail.numberOfDownloads.label;"/>
- </rows>
- </grid>
- <hbox id="detail-controls">
- <button id="detail-prefs-btn" class="addon-control preferences"
-#ifdef XP_WIN
- label="&detail.showPreferencesWin.label;"
- accesskey="&detail.showPreferencesWin.accesskey;"
- tooltiptext="&detail.showPreferencesWin.tooltip;"
-#else
- label="&detail.showPreferencesUnix.label;"
- accesskey="&detail.showPreferencesUnix.accesskey;"
- tooltiptext="&detail.showPreferencesUnix.tooltip;"
-#endif
- command="cmd_showItemPreferences"/>
- <spacer flex="1"/>
- <button id="detail-enable-btn" class="addon-control enable"
- label="&cmd.enableAddon.label;"
- accesskey="&cmd.enableAddon.accesskey;"
- command="cmd_enableItem"/>
- <button id="detail-disable-btn" class="addon-control disable"
- label="&cmd.disableAddon.label;"
- accesskey="&cmd.disableAddon.accesskey;"
- command="cmd_disableItem"/>
- <button id="detail-uninstall-btn" class="addon-control remove"
- label="&cmd.uninstallAddon.label;"
- accesskey="&cmd.uninstallAddon.accesskey;"
- command="cmd_uninstallItem"/>
- <button id="detail-purchase-btn" class="addon-control purchase"
- command="cmd_purchaseItem"/>
- <button id="detail-install-btn" class="addon-control install"
- label="&cmd.installAddon.label;"
- accesskey="&cmd.installAddon.accesskey;"
- command="cmd_installItem"/>
- <menulist id="detail-state-menulist"
- crop="none" sizetopopup="always"
- tooltiptext="&cmd.stateMenu.tooltip;">
- <menupopup>
- <menuitem id="detail-ask-to-activate-menuitem"
- class="addon-control"
- label="&cmd.askToActivate.label;"
- tooltiptext="&cmd.askToActivate.tooltip;"
- command="cmd_askToActivateItem"/>
- <menuitem id="detail-always-activate-menuitem"
- class="addon-control"
- label="&cmd.alwaysActivate.label;"
- tooltiptext="&cmd.alwaysActivate.tooltip;"
- command="cmd_alwaysActivateItem"/>
- <menuitem id="detail-never-activate-menuitem"
- class="addon-control"
- label="&cmd.neverActivate.label;"
- tooltiptext="&cmd.neverActivate.tooltip;"
- command="cmd_neverActivateItem"/>
- </menupopup>
- </menulist>
- </hbox>
- </vbox>
- </hbox>
- </vbox>
- <spacer flex="1"/>
- </hbox>
- </scrollbox>
- </deck>
- </vbox>
- </deck>
- </vbox>
- </hbox>
-</page>
diff --git a/toolkit/mozapps/webextensions/content/newaddon.xul b/toolkit/mozapps/webextensions/content/newaddon.xul
deleted file mode 100644
index 1d8545249..000000000
--- a/toolkit/mozapps/webextensions/content/newaddon.xul
+++ /dev/null
@@ -1,67 +0,0 @@
-<?xml version="1.0"?>
-<!-- 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/. -->
-
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-<?xml-stylesheet href="chrome://mozapps/skin/extensions/newaddon.css"?>
-
-<!DOCTYPE page [
-<!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd" >
-%brandDTD;
-<!ENTITY % newaddonDTD SYSTEM "chrome://mozapps/locale/extensions/newaddon.dtd">
-%newaddonDTD;
-]>
-
-<page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- xmlns:xhtml="http://www.w3.org/1999/xhtml" title="&title;"
- disablefastfind="true" id="addon-page" onload="initialize()"
- onunload="unload()" role="application" align="stretch" pack="stretch">
-
- <xhtml:link rel="shortcut icon" style="display: none"
- href="chrome://mozapps/skin/extensions/extensionGeneric-16.png"/>
-
- <script type="application/javascript"
- src="chrome://mozapps/content/extensions/newaddon.js"/>
-
- <scrollbox id="addon-scrollbox" align="center">
- <spacer id="spacer-start"/>
-
- <vbox id="addon-container" class="main-content">
- <description>&intro;</description>
-
- <hbox id="addon-info">
- <image id="icon"/>
- <vbox flex="1">
- <label id="name"/>
- <label id="author"/>
- <label id="location" crop="end"/>
- </vbox>
- </hbox>
-
- <hbox id="warning">
- <image id="warning-icon"/>
- <description flex="1">&warning;</description>
- </hbox>
-
- <checkbox id="allow" label="&allow;"/>
- <description id="later">&later;</description>
-
- <deck id="buttonDeck">
- <hbox id="continuePanel">
- <button id="continue-button" label="&continue;"
- oncommand="continueClicked()"/>
- </hbox>
- <vbox id="restartPanel">
- <description id="restartMessage">&restartMessage;</description>
- <hbox id="restartPanelButtons">
- <button id="restart-button" label="&restartButton;" oncommand="restartClicked()"/>
- <button id="cancel-button" label="&cancelButton;" oncommand="cancelClicked()"/>
- </hbox>
- </vbox>
- </deck>
- </vbox>
-
- <spacer id="spacer-end"/>
- </scrollbox>
-</page>
diff --git a/toolkit/mozapps/webextensions/content/setting.xml b/toolkit/mozapps/webextensions/content/setting.xml
deleted file mode 100644
index 2b70eb0d0..000000000
--- a/toolkit/mozapps/webextensions/content/setting.xml
+++ /dev/null
@@ -1,486 +0,0 @@
-<?xml version="1.0"?>
-<!-- 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/. -->
-
-<!DOCTYPE page [
-<!ENTITY % extensionsDTD SYSTEM "chrome://mozapps/locale/extensions/extensions.dtd">
-%extensionsDTD;
-]>
-
-<!-- import-globals-from extensions.js -->
-
-<bindings xmlns="http://www.mozilla.org/xbl"
- xmlns:xbl="http://www.mozilla.org/xbl"
- xmlns:html="http://www.w3.org/1999/xhtml"
- xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
-
- <binding id="setting-base">
- <implementation>
- <constructor><![CDATA[
- this.preferenceChanged();
-
- this.addEventListener("keypress", function(event) {
- event.stopPropagation();
- }, false);
-
- if (this.usePref)
- Services.prefs.addObserver(this.pref, this._observer, true);
- ]]></constructor>
-
- <field name="_observer"><![CDATA[({
- _self: this,
-
- QueryInterface: function(aIID) {
- const Ci = Components.interfaces;
- if (aIID.equals(Ci.nsIObserver) ||
- aIID.equals(Ci.nsISupportsWeakReference) ||
- aIID.equals(Ci.nsISupports))
- return this;
-
- throw Components.Exception("No interface", Components.results.NS_ERROR_NO_INTERFACE);
- },
-
- observe: function(aSubject, aTopic, aPrefName) {
- if (aTopic != "nsPref:changed")
- return;
-
- if (this._self.pref == aPrefName)
- this._self.preferenceChanged();
- }
- })]]>
- </field>
-
- <method name="fireEvent">
- <parameter name="eventName"/>
- <parameter name="funcStr"/>
- <body>
- <![CDATA[
- let body = funcStr || this.getAttribute(eventName);
- if (!body)
- return;
-
- try {
- let event = document.createEvent("Events");
- event.initEvent(eventName, true, true);
- let f = new Function("event", body);
- f.call(this, event);
- }
- catch (e) {
- Cu.reportError(e);
- }
- ]]>
- </body>
- </method>
-
- <method name="valueFromPreference">
- <body>
- <![CDATA[
- // Should be code to set the from the preference input.value
- throw Components.Exception("No valueFromPreference implementation",
- Components.results.NS_ERROR_NOT_IMPLEMENTED);
- ]]>
- </body>
- </method>
-
- <method name="valueToPreference">
- <body>
- <![CDATA[
- // Should be code to set the input.value from the preference
- throw Components.Exception("No valueToPreference implementation",
- Components.results.NS_ERROR_NOT_IMPLEMENTED);
- ]]>
- </body>
- </method>
-
- <method name="inputChanged">
- <body>
- <![CDATA[
- if (this.usePref && !this._updatingInput) {
- this.valueToPreference();
- this.fireEvent("oninputchanged");
- }
- ]]>
- </body>
- </method>
-
- <method name="preferenceChanged">
- <body>
- <![CDATA[
- if (this.usePref) {
- this._updatingInput = true;
- try {
- this.valueFromPreference();
- this.fireEvent("onpreferencechanged");
- } catch (e) {}
- this._updatingInput = false;
- }
- ]]>
- </body>
- </method>
-
- <property name="usePref" readonly="true" onget="return this.hasAttribute('pref');"/>
- <property name="pref" readonly="true" onget="return this.getAttribute('pref');"/>
- <property name="type" readonly="true" onget="return this.getAttribute('type');"/>
- <property name="value" onget="return this.input.value;" onset="return this.input.value = val;"/>
-
- <field name="_updatingInput">false</field>
- <field name="input">document.getAnonymousElementByAttribute(this, "anonid", "input");</field>
- <field name="settings">
- this.parentNode.localName == "settings" ? this.parentNode : null;
- </field>
- </implementation>
- </binding>
-
- <binding id="setting-bool" extends="chrome://mozapps/content/extensions/setting.xml#setting-base">
- <content>
- <xul:vbox>
- <xul:hbox class="preferences-alignment">
- <xul:label class="preferences-title" flex="1" xbl:inherits="xbl:text=title"/>
- </xul:hbox>
- <xul:description class="preferences-description" flex="1" xbl:inherits="xbl:text=desc"/>
- <xul:label class="preferences-learnmore text-link"
- onclick="document.getBindingParent(this).openLearnMore()">&setting.learnmore;</xul:label>
- </xul:vbox>
- <xul:hbox class="preferences-alignment">
- <xul:checkbox anonid="input" xbl:inherits="disabled,onlabel,offlabel,label=checkboxlabel" oncommand="inputChanged();"/>
- </xul:hbox>
- </content>
-
- <implementation>
- <method name="valueFromPreference">
- <body>
- <![CDATA[
- let val = Services.prefs.getBoolPref(this.pref);
- this.value = this.inverted ? !val : val;
- ]]>
- </body>
- </method>
-
- <method name="valueToPreference">
- <body>
- <![CDATA[
- let val = this.value;
- Services.prefs.setBoolPref(this.pref, this.inverted ? !val : val);
- ]]>
- </body>
- </method>
-
- <property name="value" onget="return this.input.checked;" onset="return this.input.setChecked(val);"/>
- <property name="inverted" readonly="true" onget="return this.getAttribute('inverted');"/>
-
- <method name="openLearnMore">
- <body>
- <![CDATA[
- window.open(this.getAttribute("learnmore"), "_blank");
- ]]>
- </body>
- </method>
- </implementation>
- </binding>
-
- <binding id="setting-boolint" extends="chrome://mozapps/content/extensions/setting.xml#setting-bool">
- <implementation>
- <method name="valueFromPreference">
- <body>
- <![CDATA[
- let val = Services.prefs.getIntPref(this.pref);
- this.value = (val == this.getAttribute("on"));
- ]]>
- </body>
- </method>
-
- <method name="valueToPreference">
- <body>
- <![CDATA[
- Services.prefs.setIntPref(this.pref, this.getAttribute(this.value ? "on" : "off"));
- ]]>
- </body>
- </method>
- </implementation>
- </binding>
-
- <binding id="setting-localized-bool" extends="chrome://mozapps/content/extensions/setting.xml#setting-bool">
- <implementation>
- <method name="valueFromPreference">
- <body>
- <![CDATA[
- let val = Services.prefs.getComplexValue(this.pref, Components.interfaces.nsIPrefLocalizedString).data;
- if (this.inverted) val = !val;
- this.value = (val == "true");
- ]]>
- </body>
- </method>
-
- <method name="valueToPreference">
- <body>
- <![CDATA[
- let val = this.value;
- if (this.inverted) val = !val;
- let pref = Components.classes["@mozilla.org/pref-localizedstring;1"].createInstance(Components.interfaces.nsIPrefLocalizedString);
- pref.data = this.inverted ? (!val).toString() : val.toString();
- Services.prefs.setComplexValue(this.pref, Components.interfaces.nsIPrefLocalizedString, pref);
- ]]>
- </body>
- </method>
- </implementation>
- </binding>
-
- <binding id="setting-integer" extends="chrome://mozapps/content/extensions/setting.xml#setting-base">
- <content>
- <xul:vbox>
- <xul:hbox class="preferences-alignment">
- <xul:label class="preferences-title" flex="1" xbl:inherits="xbl:text=title"/>
- </xul:hbox>
- <xul:description class="preferences-description" flex="1" xbl:inherits="xbl:text=desc"/>
- </xul:vbox>
- <xul:hbox class="preferences-alignment">
- <xul:textbox type="number" anonid="input" oninput="inputChanged();" onchange="inputChanged();"
- xbl:inherits="disabled,emptytext,min,max,increment,hidespinbuttons,wraparound,size"/>
- </xul:hbox>
- </content>
-
- <implementation>
- <method name="valueFromPreference">
- <body>
- <![CDATA[
- let val = Services.prefs.getIntPref(this.pref);
- this.value = val;
- ]]>
- </body>
- </method>
-
- <method name="valueToPreference">
- <body>
- <![CDATA[
- Services.prefs.setIntPref(this.pref, this.value);
- ]]>
- </body>
- </method>
- </implementation>
- </binding>
-
- <binding id="setting-control" extends="chrome://mozapps/content/extensions/setting.xml#setting-base">
- <content>
- <xul:vbox>
- <xul:hbox class="preferences-alignment">
- <xul:label class="preferences-title" flex="1" xbl:inherits="xbl:text=title"/>
- </xul:hbox>
- <xul:description class="preferences-description" flex="1" xbl:inherits="xbl:text=desc"/>
- </xul:vbox>
- <xul:hbox class="preferences-alignment">
- <children/>
- </xul:hbox>
- </content>
- </binding>
-
- <binding id="setting-string" extends="chrome://mozapps/content/extensions/setting.xml#setting-base">
- <content>
- <xul:vbox>
- <xul:hbox class="preferences-alignment">
- <xul:label class="preferences-title" flex="1" xbl:inherits="xbl:text=title"/>
- </xul:hbox>
- <xul:description class="preferences-description" flex="1" xbl:inherits="xbl:text=desc"/>
- </xul:vbox>
- <xul:hbox class="preferences-alignment">
- <xul:textbox anonid="input" flex="1" oninput="inputChanged();"
- xbl:inherits="disabled,emptytext,type=inputtype,min,max,increment,hidespinbuttons,decimalplaces,wraparound"/>
- </xul:hbox>
- </content>
-
- <implementation>
- <method name="valueFromPreference">
- <body>
- <![CDATA[
- this.value = Preferences.get(this.pref, "");
- ]]>
- </body>
- </method>
-
- <method name="valueToPreference">
- <body>
- <![CDATA[
- Preferences.set(this.pref, this.value);
- ]]>
- </body>
- </method>
- </implementation>
- </binding>
-
- <binding id="setting-color" extends="chrome://mozapps/content/extensions/setting.xml#setting-base">
- <content>
- <xul:vbox>
- <xul:hbox class="preferences-alignment">
- <xul:label class="preferences-title" flex="1" xbl:inherits="xbl:text=title"/>
- </xul:hbox>
- <xul:description class="preferences-description" flex="1" xbl:inherits="xbl:text=desc"/>
- </xul:vbox>
- <xul:hbox class="preferences-alignment">
- <xul:colorpicker type="button" anonid="input" xbl:inherits="disabled" onchange="document.getBindingParent(this).inputChanged();"/>
- </xul:hbox>
- </content>
-
- <implementation>
- <method name="valueFromPreference">
- <body>
- <![CDATA[
- // We must wait for the colorpicker's binding to be applied before setting the value
- if (!this.input.color)
- this.input.initialize();
- this.value = Services.prefs.getCharPref(this.pref);
- ]]>
- </body>
- </method>
-
- <method name="valueToPreference">
- <body>
- <![CDATA[
- Services.prefs.setCharPref(this.pref, this.value);
- ]]>
- </body>
- </method>
-
- <property name="value" onget="return this.input.color;" onset="return this.input.color = val;"/>
- </implementation>
- </binding>
-
- <binding id="setting-path" extends="chrome://mozapps/content/extensions/setting.xml#setting-base">
- <content>
- <xul:vbox>
- <xul:hbox class="preferences-alignment">
- <xul:label class="preferences-title" flex="1" xbl:inherits="xbl:text=title"/>
- </xul:hbox>
- <xul:description class="preferences-description" flex="1" xbl:inherits="xbl:text=desc"/>
- </xul:vbox>
- <xul:hbox class="preferences-alignment">
- <xul:button type="button" anonid="button" label="&settings.path.button.label;" xbl:inherits="disabled" oncommand="showPicker();"/>
- <xul:label anonid="input" flex="1" crop="center" xbl:inherits="disabled"/>
- </xul:hbox>
- </content>
-
- <implementation>
- <method name="showPicker">
- <body>
- <![CDATA[
- var filePicker = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
- filePicker.init(window, this.getAttribute("title"),
- this.type == "file" ? Ci.nsIFilePicker.modeOpen : Ci.nsIFilePicker.modeGetFolder);
- if (this.value) {
- try {
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- file.initWithPath(this.value);
- filePicker.displayDirectory = this.type == "file" ? file.parent : file;
- if (this.type == "file") {
- filePicker.defaultString = file.leafName;
- }
- } catch (e) {}
- }
- if (filePicker.show() != Ci.nsIFilePicker.returnCancel) {
- this.value = filePicker.file.path;
- this.inputChanged();
- }
- ]]>
- </body>
- </method>
-
- <method name="valueFromPreference">
- <body>
- <![CDATA[
- this.value = Preferences.get(this.pref, "");
- ]]>
- </body>
- </method>
-
- <method name="valueToPreference">
- <body>
- <![CDATA[
- Preferences.set(this.pref, this.value);
- ]]>
- </body>
- </method>
-
- <field name="_value"></field>
-
- <property name="value">
- <getter>
- <![CDATA[
- return this._value;
- ]]>
- </getter>
- <setter>
- <![CDATA[
- this._value = val;
- let label = "";
- if (val) {
- try {
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- file.initWithPath(val);
- label = this.hasAttribute("fullpath") ? file.path : file.leafName;
- } catch (e) {}
- }
- this.input.tooltipText = val;
- return this.input.value = label;
- ]]>
- </setter>
- </property>
- </implementation>
- </binding>
-
- <binding id="setting-multi" extends="chrome://mozapps/content/extensions/setting.xml#setting-base">
- <content>
- <xul:vbox>
- <xul:hbox class="preferences-alignment">
- <xul:label class="preferences-title" flex="1" xbl:inherits="xbl:text=title"/>
- </xul:hbox>
- <xul:description class="preferences-description" flex="1" xbl:inherits="xbl:text=desc"/>
- </xul:vbox>
- <xul:hbox class="preferences-alignment">
- <children includes="radiogroup|menulist"/>
- </xul:hbox>
- </content>
-
- <implementation>
- <constructor>
- <![CDATA[
- this.control.addEventListener("command", this.inputChanged.bind(this), false);
- ]]>
- </constructor>
-
- <method name="valueFromPreference">
- <body>
- <![CDATA[
- let val = Preferences.get(this.pref, "").toString();
-
- if ("itemCount" in this.control) {
- for (let i = 0; i < this.control.itemCount; i++) {
- if (this.control.getItemAtIndex(i).value == val) {
- this.control.selectedIndex = i;
- break;
- }
- }
- } else {
- this.control.setAttribute("value", val);
- }
- ]]>
- </body>
- </method>
-
- <method name="valueToPreference">
- <body>
- <![CDATA[
- // We might not have a pref already set, so we guess the type from the value attribute
- let val = this.control.selectedItem.value;
- if (val == "true" || val == "false") {
- val = val == "true";
- } else if (/^-?\d+$/.test(val)) {
- val = parseInt(val, 10);
- }
- Preferences.set(this.pref, val);
- ]]>
- </body>
- </method>
-
- <field name="control">this.getElementsByTagName(this.getAttribute("type") == "radio" ? "radiogroup" : "menulist")[0];</field>
- </implementation>
- </binding>
-</bindings>
diff --git a/toolkit/mozapps/webextensions/content/update.js b/toolkit/mozapps/webextensions/content/update.js
deleted file mode 100644
index 80d0fa688..000000000
--- a/toolkit/mozapps/webextensions/content/update.js
+++ /dev/null
@@ -1,663 +0,0 @@
-// -*- 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/. */
-
-// This UI is only opened from the Extension Manager when the app is upgraded.
-
-"use strict";
-
-const PREF_UPDATE_EXTENSIONS_ENABLED = "extensions.update.enabled";
-const PREF_XPINSTALL_ENABLED = "xpinstall.enabled";
-
-// timeout (in milliseconds) to wait for response to the metadata ping
-const METADATA_TIMEOUT = 30000;
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "AddonManager", "resource://gre/modules/AddonManager.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "AddonManagerPrivate", "resource://gre/modules/AddonManager.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Services", "resource://gre/modules/Services.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "AddonRepository", "resource://gre/modules/addons/AddonRepository.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task", "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise", "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Log", "resource://gre/modules/Log.jsm");
-var logger = null;
-
-var gUpdateWizard = {
- // When synchronizing app compatibility info this contains all installed
- // add-ons. When checking for compatible versions this contains only
- // incompatible add-ons.
- addons: [],
- // Contains a Set of IDs for add-on that were disabled by the application update.
- affectedAddonIDs: null,
- // The add-ons that we found updates available for
- addonsToUpdate: [],
- shouldSuggestAutoChecking: false,
- shouldAutoCheck: false,
- xpinstallEnabled: true,
- xpinstallLocked: false,
- // cached AddonInstall entries for add-ons we might want to update,
- // keyed by add-on ID
- addonInstalls: new Map(),
- shuttingDown: false,
- // Count the add-ons disabled by this update, enabled/disabled by
- // metadata checks, and upgraded.
- disabled: 0,
- metadataEnabled: 0,
- metadataDisabled: 0,
- upgraded: 0,
- upgradeFailed: 0,
- upgradeDeclined: 0,
-
- init: function()
- {
- logger = Log.repository.getLogger("addons.update-dialog");
- // XXX could we pass the addons themselves rather than the IDs?
- this.affectedAddonIDs = new Set(window.arguments[0]);
-
- try {
- this.shouldSuggestAutoChecking =
- !Services.prefs.getBoolPref(PREF_UPDATE_EXTENSIONS_ENABLED);
- }
- catch (e) {
- }
-
- try {
- this.xpinstallEnabled = Services.prefs.getBoolPref(PREF_XPINSTALL_ENABLED);
- this.xpinstallLocked = Services.prefs.prefIsLocked(PREF_XPINSTALL_ENABLED);
- }
- catch (e) {
- }
-
- if (Services.io.offline)
- document.documentElement.currentPage = document.getElementById("offline");
- else
- document.documentElement.currentPage = document.getElementById("versioninfo");
- },
-
- onWizardFinish: function gUpdateWizard_onWizardFinish ()
- {
- if (this.shouldSuggestAutoChecking)
- Services.prefs.setBoolPref(PREF_UPDATE_EXTENSIONS_ENABLED, this.shouldAutoCheck);
- },
-
- _setUpButton: function(aButtonID, aButtonKey, aDisabled)
- {
- var strings = document.getElementById("updateStrings");
- var button = document.documentElement.getButton(aButtonID);
- if (aButtonKey) {
- button.label = strings.getString(aButtonKey);
- try {
- button.setAttribute("accesskey", strings.getString(aButtonKey + "Accesskey"));
- }
- catch (e) {
- }
- }
- button.disabled = aDisabled;
- },
-
- setButtonLabels: function(aBackButton, aBackButtonIsDisabled,
- aNextButton, aNextButtonIsDisabled,
- aCancelButton, aCancelButtonIsDisabled)
- {
- this._setUpButton("back", aBackButton, aBackButtonIsDisabled);
- this._setUpButton("next", aNextButton, aNextButtonIsDisabled);
- this._setUpButton("cancel", aCancelButton, aCancelButtonIsDisabled);
- },
-
- // Update Errors
- errorItems: [],
-
- checkForErrors: function(aElementIDToShow)
- {
- if (this.errorItems.length > 0)
- document.getElementById(aElementIDToShow).hidden = false;
- },
-
- onWizardClose: function(aEvent)
- {
- return this.onWizardCancel();
- },
-
- onWizardCancel: function()
- {
- gUpdateWizard.shuttingDown = true;
- // Allow add-ons to continue downloading and installing
- // in the background, though some may require a later restart
- // Pages that are waiting for user input go into the background
- // on cancel
- if (gMismatchPage.waiting) {
- logger.info("Dialog closed in mismatch page");
- if (gUpdateWizard.addonInstalls.size > 0) {
- gInstallingPage.startInstalls(
- Array.from(gUpdateWizard.addonInstalls.values()));
- }
- return true;
- }
-
- // Pages that do asynchronous things will just keep running and check
- // gUpdateWizard.shuttingDown to trigger background behaviour
- if (!gInstallingPage.installing) {
- logger.info("Dialog closed while waiting for updated compatibility information");
- }
- else {
- logger.info("Dialog closed while downloading and installing updates");
- }
- return true;
- }
-};
-
-var gOfflinePage = {
- onPageAdvanced: function()
- {
- Services.io.offline = false;
- return true;
- },
-
- toggleOffline: function()
- {
- var nextbtn = document.documentElement.getButton("next");
- nextbtn.disabled = !nextbtn.disabled;
- }
-}
-
-// Addon listener to count addons enabled/disabled by metadata checks
-var listener = {
- onDisabled: function(aAddon) {
- gUpdateWizard.affectedAddonIDs.add(aAddon.id);
- gUpdateWizard.metadataDisabled++;
- },
- onEnabled: function(aAddon) {
- gUpdateWizard.affectedAddonIDs.delete(aAddon.id);
- gUpdateWizard.metadataEnabled++;
- }
-};
-
-var gVersionInfoPage = {
- _completeCount: 0,
- _totalCount: 0,
- _versionInfoDone: false,
- onPageShow: Task.async(function*() {
- gUpdateWizard.setButtonLabels(null, true,
- "nextButtonText", true,
- "cancelButtonText", false);
-
- gUpdateWizard.disabled = gUpdateWizard.affectedAddonIDs.size;
-
- // Ensure compatibility overrides are up to date before checking for
- // individual addon updates.
- AddonManager.addAddonListener(listener);
- if (AddonRepository.isMetadataStale()) {
- // Do the metadata ping, listening for any newly enabled/disabled add-ons.
- yield AddonRepository.repopulateCache(METADATA_TIMEOUT);
- if (gUpdateWizard.shuttingDown) {
- logger.debug("repopulateCache completed after dialog closed");
- }
- }
- // Fetch the add-ons that are still affected by this update,
- // excluding the hotfix add-on.
- let idlist = Array.from(gUpdateWizard.affectedAddonIDs).filter(
- a => a.id != AddonManager.hotfixID);
- if (idlist.length < 1) {
- gVersionInfoPage.onAllUpdatesFinished();
- return;
- }
-
- logger.debug("Fetching affected addons " + idlist.toSource());
- let fetchedAddons = yield new Promise((resolve, reject) =>
- AddonManager.getAddonsByIDs(idlist, resolve));
- // We shouldn't get nulls here, but let's be paranoid...
- gUpdateWizard.addons = fetchedAddons.filter(a => a);
- if (gUpdateWizard.addons.length < 1) {
- gVersionInfoPage.onAllUpdatesFinished();
- return;
- }
-
- gVersionInfoPage._totalCount = gUpdateWizard.addons.length;
-
- for (let addon of gUpdateWizard.addons) {
- logger.debug("VersionInfo Finding updates for ${id}", addon);
- addon.findUpdates(gVersionInfoPage, AddonManager.UPDATE_WHEN_NEW_APP_INSTALLED);
- }
- }),
-
- onAllUpdatesFinished: function() {
- AddonManager.removeAddonListener(listener);
- AddonManagerPrivate.recordSimpleMeasure("appUpdate_disabled",
- gUpdateWizard.disabled);
- AddonManagerPrivate.recordSimpleMeasure("appUpdate_metadata_enabled",
- gUpdateWizard.metadataEnabled);
- AddonManagerPrivate.recordSimpleMeasure("appUpdate_metadata_disabled",
- gUpdateWizard.metadataDisabled);
- // Record 0 for these here in case we exit early; values will be replaced
- // later if we actually upgrade any.
- AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgraded", 0);
- AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgradeFailed", 0);
- AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgradeDeclined", 0);
- // Filter out any add-ons that are now enabled.
- let addonList = gUpdateWizard.addons.map(a => a.id + ":" + a.appDisabled);
- logger.debug("VersionInfo updates finished: found " + addonList.toSource());
- let filteredAddons = [];
- for (let a of gUpdateWizard.addons) {
- if (a.appDisabled) {
- logger.debug("Continuing with add-on " + a.id);
- filteredAddons.push(a);
- }
- else if (gUpdateWizard.addonInstalls.has(a.id)) {
- gUpdateWizard.addonInstalls.get(a.id).cancel();
- gUpdateWizard.addonInstalls.delete(a.id);
- }
- }
- gUpdateWizard.addons = filteredAddons;
-
- if (gUpdateWizard.shuttingDown) {
- // jump directly to updating auto-update add-ons in the background
- if (gUpdateWizard.addonInstalls.size > 0) {
- let installs = Array.from(gUpdateWizard.addonInstalls.values());
- gInstallingPage.startInstalls(installs);
- }
- return;
- }
-
- if (filteredAddons.length > 0) {
- if (!gUpdateWizard.xpinstallEnabled && gUpdateWizard.xpinstallLocked) {
- document.documentElement.currentPage = document.getElementById("adminDisabled");
- return;
- }
- document.documentElement.currentPage = document.getElementById("mismatch");
- }
- else {
- logger.info("VersionInfo: No updates require further action");
- // VersionInfo compatibility updates resolved all compatibility problems,
- // close this window and continue starting the application...
- // XXX Bug 314754 - We need to use setTimeout to close the window due to
- // the EM using xmlHttpRequest when checking for updates.
- setTimeout(close, 0);
- }
- },
-
- // UpdateListener
- onUpdateFinished: function(aAddon, status) {
- ++this._completeCount;
-
- if (status != AddonManager.UPDATE_STATUS_NO_ERROR) {
- logger.debug("VersionInfo update " + this._completeCount + " of " + this._totalCount +
- " failed for " + aAddon.id + ": " + status);
- gUpdateWizard.errorItems.push(aAddon);
- }
- else {
- logger.debug("VersionInfo update " + this._completeCount + " of " + this._totalCount +
- " finished for " + aAddon.id);
- }
-
- // If we're not in the background, just make a list of add-ons that have
- // updates available
- if (!gUpdateWizard.shuttingDown) {
- // If we're still in the update check window and the add-on is now active
- // then it won't have been disabled by startup
- if (aAddon.active) {
- AddonManagerPrivate.removeStartupChange(AddonManager.STARTUP_CHANGE_DISABLED, aAddon.id);
- gUpdateWizard.metadataEnabled++;
- }
-
- // Update the status text and progress bar
- var updateStrings = document.getElementById("updateStrings");
- var statusElt = document.getElementById("versioninfo.status");
- var statusString = updateStrings.getFormattedString("statusPrefix", [aAddon.name]);
- statusElt.setAttribute("value", statusString);
-
- // Update the status text and progress bar
- var progress = document.getElementById("versioninfo.progress");
- progress.mode = "normal";
- progress.value = Math.ceil((this._completeCount / this._totalCount) * 100);
- }
-
- if (this._completeCount == this._totalCount)
- this.onAllUpdatesFinished();
- },
-
- onUpdateAvailable: function(aAddon, aInstall) {
- logger.debug("VersionInfo got an install for " + aAddon.id + ": " + aAddon.version);
- gUpdateWizard.addonInstalls.set(aAddon.id, aInstall);
- },
-};
-
-var gMismatchPage = {
- waiting: false,
-
- onPageShow: function()
- {
- gMismatchPage.waiting = true;
- gUpdateWizard.setButtonLabels(null, true,
- "mismatchCheckNow", false,
- "mismatchDontCheck", false);
- document.documentElement.getButton("next").focus();
-
- var incompatible = document.getElementById("mismatch.incompatible");
- for (let addon of gUpdateWizard.addons) {
- var listitem = document.createElement("listitem");
- listitem.setAttribute("label", addon.name + " " + addon.version);
- incompatible.appendChild(listitem);
- }
- }
-};
-
-var gUpdatePage = {
- _totalCount: 0,
- _completeCount: 0,
- onPageShow: function()
- {
- gMismatchPage.waiting = false;
- gUpdateWizard.setButtonLabels(null, true,
- "nextButtonText", true,
- "cancelButtonText", false);
- document.documentElement.getButton("next").focus();
-
- gUpdateWizard.errorItems = [];
-
- this._totalCount = gUpdateWizard.addons.length;
- for (let addon of gUpdateWizard.addons) {
- logger.debug("UpdatePage requesting update for " + addon.id);
- // Redundant call to find updates again here when we already got them
- // in the VersionInfo page: https://bugzilla.mozilla.org/show_bug.cgi?id=960597
- addon.findUpdates(this, AddonManager.UPDATE_WHEN_NEW_APP_INSTALLED);
- }
- },
-
- onAllUpdatesFinished: function() {
- if (gUpdateWizard.shuttingDown)
- return;
-
- var nextPage = document.getElementById("noupdates");
- if (gUpdateWizard.addonsToUpdate.length > 0)
- nextPage = document.getElementById("found");
- document.documentElement.currentPage = nextPage;
- },
-
- // UpdateListener
- onUpdateAvailable: function(aAddon, aInstall) {
- logger.debug("UpdatePage got an update for " + aAddon.id + ": " + aAddon.version);
- gUpdateWizard.addonsToUpdate.push(aInstall);
- },
-
- onUpdateFinished: function(aAddon, status) {
- if (status != AddonManager.UPDATE_STATUS_NO_ERROR)
- gUpdateWizard.errorItems.push(aAddon);
-
- ++this._completeCount;
-
- if (!gUpdateWizard.shuttingDown) {
- // Update the status text and progress bar
- var updateStrings = document.getElementById("updateStrings");
- var statusElt = document.getElementById("checking.status");
- var statusString = updateStrings.getFormattedString("statusPrefix", [aAddon.name]);
- statusElt.setAttribute("value", statusString);
-
- var progress = document.getElementById("checking.progress");
- progress.value = Math.ceil((this._completeCount / this._totalCount) * 100);
- }
-
- if (this._completeCount == this._totalCount)
- this.onAllUpdatesFinished()
- },
-};
-
-var gFoundPage = {
- onPageShow: function()
- {
- gUpdateWizard.setButtonLabels(null, true,
- "installButtonText", false,
- null, false);
-
- var foundUpdates = document.getElementById("found.updates");
- var itemCount = gUpdateWizard.addonsToUpdate.length;
- for (let install of gUpdateWizard.addonsToUpdate) {
- let listItem = foundUpdates.appendItem(install.name + " " + install.version);
- listItem.setAttribute("type", "checkbox");
- listItem.setAttribute("checked", "true");
- listItem.install = install;
- }
-
- if (!gUpdateWizard.xpinstallEnabled) {
- document.getElementById("xpinstallDisabledAlert").hidden = false;
- document.getElementById("enableXPInstall").focus();
- document.documentElement.getButton("next").disabled = true;
- }
- else {
- document.documentElement.getButton("next").focus();
- document.documentElement.getButton("next").disabled = false;
- }
- },
-
- toggleXPInstallEnable: function(aEvent)
- {
- var enabled = aEvent.target.checked;
- gUpdateWizard.xpinstallEnabled = enabled;
- var pref = Components.classes["@mozilla.org/preferences-service;1"]
- .getService(Components.interfaces.nsIPrefBranch);
- pref.setBoolPref(PREF_XPINSTALL_ENABLED, enabled);
- this.updateNextButton();
- },
-
- updateNextButton: function()
- {
- if (!gUpdateWizard.xpinstallEnabled) {
- document.documentElement.getButton("next").disabled = true;
- return;
- }
-
- var oneChecked = false;
- var foundUpdates = document.getElementById("found.updates");
- var updates = foundUpdates.getElementsByTagName("listitem");
- for (let update of updates) {
- if (!update.checked)
- continue;
- oneChecked = true;
- break;
- }
-
- gUpdateWizard.setButtonLabels(null, true,
- "installButtonText", true,
- null, false);
- document.getElementById("found").setAttribute("next", "installing");
- document.documentElement.getButton("next").disabled = !oneChecked;
- }
-};
-
-var gInstallingPage = {
- _installs : [],
- _errors : [],
- _strings : null,
- _currentInstall : -1,
- _installing : false,
-
- // Initialize fields we need for installing and tracking progress,
- // and start iterating through the installations
- startInstalls: function(aInstallList) {
- if (!gUpdateWizard.xpinstallEnabled) {
- return;
- }
-
- let installs = Array.from(aInstallList).map(a => a.existingAddon.id);
- logger.debug("Start installs for " + installs.toSource());
- this._errors = [];
- this._installs = aInstallList;
- this._installing = true;
- this.startNextInstall();
- },
-
- onPageShow: function()
- {
- gUpdateWizard.setButtonLabels(null, true,
- "nextButtonText", true,
- null, true);
-
- var foundUpdates = document.getElementById("found.updates");
- var updates = foundUpdates.getElementsByTagName("listitem");
- let toInstall = [];
- for (let update of updates) {
- if (!update.checked) {
- logger.info("User chose to cancel update of " + update.label);
- gUpdateWizard.upgradeDeclined++;
- update.install.cancel();
- continue;
- }
- toInstall.push(update.install);
- }
- this._strings = document.getElementById("updateStrings");
-
- this.startInstalls(toInstall);
- },
-
- startNextInstall: function() {
- if (this._currentInstall >= 0) {
- this._installs[this._currentInstall].removeListener(this);
- }
-
- this._currentInstall++;
-
- if (this._installs.length == this._currentInstall) {
- Services.obs.notifyObservers(null, "TEST:all-updates-done", null);
- AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgraded",
- gUpdateWizard.upgraded);
- AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgradeFailed",
- gUpdateWizard.upgradeFailed);
- AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgradeDeclined",
- gUpdateWizard.upgradeDeclined);
- this._installing = false;
- if (gUpdateWizard.shuttingDown) {
- return;
- }
- var nextPage = this._errors.length > 0 ? "installerrors" : "finished";
- document.getElementById("installing").setAttribute("next", nextPage);
- document.documentElement.advance();
- return;
- }
-
- let install = this._installs[this._currentInstall];
-
- if (gUpdateWizard.shuttingDown && !AddonManager.shouldAutoUpdate(install.existingAddon)) {
- logger.debug("Don't update " + install.existingAddon.id + " in background");
- gUpdateWizard.upgradeDeclined++;
- install.cancel();
- this.startNextInstall();
- return;
- }
- install.addListener(this);
- install.install();
- },
-
- // InstallListener
- onDownloadStarted: function(aInstall) {
- if (gUpdateWizard.shuttingDown) {
- return;
- }
- var strings = document.getElementById("updateStrings");
- var label = strings.getFormattedString("downloadingPrefix", [aInstall.name]);
- var actionItem = document.getElementById("actionItem");
- actionItem.value = label;
- },
-
- onDownloadProgress: function(aInstall) {
- if (gUpdateWizard.shuttingDown) {
- return;
- }
- var downloadProgress = document.getElementById("downloadProgress");
- downloadProgress.value = Math.ceil(100 * aInstall.progress / aInstall.maxProgress);
- },
-
- onDownloadEnded: function(aInstall) {
- },
-
- onDownloadFailed: function(aInstall) {
- this._errors.push(aInstall);
-
- gUpdateWizard.upgradeFailed++;
- this.startNextInstall();
- },
-
- onInstallStarted: function(aInstall) {
- if (gUpdateWizard.shuttingDown) {
- return;
- }
- var strings = document.getElementById("updateStrings");
- var label = strings.getFormattedString("installingPrefix", [aInstall.name]);
- var actionItem = document.getElementById("actionItem");
- actionItem.value = label;
- },
-
- onInstallEnded: function(aInstall, aAddon) {
- if (!gUpdateWizard.shuttingDown) {
- // Remember that this add-on was updated during startup
- AddonManagerPrivate.addStartupChange(AddonManager.STARTUP_CHANGE_CHANGED,
- aAddon.id);
- }
-
- gUpdateWizard.upgraded++;
- this.startNextInstall();
- },
-
- onInstallFailed: function(aInstall) {
- this._errors.push(aInstall);
-
- gUpdateWizard.upgradeFailed++;
- this.startNextInstall();
- }
-};
-
-var gInstallErrorsPage = {
- onPageShow: function()
- {
- gUpdateWizard.setButtonLabels(null, true, null, true, null, true);
- document.documentElement.getButton("finish").focus();
- },
-};
-
-// Displayed when there are incompatible add-ons and the xpinstall.enabled
-// pref is false and locked.
-var gAdminDisabledPage = {
- onPageShow: function()
- {
- gUpdateWizard.setButtonLabels(null, true, null, true,
- "cancelButtonText", true);
- document.documentElement.getButton("finish").focus();
- }
-};
-
-// Displayed when selected add-on updates have been installed without error.
-// There can still be add-ons that are not compatible and don't have an update.
-var gFinishedPage = {
- onPageShow: function()
- {
- gUpdateWizard.setButtonLabels(null, true, null, true, null, true);
- document.documentElement.getButton("finish").focus();
-
- if (gUpdateWizard.shouldSuggestAutoChecking) {
- document.getElementById("finishedCheckDisabled").hidden = false;
- gUpdateWizard.shouldAutoCheck = true;
- }
- else
- document.getElementById("finishedCheckEnabled").hidden = false;
-
- document.documentElement.getButton("finish").focus();
- }
-};
-
-// Displayed when there are incompatible add-ons and there are no available
-// updates.
-var gNoUpdatesPage = {
- onPageShow: function(aEvent)
- {
- gUpdateWizard.setButtonLabels(null, true, null, true, null, true);
- if (gUpdateWizard.shouldSuggestAutoChecking) {
- document.getElementById("noupdatesCheckDisabled").hidden = false;
- gUpdateWizard.shouldAutoCheck = true;
- }
- else
- document.getElementById("noupdatesCheckEnabled").hidden = false;
-
- gUpdateWizard.checkForErrors("updateCheckErrorNotFound");
- document.documentElement.getButton("finish").focus();
- }
-};
diff --git a/toolkit/mozapps/webextensions/content/update.xul b/toolkit/mozapps/webextensions/content/update.xul
deleted file mode 100644
index 745983814..000000000
--- a/toolkit/mozapps/webextensions/content/update.xul
+++ /dev/null
@@ -1,194 +0,0 @@
-<?xml version="1.0"?>
-
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
-
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-<?xml-stylesheet href="chrome://mozapps/skin/extensions/update.css" type="text/css"?>
-
-<!DOCTYPE wizard [
-<!ENTITY % updateDTD SYSTEM "chrome://mozapps/locale/extensions/update.dtd">
-<!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
-%updateDTD;
-%brandDTD;
-]>
-
-<wizard id="updateWizard"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="&updateWizard.title;"
- windowtype="Addons:Compatibility"
- branded="true"
- onload="gUpdateWizard.init();"
- onwizardfinish="gUpdateWizard.onWizardFinish();"
- onwizardcancel="return gUpdateWizard.onWizardCancel();"
- onclose="return gUpdateWizard.onWizardClose(event);"
- buttons="accept,cancel">
-
- <script type="application/javascript" src="chrome://mozapps/content/extensions/update.js"/>
-
- <stringbundleset id="updateSet">
- <stringbundle id="brandStrings" src="chrome://branding/locale/brand.properties"/>
- <stringbundle id="updateStrings" src="chrome://mozapps/locale/extensions/update.properties"/>
- </stringbundleset>
-
- <wizardpage id="dummy" pageid="dummy"/>
-
- <wizardpage id="offline" pageid="offline" next="versioninfo"
- label="&offline.title;"
- onpageadvanced="return gOfflinePage.onPageAdvanced();">
- <description>&offline.description;</description>
- <checkbox id="toggleOffline"
- checked="true"
- label="&offline.toggleOffline.label;"
- accesskey="&offline.toggleOffline.accesskey;"
- oncommand="gOfflinePage.toggleOffline();"/>
- </wizardpage>
-
- <wizardpage id="versioninfo" pageid="versioninfo" next="mismatch"
- label="&versioninfo.wizard.title;"
- onpageshow="gVersionInfoPage.onPageShow();">
- <label>&versioninfo.top.label;</label>
- <separator class="thin"/>
- <progressmeter id="versioninfo.progress" mode="undetermined"/>
- <hbox align="center">
- <image id="versioninfo.throbber" class="throbber"/>
- <label flex="1" id="versioninfo.status" crop="right">&versioninfo.waiting;</label>
- </hbox>
- <separator/>
- </wizardpage>
-
- <wizardpage id="mismatch" pageid="mismatch" next="checking"
- label="&mismatch.win.title;"
- onpageshow="gMismatchPage.onPageShow();">
- <label>&mismatch.top.label;</label>
- <separator class="thin"/>
- <listbox id="mismatch.incompatible" flex="1"/>
- <separator class="thin"/>
- <label>&mismatch.bottom.label;</label>
- </wizardpage>
-
- <wizardpage id="checking" pageid="checking" next="noupdates"
- label="&checking.wizard.title;"
- onpageshow="gUpdatePage.onPageShow();">
- <label>&checking.top.label;</label>
- <separator class="thin"/>
- <progressmeter id="checking.progress"/>
- <hbox align="center">
- <image id="checking.throbber" class="throbber"/>
- <label id="checking.status" flex="1" crop="right">&checking.status;</label>
- </hbox>
- </wizardpage>
-
- <wizardpage id="noupdates" pageid="noupdates"
- label="&noupdates.wizard.title;"
- onpageshow="gNoUpdatesPage.onPageShow();">
- <description>&noupdates.intro.desc;</description>
- <separator class="thin"/>
- <hbox id="updateCheckErrorNotFound" class="alertBox" hidden="true" align="top">
- <description flex="1">&noupdates.error.desc;</description>
- </hbox>
- <separator class="thin"/>
- <description id="noupdatesCheckEnabled" hidden="true">
- &noupdates.checkEnabled.desc;
- </description>
- <vbox id="noupdatesCheckDisabled" hidden="true">
- <description>&finished.checkDisabled.desc;</description>
- <checkbox label="&enableChecking.label;" checked="true"
- oncommand="gUpdateWizard.shouldAutoCheck = this.checked;"/>
- </vbox>
- <separator flex="1"/>
-#ifndef XP_MACOSX
- <label>&clickFinish.label;</label>
-#else
- <label>&clickFinish.labelMac;</label>
-#endif
- <separator class="thin"/>
- </wizardpage>
-
- <wizardpage id="found" pageid="found" next="installing"
- label="&found.wizard.title;"
- onpageshow="gFoundPage.onPageShow();">
- <label>&found.top.label;</label>
- <separator class="thin"/>
- <listbox id="found.updates" flex="1" seltype="multiple"
- onclick="gFoundPage.updateNextButton();"/>
- <separator class="thin"/>
- <vbox align="left" id="xpinstallDisabledAlert" hidden="true">
- <description>&found.disabledXPinstall.label;</description>
- <checkbox label="&found.enableXPInstall.label;"
- id="enableXPInstall"
- accesskey="&found.enableXPInstall.accesskey;"
- oncommand="gFoundPage.toggleXPInstallEnable(event);"/>
- </vbox>
- </wizardpage>
-
- <wizardpage id="installing" pageid="installing" next="finished"
- label="&installing.wizard.title;"
- onpageshow="gInstallingPage.onPageShow();">
- <label>&installing.top.label;</label>
- <progressmeter id="downloadProgress"/>
- <hbox align="center">
- <image id="installing.throbber" class="throbber"/>
- <label id="actionItem" flex="1" crop="right"/>
- </hbox>
- <separator/>
- </wizardpage>
-
- <wizardpage id="installerrors" pageid="installerrors"
- label="&installerrors.wizard.title;"
- onpageshow="gInstallErrorsPage.onPageShow();">
- <hbox align="top" class="alertBox">
- <description flex="1">&installerrors.intro.label;</description>
- </hbox>
- <separator flex="1"/>
-#ifndef XP_MACOSX
- <label>&clickFinish.label;</label>
-#else
- <label>&clickFinish.labelMac;</label>
-#endif
- <separator class="thin"/>
- </wizardpage>
-
- <wizardpage id="adminDisabled" pageid="adminDisabled"
- label="&adminDisabled.wizard.title;"
- onpageshow="gAdminDisabledPage.onPageShow();">
- <separator/>
- <hbox class="alertBox" align="top">
- <description flex="1">&adminDisabled.warning.label;</description>
- </hbox>
- <separator flex="1"/>
-#ifndef XP_MACOSX
- <label>&clickFinish.label;</label>
-#else
- <label>&clickFinish.labelMac;</label>
-#endif
- <separator class="thin"/>
- </wizardpage>
-
- <wizardpage id="finished" pageid="finished"
- label="&finished.wizard.title;"
- onpageshow="gFinishedPage.onPageShow();">
-
- <label>&finished.top.label;</label>
- <separator/>
- <description id="finishedCheckEnabled" hidden="true">
- &finished.checkEnabled.desc;
- </description>
- <vbox id="finishedCheckDisabled" hidden="true">
- <description>&finished.checkDisabled.desc;</description>
- <checkbox label="&enableChecking.label;" checked="true"
- oncommand="gUpdateWizard.shouldAutoCheck = this.checked;"/>
- </vbox>
- <separator flex="1"/>
-#ifndef XP_MACOSX
- <label>&clickFinish.label;</label>
-#else
- <label>&clickFinish.labelMac;</label>
-#endif
- <separator class="thin"/>
- </wizardpage>
-
-</wizard>
-
diff --git a/toolkit/mozapps/webextensions/extensions.manifest b/toolkit/mozapps/webextensions/extensions.manifest
deleted file mode 100644
index 2129012ab..000000000
--- a/toolkit/mozapps/webextensions/extensions.manifest
+++ /dev/null
@@ -1,18 +0,0 @@
-component {4399533d-08d1-458c-a87a-235f74451cfa} addonManager.js
-contract @mozilla.org/addons/integration;1 {4399533d-08d1-458c-a87a-235f74451cfa}
-#ifndef MOZ_WIDGET_ANDROID
-category update-timer addonManager @mozilla.org/addons/integration;1,getService,addon-background-update-timer,extensions.update.interval,86400
-#endif
-component {7beb3ba8-6ec3-41b4-b67c-da89b8518922} amContentHandler.js
-contract @mozilla.org/uriloader/content-handler;1?type=application/x-xpinstall {7beb3ba8-6ec3-41b4-b67c-da89b8518922}
-component {0f38e086-89a3-40a5-8ffc-9b694de1d04a} amWebInstallListener.js
-contract @mozilla.org/addons/web-install-listener;1 {0f38e086-89a3-40a5-8ffc-9b694de1d04a}
-component {9df8ef2b-94da-45c9-ab9f-132eb55fddf1} amInstallTrigger.js
-contract @mozilla.org/addons/installtrigger;1 {9df8ef2b-94da-45c9-ab9f-132eb55fddf1}
-category JavaScript-global-property InstallTrigger @mozilla.org/addons/installtrigger;1
-#ifndef MOZ_WIDGET_ANDROID
-category addon-provider-module PluginProvider resource://gre/modules/addons/PluginProvider.jsm
-#endif
-category addon-provider-module GMPProvider resource://gre/modules/addons/GMPProvider.jsm
-component {8866d8e3-4ea5-48b7-a891-13ba0ac15235} amWebAPI.js
-contract @mozilla.org/addon-web-api/manager;1 {8866d8e3-4ea5-48b7-a891-13ba0ac15235}
diff --git a/toolkit/mozapps/webextensions/internal/APIExtensionBootstrap.js b/toolkit/mozapps/webextensions/internal/APIExtensionBootstrap.js
deleted file mode 100644
index 0eae2475c..000000000
--- a/toolkit/mozapps/webextensions/internal/APIExtensionBootstrap.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-Components.utils.import("resource://gre/modules/ExtensionManagement.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-var namespace;
-var resource;
-var resProto;
-
-function install(data, reason) {
-}
-
-function startup(data, reason) {
- namespace = data.id.replace(/@.*/, "");
- resource = `extension-${namespace}-api`;
-
- resProto = Services.io.getProtocolHandler("resource")
- .QueryInterface(Components.interfaces.nsIResProtocolHandler);
-
- resProto.setSubstitution(resource, data.resourceURI);
-
- ExtensionManagement.registerAPI(
- namespace,
- `resource://${resource}/schema.json`,
- `resource://${resource}/api.js`);
-}
-
-function shutdown(data, reason) {
- resProto.setSubstitution(resource, null);
-
- ExtensionManagement.unregisterAPI(namespace);
-}
-
-function uninstall(data, reason) {
-}
diff --git a/toolkit/mozapps/webextensions/internal/AddonConstants.jsm b/toolkit/mozapps/webextensions/internal/AddonConstants.jsm
deleted file mode 100644
index 22d91fdf5..000000000
--- a/toolkit/mozapps/webextensions/internal/AddonConstants.jsm
+++ /dev/null
@@ -1,31 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-this.EXPORTED_SYMBOLS = [ "ADDON_SIGNING", "REQUIRE_SIGNING" ];
-
-// Make these non-changable properties so they can't be manipulated from other
-// code in the app.
-Object.defineProperty(this, "ADDON_SIGNING", {
- configurable: false,
- enumerable: false,
- writable: false,
-#ifdef MOZ_ADDON_SIGNING
- value: true,
-#else
- value: false,
-#endif
-});
-
-Object.defineProperty(this, "REQUIRE_SIGNING", {
- configurable: false,
- enumerable: false,
- writable: false,
-#ifdef MOZ_REQUIRE_SIGNING
- value: true,
-#else
- value: false,
-#endif
-});
diff --git a/toolkit/mozapps/webextensions/internal/AddonRepository.jsm b/toolkit/mozapps/webextensions/internal/AddonRepository.jsm
deleted file mode 100644
index 7f88d44ad..000000000
--- a/toolkit/mozapps/webextensions/internal/AddonRepository.jsm
+++ /dev/null
@@ -1,1988 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
-const Cr = Components.results;
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://gre/modules/AddonManager.jsm");
-/* globals AddonManagerPrivate*/
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "OS",
- "resource://gre/modules/osfile.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "DeferredSave",
- "resource://gre/modules/DeferredSave.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "AddonRepository_SQLiteMigrator",
- "resource://gre/modules/addons/AddonRepository_SQLiteMigrator.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ServiceRequest",
- "resource://gre/modules/ServiceRequest.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-
-
-this.EXPORTED_SYMBOLS = [ "AddonRepository" ];
-
-const PREF_GETADDONS_CACHE_ENABLED = "extensions.getAddons.cache.enabled";
-const PREF_GETADDONS_CACHE_TYPES = "extensions.getAddons.cache.types";
-const PREF_GETADDONS_CACHE_ID_ENABLED = "extensions.%ID%.getAddons.cache.enabled"
-const PREF_GETADDONS_BROWSEADDONS = "extensions.getAddons.browseAddons";
-const PREF_GETADDONS_BYIDS = "extensions.getAddons.get.url";
-const PREF_GETADDONS_BYIDS_PERFORMANCE = "extensions.getAddons.getWithPerformance.url";
-const PREF_GETADDONS_BROWSERECOMMENDED = "extensions.getAddons.recommended.browseURL";
-const PREF_GETADDONS_GETRECOMMENDED = "extensions.getAddons.recommended.url";
-const PREF_GETADDONS_BROWSESEARCHRESULTS = "extensions.getAddons.search.browseURL";
-const PREF_GETADDONS_GETSEARCHRESULTS = "extensions.getAddons.search.url";
-const PREF_GETADDONS_DB_SCHEMA = "extensions.getAddons.databaseSchema"
-
-const PREF_METADATA_LASTUPDATE = "extensions.getAddons.cache.lastUpdate";
-const PREF_METADATA_UPDATETHRESHOLD_SEC = "extensions.getAddons.cache.updateThreshold";
-const DEFAULT_METADATA_UPDATETHRESHOLD_SEC = 172800; // two days
-
-const XMLURI_PARSE_ERROR = "http://www.mozilla.org/newlayout/xml/parsererror.xml";
-
-const API_VERSION = "1.5";
-const DEFAULT_CACHE_TYPES = "extension,theme,locale,dictionary";
-
-const KEY_PROFILEDIR = "ProfD";
-const FILE_DATABASE = "addons.json";
-const DB_SCHEMA = 5;
-const DB_MIN_JSON_SCHEMA = 5;
-const DB_BATCH_TIMEOUT_MS = 50;
-
-const BLANK_DB = function() {
- return {
- addons: new Map(),
- schema: DB_SCHEMA
- };
-}
-
-const TOOLKIT_ID = "toolkit@mozilla.org";
-
-Cu.import("resource://gre/modules/Log.jsm");
-const LOGGER_ID = "addons.repository";
-
-// Create a new logger for use by the Addons Repository
-// (Requires AddonManager.jsm)
-var logger = Log.repository.getLogger(LOGGER_ID);
-
-// A map between XML keys to AddonSearchResult keys for string values
-// that require no extra parsing from XML
-const STRING_KEY_MAP = {
- name: "name",
- version: "version",
- homepage: "homepageURL",
- support: "supportURL"
-};
-
-// A map between XML keys to AddonSearchResult keys for string values
-// that require parsing from HTML
-const HTML_KEY_MAP = {
- summary: "description",
- description: "fullDescription",
- developer_comments: "developerComments",
- eula: "eula"
-};
-
-// A map between XML keys to AddonSearchResult keys for integer values
-// that require no extra parsing from XML
-const INTEGER_KEY_MAP = {
- total_downloads: "totalDownloads",
- weekly_downloads: "weeklyDownloads",
- daily_users: "dailyUsers"
-};
-
-function convertHTMLToPlainText(html) {
- if (!html)
- return html;
- var converter = Cc["@mozilla.org/widget/htmlformatconverter;1"].
- createInstance(Ci.nsIFormatConverter);
-
- var input = Cc["@mozilla.org/supports-string;1"].
- createInstance(Ci.nsISupportsString);
- input.data = html.replace(/\n/g, "<br>");
-
- var output = {};
- converter.convert("text/html", input, input.data.length, "text/unicode",
- output, {});
-
- if (output.value instanceof Ci.nsISupportsString)
- return output.value.data.replace(/\r\n/g, "\n");
- return html;
-}
-
-function getAddonsToCache(aIds, aCallback) {
- try {
- var types = Services.prefs.getCharPref(PREF_GETADDONS_CACHE_TYPES);
- }
- catch (e) { }
- if (!types)
- types = DEFAULT_CACHE_TYPES;
-
- types = types.split(",");
-
- AddonManager.getAddonsByIDs(aIds, function(aAddons) {
- let enabledIds = [];
- for (var i = 0; i < aIds.length; i++) {
- var preference = PREF_GETADDONS_CACHE_ID_ENABLED.replace("%ID%", aIds[i]);
- try {
- if (!Services.prefs.getBoolPref(preference))
- continue;
- } catch (e) {
- // If the preference doesn't exist caching is enabled by default
- }
-
- // The add-ons manager may not know about this ID yet if it is a pending
- // install. In that case we'll just cache it regardless
- if (aAddons[i] && (types.indexOf(aAddons[i].type) == -1))
- continue;
-
- enabledIds.push(aIds[i]);
- }
-
- aCallback(enabledIds);
- });
-}
-
-function AddonSearchResult(aId) {
- this.id = aId;
- this.icons = {};
- this._unsupportedProperties = {};
-}
-
-AddonSearchResult.prototype = {
- /**
- * The ID of the add-on
- */
- id: null,
-
- /**
- * The add-on type (e.g. "extension" or "theme")
- */
- type: null,
-
- /**
- * The name of the add-on
- */
- name: null,
-
- /**
- * The version of the add-on
- */
- version: null,
-
- /**
- * The creator of the add-on
- */
- creator: null,
-
- /**
- * The developers of the add-on
- */
- developers: null,
-
- /**
- * A short description of the add-on
- */
- description: null,
-
- /**
- * The full description of the add-on
- */
- fullDescription: null,
-
- /**
- * The developer comments for the add-on. This includes any information
- * that may be helpful to end users that isn't necessarily applicable to
- * the add-on description (e.g. known major bugs)
- */
- developerComments: null,
-
- /**
- * The end-user licensing agreement (EULA) of the add-on
- */
- eula: null,
-
- /**
- * The url of the add-on's icon
- */
- get iconURL() {
- return this.icons && this.icons[32];
- },
-
- /**
- * The URLs of the add-on's icons, as an object with icon size as key
- */
- icons: null,
-
- /**
- * An array of screenshot urls for the add-on
- */
- screenshots: null,
-
- /**
- * The homepage for the add-on
- */
- homepageURL: null,
-
- /**
- * The homepage for the add-on
- */
- learnmoreURL: null,
-
- /**
- * The support URL for the add-on
- */
- supportURL: null,
-
- /**
- * The contribution url of the add-on
- */
- contributionURL: null,
-
- /**
- * The suggested contribution amount
- */
- contributionAmount: null,
-
- /**
- * The URL to visit in order to purchase the add-on
- */
- purchaseURL: null,
-
- /**
- * The numerical cost of the add-on in some currency, for sorting purposes
- * only
- */
- purchaseAmount: null,
-
- /**
- * The display cost of the add-on, for display purposes only
- */
- purchaseDisplayAmount: null,
-
- /**
- * The rating of the add-on, 0-5
- */
- averageRating: null,
-
- /**
- * The number of reviews for this add-on
- */
- reviewCount: null,
-
- /**
- * The URL to the list of reviews for this add-on
- */
- reviewURL: null,
-
- /**
- * The total number of times the add-on was downloaded
- */
- totalDownloads: null,
-
- /**
- * The number of times the add-on was downloaded the current week
- */
- weeklyDownloads: null,
-
- /**
- * The number of daily users for the add-on
- */
- dailyUsers: null,
-
- /**
- * AddonInstall object generated from the add-on XPI url
- */
- install: null,
-
- /**
- * nsIURI storing where this add-on was installed from
- */
- sourceURI: null,
-
- /**
- * The status of the add-on in the repository (e.g. 4 = "Public")
- */
- repositoryStatus: null,
-
- /**
- * The size of the add-on's files in bytes. For an add-on that have not yet
- * been downloaded this may be an estimated value.
- */
- size: null,
-
- /**
- * The Date that the add-on was most recently updated
- */
- updateDate: null,
-
- /**
- * True or false depending on whether the add-on is compatible with the
- * current version of the application
- */
- isCompatible: true,
-
- /**
- * True or false depending on whether the add-on is compatible with the
- * current platform
- */
- isPlatformCompatible: true,
-
- /**
- * Array of AddonCompatibilityOverride objects, that describe overrides for
- * compatibility with an application versions.
- **/
- compatibilityOverrides: null,
-
- /**
- * True if the add-on has a secure means of updating
- */
- providesUpdatesSecurely: true,
-
- /**
- * The current blocklist state of the add-on
- */
- blocklistState: Ci.nsIBlocklistService.STATE_NOT_BLOCKED,
-
- /**
- * True if this add-on cannot be used in the application based on version
- * compatibility, dependencies and blocklisting
- */
- appDisabled: false,
-
- /**
- * True if the user wants this add-on to be disabled
- */
- userDisabled: false,
-
- /**
- * Indicates what scope the add-on is installed in, per profile, user,
- * system or application
- */
- scope: AddonManager.SCOPE_PROFILE,
-
- /**
- * True if the add-on is currently functional
- */
- isActive: true,
-
- /**
- * A bitfield holding all of the current operations that are waiting to be
- * performed for this add-on
- */
- pendingOperations: AddonManager.PENDING_NONE,
-
- /**
- * A bitfield holding all the the operations that can be performed on
- * this add-on
- */
- permissions: 0,
-
- /**
- * Tests whether this add-on is known to be compatible with a
- * particular application and platform version.
- *
- * @param appVersion
- * An application version to test against
- * @param platformVersion
- * A platform version to test against
- * @return Boolean representing if the add-on is compatible
- */
- isCompatibleWith: function(aAppVersion, aPlatformVersion) {
- return true;
- },
-
- /**
- * Starts an update check for this add-on. This will perform
- * asynchronously and deliver results to the given listener.
- *
- * @param aListener
- * An UpdateListener for the update process
- * @param aReason
- * A reason code for performing the update
- * @param aAppVersion
- * An application version to check for updates for
- * @param aPlatformVersion
- * A platform version to check for updates for
- */
- findUpdates: function(aListener, aReason, aAppVersion, aPlatformVersion) {
- if ("onNoCompatibilityUpdateAvailable" in aListener)
- aListener.onNoCompatibilityUpdateAvailable(this);
- if ("onNoUpdateAvailable" in aListener)
- aListener.onNoUpdateAvailable(this);
- if ("onUpdateFinished" in aListener)
- aListener.onUpdateFinished(this);
- },
-
- toJSON: function() {
- let json = {};
-
- for (let property of Object.keys(this)) {
- let value = this[property];
- if (property.startsWith("_") ||
- typeof(value) === "function")
- continue;
-
- try {
- switch (property) {
- case "sourceURI":
- json.sourceURI = value ? value.spec : "";
- break;
-
- case "updateDate":
- json.updateDate = value ? value.getTime() : "";
- break;
-
- default:
- json[property] = value;
- }
- } catch (ex) {
- logger.warn("Error writing property value for " + property);
- }
- }
-
- for (let property of Object.keys(this._unsupportedProperties)) {
- let value = this._unsupportedProperties[property];
- if (!property.startsWith("_"))
- json[property] = value;
- }
-
- return json;
- }
-}
-
-/**
- * The add-on repository is a source of add-ons that can be installed. It can
- * be searched in three ways. The first takes a list of IDs and returns a
- * list of the corresponding add-ons. The second returns a list of add-ons that
- * come highly recommended. This list should change frequently. The third is to
- * search for specific search terms entered by the user. Searches are
- * asynchronous and results should be passed to the provided callback object
- * when complete. The results passed to the callback should only include add-ons
- * that are compatible with the current application and are not already
- * installed.
- */
-this.AddonRepository = {
- /**
- * Whether caching is currently enabled
- */
- get cacheEnabled() {
- let preference = PREF_GETADDONS_CACHE_ENABLED;
- let enabled = false;
- try {
- enabled = Services.prefs.getBoolPref(preference);
- } catch (e) {
- logger.warn("cacheEnabled: Couldn't get pref: " + preference);
- }
-
- return enabled;
- },
-
- // A cache of the add-ons stored in the database
- _addons: null,
-
- // Whether a search is currently in progress
- _searching: false,
-
- // XHR associated with the current request
- _request: null,
-
- /*
- * Addon search results callback object that contains two functions
- *
- * searchSucceeded - Called when a search has suceeded.
- *
- * @param aAddons
- * An array of the add-on results. In the case of searching for
- * specific terms the ordering of results may be determined by
- * the search provider.
- * @param aAddonCount
- * The length of aAddons
- * @param aTotalResults
- * The total results actually available in the repository
- *
- *
- * searchFailed - Called when an error occurred when performing a search.
- */
- _callback: null,
-
- // Maximum number of results to return
- _maxResults: null,
-
- /**
- * Shut down AddonRepository
- * return: promise{integer} resolves with the result of flushing
- * the AddonRepository database
- */
- shutdown: function() {
- this.cancelSearch();
-
- this._addons = null;
- return AddonDatabase.shutdown(false);
- },
-
- metadataAge: function() {
- let now = Math.round(Date.now() / 1000);
-
- let lastUpdate = 0;
- try {
- lastUpdate = Services.prefs.getIntPref(PREF_METADATA_LASTUPDATE);
- } catch (e) {}
-
- // Handle clock jumps
- if (now < lastUpdate) {
- return now;
- }
- return now - lastUpdate;
- },
-
- isMetadataStale: function() {
- let threshold = DEFAULT_METADATA_UPDATETHRESHOLD_SEC;
- try {
- threshold = Services.prefs.getIntPref(PREF_METADATA_UPDATETHRESHOLD_SEC);
- } catch (e) {}
- return (this.metadataAge() > threshold);
- },
-
- /**
- * Asynchronously get a cached add-on by id. The add-on (or null if the
- * add-on is not found) is passed to the specified callback. If caching is
- * disabled, null is passed to the specified callback.
- *
- * @param aId
- * The id of the add-on to get
- * @param aCallback
- * The callback to pass the result back to
- */
- getCachedAddonByID: Task.async(function*(aId, aCallback) {
- if (!aId || !this.cacheEnabled) {
- aCallback(null);
- return;
- }
-
- function getAddon(aAddons) {
- aCallback(aAddons.get(aId) || null);
- }
-
- if (this._addons == null) {
- AddonDatabase.retrieveStoredData().then(aAddons => {
- this._addons = aAddons;
- getAddon(aAddons);
- });
-
- return;
- }
-
- getAddon(this._addons);
- }),
-
- /**
- * Asynchronously repopulate cache so it only contains the add-ons
- * corresponding to the specified ids. If caching is disabled,
- * the cache is completely removed.
- *
- * @param aTimeout
- * (Optional) timeout in milliseconds to abandon the XHR request
- * if we have not received a response from the server.
- * @return Promise{null}
- * Resolves when the metadata ping is complete
- */
- repopulateCache: function(aTimeout) {
- return this._repopulateCacheInternal(false, aTimeout);
- },
-
- /*
- * Clear and delete the AddonRepository database
- * @return Promise{null} resolves when the database is deleted
- */
- _clearCache: function() {
- this._addons = null;
- return AddonDatabase.delete().then(() =>
- new Promise((resolve, reject) =>
- AddonManagerPrivate.updateAddonRepositoryData(resolve))
- );
- },
-
- _repopulateCacheInternal: Task.async(function*(aSendPerformance, aTimeout) {
- let allAddons = yield new Promise((resolve, reject) =>
- AddonManager.getAllAddons(resolve));
-
- // Filter the hotfix out of our list of add-ons
- allAddons = allAddons.filter(a => a.id != AddonManager.hotfixID);
-
- // Completely remove cache if caching is not enabled
- if (!this.cacheEnabled) {
- logger.debug("Clearing cache because it is disabled");
- yield this._clearCache();
- return;
- }
-
- let ids = allAddons.map(a => a.id);
- logger.debug("Repopulate add-on cache with " + ids.toSource());
-
- let addonsToCache = yield new Promise((resolve, reject) =>
- getAddonsToCache(ids, resolve));
-
- // Completely remove cache if there are no add-ons to cache
- if (addonsToCache.length == 0) {
- logger.debug("Clearing cache because 0 add-ons were requested");
- yield this._clearCache();
- return;
- }
-
- yield new Promise((resolve, reject) =>
- this._beginGetAddons(addonsToCache, {
- searchSucceeded: aAddons => {
- this._addons = new Map();
- for (let addon of aAddons) {
- this._addons.set(addon.id, addon);
- }
- AddonDatabase.repopulate(aAddons, resolve);
- },
- searchFailed: () => {
- logger.warn("Search failed when repopulating cache");
- resolve();
- }
- }, aSendPerformance, aTimeout));
-
- // Always call AddonManager updateAddonRepositoryData after we refill the cache
- yield new Promise((resolve, reject) =>
- AddonManagerPrivate.updateAddonRepositoryData(resolve));
- }),
-
- /**
- * Asynchronously add add-ons to the cache corresponding to the specified
- * ids. If caching is disabled, the cache is unchanged and the callback is
- * immediately called if it is defined.
- *
- * @param aIds
- * The array of add-on ids to add to the cache
- * @param aCallback
- * The optional callback to call once complete
- */
- cacheAddons: function(aIds, aCallback) {
- logger.debug("cacheAddons: enabled " + this.cacheEnabled + " IDs " + aIds.toSource());
- if (!this.cacheEnabled) {
- if (aCallback)
- aCallback();
- return;
- }
-
- getAddonsToCache(aIds, aAddons => {
- // If there are no add-ons to cache, act as if caching is disabled
- if (aAddons.length == 0) {
- if (aCallback)
- aCallback();
- return;
- }
-
- this.getAddonsByIDs(aAddons, {
- searchSucceeded: aAddons => {
- for (let addon of aAddons) {
- this._addons.set(addon.id, addon);
- }
- AddonDatabase.insertAddons(aAddons, aCallback);
- },
- searchFailed: () => {
- logger.warn("Search failed when adding add-ons to cache");
- if (aCallback)
- aCallback();
- }
- });
- });
- },
-
- /**
- * The homepage for visiting this repository. If the corresponding preference
- * is not defined, defaults to about:blank.
- */
- get homepageURL() {
- let url = this._formatURLPref(PREF_GETADDONS_BROWSEADDONS, {});
- return (url != null) ? url : "about:blank";
- },
-
- /**
- * Returns whether this instance is currently performing a search. New
- * searches will not be performed while this is the case.
- */
- get isSearching() {
- return this._searching;
- },
-
- /**
- * The url that can be visited to see recommended add-ons in this repository.
- * If the corresponding preference is not defined, defaults to about:blank.
- */
- getRecommendedURL: function() {
- let url = this._formatURLPref(PREF_GETADDONS_BROWSERECOMMENDED, {});
- return (url != null) ? url : "about:blank";
- },
-
- /**
- * Retrieves the url that can be visited to see search results for the given
- * terms. If the corresponding preference is not defined, defaults to
- * about:blank.
- *
- * @param aSearchTerms
- * Search terms used to search the repository
- */
- getSearchURL: function(aSearchTerms) {
- let url = this._formatURLPref(PREF_GETADDONS_BROWSESEARCHRESULTS, {
- TERMS : encodeURIComponent(aSearchTerms)
- });
- return (url != null) ? url : "about:blank";
- },
-
- /**
- * Cancels the search in progress. If there is no search in progress this
- * does nothing.
- */
- cancelSearch: function() {
- this._searching = false;
- if (this._request) {
- this._request.abort();
- this._request = null;
- }
- this._callback = null;
- },
-
- /**
- * Begins a search for add-ons in this repository by ID. Results will be
- * passed to the given callback.
- *
- * @param aIDs
- * The array of ids to search for
- * @param aCallback
- * The callback to pass results to
- */
- getAddonsByIDs: function(aIDs, aCallback) {
- return this._beginGetAddons(aIDs, aCallback, false);
- },
-
- /**
- * Begins a search of add-ons, potentially sending performance data.
- *
- * @param aIDs
- * Array of ids to search for.
- * @param aCallback
- * Function to pass results to.
- * @param aSendPerformance
- * Boolean indicating whether to send performance data with the
- * request.
- * @param aTimeout
- * (Optional) timeout in milliseconds to abandon the XHR request
- * if we have not received a response from the server.
- */
- _beginGetAddons: function(aIDs, aCallback, aSendPerformance, aTimeout) {
- let ids = aIDs.slice(0);
-
- let params = {
- API_VERSION : API_VERSION,
- IDS : ids.map(encodeURIComponent).join(',')
- };
-
- let pref = PREF_GETADDONS_BYIDS;
-
- if (aSendPerformance) {
- let type = Services.prefs.getPrefType(PREF_GETADDONS_BYIDS_PERFORMANCE);
- if (type == Services.prefs.PREF_STRING) {
- pref = PREF_GETADDONS_BYIDS_PERFORMANCE;
-
- let startupInfo = Cc["@mozilla.org/toolkit/app-startup;1"].
- getService(Ci.nsIAppStartup).
- getStartupInfo();
-
- params.TIME_MAIN = "";
- params.TIME_FIRST_PAINT = "";
- params.TIME_SESSION_RESTORED = "";
- if (startupInfo.process) {
- if (startupInfo.main) {
- params.TIME_MAIN = startupInfo.main - startupInfo.process;
- }
- if (startupInfo.firstPaint) {
- params.TIME_FIRST_PAINT = startupInfo.firstPaint -
- startupInfo.process;
- }
- if (startupInfo.sessionRestored) {
- params.TIME_SESSION_RESTORED = startupInfo.sessionRestored -
- startupInfo.process;
- }
- }
- }
- }
-
- let url = this._formatURLPref(pref, params);
-
- let handleResults = (aElements, aTotalResults, aCompatData) => {
- // Don't use this._parseAddons() so that, for example,
- // incompatible add-ons are not filtered out
- let results = [];
- for (let i = 0; i < aElements.length && results.length < this._maxResults; i++) {
- let result = this._parseAddon(aElements[i], null, aCompatData);
- if (result == null)
- continue;
-
- // Ignore add-on if it wasn't actually requested
- let idIndex = ids.indexOf(result.addon.id);
- if (idIndex == -1)
- continue;
-
- // Ignore add-on if the add-on manager doesn't know about its type:
- if (!(result.addon.type in AddonManager.addonTypes)) {
- continue;
- }
-
- results.push(result);
- // Ignore this add-on from now on
- ids.splice(idIndex, 1);
- }
-
- // Include any compatibility overrides for addons not hosted by the
- // remote repository.
- for (let id in aCompatData) {
- let addonCompat = aCompatData[id];
- if (addonCompat.hosted)
- continue;
-
- let addon = new AddonSearchResult(addonCompat.id);
- // Compatibility overrides can only be for extensions.
- addon.type = "extension";
- addon.compatibilityOverrides = addonCompat.compatRanges;
- let result = {
- addon: addon,
- xpiURL: null,
- xpiHash: null
- };
- results.push(result);
- }
-
- // aTotalResults irrelevant
- this._reportSuccess(results, -1);
- }
-
- this._beginSearch(url, ids.length, aCallback, handleResults, aTimeout);
- },
-
- /**
- * Performs the daily background update check.
- *
- * This API both searches for the add-on IDs specified and sends performance
- * data. It is meant to be called as part of the daily update ping. It should
- * not be used for any other purpose. Use repopulateCache instead.
- *
- * @return Promise{null} Resolves when the metadata update is complete.
- */
- backgroundUpdateCheck: function() {
- return this._repopulateCacheInternal(true);
- },
-
- /**
- * Begins a search for recommended add-ons in this repository. Results will
- * be passed to the given callback.
- *
- * @param aMaxResults
- * The maximum number of results to return
- * @param aCallback
- * The callback to pass results to
- */
- retrieveRecommendedAddons: function(aMaxResults, aCallback) {
- let url = this._formatURLPref(PREF_GETADDONS_GETRECOMMENDED, {
- API_VERSION : API_VERSION,
-
- // Get twice as many results to account for potential filtering
- MAX_RESULTS : 2 * aMaxResults
- });
-
- let handleResults = (aElements, aTotalResults) => {
- this._getLocalAddonIds(aLocalAddonIds => {
- // aTotalResults irrelevant
- this._parseAddons(aElements, -1, aLocalAddonIds);
- });
- }
-
- this._beginSearch(url, aMaxResults, aCallback, handleResults);
- },
-
- /**
- * Begins a search for add-ons in this repository. Results will be passed to
- * the given callback.
- *
- * @param aSearchTerms
- * The terms to search for
- * @param aMaxResults
- * The maximum number of results to return
- * @param aCallback
- * The callback to pass results to
- */
- searchAddons: function(aSearchTerms, aMaxResults, aCallback) {
- let compatMode = "normal";
- if (!AddonManager.checkCompatibility)
- compatMode = "ignore";
- else if (AddonManager.strictCompatibility)
- compatMode = "strict";
-
- let substitutions = {
- API_VERSION : API_VERSION,
- TERMS : encodeURIComponent(aSearchTerms),
- // Get twice as many results to account for potential filtering
- MAX_RESULTS : 2 * aMaxResults,
- COMPATIBILITY_MODE : compatMode,
- };
-
- let url = this._formatURLPref(PREF_GETADDONS_GETSEARCHRESULTS, substitutions);
-
- let handleResults = (aElements, aTotalResults) => {
- this._getLocalAddonIds(aLocalAddonIds => {
- this._parseAddons(aElements, aTotalResults, aLocalAddonIds);
- });
- }
-
- this._beginSearch(url, aMaxResults, aCallback, handleResults);
- },
-
- // Posts results to the callback
- _reportSuccess: function(aResults, aTotalResults) {
- this._searching = false;
- this._request = null;
- // The callback may want to trigger a new search so clear references early
- let addons = aResults.map(result => result.addon);
- let callback = this._callback;
- this._callback = null;
- callback.searchSucceeded(addons, addons.length, aTotalResults);
- },
-
- // Notifies the callback of a failure
- _reportFailure: function() {
- this._searching = false;
- this._request = null;
- // The callback may want to trigger a new search so clear references early
- let callback = this._callback;
- this._callback = null;
- callback.searchFailed();
- },
-
- // Get descendant by unique tag name. Returns null if not unique tag name.
- _getUniqueDescendant: function(aElement, aTagName) {
- let elementsList = aElement.getElementsByTagName(aTagName);
- return (elementsList.length == 1) ? elementsList[0] : null;
- },
-
- // Get direct descendant by unique tag name.
- // Returns null if not unique tag name.
- _getUniqueDirectDescendant: function(aElement, aTagName) {
- let elementsList = Array.filter(aElement.children,
- aChild => aChild.tagName == aTagName);
- return (elementsList.length == 1) ? elementsList[0] : null;
- },
-
- // Parse out trimmed text content. Returns null if text content empty.
- _getTextContent: function(aElement) {
- let textContent = aElement.textContent.trim();
- return (textContent.length > 0) ? textContent : null;
- },
-
- // Parse out trimmed text content of a descendant with the specified tag name
- // Returns null if the parsing unsuccessful.
- _getDescendantTextContent: function(aElement, aTagName) {
- let descendant = this._getUniqueDescendant(aElement, aTagName);
- return (descendant != null) ? this._getTextContent(descendant) : null;
- },
-
- // Parse out trimmed text content of a direct descendant with the specified
- // tag name.
- // Returns null if the parsing unsuccessful.
- _getDirectDescendantTextContent: function(aElement, aTagName) {
- let descendant = this._getUniqueDirectDescendant(aElement, aTagName);
- return (descendant != null) ? this._getTextContent(descendant) : null;
- },
-
- /*
- * Creates an AddonSearchResult by parsing an <addon> element
- *
- * @param aElement
- * The <addon> element to parse
- * @param aSkip
- * Object containing ids and sourceURIs of add-ons to skip.
- * @param aCompatData
- * Array of parsed addon_compatibility elements to accosiate with the
- * resulting AddonSearchResult. Optional.
- * @return Result object containing the parsed AddonSearchResult, xpiURL and
- * xpiHash if the parsing was successful. Otherwise returns null.
- */
- _parseAddon: function(aElement, aSkip, aCompatData) {
- let skipIDs = (aSkip && aSkip.ids) ? aSkip.ids : [];
- let skipSourceURIs = (aSkip && aSkip.sourceURIs) ? aSkip.sourceURIs : [];
-
- let guid = this._getDescendantTextContent(aElement, "guid");
- if (guid == null || skipIDs.indexOf(guid) != -1)
- return null;
-
- let addon = new AddonSearchResult(guid);
- let result = {
- addon: addon,
- xpiURL: null,
- xpiHash: null
- };
-
- if (aCompatData && guid in aCompatData)
- addon.compatibilityOverrides = aCompatData[guid].compatRanges;
-
- for (let node = aElement.firstChild; node; node = node.nextSibling) {
- if (!(node instanceof Ci.nsIDOMElement))
- continue;
-
- let localName = node.localName;
-
- // Handle case where the wanted string value is located in text content
- // but only if the content is not empty
- if (localName in STRING_KEY_MAP) {
- addon[STRING_KEY_MAP[localName]] = this._getTextContent(node) || addon[STRING_KEY_MAP[localName]];
- continue;
- }
-
- // Handle case where the wanted string value is html located in text content
- if (localName in HTML_KEY_MAP) {
- addon[HTML_KEY_MAP[localName]] = convertHTMLToPlainText(this._getTextContent(node));
- continue;
- }
-
- // Handle case where the wanted integer value is located in text content
- if (localName in INTEGER_KEY_MAP) {
- let value = parseInt(this._getTextContent(node));
- if (value >= 0)
- addon[INTEGER_KEY_MAP[localName]] = value;
- continue;
- }
-
- // Handle cases that aren't as simple as grabbing the text content
- switch (localName) {
- case "type":
- // Map AMO's type id to corresponding string
- // https://github.com/mozilla/olympia/blob/master/apps/constants/base.py#L127
- // These definitions need to be updated whenever AMO adds a new type.
- let id = parseInt(node.getAttribute("id"));
- switch (id) {
- case 1:
- addon.type = "extension";
- break;
- case 2:
- addon.type = "theme";
- break;
- case 3:
- addon.type = "dictionary";
- break;
- case 4:
- addon.type = "search";
- break;
- case 5:
- case 6:
- addon.type = "locale";
- break;
- case 7:
- addon.type = "plugin";
- break;
- case 8:
- addon.type = "api";
- break;
- case 9:
- addon.type = "lightweight-theme";
- break;
- case 11:
- addon.type = "webapp";
- break;
- default:
- logger.info("Unknown type id " + id + " found when parsing response for GUID " + guid);
- }
- break;
- case "authors":
- let authorNodes = node.getElementsByTagName("author");
- for (let authorNode of authorNodes) {
- let name = this._getDescendantTextContent(authorNode, "name");
- let link = this._getDescendantTextContent(authorNode, "link");
- if (name == null || link == null)
- continue;
-
- let author = new AddonManagerPrivate.AddonAuthor(name, link);
- if (addon.creator == null)
- addon.creator = author;
- else {
- if (addon.developers == null)
- addon.developers = [];
-
- addon.developers.push(author);
- }
- }
- break;
- case "previews":
- let previewNodes = node.getElementsByTagName("preview");
- for (let previewNode of previewNodes) {
- let full = this._getUniqueDescendant(previewNode, "full");
- if (full == null)
- continue;
-
- let fullURL = this._getTextContent(full);
- let fullWidth = full.getAttribute("width");
- let fullHeight = full.getAttribute("height");
-
- let thumbnailURL, thumbnailWidth, thumbnailHeight;
- let thumbnail = this._getUniqueDescendant(previewNode, "thumbnail");
- if (thumbnail) {
- thumbnailURL = this._getTextContent(thumbnail);
- thumbnailWidth = thumbnail.getAttribute("width");
- thumbnailHeight = thumbnail.getAttribute("height");
- }
- let caption = this._getDescendantTextContent(previewNode, "caption");
- let screenshot = new AddonManagerPrivate.AddonScreenshot(fullURL, fullWidth, fullHeight,
- thumbnailURL, thumbnailWidth,
- thumbnailHeight, caption);
-
- if (addon.screenshots == null)
- addon.screenshots = [];
-
- if (previewNode.getAttribute("primary") == 1)
- addon.screenshots.unshift(screenshot);
- else
- addon.screenshots.push(screenshot);
- }
- break;
- case "learnmore":
- addon.learnmoreURL = this._getTextContent(node);
- addon.homepageURL = addon.homepageURL || addon.learnmoreURL;
- break;
- case "contribution_data":
- let meetDevelopers = this._getDescendantTextContent(node, "meet_developers");
- let suggestedAmount = this._getDescendantTextContent(node, "suggested_amount");
- if (meetDevelopers != null) {
- addon.contributionURL = meetDevelopers;
- addon.contributionAmount = suggestedAmount;
- }
- break
- case "payment_data":
- let link = this._getDescendantTextContent(node, "link");
- let amountTag = this._getUniqueDescendant(node, "amount");
- let amount = parseFloat(amountTag.getAttribute("amount"));
- let displayAmount = this._getTextContent(amountTag);
- if (link != null && amount != null && displayAmount != null) {
- addon.purchaseURL = link;
- addon.purchaseAmount = amount;
- addon.purchaseDisplayAmount = displayAmount;
- }
- break
- case "rating":
- let averageRating = parseInt(this._getTextContent(node));
- if (averageRating >= 0)
- addon.averageRating = Math.min(5, averageRating);
- break;
- case "reviews":
- let url = this._getTextContent(node);
- let num = parseInt(node.getAttribute("num"));
- if (url != null && num >= 0) {
- addon.reviewURL = url;
- addon.reviewCount = num;
- }
- break;
- case "status":
- let repositoryStatus = parseInt(node.getAttribute("id"));
- if (!isNaN(repositoryStatus))
- addon.repositoryStatus = repositoryStatus;
- break;
- case "all_compatible_os":
- let nodes = node.getElementsByTagName("os");
- addon.isPlatformCompatible = Array.some(nodes, function(aNode) {
- let text = aNode.textContent.toLowerCase().trim();
- return text == "all" || text == Services.appinfo.OS.toLowerCase();
- });
- break;
- case "install":
- // No os attribute means the xpi is compatible with any os
- if (node.hasAttribute("os")) {
- let os = node.getAttribute("os").trim().toLowerCase();
- // If the os is not ALL and not the current OS then ignore this xpi
- if (os != "all" && os != Services.appinfo.OS.toLowerCase())
- break;
- }
-
- let xpiURL = this._getTextContent(node);
- if (xpiURL == null)
- break;
-
- if (skipSourceURIs.indexOf(xpiURL) != -1)
- return null;
-
- result.xpiURL = xpiURL;
- addon.sourceURI = NetUtil.newURI(xpiURL);
-
- let size = parseInt(node.getAttribute("size"));
- addon.size = (size >= 0) ? size : null;
-
- let xpiHash = node.getAttribute("hash");
- if (xpiHash != null)
- xpiHash = xpiHash.trim();
- result.xpiHash = xpiHash ? xpiHash : null;
- break;
- case "last_updated":
- let epoch = parseInt(node.getAttribute("epoch"));
- if (!isNaN(epoch))
- addon.updateDate = new Date(1000 * epoch);
- break;
- case "icon":
- addon.icons[node.getAttribute("size")] = this._getTextContent(node);
- break;
- }
- }
-
- return result;
- },
-
- _parseAddons: function(aElements, aTotalResults, aSkip) {
- let results = [];
-
- let isSameApplication = aAppNode => this._getTextContent(aAppNode) == Services.appinfo.ID;
-
- for (let i = 0; i < aElements.length && results.length < this._maxResults; i++) {
- let element = aElements[i];
-
- let tags = this._getUniqueDescendant(element, "compatible_applications");
- if (tags == null)
- continue;
-
- let applications = tags.getElementsByTagName("appID");
- let compatible = Array.some(applications, aAppNode => {
- if (!isSameApplication(aAppNode))
- return false;
-
- let parent = aAppNode.parentNode;
- let minVersion = this._getDescendantTextContent(parent, "min_version");
- let maxVersion = this._getDescendantTextContent(parent, "max_version");
- if (minVersion == null || maxVersion == null)
- return false;
-
- let currentVersion = Services.appinfo.version;
- return (Services.vc.compare(minVersion, currentVersion) <= 0 &&
- ((!AddonManager.strictCompatibility) ||
- Services.vc.compare(currentVersion, maxVersion) <= 0));
- });
-
- // Ignore add-ons not compatible with this Application
- if (!compatible) {
- if (AddonManager.checkCompatibility)
- continue;
-
- if (!Array.some(applications, isSameApplication))
- continue;
- }
-
- // Add-on meets all requirements, so parse out data.
- // Don't pass in compatiblity override data, because that's only returned
- // in GUID searches, which don't use _parseAddons().
- let result = this._parseAddon(element, aSkip);
- if (result == null)
- continue;
-
- // Ignore add-on missing a required attribute
- let requiredAttributes = ["id", "name", "version", "type", "creator"];
- if (requiredAttributes.some(aAttribute => !result.addon[aAttribute]))
- continue;
-
- // Ignore add-on with a type AddonManager doesn't understand:
- if (!(result.addon.type in AddonManager.addonTypes))
- continue;
-
- // Add only if the add-on is compatible with the platform
- if (!result.addon.isPlatformCompatible)
- continue;
-
- // Add only if there was an xpi compatible with this OS or there was a
- // way to purchase the add-on
- if (!result.xpiURL && !result.addon.purchaseURL)
- continue;
-
- result.addon.isCompatible = compatible;
-
- results.push(result);
- // Ignore this add-on from now on by adding it to the skip array
- aSkip.ids.push(result.addon.id);
- }
-
- // Immediately report success if no AddonInstall instances to create
- let pendingResults = results.length;
- if (pendingResults == 0) {
- this._reportSuccess(results, aTotalResults);
- return;
- }
-
- // Create an AddonInstall for each result
- for (let result of results) {
- let addon = result.addon;
- let callback = aInstall => {
- addon.install = aInstall;
- pendingResults--;
- if (pendingResults == 0)
- this._reportSuccess(results, aTotalResults);
- }
-
- if (result.xpiURL) {
- AddonManager.getInstallForURL(result.xpiURL, callback,
- "application/x-xpinstall", result.xpiHash,
- addon.name, addon.icons, addon.version);
- }
- else {
- callback(null);
- }
- }
- },
-
- // Parses addon_compatibility nodes, that describe compatibility overrides.
- _parseAddonCompatElement: function(aResultObj, aElement) {
- let guid = this._getDescendantTextContent(aElement, "guid");
- if (!guid) {
- logger.debug("Compatibility override is missing guid.");
- return;
- }
-
- let compat = {id: guid};
- compat.hosted = aElement.getAttribute("hosted") != "false";
-
- function findMatchingAppRange(aNodes) {
- let toolkitAppRange = null;
- for (let node of aNodes) {
- let appID = this._getDescendantTextContent(node, "appID");
- if (appID != Services.appinfo.ID && appID != TOOLKIT_ID)
- continue;
-
- let minVersion = this._getDescendantTextContent(node, "min_version");
- let maxVersion = this._getDescendantTextContent(node, "max_version");
- if (minVersion == null || maxVersion == null)
- continue;
-
- let appRange = { appID: appID,
- appMinVersion: minVersion,
- appMaxVersion: maxVersion };
-
- // Only use Toolkit app ranges if no ranges match the application ID.
- if (appID == TOOLKIT_ID)
- toolkitAppRange = appRange;
- else
- return appRange;
- }
- return toolkitAppRange;
- }
-
- function parseRangeNode(aNode) {
- let type = aNode.getAttribute("type");
- // Only "incompatible" (blacklisting) is supported for now.
- if (type != "incompatible") {
- logger.debug("Compatibility override of unsupported type found.");
- return null;
- }
-
- let override = new AddonManagerPrivate.AddonCompatibilityOverride(type);
-
- override.minVersion = this._getDirectDescendantTextContent(aNode, "min_version");
- override.maxVersion = this._getDirectDescendantTextContent(aNode, "max_version");
-
- if (!override.minVersion) {
- logger.debug("Compatibility override is missing min_version.");
- return null;
- }
- if (!override.maxVersion) {
- logger.debug("Compatibility override is missing max_version.");
- return null;
- }
-
- let appRanges = aNode.querySelectorAll("compatible_applications > application");
- let appRange = findMatchingAppRange.bind(this)(appRanges);
- if (!appRange) {
- logger.debug("Compatibility override is missing a valid application range.");
- return null;
- }
-
- override.appID = appRange.appID;
- override.appMinVersion = appRange.appMinVersion;
- override.appMaxVersion = appRange.appMaxVersion;
-
- return override;
- }
-
- let rangeNodes = aElement.querySelectorAll("version_ranges > version_range");
- compat.compatRanges = Array.map(rangeNodes, parseRangeNode.bind(this))
- .filter(aItem => !!aItem);
- if (compat.compatRanges.length == 0)
- return;
-
- aResultObj[compat.id] = compat;
- },
-
- // Parses addon_compatibility elements.
- _parseAddonCompatData: function(aElements) {
- let compatData = {};
- Array.forEach(aElements, this._parseAddonCompatElement.bind(this, compatData));
- return compatData;
- },
-
- // Begins a new search if one isn't currently executing
- _beginSearch: function(aURI, aMaxResults, aCallback, aHandleResults, aTimeout) {
- if (this._searching || aURI == null || aMaxResults <= 0) {
- logger.warn("AddonRepository search failed: searching " + this._searching + " aURI " + aURI +
- " aMaxResults " + aMaxResults);
- aCallback.searchFailed();
- return;
- }
-
- this._searching = true;
- this._callback = aCallback;
- this._maxResults = aMaxResults;
-
- logger.debug("Requesting " + aURI);
-
- this._request = new ServiceRequest();
- this._request.mozBackgroundRequest = true;
- this._request.open("GET", aURI, true);
- this._request.overrideMimeType("text/xml");
- if (aTimeout) {
- this._request.timeout = aTimeout;
- }
-
- this._request.addEventListener("error", aEvent => this._reportFailure(), false);
- this._request.addEventListener("timeout", aEvent => this._reportFailure(), false);
- this._request.addEventListener("load", aEvent => {
- logger.debug("Got metadata search load event");
- let request = aEvent.target;
- let responseXML = request.responseXML;
-
- if (!responseXML || responseXML.documentElement.namespaceURI == XMLURI_PARSE_ERROR ||
- (request.status != 200 && request.status != 0)) {
- this._reportFailure();
- return;
- }
-
- let documentElement = responseXML.documentElement;
- let elements = documentElement.getElementsByTagName("addon");
- let totalResults = elements.length;
- let parsedTotalResults = parseInt(documentElement.getAttribute("total_results"));
- // Parsed value of total results only makes sense if >= elements.length
- if (parsedTotalResults >= totalResults)
- totalResults = parsedTotalResults;
-
- let compatElements = documentElement.getElementsByTagName("addon_compatibility");
- let compatData = this._parseAddonCompatData(compatElements);
-
- aHandleResults(elements, totalResults, compatData);
- }, false);
- this._request.send(null);
- },
-
- // Gets the id's of local add-ons, and the sourceURI's of local installs,
- // passing the results to aCallback
- _getLocalAddonIds: function(aCallback) {
- let localAddonIds = {ids: null, sourceURIs: null};
-
- AddonManager.getAllAddons(function(aAddons) {
- localAddonIds.ids = aAddons.map(a => a.id);
- if (localAddonIds.sourceURIs)
- aCallback(localAddonIds);
- });
-
- AddonManager.getAllInstalls(function(aInstalls) {
- localAddonIds.sourceURIs = [];
- for (let install of aInstalls) {
- if (install.state != AddonManager.STATE_AVAILABLE)
- localAddonIds.sourceURIs.push(install.sourceURI.spec);
- }
-
- if (localAddonIds.ids)
- aCallback(localAddonIds);
- });
- },
-
- // Create url from preference, returning null if preference does not exist
- _formatURLPref: function(aPreference, aSubstitutions) {
- let url = null;
- try {
- url = Services.prefs.getCharPref(aPreference);
- } catch (e) {
- logger.warn("_formatURLPref: Couldn't get pref: " + aPreference);
- return null;
- }
-
- url = url.replace(/%([A-Z_]+)%/g, function(aMatch, aKey) {
- return (aKey in aSubstitutions) ? aSubstitutions[aKey] : aMatch;
- });
-
- return Services.urlFormatter.formatURL(url);
- },
-
- // Find a AddonCompatibilityOverride that matches a given aAddonVersion and
- // application/platform version.
- findMatchingCompatOverride: function(aAddonVersion,
- aCompatOverrides,
- aAppVersion,
- aPlatformVersion) {
- for (let override of aCompatOverrides) {
-
- let appVersion = null;
- if (override.appID == TOOLKIT_ID)
- appVersion = aPlatformVersion || Services.appinfo.platformVersion;
- else
- appVersion = aAppVersion || Services.appinfo.version;
-
- if (Services.vc.compare(override.minVersion, aAddonVersion) <= 0 &&
- Services.vc.compare(aAddonVersion, override.maxVersion) <= 0 &&
- Services.vc.compare(override.appMinVersion, appVersion) <= 0 &&
- Services.vc.compare(appVersion, override.appMaxVersion) <= 0) {
- return override;
- }
- }
- return null;
- },
-
- flush: function() {
- return AddonDatabase.flush();
- }
-};
-
-var AddonDatabase = {
- connectionPromise: null,
- // the in-memory database
- DB: BLANK_DB(),
-
- /**
- * A getter to retrieve the path to the DB
- */
- get jsonFile() {
- return OS.Path.join(OS.Constants.Path.profileDir, FILE_DATABASE);
- },
-
- /**
- * Asynchronously opens a new connection to the database file.
- *
- * @return {Promise} a promise that resolves to the database.
- */
- openConnection: function() {
- if (!this.connectionPromise) {
- this.connectionPromise = Task.spawn(function*() {
- this.DB = BLANK_DB();
-
- let inputDB, schema;
-
- try {
- let data = yield OS.File.read(this.jsonFile, { encoding: "utf-8"})
- inputDB = JSON.parse(data);
-
- if (!inputDB.hasOwnProperty("addons") ||
- !Array.isArray(inputDB.addons)) {
- throw new Error("No addons array.");
- }
-
- if (!inputDB.hasOwnProperty("schema")) {
- throw new Error("No schema specified.");
- }
-
- schema = parseInt(inputDB.schema, 10);
-
- if (!Number.isInteger(schema) ||
- schema < DB_MIN_JSON_SCHEMA) {
- throw new Error("Invalid schema value.");
- }
- } catch (e) {
- if (e instanceof OS.File.Error && e.becauseNoSuchFile) {
- logger.debug("No " + FILE_DATABASE + " found.");
- } else {
- logger.error(`Malformed ${FILE_DATABASE}: ${e} - resetting to empty`);
- }
-
- // Create a blank addons.json file
- this._saveDBToDisk();
-
- let dbSchema = 0;
- try {
- dbSchema = Services.prefs.getIntPref(PREF_GETADDONS_DB_SCHEMA);
- } catch (e) {}
-
- if (dbSchema < DB_MIN_JSON_SCHEMA) {
- let results = yield new Promise((resolve, reject) => {
- AddonRepository_SQLiteMigrator.migrate(resolve);
- });
-
- if (results.length) {
- yield this._insertAddons(results);
- }
-
- }
-
- Services.prefs.setIntPref(PREF_GETADDONS_DB_SCHEMA, DB_SCHEMA);
- return this.DB;
- }
-
- Services.prefs.setIntPref(PREF_GETADDONS_DB_SCHEMA, DB_SCHEMA);
-
- // We use _insertAddon manually instead of calling
- // insertAddons to avoid the write to disk which would
- // be a waste since this is the data that was just read.
- for (let addon of inputDB.addons) {
- this._insertAddon(addon);
- }
-
- return this.DB;
- }.bind(this));
- }
-
- return this.connectionPromise;
- },
-
- /**
- * A lazy getter for the database connection.
- */
- get connection() {
- return this.openConnection();
- },
-
- /**
- * Asynchronously shuts down the database connection and releases all
- * cached objects
- *
- * @param aCallback
- * An optional callback to call once complete
- * @param aSkipFlush
- * An optional boolean to skip flushing data to disk. Useful
- * when the database is going to be deleted afterwards.
- */
- shutdown: function(aSkipFlush) {
- if (!this.connectionPromise) {
- return Promise.resolve();
- }
-
- this.connectionPromise = null;
-
- if (aSkipFlush) {
- return Promise.resolve();
- }
- return this.Writer.flush();
- },
-
- /**
- * Asynchronously deletes the database, shutting down the connection
- * first if initialized
- *
- * @param aCallback
- * An optional callback to call once complete
- * @return Promise{null} resolves when the database has been deleted
- */
- delete: function(aCallback) {
- this.DB = BLANK_DB();
-
- this._deleting = this.Writer.flush()
- .then(null, () => {})
- // shutdown(true) never rejects
- .then(() => this.shutdown(true))
- .then(() => OS.File.remove(this.jsonFile, {}))
- .then(null, error => logger.error("Unable to delete Addon Repository file " +
- this.jsonFile, error))
- .then(() => this._deleting = null)
- .then(aCallback);
- return this._deleting;
- },
-
- toJSON: function() {
- let json = {
- schema: this.DB.schema,
- addons: []
- }
-
- for (let [, value] of this.DB.addons)
- json.addons.push(value);
-
- return json;
- },
-
- /*
- * This is a deferred task writer that is used
- * to batch operations done within 50ms of each
- * other and thus generating only one write to disk
- */
- get Writer() {
- delete this.Writer;
- this.Writer = new DeferredSave(
- this.jsonFile,
- () => { return JSON.stringify(this); },
- DB_BATCH_TIMEOUT_MS
- );
- return this.Writer;
- },
-
- /**
- * Flush any pending I/O on the addons.json file
- * @return: Promise{null}
- * Resolves when the pending I/O (writing out or deleting
- * addons.json) completes
- */
- flush: function() {
- if (this._deleting) {
- return this._deleting;
- }
- return this.Writer.flush();
- },
-
- /**
- * Asynchronously retrieve all add-ons from the database
- * @return: Promise{Map}
- * Resolves when the add-ons are retrieved from the database
- */
- retrieveStoredData: function() {
- return this.openConnection().then(db => db.addons);
- },
-
- /**
- * Asynchronously repopulates the database so it only contains the
- * specified add-ons
- *
- * @param aAddons
- * The array of add-ons to repopulate the database with
- * @param aCallback
- * An optional callback to call once complete
- */
- repopulate: function(aAddons, aCallback) {
- this.DB.addons.clear();
- this.insertAddons(aAddons, function() {
- let now = Math.round(Date.now() / 1000);
- logger.debug("Cache repopulated, setting " + PREF_METADATA_LASTUPDATE + " to " + now);
- Services.prefs.setIntPref(PREF_METADATA_LASTUPDATE, now);
- if (aCallback)
- aCallback();
- });
- },
-
- /**
- * Asynchronously inserts an array of add-ons into the database
- *
- * @param aAddons
- * The array of add-ons to insert
- * @param aCallback
- * An optional callback to call once complete
- */
- insertAddons: Task.async(function*(aAddons, aCallback) {
- yield this.openConnection();
- yield this._insertAddons(aAddons, aCallback);
- }),
-
- _insertAddons: Task.async(function*(aAddons, aCallback) {
- for (let addon of aAddons) {
- this._insertAddon(addon);
- }
-
- yield this._saveDBToDisk();
- aCallback && aCallback();
- }),
-
- /**
- * Inserts an individual add-on into the database. If the add-on already
- * exists in the database (by id), then the specified add-on will not be
- * inserted.
- *
- * @param aAddon
- * The add-on to insert into the database
- * @param aCallback
- * The callback to call once complete
- */
- _insertAddon: function(aAddon) {
- let newAddon = this._parseAddon(aAddon);
- if (!newAddon ||
- !newAddon.id ||
- this.DB.addons.has(newAddon.id))
- return;
-
- this.DB.addons.set(newAddon.id, newAddon);
- },
-
- /*
- * Creates an AddonSearchResult by parsing an object structure
- * retrieved from the DB JSON representation.
- *
- * @param aObj
- * The object to parse
- * @return Returns an AddonSearchResult object.
- */
- _parseAddon: function(aObj) {
- if (aObj instanceof AddonSearchResult)
- return aObj;
-
- let id = aObj.id;
- if (!aObj.id)
- return null;
-
- let addon = new AddonSearchResult(id);
-
- for (let expectedProperty of Object.keys(AddonSearchResult.prototype)) {
- if (!(expectedProperty in aObj) ||
- typeof(aObj[expectedProperty]) === "function")
- continue;
-
- let value = aObj[expectedProperty];
-
- try {
- switch (expectedProperty) {
- case "sourceURI":
- addon.sourceURI = value ? NetUtil.newURI(value) : null;
- break;
-
- case "creator":
- addon.creator = value
- ? this._makeDeveloper(value)
- : null;
- break;
-
- case "updateDate":
- addon.updateDate = value ? new Date(value) : null;
- break;
-
- case "developers":
- if (!addon.developers) addon.developers = [];
- for (let developer of value) {
- addon.developers.push(this._makeDeveloper(developer));
- }
- break;
-
- case "screenshots":
- if (!addon.screenshots) addon.screenshots = [];
- for (let screenshot of value) {
- addon.screenshots.push(this._makeScreenshot(screenshot));
- }
- break;
-
- case "compatibilityOverrides":
- if (!addon.compatibilityOverrides) addon.compatibilityOverrides = [];
- for (let override of value) {
- addon.compatibilityOverrides.push(
- this._makeCompatOverride(override)
- );
- }
- break;
-
- case "icons":
- if (!addon.icons) addon.icons = {};
- for (let size of Object.keys(aObj.icons)) {
- addon.icons[size] = aObj.icons[size];
- }
- break;
-
- case "iconURL":
- break;
-
- default:
- addon[expectedProperty] = value;
- }
- } catch (ex) {
- logger.warn("Error in parsing property value for " + expectedProperty + " | " + ex);
- }
-
- // delete property from obj to indicate we've already
- // handled it. The remaining public properties will
- // be stored separately and just passed through to
- // be written back to the DB.
- delete aObj[expectedProperty];
- }
-
- // Copy remaining properties to a separate object
- // to prevent accidental access on downgraded versions.
- // The properties will be merged in the same object
- // prior to being written back through toJSON.
- for (let remainingProperty of Object.keys(aObj)) {
- switch (typeof(aObj[remainingProperty])) {
- case "boolean":
- case "number":
- case "string":
- case "object":
- // these types are accepted
- break;
- default:
- continue;
- }
-
- if (!remainingProperty.startsWith("_"))
- addon._unsupportedProperties[remainingProperty] =
- aObj[remainingProperty];
- }
-
- return addon;
- },
-
- /**
- * Write the in-memory DB to disk, after waiting for
- * the DB_BATCH_TIMEOUT_MS timeout.
- *
- * @return Promise A promise that resolves after the
- * write to disk has completed.
- */
- _saveDBToDisk: function() {
- return this.Writer.saveChanges().then(
- null,
- e => logger.error("SaveDBToDisk failed", e));
- },
-
- /**
- * Make a developer object from a vanilla
- * JS object from the JSON database
- *
- * @param aObj
- * The JS object to use
- * @return The created developer
- */
- _makeDeveloper: function(aObj) {
- let name = aObj.name;
- let url = aObj.url;
- return new AddonManagerPrivate.AddonAuthor(name, url);
- },
-
- /**
- * Make a screenshot object from a vanilla
- * JS object from the JSON database
- *
- * @param aObj
- * The JS object to use
- * @return The created screenshot
- */
- _makeScreenshot: function(aObj) {
- let url = aObj.url;
- let width = aObj.width;
- let height = aObj.height;
- let thumbnailURL = aObj.thumbnailURL;
- let thumbnailWidth = aObj.thumbnailWidth;
- let thumbnailHeight = aObj.thumbnailHeight;
- let caption = aObj.caption;
- return new AddonManagerPrivate.AddonScreenshot(url, width, height, thumbnailURL,
- thumbnailWidth, thumbnailHeight, caption);
- },
-
- /**
- * Make a CompatibilityOverride from a vanilla
- * JS object from the JSON database
- *
- * @param aObj
- * The JS object to use
- * @return The created CompatibilityOverride
- */
- _makeCompatOverride: function(aObj) {
- let type = aObj.type;
- let minVersion = aObj.minVersion;
- let maxVersion = aObj.maxVersion;
- let appID = aObj.appID;
- let appMinVersion = aObj.appMinVersion;
- let appMaxVersion = aObj.appMaxVersion;
- return new AddonManagerPrivate.AddonCompatibilityOverride(type,
- minVersion,
- maxVersion,
- appID,
- appMinVersion,
- appMaxVersion);
- },
-};
diff --git a/toolkit/mozapps/webextensions/internal/AddonRepository_SQLiteMigrator.jsm b/toolkit/mozapps/webextensions/internal/AddonRepository_SQLiteMigrator.jsm
deleted file mode 100644
index e3479643b..000000000
--- a/toolkit/mozapps/webextensions/internal/AddonRepository_SQLiteMigrator.jsm
+++ /dev/null
@@ -1,522 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/AddonManager.jsm");
-/* globals AddonManagerPrivate*/
-Cu.import("resource://gre/modules/FileUtils.jsm");
-
-const KEY_PROFILEDIR = "ProfD";
-const FILE_DATABASE = "addons.sqlite";
-const LAST_DB_SCHEMA = 4;
-
-// Add-on properties present in the columns of the database
-const PROP_SINGLE = ["id", "type", "name", "version", "creator", "description",
- "fullDescription", "developerComments", "eula",
- "homepageURL", "supportURL", "contributionURL",
- "contributionAmount", "averageRating", "reviewCount",
- "reviewURL", "totalDownloads", "weeklyDownloads",
- "dailyUsers", "sourceURI", "repositoryStatus", "size",
- "updateDate"];
-
-Cu.import("resource://gre/modules/Log.jsm");
-const LOGGER_ID = "addons.repository.sqlmigrator";
-
-// Create a new logger for use by the Addons Repository SQL Migrator
-// (Requires AddonManager.jsm)
-var logger = Log.repository.getLogger(LOGGER_ID);
-
-this.EXPORTED_SYMBOLS = ["AddonRepository_SQLiteMigrator"];
-
-
-this.AddonRepository_SQLiteMigrator = {
-
- /**
- * Migrates data from a previous SQLite version of the
- * database to the JSON version.
- *
- * @param structFunctions an object that contains functions
- * to create the various objects used
- * in the new JSON format
- * @param aCallback A callback to be called when migration
- * finishes, with the results in an array
- * @returns bool True if a migration will happen (DB was
- * found and succesfully opened)
- */
- migrate: function(aCallback) {
- if (!this._openConnection()) {
- this._closeConnection();
- aCallback([]);
- return false;
- }
-
- logger.debug("Importing addon repository from previous " + FILE_DATABASE + " storage.");
-
- this._retrieveStoredData((results) => {
- this._closeConnection();
- let resultArray = Object.keys(results).map(k => results[k]);
- logger.debug(resultArray.length + " addons imported.")
- aCallback(resultArray);
- });
-
- return true;
- },
-
- /**
- * Synchronously opens a new connection to the database file.
- *
- * @return bool Whether the DB was opened successfully.
- */
- _openConnection: function() {
- delete this.connection;
-
- let dbfile = FileUtils.getFile(KEY_PROFILEDIR, [FILE_DATABASE], true);
- if (!dbfile.exists())
- return false;
-
- try {
- this.connection = Services.storage.openUnsharedDatabase(dbfile);
- } catch (e) {
- return false;
- }
-
- this.connection.executeSimpleSQL("PRAGMA locking_mode = EXCLUSIVE");
-
- // Any errors in here should rollback
- try {
- this.connection.beginTransaction();
-
- switch (this.connection.schemaVersion) {
- case 0:
- return false;
-
- case 1:
- logger.debug("Upgrading database schema to version 2");
- this.connection.executeSimpleSQL("ALTER TABLE screenshot ADD COLUMN width INTEGER");
- this.connection.executeSimpleSQL("ALTER TABLE screenshot ADD COLUMN height INTEGER");
- this.connection.executeSimpleSQL("ALTER TABLE screenshot ADD COLUMN thumbnailWidth INTEGER");
- this.connection.executeSimpleSQL("ALTER TABLE screenshot ADD COLUMN thumbnailHeight INTEGER");
- case 2:
- logger.debug("Upgrading database schema to version 3");
- this.connection.createTable("compatibility_override",
- "addon_internal_id INTEGER, " +
- "num INTEGER, " +
- "type TEXT, " +
- "minVersion TEXT, " +
- "maxVersion TEXT, " +
- "appID TEXT, " +
- "appMinVersion TEXT, " +
- "appMaxVersion TEXT, " +
- "PRIMARY KEY (addon_internal_id, num)");
- case 3:
- logger.debug("Upgrading database schema to version 4");
- this.connection.createTable("icon",
- "addon_internal_id INTEGER, " +
- "size INTEGER, " +
- "url TEXT, " +
- "PRIMARY KEY (addon_internal_id, size)");
- this._createIndices();
- this._createTriggers();
- this.connection.schemaVersion = LAST_DB_SCHEMA;
- case LAST_DB_SCHEMA:
- break;
- default:
- return false;
- }
- this.connection.commitTransaction();
- } catch (e) {
- logger.error("Failed to open " + FILE_DATABASE + ". Data import will not happen.", e);
- this.logSQLError(this.connection.lastError, this.connection.lastErrorString);
- this.connection.rollbackTransaction();
- return false;
- }
-
- return true;
- },
-
- _closeConnection: function() {
- for (let key in this.asyncStatementsCache) {
- let stmt = this.asyncStatementsCache[key];
- stmt.finalize();
- }
- this.asyncStatementsCache = {};
-
- if (this.connection)
- this.connection.asyncClose();
-
- delete this.connection;
- },
-
- /**
- * Asynchronously retrieve all add-ons from the database, and pass it
- * to the specified callback
- *
- * @param aCallback
- * The callback to pass the add-ons back to
- */
- _retrieveStoredData: function(aCallback) {
- let addons = {};
-
- // Retrieve all data from the addon table
- let getAllAddons = () => {
- this.getAsyncStatement("getAllAddons").executeAsync({
- handleResult: aResults => {
- let row = null;
- while ((row = aResults.getNextRow())) {
- let internal_id = row.getResultByName("internal_id");
- addons[internal_id] = this._makeAddonFromAsyncRow(row);
- }
- },
-
- handleError: this.asyncErrorLogger,
-
- handleCompletion: function(aReason) {
- if (aReason != Ci.mozIStorageStatementCallback.REASON_FINISHED) {
- logger.error("Error retrieving add-ons from database. Returning empty results");
- aCallback({});
- return;
- }
-
- getAllDevelopers();
- }
- });
- }
-
- // Retrieve all data from the developer table
- let getAllDevelopers = () => {
- this.getAsyncStatement("getAllDevelopers").executeAsync({
- handleResult: aResults => {
- let row = null;
- while ((row = aResults.getNextRow())) {
- let addon_internal_id = row.getResultByName("addon_internal_id");
- if (!(addon_internal_id in addons)) {
- logger.warn("Found a developer not linked to an add-on in database");
- continue;
- }
-
- let addon = addons[addon_internal_id];
- if (!addon.developers)
- addon.developers = [];
-
- addon.developers.push(this._makeDeveloperFromAsyncRow(row));
- }
- },
-
- handleError: this.asyncErrorLogger,
-
- handleCompletion: function(aReason) {
- if (aReason != Ci.mozIStorageStatementCallback.REASON_FINISHED) {
- logger.error("Error retrieving developers from database. Returning empty results");
- aCallback({});
- return;
- }
-
- getAllScreenshots();
- }
- });
- }
-
- // Retrieve all data from the screenshot table
- let getAllScreenshots = () => {
- this.getAsyncStatement("getAllScreenshots").executeAsync({
- handleResult: aResults => {
- let row = null;
- while ((row = aResults.getNextRow())) {
- let addon_internal_id = row.getResultByName("addon_internal_id");
- if (!(addon_internal_id in addons)) {
- logger.warn("Found a screenshot not linked to an add-on in database");
- continue;
- }
-
- let addon = addons[addon_internal_id];
- if (!addon.screenshots)
- addon.screenshots = [];
- addon.screenshots.push(this._makeScreenshotFromAsyncRow(row));
- }
- },
-
- handleError: this.asyncErrorLogger,
-
- handleCompletion: function(aReason) {
- if (aReason != Ci.mozIStorageStatementCallback.REASON_FINISHED) {
- logger.error("Error retrieving screenshots from database. Returning empty results");
- aCallback({});
- return;
- }
-
- getAllCompatOverrides();
- }
- });
- }
-
- let getAllCompatOverrides = () => {
- this.getAsyncStatement("getAllCompatOverrides").executeAsync({
- handleResult: aResults => {
- let row = null;
- while ((row = aResults.getNextRow())) {
- let addon_internal_id = row.getResultByName("addon_internal_id");
- if (!(addon_internal_id in addons)) {
- logger.warn("Found a compatibility override not linked to an add-on in database");
- continue;
- }
-
- let addon = addons[addon_internal_id];
- if (!addon.compatibilityOverrides)
- addon.compatibilityOverrides = [];
- addon.compatibilityOverrides.push(this._makeCompatOverrideFromAsyncRow(row));
- }
- },
-
- handleError: this.asyncErrorLogger,
-
- handleCompletion: function(aReason) {
- if (aReason != Ci.mozIStorageStatementCallback.REASON_FINISHED) {
- logger.error("Error retrieving compatibility overrides from database. Returning empty results");
- aCallback({});
- return;
- }
-
- getAllIcons();
- }
- });
- }
-
- let getAllIcons = () => {
- this.getAsyncStatement("getAllIcons").executeAsync({
- handleResult: aResults => {
- let row = null;
- while ((row = aResults.getNextRow())) {
- let addon_internal_id = row.getResultByName("addon_internal_id");
- if (!(addon_internal_id in addons)) {
- logger.warn("Found an icon not linked to an add-on in database");
- continue;
- }
-
- let addon = addons[addon_internal_id];
- let { size, url } = this._makeIconFromAsyncRow(row);
- addon.icons[size] = url;
- if (size == 32)
- addon.iconURL = url;
- }
- },
-
- handleError: this.asyncErrorLogger,
-
- handleCompletion: function(aReason) {
- if (aReason != Ci.mozIStorageStatementCallback.REASON_FINISHED) {
- logger.error("Error retrieving icons from database. Returning empty results");
- aCallback({});
- return;
- }
-
- let returnedAddons = {};
- for (let id in addons) {
- let addon = addons[id];
- returnedAddons[addon.id] = addon;
- }
- aCallback(returnedAddons);
- }
- });
- }
-
- // Begin asynchronous process
- getAllAddons();
- },
-
- // A cache of statements that are used and need to be finalized on shutdown
- asyncStatementsCache: {},
-
- /**
- * Gets a cached async statement or creates a new statement if it doesn't
- * already exist.
- *
- * @param aKey
- * A unique key to reference the statement
- * @return a mozIStorageAsyncStatement for the SQL corresponding to the
- * unique key
- */
- getAsyncStatement: function(aKey) {
- if (aKey in this.asyncStatementsCache)
- return this.asyncStatementsCache[aKey];
-
- let sql = this.queries[aKey];
- try {
- return this.asyncStatementsCache[aKey] = this.connection.createAsyncStatement(sql);
- } catch (e) {
- logger.error("Error creating statement " + aKey + " (" + sql + ")");
- throw Components.Exception("Error creating statement " + aKey + " (" + sql + "): " + e,
- e.result);
- }
- },
-
- // The queries used by the database
- queries: {
- getAllAddons: "SELECT internal_id, id, type, name, version, " +
- "creator, creatorURL, description, fullDescription, " +
- "developerComments, eula, homepageURL, supportURL, " +
- "contributionURL, contributionAmount, averageRating, " +
- "reviewCount, reviewURL, totalDownloads, weeklyDownloads, " +
- "dailyUsers, sourceURI, repositoryStatus, size, updateDate " +
- "FROM addon",
-
- getAllDevelopers: "SELECT addon_internal_id, name, url FROM developer " +
- "ORDER BY addon_internal_id, num",
-
- getAllScreenshots: "SELECT addon_internal_id, url, width, height, " +
- "thumbnailURL, thumbnailWidth, thumbnailHeight, caption " +
- "FROM screenshot ORDER BY addon_internal_id, num",
-
- getAllCompatOverrides: "SELECT addon_internal_id, type, minVersion, " +
- "maxVersion, appID, appMinVersion, appMaxVersion " +
- "FROM compatibility_override " +
- "ORDER BY addon_internal_id, num",
-
- getAllIcons: "SELECT addon_internal_id, size, url FROM icon " +
- "ORDER BY addon_internal_id, size",
- },
-
- /**
- * Make add-on structure from an asynchronous row.
- *
- * @param aRow
- * The asynchronous row to use
- * @return The created add-on
- */
- _makeAddonFromAsyncRow: function(aRow) {
- // This is intentionally not an AddonSearchResult object in order
- // to allow AddonDatabase._parseAddon to parse it, same as if it
- // was read from the JSON database.
-
- let addon = { icons: {} };
-
- for (let prop of PROP_SINGLE) {
- addon[prop] = aRow.getResultByName(prop)
- }
-
- return addon;
- },
-
- /**
- * Make a developer from an asynchronous row
- *
- * @param aRow
- * The asynchronous row to use
- * @return The created developer
- */
- _makeDeveloperFromAsyncRow: function(aRow) {
- let name = aRow.getResultByName("name");
- let url = aRow.getResultByName("url")
- return new AddonManagerPrivate.AddonAuthor(name, url);
- },
-
- /**
- * Make a screenshot from an asynchronous row
- *
- * @param aRow
- * The asynchronous row to use
- * @return The created screenshot
- */
- _makeScreenshotFromAsyncRow: function(aRow) {
- let url = aRow.getResultByName("url");
- let width = aRow.getResultByName("width");
- let height = aRow.getResultByName("height");
- let thumbnailURL = aRow.getResultByName("thumbnailURL");
- let thumbnailWidth = aRow.getResultByName("thumbnailWidth");
- let thumbnailHeight = aRow.getResultByName("thumbnailHeight");
- let caption = aRow.getResultByName("caption");
- return new AddonManagerPrivate.AddonScreenshot(url, width, height, thumbnailURL,
- thumbnailWidth, thumbnailHeight, caption);
- },
-
- /**
- * Make a CompatibilityOverride from an asynchronous row
- *
- * @param aRow
- * The asynchronous row to use
- * @return The created CompatibilityOverride
- */
- _makeCompatOverrideFromAsyncRow: function(aRow) {
- let type = aRow.getResultByName("type");
- let minVersion = aRow.getResultByName("minVersion");
- let maxVersion = aRow.getResultByName("maxVersion");
- let appID = aRow.getResultByName("appID");
- let appMinVersion = aRow.getResultByName("appMinVersion");
- let appMaxVersion = aRow.getResultByName("appMaxVersion");
- return new AddonManagerPrivate.AddonCompatibilityOverride(type,
- minVersion,
- maxVersion,
- appID,
- appMinVersion,
- appMaxVersion);
- },
-
- /**
- * Make an icon from an asynchronous row
- *
- * @param aRow
- * The asynchronous row to use
- * @return An object containing the size and URL of the icon
- */
- _makeIconFromAsyncRow: function(aRow) {
- let size = aRow.getResultByName("size");
- let url = aRow.getResultByName("url");
- return { size: size, url: url };
- },
-
- /**
- * A helper function to log an SQL error.
- *
- * @param aError
- * The storage error code associated with the error
- * @param aErrorString
- * An error message
- */
- logSQLError: function(aError, aErrorString) {
- logger.error("SQL error " + aError + ": " + aErrorString);
- },
-
- /**
- * A helper function to log any errors that occur during async statements.
- *
- * @param aError
- * A mozIStorageError to log
- */
- asyncErrorLogger: function(aError) {
- logger.error("Async SQL error " + aError.result + ": " + aError.message);
- },
-
- /**
- * Synchronously creates the triggers in the database.
- */
- _createTriggers: function() {
- this.connection.executeSimpleSQL("DROP TRIGGER IF EXISTS delete_addon");
- this.connection.executeSimpleSQL("CREATE TRIGGER delete_addon AFTER DELETE " +
- "ON addon BEGIN " +
- "DELETE FROM developer WHERE addon_internal_id=old.internal_id; " +
- "DELETE FROM screenshot WHERE addon_internal_id=old.internal_id; " +
- "DELETE FROM compatibility_override WHERE addon_internal_id=old.internal_id; " +
- "DELETE FROM icon WHERE addon_internal_id=old.internal_id; " +
- "END");
- },
-
- /**
- * Synchronously creates the indices in the database.
- */
- _createIndices: function() {
- this.connection.executeSimpleSQL("CREATE INDEX IF NOT EXISTS developer_idx " +
- "ON developer (addon_internal_id)");
- this.connection.executeSimpleSQL("CREATE INDEX IF NOT EXISTS screenshot_idx " +
- "ON screenshot (addon_internal_id)");
- this.connection.executeSimpleSQL("CREATE INDEX IF NOT EXISTS compatibility_override_idx " +
- "ON compatibility_override (addon_internal_id)");
- this.connection.executeSimpleSQL("CREATE INDEX IF NOT EXISTS icon_idx " +
- "ON icon (addon_internal_id)");
- }
-}
diff --git a/toolkit/mozapps/webextensions/internal/GMPProvider.jsm b/toolkit/mozapps/webextensions/internal/GMPProvider.jsm
deleted file mode 100644
index 9bb34a7af..000000000
--- a/toolkit/mozapps/webextensions/internal/GMPProvider.jsm
+++ /dev/null
@@ -1,699 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
-
-this.EXPORTED_SYMBOLS = [];
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/AddonManager.jsm");
-/* globals AddonManagerPrivate*/
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Preferences.jsm");
-Cu.import("resource://gre/modules/osfile.jsm");
-/* globals OS*/
-Cu.import("resource://gre/modules/Log.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/GMPUtils.jsm");
-/* globals EME_ADOBE_ID, GMP_PLUGIN_IDS, GMPPrefs, GMPUtils, OPEN_H264_ID, WIDEVINE_ID */
-Cu.import("resource://gre/modules/AppConstants.jsm");
-Cu.import("resource://gre/modules/UpdateUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(
- this, "GMPInstallManager", "resource://gre/modules/GMPInstallManager.jsm");
-XPCOMUtils.defineLazyModuleGetter(
- this, "setTimeout", "resource://gre/modules/Timer.jsm");
-
-const URI_EXTENSION_STRINGS = "chrome://mozapps/locale/extensions/extensions.properties";
-const STRING_TYPE_NAME = "type.%ID%.name";
-
-const SEC_IN_A_DAY = 24 * 60 * 60;
-// How long to wait after a user enabled EME before attempting to download CDMs.
-const GMP_CHECK_DELAY = 10 * 1000; // milliseconds
-
-const NS_GRE_DIR = "GreD";
-const CLEARKEY_PLUGIN_ID = "gmp-clearkey";
-const CLEARKEY_VERSION = "0.1";
-
-const GMP_LICENSE_INFO = "gmp_license_info";
-const GMP_PRIVACY_INFO = "gmp_privacy_info";
-const GMP_LEARN_MORE = "learn_more_label";
-
-const GMP_PLUGINS = [
- {
- id: OPEN_H264_ID,
- name: "openH264_name",
- description: "openH264_description2",
- // The following licenseURL is part of an awful hack to include the OpenH264
- // license without having bug 624602 fixed yet, and intentionally ignores
- // localisation.
- licenseURL: "chrome://mozapps/content/extensions/OpenH264-license.txt",
- homepageURL: "http://www.openh264.org/",
- optionsURL: "chrome://mozapps/content/extensions/gmpPrefs.xul",
- },
- {
- id: EME_ADOBE_ID,
- name: "eme-adobe_name",
- description: "eme-adobe_description",
- // The following learnMoreURL is another hack to be able to support a SUMO page for this
- // feature.
- get learnMoreURL() {
- return Services.urlFormatter.formatURLPref("app.support.baseURL") + "drm-content";
- },
- licenseURL: "http://help.adobe.com/en_US/primetime/drm/HTML5_CDM_EULA/index.html",
- homepageURL: "http://help.adobe.com/en_US/primetime/drm/HTML5_CDM",
- optionsURL: "chrome://mozapps/content/extensions/gmpPrefs.xul",
- isEME: true,
- },
- {
- id: WIDEVINE_ID,
- name: "widevine_description",
- // Describe the purpose of both CDMs in the same way.
- description: "eme-adobe_description",
- licenseURL: "https://www.google.com/policies/privacy/",
- homepageURL: "https://www.widevine.com/",
- optionsURL: "chrome://mozapps/content/extensions/gmpPrefs.xul",
- isEME: true
- }];
-XPCOMUtils.defineConstant(this, "GMP_PLUGINS", GMP_PLUGINS);
-
-XPCOMUtils.defineLazyGetter(this, "pluginsBundle",
- () => Services.strings.createBundle("chrome://global/locale/plugins.properties"));
-XPCOMUtils.defineLazyGetter(this, "gmpService",
- () => Cc["@mozilla.org/gecko-media-plugin-service;1"].getService(Ci.mozIGeckoMediaPluginChromeService));
-
-var messageManager = Cc["@mozilla.org/globalmessagemanager;1"]
- .getService(Ci.nsIMessageListenerManager);
-
-var gLogger;
-var gLogAppenderDump = null;
-
-function configureLogging() {
- if (!gLogger) {
- gLogger = Log.repository.getLogger("Toolkit.GMP");
- gLogger.addAppender(new Log.ConsoleAppender(new Log.BasicFormatter()));
- }
- gLogger.level = GMPPrefs.get(GMPPrefs.KEY_LOGGING_LEVEL, Log.Level.Warn);
-
- let logDumping = GMPPrefs.get(GMPPrefs.KEY_LOGGING_DUMP, false);
- if (logDumping != !!gLogAppenderDump) {
- if (logDumping) {
- gLogAppenderDump = new Log.DumpAppender(new Log.BasicFormatter());
- gLogger.addAppender(gLogAppenderDump);
- } else {
- gLogger.removeAppender(gLogAppenderDump);
- gLogAppenderDump = null;
- }
- }
-}
-
-
-
-/**
- * The GMPWrapper provides the info for the various GMP plugins to public
- * callers through the API.
- */
-function GMPWrapper(aPluginInfo) {
- this._plugin = aPluginInfo;
- this._log =
- Log.repository.getLoggerWithMessagePrefix("Toolkit.GMP",
- "GMPWrapper(" +
- this._plugin.id + ") ");
- Preferences.observe(GMPPrefs.getPrefKey(GMPPrefs.KEY_PLUGIN_ENABLED,
- this._plugin.id),
- this.onPrefEnabledChanged, this);
- Preferences.observe(GMPPrefs.getPrefKey(GMPPrefs.KEY_PLUGIN_VERSION,
- this._plugin.id),
- this.onPrefVersionChanged, this);
- if (this._plugin.isEME) {
- Preferences.observe(GMPPrefs.KEY_EME_ENABLED,
- this.onPrefEMEGlobalEnabledChanged, this);
- messageManager.addMessageListener("EMEVideo:ContentMediaKeysRequest", this);
- }
-}
-
-GMPWrapper.prototype = {
- // An active task that checks for plugin updates and installs them.
- _updateTask: null,
- _gmpPath: null,
- _isUpdateCheckPending: false,
-
- optionsType: AddonManager.OPTIONS_TYPE_INLINE,
- get optionsURL() { return this._plugin.optionsURL; },
-
- set gmpPath(aPath) { this._gmpPath = aPath; },
- get gmpPath() {
- if (!this._gmpPath && this.isInstalled) {
- this._gmpPath = OS.Path.join(OS.Constants.Path.profileDir,
- this._plugin.id,
- GMPPrefs.get(GMPPrefs.KEY_PLUGIN_VERSION,
- null, this._plugin.id));
- }
- return this._gmpPath;
- },
-
- get id() { return this._plugin.id; },
- get type() { return "plugin"; },
- get isGMPlugin() { return true; },
- get name() { return this._plugin.name; },
- get creator() { return null; },
- get homepageURL() { return this._plugin.homepageURL; },
-
- get description() { return this._plugin.description; },
- get fullDescription() { return this._plugin.fullDescription; },
-
- get version() { return GMPPrefs.get(GMPPrefs.KEY_PLUGIN_VERSION, null,
- this._plugin.id); },
-
- get isActive() {
- return !this.appDisabled &&
- !this.userDisabled &&
- !GMPUtils.isPluginHidden(this._plugin);
- },
- get appDisabled() {
- if (this._plugin.isEME && !GMPPrefs.get(GMPPrefs.KEY_EME_ENABLED, true)) {
- // If "media.eme.enabled" is false, all EME plugins are disabled.
- return true;
- }
- return false;
- },
-
- get userDisabled() {
- return !GMPPrefs.get(GMPPrefs.KEY_PLUGIN_ENABLED, true, this._plugin.id);
- },
- set userDisabled(aVal) { GMPPrefs.set(GMPPrefs.KEY_PLUGIN_ENABLED,
- aVal === false,
- this._plugin.id); },
-
- get blocklistState() { return Ci.nsIBlocklistService.STATE_NOT_BLOCKED; },
- get size() { return 0; },
- get scope() { return AddonManager.SCOPE_APPLICATION; },
- get pendingOperations() { return AddonManager.PENDING_NONE; },
-
- get operationsRequiringRestart() { return AddonManager.OP_NEEDS_RESTART_NONE },
-
- get permissions() {
- let permissions = 0;
- if (!this.appDisabled) {
- permissions |= AddonManager.PERM_CAN_UPGRADE;
- permissions |= this.userDisabled ? AddonManager.PERM_CAN_ENABLE :
- AddonManager.PERM_CAN_DISABLE;
- }
- return permissions;
- },
-
- get updateDate() {
- let time = Number(GMPPrefs.get(GMPPrefs.KEY_PLUGIN_LAST_UPDATE, null,
- this._plugin.id));
- if (!isNaN(time) && this.isInstalled) {
- return new Date(time * 1000)
- }
- return null;
- },
-
- get isCompatible() {
- return true;
- },
-
- get isPlatformCompatible() {
- return true;
- },
-
- get providesUpdatesSecurely() {
- return true;
- },
-
- get foreignInstall() {
- return false;
- },
-
- isCompatibleWith: function(aAppVersion, aPlatformVersion) {
- return true;
- },
-
- get applyBackgroundUpdates() {
- if (!GMPPrefs.isSet(GMPPrefs.KEY_PLUGIN_AUTOUPDATE, this._plugin.id)) {
- return AddonManager.AUTOUPDATE_DEFAULT;
- }
-
- return GMPPrefs.get(GMPPrefs.KEY_PLUGIN_AUTOUPDATE, true, this._plugin.id) ?
- AddonManager.AUTOUPDATE_ENABLE : AddonManager.AUTOUPDATE_DISABLE;
- },
-
- set applyBackgroundUpdates(aVal) {
- if (aVal == AddonManager.AUTOUPDATE_DEFAULT) {
- GMPPrefs.reset(GMPPrefs.KEY_PLUGIN_AUTOUPDATE, this._plugin.id);
- } else if (aVal == AddonManager.AUTOUPDATE_ENABLE) {
- GMPPrefs.set(GMPPrefs.KEY_PLUGIN_AUTOUPDATE, true, this._plugin.id);
- } else if (aVal == AddonManager.AUTOUPDATE_DISABLE) {
- GMPPrefs.set(GMPPrefs.KEY_PLUGIN_AUTOUPDATE, false, this._plugin.id);
- }
- },
-
- findUpdates: function(aListener, aReason, aAppVersion, aPlatformVersion) {
- this._log.trace("findUpdates() - " + this._plugin.id + " - reason=" +
- aReason);
-
- AddonManagerPrivate.callNoUpdateListeners(this, aListener);
-
- if (aReason === AddonManager.UPDATE_WHEN_PERIODIC_UPDATE) {
- if (!AddonManager.shouldAutoUpdate(this)) {
- this._log.trace("findUpdates() - " + this._plugin.id +
- " - no autoupdate");
- return Promise.resolve(false);
- }
-
- let secSinceLastCheck =
- Date.now() / 1000 - Preferences.get(GMPPrefs.KEY_UPDATE_LAST_CHECK, 0);
- if (secSinceLastCheck <= SEC_IN_A_DAY) {
- this._log.trace("findUpdates() - " + this._plugin.id +
- " - last check was less then a day ago");
- return Promise.resolve(false);
- }
- } else if (aReason !== AddonManager.UPDATE_WHEN_USER_REQUESTED) {
- this._log.trace("findUpdates() - " + this._plugin.id +
- " - the given reason to update is not supported");
- return Promise.resolve(false);
- }
-
- if (this._updateTask !== null) {
- this._log.trace("findUpdates() - " + this._plugin.id +
- " - update task already running");
- return this._updateTask;
- }
-
- this._updateTask = Task.spawn(function*() {
- this._log.trace("findUpdates() - updateTask");
- try {
- let installManager = new GMPInstallManager();
- let res = yield installManager.checkForAddons();
- let update = res.gmpAddons.find(addon => addon.id === this._plugin.id);
- if (update && update.isValid && !update.isInstalled) {
- this._log.trace("findUpdates() - found update for " +
- this._plugin.id + ", installing");
- yield installManager.installAddon(update);
- } else {
- this._log.trace("findUpdates() - no updates for " + this._plugin.id);
- }
- this._log.info("findUpdates() - updateTask succeeded for " +
- this._plugin.id);
- } catch (e) {
- this._log.error("findUpdates() - updateTask for " + this._plugin.id +
- " threw", e);
- throw e;
- } finally {
- this._updateTask = null;
- return true;
- }
- }.bind(this));
-
- return this._updateTask;
- },
-
- get pluginMimeTypes() { return []; },
- get pluginLibraries() {
- if (this.isInstalled) {
- let path = this.version;
- return [path];
- }
- return [];
- },
- get pluginFullpath() {
- if (this.isInstalled) {
- let path = OS.Path.join(OS.Constants.Path.profileDir,
- this._plugin.id,
- this.version);
- return [path];
- }
- return [];
- },
-
- get isInstalled() {
- return this.version && this.version.length > 0;
- },
-
- _handleEnabledChanged: function() {
- this._log.info("_handleEnabledChanged() id=" +
- this._plugin.id + " isActive=" + this.isActive);
-
- AddonManagerPrivate.callAddonListeners(this.isActive ?
- "onEnabling" : "onDisabling",
- this, false);
- if (this._gmpPath) {
- if (this.isActive) {
- this._log.info("onPrefEnabledChanged() - adding gmp directory " +
- this._gmpPath);
- gmpService.addPluginDirectory(this._gmpPath);
- } else {
- this._log.info("onPrefEnabledChanged() - removing gmp directory " +
- this._gmpPath);
- gmpService.removePluginDirectory(this._gmpPath);
- }
- }
- AddonManagerPrivate.callAddonListeners(this.isActive ?
- "onEnabled" : "onDisabled",
- this);
- },
-
- onPrefEMEGlobalEnabledChanged: function() {
- this._log.info("onPrefEMEGlobalEnabledChanged() id=" + this._plugin.id +
- " appDisabled=" + this.appDisabled + " isActive=" + this.isActive +
- " hidden=" + GMPUtils.isPluginHidden(this._plugin));
-
- AddonManagerPrivate.callAddonListeners("onPropertyChanged", this,
- ["appDisabled"]);
- // If EME or the GMP itself are disabled, uninstall the GMP.
- // Otherwise, check for updates, so we download and install the GMP.
- if (this.appDisabled) {
- this.uninstallPlugin();
- } else if (!GMPUtils.isPluginHidden(this._plugin)) {
- AddonManagerPrivate.callInstallListeners("onExternalInstall", null, this,
- null, false);
- AddonManagerPrivate.callAddonListeners("onInstalling", this, false);
- AddonManagerPrivate.callAddonListeners("onInstalled", this);
- this.checkForUpdates(GMP_CHECK_DELAY);
- }
- if (!this.userDisabled) {
- this._handleEnabledChanged();
- }
- },
-
- checkForUpdates: function(delay) {
- if (this._isUpdateCheckPending) {
- return;
- }
- this._isUpdateCheckPending = true;
- GMPPrefs.reset(GMPPrefs.KEY_UPDATE_LAST_CHECK, null);
- // Delay this in case the user changes his mind and doesn't want to
- // enable EME after all.
- setTimeout(() => {
- if (!this.appDisabled) {
- let gmpInstallManager = new GMPInstallManager();
- // We don't really care about the results, if someone is interested
- // they can check the log.
- gmpInstallManager.simpleCheckAndInstall().then(null, () => {});
- }
- this._isUpdateCheckPending = false;
- }, delay);
- },
-
- receiveMessage: function({target: browser, data: data}) {
- this._log.trace("receiveMessage() data=" + data);
- let parsedData;
- try {
- parsedData = JSON.parse(data);
- } catch (ex) {
- this._log.error("Malformed EME video message with data: " + data);
- return;
- }
- let {status: status, keySystem: keySystem} = parsedData;
- if (status == "cdm-not-installed") {
- this.checkForUpdates(0);
- }
- },
-
- onPrefEnabledChanged: function() {
- if (!this._plugin.isEME || !this.appDisabled) {
- this._handleEnabledChanged();
- }
- },
-
- onPrefVersionChanged: function() {
- AddonManagerPrivate.callAddonListeners("onUninstalling", this, false);
- if (this._gmpPath) {
- this._log.info("onPrefVersionChanged() - unregistering gmp directory " +
- this._gmpPath);
- gmpService.removeAndDeletePluginDirectory(this._gmpPath, true /* can defer */);
- }
- AddonManagerPrivate.callAddonListeners("onUninstalled", this);
-
- AddonManagerPrivate.callInstallListeners("onExternalInstall", null, this,
- null, false);
- AddonManagerPrivate.callAddonListeners("onInstalling", this, false);
- this._gmpPath = null;
- if (this.isInstalled) {
- this._gmpPath = OS.Path.join(OS.Constants.Path.profileDir,
- this._plugin.id,
- GMPPrefs.get(GMPPrefs.KEY_PLUGIN_VERSION,
- null, this._plugin.id));
- }
- if (this._gmpPath && this.isActive) {
- this._log.info("onPrefVersionChanged() - registering gmp directory " +
- this._gmpPath);
- gmpService.addPluginDirectory(this._gmpPath);
- }
- AddonManagerPrivate.callAddonListeners("onInstalled", this);
- },
-
- uninstallPlugin: function() {
- AddonManagerPrivate.callAddonListeners("onUninstalling", this, false);
- if (this.gmpPath) {
- this._log.info("uninstallPlugin() - unregistering gmp directory " +
- this.gmpPath);
- gmpService.removeAndDeletePluginDirectory(this.gmpPath);
- }
- GMPPrefs.reset(GMPPrefs.KEY_PLUGIN_VERSION, this.id);
- GMPPrefs.reset(GMPPrefs.KEY_PLUGIN_ABI, this.id);
- GMPPrefs.reset(GMPPrefs.KEY_PLUGIN_LAST_UPDATE, this.id);
- AddonManagerPrivate.callAddonListeners("onUninstalled", this);
- },
-
- shutdown: function() {
- Preferences.ignore(GMPPrefs.getPrefKey(GMPPrefs.KEY_PLUGIN_ENABLED,
- this._plugin.id),
- this.onPrefEnabledChanged, this);
- Preferences.ignore(GMPPrefs.getPrefKey(GMPPrefs.KEY_PLUGIN_VERSION,
- this._plugin.id),
- this.onPrefVersionChanged, this);
- if (this._plugin.isEME) {
- Preferences.ignore(GMPPrefs.KEY_EME_ENABLED,
- this.onPrefEMEGlobalEnabledChanged, this);
- messageManager.removeMessageListener("EMEVideo:ContentMediaKeysRequest", this);
- }
- return this._updateTask;
- },
-
- _arePluginFilesOnDisk: function() {
- let fileExists = function(aGmpPath, aFileName) {
- let f = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- let path = OS.Path.join(aGmpPath, aFileName);
- f.initWithPath(path);
- return f.exists();
- };
-
- let id = this._plugin.id.substring(4);
- let libName = AppConstants.DLL_PREFIX + id + AppConstants.DLL_SUFFIX;
- let infoName;
- if (this._plugin.id == WIDEVINE_ID) {
- infoName = "manifest.json";
- } else {
- infoName = id + ".info";
- }
-
- return fileExists(this.gmpPath, libName) &&
- fileExists(this.gmpPath, infoName) &&
- (this._plugin.id != EME_ADOBE_ID || fileExists(this.gmpPath, id + ".voucher"));
- },
-
- validate: function() {
- if (!this.isInstalled) {
- // Not installed -> Valid.
- return {
- installed: false,
- valid: true
- };
- }
-
- let abi = GMPPrefs.get(GMPPrefs.KEY_PLUGIN_ABI, UpdateUtils.ABI, this._plugin.id);
- if (abi != UpdateUtils.ABI) {
- // ABI doesn't match. Possibly this is a profile migrated across platforms
- // or from 32 -> 64 bit.
- return {
- installed: true,
- mismatchedABI: true,
- valid: false
- };
- }
-
- // Installed -> Check if files are missing.
- let filesOnDisk = this._arePluginFilesOnDisk();
- return {
- installed: true,
- valid: filesOnDisk
- };
- },
-};
-
-var GMPProvider = {
- get name() { return "GMPProvider"; },
-
- _plugins: null,
-
- startup: function() {
- configureLogging();
- this._log = Log.repository.getLoggerWithMessagePrefix("Toolkit.GMP",
- "GMPProvider.");
- this.buildPluginList();
- this.ensureProperCDMInstallState();
-
- Preferences.observe(GMPPrefs.KEY_LOG_BASE, configureLogging);
-
- for (let [id, plugin] of this._plugins) {
- let wrapper = plugin.wrapper;
- let gmpPath = wrapper.gmpPath;
- let isEnabled = wrapper.isActive;
- this._log.trace("startup - enabled=" + isEnabled + ", gmpPath=" +
- gmpPath);
-
- if (gmpPath && isEnabled) {
- let validation = wrapper.validate();
- if (validation.mismatchedABI) {
- this._log.info("startup - gmp " + plugin.id +
- " mismatched ABI, uninstalling");
- wrapper.uninstallPlugin();
- continue;
- }
- if (!validation.valid) {
- this._log.info("startup - gmp " + plugin.id +
- " invalid, uninstalling");
- wrapper.uninstallPlugin();
- continue;
- }
- this._log.info("startup - adding gmp directory " + gmpPath);
- try {
- gmpService.addPluginDirectory(gmpPath);
- } catch (e) {
- if (e.name != 'NS_ERROR_NOT_AVAILABLE')
- throw e;
- this._log.warn("startup - adding gmp directory failed with " +
- e.name + " - sandboxing not available?", e);
- }
- }
- }
-
- try {
- let greDir = Services.dirsvc.get(NS_GRE_DIR,
- Ci.nsILocalFile);
- let clearkeyPath = OS.Path.join(greDir.path,
- CLEARKEY_PLUGIN_ID,
- CLEARKEY_VERSION);
- this._log.info("startup - adding clearkey CDM directory " +
- clearkeyPath);
- gmpService.addPluginDirectory(clearkeyPath);
- } catch (e) {
- this._log.warn("startup - adding clearkey CDM failed", e);
- }
- },
-
- shutdown: function() {
- this._log.trace("shutdown");
- Preferences.ignore(GMPPrefs.KEY_LOG_BASE, configureLogging);
-
- let shutdownTask = Task.spawn(function*() {
- this._log.trace("shutdown - shutdownTask");
- let shutdownSucceeded = true;
-
- for (let plugin of this._plugins.values()) {
- try {
- yield plugin.wrapper.shutdown();
- } catch (e) {
- shutdownSucceeded = false;
- }
- }
-
- this._plugins = null;
-
- if (!shutdownSucceeded) {
- throw new Error("Shutdown failed");
- }
- }.bind(this));
-
- return shutdownTask;
- },
-
- getAddonByID: function(aId, aCallback) {
- if (!this.isEnabled) {
- aCallback(null);
- return;
- }
-
- let plugin = this._plugins.get(aId);
- if (plugin && !GMPUtils.isPluginHidden(plugin)) {
- aCallback(plugin.wrapper);
- } else {
- aCallback(null);
- }
- },
-
- getAddonsByTypes: function(aTypes, aCallback) {
- if (!this.isEnabled ||
- (aTypes && aTypes.indexOf("plugin") < 0)) {
- aCallback([]);
- return;
- }
-
- let results = Array.from(this._plugins.values())
- .filter(p => !GMPUtils.isPluginHidden(p))
- .map(p => p.wrapper);
-
- aCallback(results);
- },
-
- get isEnabled() {
- return GMPPrefs.get(GMPPrefs.KEY_PROVIDER_ENABLED, false);
- },
-
- generateFullDescription: function(aPlugin) {
- let rv = [];
- for (let [urlProp, labelId] of [["learnMoreURL", GMP_LEARN_MORE],
- ["licenseURL", aPlugin.id == WIDEVINE_ID ?
- GMP_PRIVACY_INFO : GMP_LICENSE_INFO]]) {
- if (aPlugin[urlProp]) {
- let label = pluginsBundle.GetStringFromName(labelId);
- rv.push(`<xhtml:a href="${aPlugin[urlProp]}" target="_blank">${label}</xhtml:a>.`);
- }
- }
- return rv.length ? rv.join("<xhtml:br /><xhtml:br />") : undefined;
- },
-
- buildPluginList: function() {
- this._plugins = new Map();
- for (let aPlugin of GMP_PLUGINS) {
- let plugin = {
- id: aPlugin.id,
- name: pluginsBundle.GetStringFromName(aPlugin.name),
- description: pluginsBundle.GetStringFromName(aPlugin.description),
- homepageURL: aPlugin.homepageURL,
- optionsURL: aPlugin.optionsURL,
- wrapper: null,
- isEME: aPlugin.isEME,
- };
- plugin.fullDescription = this.generateFullDescription(aPlugin);
- plugin.wrapper = new GMPWrapper(plugin);
- this._plugins.set(plugin.id, plugin);
- }
- },
-
- ensureProperCDMInstallState: function() {
- if (!GMPPrefs.get(GMPPrefs.KEY_EME_ENABLED, true)) {
- for (let [id, plugin] of this._plugins) {
- if (plugin.isEME && plugin.wrapper.isInstalled) {
- gmpService.addPluginDirectory(plugin.wrapper.gmpPath);
- plugin.wrapper.uninstallPlugin();
- }
- }
- }
- },
-};
-
-AddonManagerPrivate.registerProvider(GMPProvider, [
- new AddonManagerPrivate.AddonType("plugin", URI_EXTENSION_STRINGS,
- STRING_TYPE_NAME,
- AddonManager.VIEW_TYPE_LIST, 6000,
- AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE)
-]);
diff --git a/toolkit/mozapps/webextensions/internal/LightweightThemeImageOptimizer.jsm b/toolkit/mozapps/webextensions/internal/LightweightThemeImageOptimizer.jsm
deleted file mode 100644
index 49dfa237f..000000000
--- a/toolkit/mozapps/webextensions/internal/LightweightThemeImageOptimizer.jsm
+++ /dev/null
@@ -1,180 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-this.EXPORTED_SYMBOLS = ["LightweightThemeImageOptimizer"];
-
-const Cu = Components.utils;
-const Ci = Components.interfaces;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Services",
- "resource://gre/modules/Services.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-
-const ORIGIN_TOP_RIGHT = 1;
-const ORIGIN_BOTTOM_LEFT = 2;
-
-this.LightweightThemeImageOptimizer = {
- optimize: function(aThemeData, aScreen) {
- let data = Object.assign({}, aThemeData);
- if (!data.headerURL) {
- return data;
- }
-
- data.headerURL = ImageCropper.getCroppedImageURL(
- data.headerURL, aScreen, ORIGIN_TOP_RIGHT);
-
- if (data.footerURL) {
- data.footerURL = ImageCropper.getCroppedImageURL(
- data.footerURL, aScreen, ORIGIN_BOTTOM_LEFT);
- }
-
- return data;
- },
-
- purge: function() {
- let dir = FileUtils.getDir("ProfD", ["lwtheme"]);
- dir.followLinks = false;
- try {
- dir.remove(true);
- } catch (e) {}
- }
-};
-
-Object.freeze(LightweightThemeImageOptimizer);
-
-var ImageCropper = {
- _inProgress: {},
-
- getCroppedImageURL: function(aImageURL, aScreen, aOrigin) {
- // We can crop local files, only.
- if (!aImageURL.startsWith("file://")) {
- return aImageURL;
- }
-
- // Generate the cropped image's file name using its
- // base name and the current screen size.
- let uri = Services.io.newURI(aImageURL, null, null);
- let file = uri.QueryInterface(Ci.nsIFileURL).file;
-
- // Make sure the source file exists.
- if (!file.exists()) {
- return aImageURL;
- }
-
- let fileName = file.leafName + "-" + aScreen.width + "x" + aScreen.height;
- let croppedFile = FileUtils.getFile("ProfD", ["lwtheme", fileName]);
-
- // If we have a local file that is not in progress, return it.
- if (croppedFile.exists() && !(croppedFile.path in this._inProgress)) {
- let fileURI = Services.io.newFileURI(croppedFile);
-
- // Copy the query part to avoid wrong caching.
- fileURI.QueryInterface(Ci.nsIURL).query = uri.query;
- return fileURI.spec;
- }
-
- // Crop the given image in the background.
- this._crop(uri, croppedFile, aScreen, aOrigin);
-
- // Return the original image while we're waiting for the cropped version
- // to be written to disk.
- return aImageURL;
- },
-
- _crop: function(aURI, aTargetFile, aScreen, aOrigin) {
- let inProgress = this._inProgress;
- inProgress[aTargetFile.path] = true;
-
- function resetInProgress() {
- delete inProgress[aTargetFile.path];
- }
-
- ImageFile.read(aURI, function(aInputStream, aContentType) {
- if (aInputStream && aContentType) {
- let image = ImageTools.decode(aInputStream, aContentType);
- if (image && image.width && image.height) {
- let stream = ImageTools.encode(image, aScreen, aOrigin, aContentType);
- if (stream) {
- ImageFile.write(aTargetFile, stream, resetInProgress);
- return;
- }
- }
- }
-
- resetInProgress();
- });
- }
-};
-
-var ImageFile = {
- read: function(aURI, aCallback) {
- this._netUtil.asyncFetch({
- uri: aURI,
- loadUsingSystemPrincipal: true,
- contentPolicyType: Ci.nsIContentPolicy.TYPE_INTERNAL_IMAGE
- }, function(aInputStream, aStatus, aRequest) {
- if (Components.isSuccessCode(aStatus) && aRequest instanceof Ci.nsIChannel) {
- let channel = aRequest.QueryInterface(Ci.nsIChannel);
- aCallback(aInputStream, channel.contentType);
- } else {
- aCallback();
- }
- });
- },
-
- write: function(aFile, aInputStream, aCallback) {
- let fos = FileUtils.openSafeFileOutputStream(aFile);
- this._netUtil.asyncCopy(aInputStream, fos, function(aResult) {
- FileUtils.closeSafeFileOutputStream(fos);
-
- // Remove the file if writing was not successful.
- if (!Components.isSuccessCode(aResult)) {
- try {
- aFile.remove(false);
- } catch (e) {}
- }
-
- aCallback();
- });
- }
-};
-
-XPCOMUtils.defineLazyModuleGetter(ImageFile, "_netUtil",
- "resource://gre/modules/NetUtil.jsm", "NetUtil");
-
-var ImageTools = {
- decode: function(aInputStream, aContentType) {
- let outParam = {value: null};
-
- try {
- this._imgTools.decodeImageData(aInputStream, aContentType, outParam);
- } catch (e) {}
-
- return outParam.value;
- },
-
- encode: function(aImage, aScreen, aOrigin, aContentType) {
- let stream;
- let width = Math.min(aImage.width, aScreen.width);
- let height = Math.min(aImage.height, aScreen.height);
- let x = aOrigin == ORIGIN_TOP_RIGHT ? aImage.width - width : 0;
-
- try {
- stream = this._imgTools.encodeCroppedImage(aImage, aContentType, x, 0,
- width, height);
- } catch (e) {}
-
- return stream;
- }
-};
-
-XPCOMUtils.defineLazyServiceGetter(ImageTools, "_imgTools",
- "@mozilla.org/image/tools;1", "imgITools");
-
diff --git a/toolkit/mozapps/webextensions/internal/PluginProvider.jsm b/toolkit/mozapps/webextensions/internal/PluginProvider.jsm
deleted file mode 100644
index 075159a9a..000000000
--- a/toolkit/mozapps/webextensions/internal/PluginProvider.jsm
+++ /dev/null
@@ -1,600 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
-
-this.EXPORTED_SYMBOLS = [];
-
-Cu.import("resource://gre/modules/AddonManager.jsm");
-/* globals AddonManagerPrivate*/
-Cu.import("resource://gre/modules/Services.jsm");
-
-const URI_EXTENSION_STRINGS = "chrome://mozapps/locale/extensions/extensions.properties";
-const STRING_TYPE_NAME = "type.%ID%.name";
-const LIST_UPDATED_TOPIC = "plugins-list-updated";
-const FLASH_MIME_TYPE = "application/x-shockwave-flash";
-
-Cu.import("resource://gre/modules/Log.jsm");
-const LOGGER_ID = "addons.plugins";
-
-// Create a new logger for use by the Addons Plugin Provider
-// (Requires AddonManager.jsm)
-var logger = Log.repository.getLogger(LOGGER_ID);
-
-function getIDHashForString(aStr) {
- // return the two-digit hexadecimal code for a byte
- let toHexString = charCode => ("0" + charCode.toString(16)).slice(-2);
-
- let hasher = Cc["@mozilla.org/security/hash;1"].
- createInstance(Ci.nsICryptoHash);
- hasher.init(Ci.nsICryptoHash.MD5);
- let stringStream = Cc["@mozilla.org/io/string-input-stream;1"].
- createInstance(Ci.nsIStringInputStream);
- stringStream.data = aStr ? aStr : "null";
- hasher.updateFromStream(stringStream, -1);
-
- // convert the binary hash data to a hex string.
- let binary = hasher.finish(false);
- let hash = Array.from(binary, c => toHexString(c.charCodeAt(0)));
- hash = hash.join("").toLowerCase();
- return "{" + hash.substr(0, 8) + "-" +
- hash.substr(8, 4) + "-" +
- hash.substr(12, 4) + "-" +
- hash.substr(16, 4) + "-" +
- hash.substr(20) + "}";
-}
-
-var PluginProvider = {
- get name() {
- return "PluginProvider";
- },
-
- // A dictionary mapping IDs to names and descriptions
- plugins: null,
-
- startup: function() {
- Services.obs.addObserver(this, LIST_UPDATED_TOPIC, false);
- Services.obs.addObserver(this, AddonManager.OPTIONS_NOTIFICATION_DISPLAYED, false);
- },
-
- /**
- * Called when the application is shutting down. Only necessary for tests
- * to be able to simulate a shutdown.
- */
- shutdown: function() {
- this.plugins = null;
- Services.obs.removeObserver(this, AddonManager.OPTIONS_NOTIFICATION_DISPLAYED);
- Services.obs.removeObserver(this, LIST_UPDATED_TOPIC);
- },
-
- observe: function(aSubject, aTopic, aData) {
- switch (aTopic) {
- case AddonManager.OPTIONS_NOTIFICATION_DISPLAYED:
- this.getAddonByID(aData, function(plugin) {
- if (!plugin)
- return;
-
- let libLabel = aSubject.getElementById("pluginLibraries");
- libLabel.textContent = plugin.pluginLibraries.join(", ");
-
- let typeLabel = aSubject.getElementById("pluginMimeTypes"), types = [];
- for (let type of plugin.pluginMimeTypes) {
- let extras = [type.description.trim(), type.suffixes].
- filter(x => x).join(": ");
- types.push(type.type + (extras ? " (" + extras + ")" : ""));
- }
- typeLabel.textContent = types.join(",\n");
- let showProtectedModePref = canDisableFlashProtectedMode(plugin);
- aSubject.getElementById("pluginEnableProtectedMode")
- .setAttribute("collapsed", showProtectedModePref ? "" : "true");
- });
- break;
- case LIST_UPDATED_TOPIC:
- if (this.plugins)
- this.updatePluginList();
- break;
- }
- },
-
- /**
- * Creates a PluginWrapper for a plugin object.
- */
- buildWrapper: function(aPlugin) {
- return new PluginWrapper(aPlugin.id,
- aPlugin.name,
- aPlugin.description,
- aPlugin.tags);
- },
-
- /**
- * Called to get an Addon with a particular ID.
- *
- * @param aId
- * The ID of the add-on to retrieve
- * @param aCallback
- * A callback to pass the Addon to
- */
- getAddonByID: function(aId, aCallback) {
- if (!this.plugins)
- this.buildPluginList();
-
- if (aId in this.plugins)
- aCallback(this.buildWrapper(this.plugins[aId]));
- else
- aCallback(null);
- },
-
- /**
- * Called to get Addons of a particular type.
- *
- * @param aTypes
- * An array of types to fetch. Can be null to get all types.
- * @param callback
- * A callback to pass an array of Addons to
- */
- getAddonsByTypes: function(aTypes, aCallback) {
- if (aTypes && aTypes.indexOf("plugin") < 0) {
- aCallback([]);
- return;
- }
-
- if (!this.plugins)
- this.buildPluginList();
-
- let results = [];
-
- for (let id in this.plugins)
- this.getAddonByID(id, (addon) => results.push(addon));
-
- aCallback(results);
- },
-
- /**
- * Called to get Addons that have pending operations.
- *
- * @param aTypes
- * An array of types to fetch. Can be null to get all types
- * @param aCallback
- * A callback to pass an array of Addons to
- */
- getAddonsWithOperationsByTypes: function(aTypes, aCallback) {
- aCallback([]);
- },
-
- /**
- * Called to get the current AddonInstalls, optionally restricting by type.
- *
- * @param aTypes
- * An array of types or null to get all types
- * @param aCallback
- * A callback to pass the array of AddonInstalls to
- */
- getInstallsByTypes: function(aTypes, aCallback) {
- aCallback([]);
- },
-
- /**
- * Builds a list of the current plugins reported by the plugin host
- *
- * @return a dictionary of plugins indexed by our generated ID
- */
- getPluginList: function() {
- let tags = Cc["@mozilla.org/plugin/host;1"].
- getService(Ci.nsIPluginHost).
- getPluginTags({});
-
- let list = {};
- let seenPlugins = {};
- for (let tag of tags) {
- if (!(tag.name in seenPlugins))
- seenPlugins[tag.name] = {};
- if (!(tag.description in seenPlugins[tag.name])) {
- let plugin = {
- id: getIDHashForString(tag.name + tag.description),
- name: tag.name,
- description: tag.description,
- tags: [tag]
- };
-
- seenPlugins[tag.name][tag.description] = plugin;
- list[plugin.id] = plugin;
- }
- else {
- seenPlugins[tag.name][tag.description].tags.push(tag);
- }
- }
-
- return list;
- },
-
- /**
- * Builds the list of known plugins from the plugin host
- */
- buildPluginList: function() {
- this.plugins = this.getPluginList();
- },
-
- /**
- * Updates the plugins from the plugin host by comparing the current plugins
- * to the last known list sending out any necessary API notifications for
- * changes.
- */
- updatePluginList: function() {
- let newList = this.getPluginList();
-
- let lostPlugins = Object.keys(this.plugins).filter(id => !(id in newList)).
- map(id => this.buildWrapper(this.plugins[id]));
- let newPlugins = Object.keys(newList).filter(id => !(id in this.plugins)).
- map(id => this.buildWrapper(newList[id]));
- let matchedIDs = Object.keys(newList).filter(id => id in this.plugins);
-
- // The plugin host generates new tags for every plugin after a scan and
- // if the plugin's filename has changed then the disabled state won't have
- // been carried across, send out notifications for anything that has
- // changed (see bug 830267).
- let changedWrappers = [];
- for (let id of matchedIDs) {
- let oldWrapper = this.buildWrapper(this.plugins[id]);
- let newWrapper = this.buildWrapper(newList[id]);
-
- if (newWrapper.isActive != oldWrapper.isActive) {
- AddonManagerPrivate.callAddonListeners(newWrapper.isActive ?
- "onEnabling" : "onDisabling",
- newWrapper, false);
- changedWrappers.push(newWrapper);
- }
- }
-
- // Notify about new installs
- for (let plugin of newPlugins) {
- AddonManagerPrivate.callInstallListeners("onExternalInstall", null,
- plugin, null, false);
- AddonManagerPrivate.callAddonListeners("onInstalling", plugin, false);
- }
-
- // Notify for any plugins that have vanished.
- for (let plugin of lostPlugins)
- AddonManagerPrivate.callAddonListeners("onUninstalling", plugin, false);
-
- this.plugins = newList;
-
- // Signal that new installs are complete
- for (let plugin of newPlugins)
- AddonManagerPrivate.callAddonListeners("onInstalled", plugin);
-
- // Signal that enables/disables are complete
- for (let wrapper of changedWrappers) {
- AddonManagerPrivate.callAddonListeners(wrapper.isActive ?
- "onEnabled" : "onDisabled",
- wrapper);
- }
-
- // Signal that uninstalls are complete
- for (let plugin of lostPlugins)
- AddonManagerPrivate.callAddonListeners("onUninstalled", plugin);
- }
-};
-
-function isFlashPlugin(aPlugin) {
- for (let type of aPlugin.pluginMimeTypes) {
- if (type.type == FLASH_MIME_TYPE) {
- return true;
- }
- }
- return false;
-}
-// Protected mode is win32-only, not win64
-function canDisableFlashProtectedMode(aPlugin) {
- return isFlashPlugin(aPlugin) && Services.appinfo.XPCOMABI == "x86-msvc";
-}
-
-const wrapperMap = new WeakMap();
-let pluginFor = wrapper => wrapperMap.get(wrapper);
-
-/**
- * The PluginWrapper wraps a set of nsIPluginTags to provide the data visible to
- * public callers through the API.
- */
-function PluginWrapper(id, name, description, tags) {
- wrapperMap.set(this, { id, name, description, tags });
-}
-
-PluginWrapper.prototype = {
- get id() {
- return pluginFor(this).id;
- },
-
- get type() {
- return "plugin";
- },
-
- get name() {
- return pluginFor(this).name;
- },
-
- get creator() {
- return null;
- },
-
- get description() {
- return pluginFor(this).description.replace(/<\/?[a-z][^>]*>/gi, " ");
- },
-
- get version() {
- let { tags: [tag] } = pluginFor(this);
- return tag.version;
- },
-
- get homepageURL() {
- let { description } = pluginFor(this);
- if (/<A\s+HREF=[^>]*>/i.test(description))
- return /<A\s+HREF=["']?([^>"'\s]*)/i.exec(description)[1];
- return null;
- },
-
- get isActive() {
- let { tags: [tag] } = pluginFor(this);
- return !tag.blocklisted && !tag.disabled;
- },
-
- get appDisabled() {
- let { tags: [tag] } = pluginFor(this);
- return tag.blocklisted;
- },
-
- get userDisabled() {
- let { tags: [tag] } = pluginFor(this);
- if (tag.disabled)
- return true;
-
- if ((Services.prefs.getBoolPref("plugins.click_to_play") && tag.clicktoplay) ||
- this.blocklistState == Ci.nsIBlocklistService.STATE_VULNERABLE_UPDATE_AVAILABLE ||
- this.blocklistState == Ci.nsIBlocklistService.STATE_VULNERABLE_NO_UPDATE)
- return AddonManager.STATE_ASK_TO_ACTIVATE;
-
- return false;
- },
-
- set userDisabled(val) {
- let previousVal = this.userDisabled;
- if (val === previousVal)
- return val;
-
- let { tags } = pluginFor(this);
-
- for (let tag of tags) {
- if (val === true)
- tag.enabledState = Ci.nsIPluginTag.STATE_DISABLED;
- else if (val === false)
- tag.enabledState = Ci.nsIPluginTag.STATE_ENABLED;
- else if (val == AddonManager.STATE_ASK_TO_ACTIVATE)
- tag.enabledState = Ci.nsIPluginTag.STATE_CLICKTOPLAY;
- }
-
- // If 'userDisabled' was 'true' and we're going to a state that's not
- // that, we're enabling, so call those listeners.
- if (previousVal === true && val !== true) {
- AddonManagerPrivate.callAddonListeners("onEnabling", this, false);
- AddonManagerPrivate.callAddonListeners("onEnabled", this);
- }
-
- // If 'userDisabled' was not 'true' and we're going to a state where
- // it is, we're disabling, so call those listeners.
- if (previousVal !== true && val === true) {
- AddonManagerPrivate.callAddonListeners("onDisabling", this, false);
- AddonManagerPrivate.callAddonListeners("onDisabled", this);
- }
-
- // If the 'userDisabled' value involved AddonManager.STATE_ASK_TO_ACTIVATE,
- // call the onPropertyChanged listeners.
- if (previousVal == AddonManager.STATE_ASK_TO_ACTIVATE ||
- val == AddonManager.STATE_ASK_TO_ACTIVATE) {
- AddonManagerPrivate.callAddonListeners("onPropertyChanged", this, ["userDisabled"]);
- }
-
- return val;
- },
-
- get blocklistState() {
- let { tags: [tag] } = pluginFor(this);
- let bs = Cc["@mozilla.org/extensions/blocklist;1"].
- getService(Ci.nsIBlocklistService);
- return bs.getPluginBlocklistState(tag);
- },
-
- get blocklistURL() {
- let { tags: [tag] } = pluginFor(this);
- let bs = Cc["@mozilla.org/extensions/blocklist;1"].
- getService(Ci.nsIBlocklistService);
- return bs.getPluginBlocklistURL(tag);
- },
-
- get size() {
- function getDirectorySize(aFile) {
- let size = 0;
- let entries = aFile.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
- let entry;
- while ((entry = entries.nextFile)) {
- if (entry.isSymlink() || !entry.isDirectory())
- size += entry.fileSize;
- else
- size += getDirectorySize(entry);
- }
- entries.close();
- return size;
- }
-
- let size = 0;
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- for (let tag of pluginFor(this).tags) {
- file.initWithPath(tag.fullpath);
- if (file.isDirectory())
- size += getDirectorySize(file);
- else
- size += file.fileSize;
- }
- return size;
- },
-
- get pluginLibraries() {
- let libs = [];
- for (let tag of pluginFor(this).tags)
- libs.push(tag.filename);
- return libs;
- },
-
- get pluginFullpath() {
- let paths = [];
- for (let tag of pluginFor(this).tags)
- paths.push(tag.fullpath);
- return paths;
- },
-
- get pluginMimeTypes() {
- let types = [];
- for (let tag of pluginFor(this).tags) {
- let mimeTypes = tag.getMimeTypes({});
- let mimeDescriptions = tag.getMimeDescriptions({});
- let extensions = tag.getExtensions({});
- for (let i = 0; i < mimeTypes.length; i++) {
- let type = {};
- type.type = mimeTypes[i];
- type.description = mimeDescriptions[i];
- type.suffixes = extensions[i];
-
- types.push(type);
- }
- }
- return types;
- },
-
- get installDate() {
- let date = 0;
- for (let tag of pluginFor(this).tags) {
- date = Math.max(date, tag.lastModifiedTime);
- }
- return new Date(date);
- },
-
- get scope() {
- let { tags: [tag] } = pluginFor(this);
- let path = tag.fullpath;
- // Plugins inside the application directory are in the application scope
- let dir = Services.dirsvc.get("APlugns", Ci.nsIFile);
- if (path.startsWith(dir.path))
- return AddonManager.SCOPE_APPLICATION;
-
- // Plugins inside the profile directory are in the profile scope
- dir = Services.dirsvc.get("ProfD", Ci.nsIFile);
- if (path.startsWith(dir.path))
- return AddonManager.SCOPE_PROFILE;
-
- // Plugins anywhere else in the user's home are in the user scope,
- // but not all platforms have a home directory.
- try {
- dir = Services.dirsvc.get("Home", Ci.nsIFile);
- if (path.startsWith(dir.path))
- return AddonManager.SCOPE_USER;
- } catch (e) {
- if (!e.result || e.result != Components.results.NS_ERROR_FAILURE)
- throw e;
- // Do nothing: missing "Home".
- }
-
- // Any other locations are system scope
- return AddonManager.SCOPE_SYSTEM;
- },
-
- get pendingOperations() {
- return AddonManager.PENDING_NONE;
- },
-
- get operationsRequiringRestart() {
- return AddonManager.OP_NEEDS_RESTART_NONE;
- },
-
- get permissions() {
- let { tags: [tag] } = pluginFor(this);
- let permissions = 0;
- if (tag.isEnabledStateLocked) {
- return permissions;
- }
- if (!this.appDisabled) {
-
- if (this.userDisabled !== true)
- permissions |= AddonManager.PERM_CAN_DISABLE;
-
- let blocklistState = this.blocklistState;
- let isCTPBlocklisted =
- (blocklistState == Ci.nsIBlocklistService.STATE_VULNERABLE_NO_UPDATE ||
- blocklistState == Ci.nsIBlocklistService.STATE_VULNERABLE_UPDATE_AVAILABLE);
-
- if (this.userDisabled !== AddonManager.STATE_ASK_TO_ACTIVATE &&
- (Services.prefs.getBoolPref("plugins.click_to_play") ||
- isCTPBlocklisted)) {
- permissions |= AddonManager.PERM_CAN_ASK_TO_ACTIVATE;
- }
-
- if (this.userDisabled !== false && !isCTPBlocklisted) {
- permissions |= AddonManager.PERM_CAN_ENABLE;
- }
- }
- return permissions;
- },
-
- get optionsType() {
- if (canDisableFlashProtectedMode(this)) {
- return AddonManager.OPTIONS_TYPE_INLINE;
- }
- return AddonManager.OPTIONS_TYPE_INLINE_INFO;
- },
-
- get optionsURL() {
- return "chrome://mozapps/content/extensions/pluginPrefs.xul";
- },
-
- get updateDate() {
- return this.installDate;
- },
-
- get isCompatible() {
- return true;
- },
-
- get isPlatformCompatible() {
- return true;
- },
-
- get providesUpdatesSecurely() {
- return true;
- },
-
- get foreignInstall() {
- return true;
- },
-
- isCompatibleWith: function(aAppVersion, aPlatformVersion) {
- return true;
- },
-
- findUpdates: function(aListener, aReason, aAppVersion, aPlatformVersion) {
- if ("onNoCompatibilityUpdateAvailable" in aListener)
- aListener.onNoCompatibilityUpdateAvailable(this);
- if ("onNoUpdateAvailable" in aListener)
- aListener.onNoUpdateAvailable(this);
- if ("onUpdateFinished" in aListener)
- aListener.onUpdateFinished(this);
- }
-};
-
-AddonManagerPrivate.registerProvider(PluginProvider, [
- new AddonManagerPrivate.AddonType("plugin", URI_EXTENSION_STRINGS,
- STRING_TYPE_NAME,
- AddonManager.VIEW_TYPE_LIST, 6000,
- AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE)
-]);
diff --git a/toolkit/mozapps/webextensions/internal/WebExtensionBootstrap.js b/toolkit/mozapps/webextensions/internal/WebExtensionBootstrap.js
deleted file mode 100644
index a920c2eae..000000000
--- a/toolkit/mozapps/webextensions/internal/WebExtensionBootstrap.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-Components.utils.import("resource://gre/modules/Extension.jsm");
-
-var extension;
-
-const BOOTSTRAP_REASON_TO_STRING_MAP = {
- 1: "APP_STARTUP",
- 2: "APP_SHUTDOWN",
- 3: "ADDON_ENABLE",
- 4: "ADDON_DISABLE",
- 5: "ADDON_INSTALL",
- 6: "ADDON_UNINSTALL",
- 7: "ADDON_UPGRADE",
- 8: "ADDON_DOWNGRADE",
-}
-
-function install(data, reason)
-{
-}
-
-function startup(data, reason)
-{
- extension = new Extension(data, BOOTSTRAP_REASON_TO_STRING_MAP[reason]);
- extension.startup();
-}
-
-function shutdown(data, reason)
-{
- extension.shutdown();
-}
-
-function uninstall(data, reason)
-{
-}
diff --git a/toolkit/mozapps/webextensions/internal/XPIProvider.jsm b/toolkit/mozapps/webextensions/internal/XPIProvider.jsm
deleted file mode 100644
index c95221417..000000000
--- a/toolkit/mozapps/webextensions/internal/XPIProvider.jsm
+++ /dev/null
@@ -1,9217 +0,0 @@
- /* 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/. */
-
-"use strict";
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cr = Components.results;
-const Cu = Components.utils;
-
-this.EXPORTED_SYMBOLS = ["XPIProvider"];
-
-const CONSTANTS = {};
-Cu.import("resource://gre/modules/addons/AddonConstants.jsm", CONSTANTS);
-const { ADDON_SIGNING, REQUIRE_SIGNING } = CONSTANTS
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/AddonManager.jsm");
-Cu.import("resource://gre/modules/Preferences.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "AddonRepository",
- "resource://gre/modules/addons/AddonRepository.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ChromeManifestParser",
- "resource://gre/modules/ChromeManifestParser.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "LightweightThemeManager",
- "resource://gre/modules/LightweightThemeManager.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ExtensionData",
- "resource://gre/modules/Extension.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ExtensionManagement",
- "resource://gre/modules/ExtensionManagement.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Locale",
- "resource://gre/modules/Locale.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ZipUtils",
- "resource://gre/modules/ZipUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PermissionsUtils",
- "resource://gre/modules/PermissionsUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "OS",
- "resource://gre/modules/osfile.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "BrowserToolboxProcess",
- "resource://devtools/client/framework/ToolboxProcess.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ConsoleAPI",
- "resource://gre/modules/Console.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ProductAddonChecker",
- "resource://gre/modules/addons/ProductAddonChecker.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "UpdateUtils",
- "resource://gre/modules/UpdateUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
- "resource://gre/modules/AppConstants.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "LegacyExtensionsUtils",
- "resource://gre/modules/LegacyExtensionsUtils.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "Blocklist",
- "@mozilla.org/extensions/blocklist;1",
- Ci.nsIBlocklistService);
-XPCOMUtils.defineLazyServiceGetter(this,
- "ChromeRegistry",
- "@mozilla.org/chrome/chrome-registry;1",
- "nsIChromeRegistry");
-XPCOMUtils.defineLazyServiceGetter(this,
- "ResProtocolHandler",
- "@mozilla.org/network/protocol;1?name=resource",
- "nsIResProtocolHandler");
-XPCOMUtils.defineLazyServiceGetter(this,
- "AddonPolicyService",
- "@mozilla.org/addons/policy-service;1",
- "nsIAddonPolicyService");
-XPCOMUtils.defineLazyServiceGetter(this,
- "AddonPathService",
- "@mozilla.org/addon-path-service;1",
- "amIAddonPathService");
-
-XPCOMUtils.defineLazyGetter(this, "CertUtils", function() {
- let certUtils = {};
- Components.utils.import("resource://gre/modules/CertUtils.jsm", certUtils);
- return certUtils;
-});
-
-Cu.importGlobalProperties(["URL"]);
-
-const nsIFile = Components.Constructor("@mozilla.org/file/local;1", "nsIFile",
- "initWithPath");
-
-const PREF_DB_SCHEMA = "extensions.databaseSchema";
-const PREF_INSTALL_CACHE = "extensions.installCache";
-const PREF_XPI_STATE = "extensions.xpiState";
-const PREF_BOOTSTRAP_ADDONS = "extensions.bootstrappedAddons";
-const PREF_PENDING_OPERATIONS = "extensions.pendingOperations";
-const PREF_EM_DSS_ENABLED = "extensions.dss.enabled";
-const PREF_DSS_SWITCHPENDING = "extensions.dss.switchPending";
-const PREF_DSS_SKIN_TO_SELECT = "extensions.lastSelectedSkin";
-const PREF_GENERAL_SKINS_SELECTEDSKIN = "general.skins.selectedSkin";
-const PREF_EM_UPDATE_URL = "extensions.update.url";
-const PREF_EM_UPDATE_BACKGROUND_URL = "extensions.update.background.url";
-const PREF_EM_ENABLED_ADDONS = "extensions.enabledAddons";
-const PREF_EM_EXTENSION_FORMAT = "extensions.";
-const PREF_EM_ENABLED_SCOPES = "extensions.enabledScopes";
-const PREF_EM_SHOW_MISMATCH_UI = "extensions.showMismatchUI";
-const PREF_XPI_ENABLED = "xpinstall.enabled";
-const PREF_XPI_WHITELIST_REQUIRED = "xpinstall.whitelist.required";
-const PREF_XPI_DIRECT_WHITELISTED = "xpinstall.whitelist.directRequest";
-const PREF_XPI_FILE_WHITELISTED = "xpinstall.whitelist.fileRequest";
-// xpinstall.signatures.required only supported in dev builds
-const PREF_XPI_SIGNATURES_REQUIRED = "xpinstall.signatures.required";
-const PREF_XPI_SIGNATURES_DEV_ROOT = "xpinstall.signatures.dev-root";
-const PREF_XPI_PERMISSIONS_BRANCH = "xpinstall.";
-const PREF_XPI_UNPACK = "extensions.alwaysUnpack";
-const PREF_INSTALL_REQUIREBUILTINCERTS = "extensions.install.requireBuiltInCerts";
-const PREF_INSTALL_REQUIRESECUREORIGIN = "extensions.install.requireSecureOrigin";
-const PREF_INSTALL_DISTRO_ADDONS = "extensions.installDistroAddons";
-const PREF_BRANCH_INSTALLED_ADDON = "extensions.installedDistroAddon.";
-const PREF_INTERPOSITION_ENABLED = "extensions.interposition.enabled";
-const PREF_SYSTEM_ADDON_SET = "extensions.systemAddonSet";
-const PREF_SYSTEM_ADDON_UPDATE_URL = "extensions.systemAddon.update.url";
-
-const PREF_EM_MIN_COMPAT_APP_VERSION = "extensions.minCompatibleAppVersion";
-const PREF_EM_MIN_COMPAT_PLATFORM_VERSION = "extensions.minCompatiblePlatformVersion";
-
-const PREF_EM_HOTFIX_ID = "extensions.hotfix.id";
-const PREF_EM_CERT_CHECKATTRIBUTES = "extensions.hotfix.cert.checkAttributes";
-const PREF_EM_HOTFIX_CERTS = "extensions.hotfix.certs.";
-
-const URI_EXTENSION_UPDATE_DIALOG = "chrome://mozapps/content/extensions/update.xul";
-const URI_EXTENSION_STRINGS = "chrome://mozapps/locale/extensions/extensions.properties";
-
-const STRING_TYPE_NAME = "type.%ID%.name";
-
-const DIR_EXTENSIONS = "extensions";
-const DIR_SYSTEM_ADDONS = "features";
-const DIR_STAGE = "staged";
-const DIR_TRASH = "trash";
-
-const FILE_DATABASE = "extensions.json";
-const FILE_OLD_CACHE = "extensions.cache";
-const FILE_RDF_MANIFEST = "install.rdf";
-const FILE_WEB_MANIFEST = "manifest.json";
-const FILE_XPI_ADDONS_LIST = "extensions.ini";
-
-const KEY_PROFILEDIR = "ProfD";
-const KEY_ADDON_APP_DIR = "XREAddonAppDir";
-const KEY_TEMPDIR = "TmpD";
-const KEY_APP_DISTRIBUTION = "XREAppDist";
-const KEY_APP_FEATURES = "XREAppFeat";
-
-const KEY_APP_PROFILE = "app-profile";
-const KEY_APP_SYSTEM_ADDONS = "app-system-addons";
-const KEY_APP_SYSTEM_DEFAULTS = "app-system-defaults";
-const KEY_APP_GLOBAL = "app-global";
-const KEY_APP_SYSTEM_LOCAL = "app-system-local";
-const KEY_APP_SYSTEM_SHARE = "app-system-share";
-const KEY_APP_SYSTEM_USER = "app-system-user";
-const KEY_APP_TEMPORARY = "app-temporary";
-
-const NOTIFICATION_FLUSH_PERMISSIONS = "flush-pending-permissions";
-const XPI_PERMISSION = "install";
-
-const RDFURI_INSTALL_MANIFEST_ROOT = "urn:mozilla:install-manifest";
-const PREFIX_NS_EM = "http://www.mozilla.org/2004/em-rdf#";
-
-const TOOLKIT_ID = "toolkit@mozilla.org";
-const WEBEXTENSIONS_ID = "webextensions@mozilla.org";
-const WEBEXTENSIONS_VERSION = "52.0";
-
-const XPI_SIGNATURE_CHECK_PERIOD = 24 * 60 * 60;
-
-XPCOMUtils.defineConstant(this, "DB_SCHEMA", 19);
-
-const NOTIFICATION_TOOLBOXPROCESS_LOADED = "ToolboxProcessLoaded";
-
-// Properties that exist in the install manifest
-const PROP_METADATA = ["id", "version", "type", "internalName", "updateURL",
- "updateKey", "optionsURL", "optionsType", "aboutURL",
- "iconURL", "icon64URL"];
-const PROP_LOCALE_SINGLE = ["name", "description", "creator", "homepageURL"];
-const PROP_LOCALE_MULTI = ["developers", "translators", "contributors"];
-const PROP_TARGETAPP = ["id", "minVersion", "maxVersion"];
-
-// Properties to cache and reload when an addon installation is pending
-const PENDING_INSTALL_METADATA =
- ["syncGUID", "targetApplications", "userDisabled", "softDisabled",
- "existingAddonID", "sourceURI", "releaseNotesURI", "installDate",
- "updateDate", "applyBackgroundUpdates", "compatibilityOverrides"];
-
-// Note: When adding/changing/removing items here, remember to change the
-// DB schema version to ensure changes are picked up ASAP.
-const STATIC_BLOCKLIST_PATTERNS = [
- { creator: "Mozilla Corp.",
- level: Blocklist.STATE_BLOCKED,
- blockID: "i162" },
- { creator: "Mozilla.org",
- level: Blocklist.STATE_BLOCKED,
- blockID: "i162" }
-];
-
-
-const BOOTSTRAP_REASONS = {
- APP_STARTUP : 1,
- APP_SHUTDOWN : 2,
- ADDON_ENABLE : 3,
- ADDON_DISABLE : 4,
- ADDON_INSTALL : 5,
- ADDON_UNINSTALL : 6,
- ADDON_UPGRADE : 7,
- ADDON_DOWNGRADE : 8
-};
-
-// Map new string type identifiers to old style nsIUpdateItem types
-const TYPES = {
- extension: 2,
- theme: 4,
- locale: 8,
- multipackage: 32,
- dictionary: 64,
- experiment: 128,
-};
-
-if (!AppConstants.RELEASE_OR_BETA)
- TYPES.apiextension = 256;
-
-// Some add-on types that we track internally are presented as other types
-// externally
-const TYPE_ALIASES = {
- "webextension": "extension",
- "apiextension": "extension",
-};
-
-const CHROME_TYPES = new Set([
- "extension",
- "locale",
- "experiment",
-]);
-
-const RESTARTLESS_TYPES = new Set([
- "webextension",
- "dictionary",
- "experiment",
- "locale",
- "apiextension",
-]);
-
-const SIGNED_TYPES = new Set([
- "webextension",
- "extension",
- "experiment",
- "apiextension",
-]);
-
-// This is a random number array that can be used as "salt" when generating
-// an automatic ID based on the directory path of an add-on. It will prevent
-// someone from creating an ID for a permanent add-on that could be replaced
-// by a temporary add-on (because that would be confusing, I guess).
-const TEMP_INSTALL_ID_GEN_SESSION =
- new Uint8Array(Float64Array.of(Math.random()).buffer);
-
-// Whether add-on signing is required.
-function mustSign(aType) {
- if (!SIGNED_TYPES.has(aType))
- return false;
- return REQUIRE_SIGNING || Preferences.get(PREF_XPI_SIGNATURES_REQUIRED, false);
-}
-
-// Keep track of where we are in startup for telemetry
-// event happened during XPIDatabase.startup()
-const XPI_STARTING = "XPIStarting";
-// event happened after startup() but before the final-ui-startup event
-const XPI_BEFORE_UI_STARTUP = "BeforeFinalUIStartup";
-// event happened after final-ui-startup
-const XPI_AFTER_UI_STARTUP = "AfterFinalUIStartup";
-
-const COMPATIBLE_BY_DEFAULT_TYPES = {
- extension: true,
- dictionary: true
-};
-
-const MSG_JAR_FLUSH = "AddonJarFlush";
-const MSG_MESSAGE_MANAGER_CACHES_FLUSH = "AddonMessageManagerCachesFlush";
-
-var gGlobalScope = this;
-
-/**
- * Valid IDs fit this pattern.
- */
-var gIDTest = /^(\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}|[a-z0-9-\._]*\@[a-z0-9-\._]+)$/i;
-
-Cu.import("resource://gre/modules/Log.jsm");
-const LOGGER_ID = "addons.xpi";
-
-// Create a new logger for use by all objects in this Addons XPI Provider module
-// (Requires AddonManager.jsm)
-var logger = Log.repository.getLogger(LOGGER_ID);
-
-const LAZY_OBJECTS = ["XPIDatabase", "XPIDatabaseReconcile"];
-/* globals XPIDatabase, XPIDatabaseReconcile*/
-
-var gLazyObjectsLoaded = false;
-
-function loadLazyObjects() {
- let uri = "resource://gre/modules/addons/XPIProviderUtils.js";
- let scope = Cu.Sandbox(Services.scriptSecurityManager.getSystemPrincipal(), {
- sandboxName: uri,
- wantGlobalProperties: ["TextDecoder"],
- });
-
- let shared = {
- ADDON_SIGNING,
- SIGNED_TYPES,
- BOOTSTRAP_REASONS,
- DB_SCHEMA,
- AddonInternal,
- XPIProvider,
- XPIStates,
- syncLoadManifestFromFile,
- isUsableAddon,
- recordAddonTelemetry,
- applyBlocklistChanges,
- flushChromeCaches,
- canRunInSafeMode,
- }
-
- for (let key of Object.keys(shared))
- scope[key] = shared[key];
-
- Services.scriptloader.loadSubScript(uri, scope);
-
- for (let name of LAZY_OBJECTS) {
- delete gGlobalScope[name];
- gGlobalScope[name] = scope[name];
- }
- gLazyObjectsLoaded = true;
- return scope;
-}
-
-LAZY_OBJECTS.forEach(name => {
- Object.defineProperty(gGlobalScope, name, {
- get: function() {
- let objs = loadLazyObjects();
- return objs[name];
- },
- configurable: true
- });
-});
-
-
-// Behaves like Promise.all except waits for all promises to resolve/reject
-// before resolving/rejecting itself
-function waitForAllPromises(promises) {
- return new Promise((resolve, reject) => {
- let shouldReject = false;
- let rejectValue = null;
-
- let newPromises = promises.map(
- p => p.catch(value => {
- shouldReject = true;
- rejectValue = value;
- })
- );
- Promise.all(newPromises)
- .then((results) => shouldReject ? reject(rejectValue) : resolve(results));
- });
-}
-
-function findMatchingStaticBlocklistItem(aAddon) {
- for (let item of STATIC_BLOCKLIST_PATTERNS) {
- if ("creator" in item && typeof item.creator == "string") {
- if ((aAddon.defaultLocale && aAddon.defaultLocale.creator == item.creator) ||
- (aAddon.selectedLocale && aAddon.selectedLocale.creator == item.creator)) {
- return item;
- }
- }
- }
- return null;
-}
-
-/**
- * Converts an iterable of addon objects into a map with the add-on's ID as key.
- */
-function addonMap(addons) {
- return new Map(addons.map(a => [a.id, a]));
-}
-
-/**
- * Sets permissions on a file
- *
- * @param aFile
- * The file or directory to operate on.
- * @param aPermissions
- * The permisions to set
- */
-function setFilePermissions(aFile, aPermissions) {
- try {
- aFile.permissions = aPermissions;
- }
- catch (e) {
- logger.warn("Failed to set permissions " + aPermissions.toString(8) + " on " +
- aFile.path, e);
- }
-}
-
-/**
- * Write a given string to a file
- *
- * @param file
- * The nsIFile instance to write into
- * @param string
- * The string to write
- */
-function writeStringToFile(file, string) {
- let stream = Cc["@mozilla.org/network/file-output-stream;1"].
- createInstance(Ci.nsIFileOutputStream);
- let converter = Cc["@mozilla.org/intl/converter-output-stream;1"].
- createInstance(Ci.nsIConverterOutputStream);
-
- try {
- stream.init(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE |
- FileUtils.MODE_TRUNCATE, FileUtils.PERMS_FILE,
- 0);
- converter.init(stream, "UTF-8", 0, 0x0000);
- converter.writeString(string);
- }
- finally {
- converter.close();
- stream.close();
- }
-}
-
-/**
- * A safe way to install a file or the contents of a directory to a new
- * directory. The file or directory is moved or copied recursively and if
- * anything fails an attempt is made to rollback the entire operation. The
- * operation may also be rolled back to its original state after it has
- * completed by calling the rollback method.
- *
- * Operations can be chained. Calling move or copy multiple times will remember
- * the whole set and if one fails all of the operations will be rolled back.
- */
-function SafeInstallOperation() {
- this._installedFiles = [];
- this._createdDirs = [];
-}
-
-SafeInstallOperation.prototype = {
- _installedFiles: null,
- _createdDirs: null,
-
- _installFile: function(aFile, aTargetDirectory, aCopy) {
- let oldFile = aCopy ? null : aFile.clone();
- let newFile = aFile.clone();
- try {
- if (aCopy) {
- newFile.copyTo(aTargetDirectory, null);
- // copyTo does not update the nsIFile with the new.
- newFile = aTargetDirectory.clone();
- newFile.append(aFile.leafName);
- // Windows roaming profiles won't properly sync directories if a new file
- // has an older lastModifiedTime than a previous file, so update.
- newFile.lastModifiedTime = Date.now();
- }
- else {
- newFile.moveTo(aTargetDirectory, null);
- }
- }
- catch (e) {
- logger.error("Failed to " + (aCopy ? "copy" : "move") + " file " + aFile.path +
- " to " + aTargetDirectory.path, e);
- throw e;
- }
- this._installedFiles.push({ oldFile: oldFile, newFile: newFile });
- },
-
- _installDirectory: function(aDirectory, aTargetDirectory, aCopy) {
- if (aDirectory.contains(aTargetDirectory)) {
- let err = new Error(`Not installing ${aDirectory} into its own descendent ${aTargetDirectory}`);
- logger.error(err);
- throw err;
- }
-
- let newDir = aTargetDirectory.clone();
- newDir.append(aDirectory.leafName);
- try {
- newDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
- }
- catch (e) {
- logger.error("Failed to create directory " + newDir.path, e);
- throw e;
- }
- this._createdDirs.push(newDir);
-
- // Use a snapshot of the directory contents to avoid possible issues with
- // iterating over a directory while removing files from it (the YAFFS2
- // embedded filesystem has this issue, see bug 772238), and to remove
- // normal files before their resource forks on OSX (see bug 733436).
- let entries = getDirectoryEntries(aDirectory, true);
- for (let entry of entries) {
- try {
- this._installDirEntry(entry, newDir, aCopy);
- }
- catch (e) {
- logger.error("Failed to " + (aCopy ? "copy" : "move") + " entry " +
- entry.path, e);
- throw e;
- }
- }
-
- // If this is only a copy operation then there is nothing else to do
- if (aCopy)
- return;
-
- // The directory should be empty by this point. If it isn't this will throw
- // and all of the operations will be rolled back
- try {
- setFilePermissions(aDirectory, FileUtils.PERMS_DIRECTORY);
- aDirectory.remove(false);
- }
- catch (e) {
- logger.error("Failed to remove directory " + aDirectory.path, e);
- throw e;
- }
-
- // Note we put the directory move in after all the file moves so the
- // directory is recreated before all the files are moved back
- this._installedFiles.push({ oldFile: aDirectory, newFile: newDir });
- },
-
- _installDirEntry: function(aDirEntry, aTargetDirectory, aCopy) {
- let isDir = null;
-
- try {
- isDir = aDirEntry.isDirectory() && !aDirEntry.isSymlink();
- }
- catch (e) {
- // If the file has already gone away then don't worry about it, this can
- // happen on OSX where the resource fork is automatically moved with the
- // data fork for the file. See bug 733436.
- if (e.result == Cr.NS_ERROR_FILE_TARGET_DOES_NOT_EXIST)
- return;
-
- logger.error("Failure " + (aCopy ? "copying" : "moving") + " " + aDirEntry.path +
- " to " + aTargetDirectory.path);
- throw e;
- }
-
- try {
- if (isDir)
- this._installDirectory(aDirEntry, aTargetDirectory, aCopy);
- else
- this._installFile(aDirEntry, aTargetDirectory, aCopy);
- }
- catch (e) {
- logger.error("Failure " + (aCopy ? "copying" : "moving") + " " + aDirEntry.path +
- " to " + aTargetDirectory.path);
- throw e;
- }
- },
-
- /**
- * Moves a file or directory into a new directory. If an error occurs then all
- * files that have been moved will be moved back to their original location.
- *
- * @param aFile
- * The file or directory to be moved.
- * @param aTargetDirectory
- * The directory to move into, this is expected to be an empty
- * directory.
- */
- moveUnder: function(aFile, aTargetDirectory) {
- try {
- this._installDirEntry(aFile, aTargetDirectory, false);
- }
- catch (e) {
- this.rollback();
- throw e;
- }
- },
-
- /**
- * Renames a file to a new location. If an error occurs then all
- * files that have been moved will be moved back to their original location.
- *
- * @param aOldLocation
- * The old location of the file.
- * @param aNewLocation
- * The new location of the file.
- */
- moveTo: function(aOldLocation, aNewLocation) {
- try {
- let oldFile = aOldLocation.clone(), newFile = aNewLocation.clone();
- oldFile.moveTo(newFile.parent, newFile.leafName);
- this._installedFiles.push({ oldFile: oldFile, newFile: newFile, isMoveTo: true});
- }
- catch (e) {
- this.rollback();
- throw e;
- }
- },
-
- /**
- * Copies a file or directory into a new directory. If an error occurs then
- * all new files that have been created will be removed.
- *
- * @param aFile
- * The file or directory to be copied.
- * @param aTargetDirectory
- * The directory to copy into, this is expected to be an empty
- * directory.
- */
- copy: function(aFile, aTargetDirectory) {
- try {
- this._installDirEntry(aFile, aTargetDirectory, true);
- }
- catch (e) {
- this.rollback();
- throw e;
- }
- },
-
- /**
- * Rolls back all the moves that this operation performed. If an exception
- * occurs here then both old and new directories are left in an indeterminate
- * state
- */
- rollback: function() {
- while (this._installedFiles.length > 0) {
- let move = this._installedFiles.pop();
- if (move.isMoveTo) {
- move.newFile.moveTo(move.oldDir.parent, move.oldDir.leafName);
- }
- else if (move.newFile.isDirectory() && !move.newFile.isSymlink()) {
- let oldDir = move.oldFile.parent.clone();
- oldDir.append(move.oldFile.leafName);
- oldDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
- }
- else if (!move.oldFile) {
- // No old file means this was a copied file
- move.newFile.remove(true);
- }
- else {
- move.newFile.moveTo(move.oldFile.parent, null);
- }
- }
-
- while (this._createdDirs.length > 0)
- recursiveRemove(this._createdDirs.pop());
- }
-};
-
-/**
- * Sets the userDisabled and softDisabled properties of an add-on based on what
- * values those properties had for a previous instance of the add-on. The
- * previous instance may be a previous install or in the case of an application
- * version change the same add-on.
- *
- * NOTE: this may modify aNewAddon in place; callers should save the database if
- * necessary
- *
- * @param aOldAddon
- * The previous instance of the add-on
- * @param aNewAddon
- * The new instance of the add-on
- * @param aAppVersion
- * The optional application version to use when checking the blocklist
- * or undefined to use the current application
- * @param aPlatformVersion
- * The optional platform version to use when checking the blocklist or
- * undefined to use the current platform
- */
-function applyBlocklistChanges(aOldAddon, aNewAddon, aOldAppVersion,
- aOldPlatformVersion) {
- // Copy the properties by default
- aNewAddon.userDisabled = aOldAddon.userDisabled;
- aNewAddon.softDisabled = aOldAddon.softDisabled;
-
- let oldBlocklistState = Blocklist.getAddonBlocklistState(aOldAddon.wrapper,
- aOldAppVersion,
- aOldPlatformVersion);
- let newBlocklistState = Blocklist.getAddonBlocklistState(aNewAddon.wrapper);
-
- // If the blocklist state hasn't changed then the properties don't need to
- // change
- if (newBlocklistState == oldBlocklistState)
- return;
-
- if (newBlocklistState == Blocklist.STATE_SOFTBLOCKED) {
- if (aNewAddon.type != "theme") {
- // The add-on has become softblocked, set softDisabled if it isn't already
- // userDisabled
- aNewAddon.softDisabled = !aNewAddon.userDisabled;
- }
- else {
- // Themes just get userDisabled to switch back to the default theme
- aNewAddon.userDisabled = true;
- }
- }
- else {
- // If the new add-on is not softblocked then it cannot be softDisabled
- aNewAddon.softDisabled = false;
- }
-}
-
-/**
- * Evaluates whether an add-on is allowed to run in safe mode.
- *
- * @param aAddon
- * The add-on to check
- * @return true if the add-on should run in safe mode
- */
-function canRunInSafeMode(aAddon) {
- // Even though the updated system add-ons aren't generally run in safe mode we
- // include them here so their uninstall functions get called when switching
- // back to the default set.
-
- // TODO product should make the call about temporary add-ons running
- // in safe mode. assuming for now that they are.
- if (aAddon._installLocation.name == KEY_APP_TEMPORARY)
- return true;
-
- return aAddon._installLocation.name == KEY_APP_SYSTEM_DEFAULTS ||
- aAddon._installLocation.name == KEY_APP_SYSTEM_ADDONS;
-}
-
-/**
- * Calculates whether an add-on should be appDisabled or not.
- *
- * @param aAddon
- * The add-on to check
- * @return true if the add-on should not be appDisabled
- */
-function isUsableAddon(aAddon) {
- // Hack to ensure the default theme is always usable
- if (aAddon.type == "theme" && aAddon.internalName == XPIProvider.defaultSkin)
- return true;
-
- if (mustSign(aAddon.type) && !aAddon.isCorrectlySigned) {
- logger.warn(`Add-on ${aAddon.id} is not correctly signed.`);
- return false;
- }
-
- if (aAddon.blocklistState == Blocklist.STATE_BLOCKED) {
- logger.warn(`Add-on ${aAddon.id} is blocklisted.`);
- return false;
- }
-
- // Experiments are installed through an external mechanism that
- // limits target audience to compatible clients. We trust it knows what
- // it's doing and skip compatibility checks.
- //
- // This decision does forfeit defense in depth. If the experiments system
- // is ever wrong about targeting an add-on to a specific application
- // or platform, the client will likely see errors.
- if (aAddon.type == "experiment")
- return true;
-
- if (AddonManager.checkUpdateSecurity && !aAddon.providesUpdatesSecurely) {
- logger.warn(`Updates for add-on ${aAddon.id} must be provided over HTTPS.`);
- return false;
- }
-
-
- if (!aAddon.isPlatformCompatible) {
- logger.warn(`Add-on ${aAddon.id} is not compatible with platform.`);
- return false;
- }
-
- if (aAddon.dependencies.length) {
- let isActive = id => {
- let active = XPIProvider.activeAddons.get(id);
- return active && !active.disable;
- };
-
- if (aAddon.dependencies.some(id => !isActive(id)))
- return false;
- }
-
- if (AddonManager.checkCompatibility) {
- if (!aAddon.isCompatible) {
- logger.warn(`Add-on ${aAddon.id} is not compatible with application version.`);
- return false;
- }
- }
- else {
- if (!aAddon.matchingTargetApplication) {
- logger.warn(`Add-on ${aAddon.id} is not compatible with target application.`);
- return false;
- }
- }
-
- return true;
-}
-
-XPCOMUtils.defineLazyServiceGetter(this, "gRDF", "@mozilla.org/rdf/rdf-service;1",
- Ci.nsIRDFService);
-
-function EM_R(aProperty) {
- return gRDF.GetResource(PREFIX_NS_EM + aProperty);
-}
-
-function createAddonDetails(id, aAddon) {
- return {
- id: id || aAddon.id,
- type: aAddon.type,
- version: aAddon.version,
- multiprocessCompatible: aAddon.multiprocessCompatible,
- mpcOptedOut: aAddon.mpcOptedOut,
- runInSafeMode: aAddon.runInSafeMode,
- dependencies: aAddon.dependencies,
- hasEmbeddedWebExtension: aAddon.hasEmbeddedWebExtension,
- };
-}
-
-/**
- * Converts an internal add-on type to the type presented through the API.
- *
- * @param aType
- * The internal add-on type
- * @return an external add-on type
- */
-function getExternalType(aType) {
- if (aType in TYPE_ALIASES)
- return TYPE_ALIASES[aType];
- return aType;
-}
-
-function getManifestFileForDir(aDir) {
- let file = aDir.clone();
- file.append(FILE_RDF_MANIFEST);
- if (file.exists() && file.isFile())
- return file;
- file.leafName = FILE_WEB_MANIFEST;
- if (file.exists() && file.isFile())
- return file;
- return null;
-}
-
-function getManifestEntryForZipReader(aZipReader) {
- if (aZipReader.hasEntry(FILE_RDF_MANIFEST))
- return FILE_RDF_MANIFEST;
- if (aZipReader.hasEntry(FILE_WEB_MANIFEST))
- return FILE_WEB_MANIFEST;
- return null;
-}
-
-/**
- * Converts a list of API types to a list of API types and any aliases for those
- * types.
- *
- * @param aTypes
- * An array of types or null for all types
- * @return an array of types or null for all types
- */
-function getAllAliasesForTypes(aTypes) {
- if (!aTypes)
- return null;
-
- // Build a set of all requested types and their aliases
- let typeset = new Set(aTypes);
-
- for (let alias of Object.keys(TYPE_ALIASES)) {
- // Ignore any requested internal types
- typeset.delete(alias);
-
- // Add any alias for the internal type
- if (typeset.has(TYPE_ALIASES[alias]))
- typeset.add(alias);
- }
-
- return [...typeset];
-}
-
-/**
- * Converts an RDF literal, resource or integer into a string.
- *
- * @param aLiteral
- * The RDF object to convert
- * @return a string if the object could be converted or null
- */
-function getRDFValue(aLiteral) {
- if (aLiteral instanceof Ci.nsIRDFLiteral)
- return aLiteral.Value;
- if (aLiteral instanceof Ci.nsIRDFResource)
- return aLiteral.Value;
- if (aLiteral instanceof Ci.nsIRDFInt)
- return aLiteral.Value;
- return null;
-}
-
-/**
- * Gets an RDF property as a string
- *
- * @param aDs
- * The RDF datasource to read the property from
- * @param aResource
- * The RDF resource to read the property from
- * @param aProperty
- * The property to read
- * @return a string if the property existed or null
- */
-function getRDFProperty(aDs, aResource, aProperty) {
- return getRDFValue(aDs.GetTarget(aResource, EM_R(aProperty), true));
-}
-
-/**
- * Reads an AddonInternal object from a manifest stream.
- *
- * @param aUri
- * A |file:| or |jar:| URL for the manifest
- * @return an AddonInternal object
- * @throws if the install manifest in the stream is corrupt or could not
- * be read
- */
-var loadManifestFromWebManifest = Task.async(function*(aUri) {
- // We're passed the URI for the manifest file. Get the URI for its
- // parent directory.
- let uri = NetUtil.newURI("./", null, aUri);
-
- let extension = new ExtensionData(uri);
-
- let manifest = yield extension.readManifest();
-
- // Read the list of available locales, and pre-load messages for
- // all locales.
- let locales = yield extension.initAllLocales();
-
- // If there were any errors loading the extension, bail out now.
- if (extension.errors.length)
- throw new Error("Extension is invalid");
-
- let bss = (manifest.browser_specific_settings && manifest.browser_specific_settings.gecko)
- || (manifest.applications && manifest.applications.gecko) || {};
- if (manifest.browser_specific_settings && manifest.applications) {
- logger.warn("Ignoring applications property in manifest");
- }
-
- // A * is illegal in strict_min_version
- if (bss.strict_min_version && bss.strict_min_version.split(".").some(part => part == "*")) {
- throw new Error("The use of '*' in strict_min_version is invalid");
- }
-
- let addon = new AddonInternal();
- addon.id = bss.id;
- addon.version = manifest.version;
- addon.type = "webextension";
- addon.unpack = false;
- addon.strictCompatibility = true;
- addon.bootstrap = true;
- addon.hasBinaryComponents = false;
- addon.multiprocessCompatible = true;
- addon.internalName = null;
- addon.updateURL = bss.update_url;
- addon.updateKey = null;
- addon.optionsURL = null;
- addon.optionsType = null;
- addon.aboutURL = null;
- addon.dependencies = Object.freeze(Array.from(extension.dependencies));
-
- if (manifest.options_ui) {
- // Store just the relative path here, the AddonWrapper getURL
- // wrapper maps this to a full URL.
- addon.optionsURL = manifest.options_ui.page;
- if (manifest.options_ui.open_in_tab)
- addon.optionsType = AddonManager.OPTIONS_TYPE_TAB;
- else
- addon.optionsType = AddonManager.OPTIONS_TYPE_INLINE_BROWSER;
- }
-
- // WebExtensions don't use iconURLs
- addon.iconURL = null;
- addon.icon64URL = null;
- addon.icons = manifest.icons || {};
-
- addon.applyBackgroundUpdates = AddonManager.AUTOUPDATE_DEFAULT;
-
- function getLocale(aLocale) {
- // Use the raw manifest, here, since we need values with their
- // localization placeholders still in place.
- let rawManifest = extension.rawManifest;
-
- // As a convenience, allow author to be set if its a string bug 1313567.
- let creator = typeof(rawManifest.author) === 'string' ? rawManifest.author : null;
- let homepageURL = rawManifest.homepage_url;
-
- // Allow developer to override creator and homepage_url.
- if (rawManifest.developer) {
- if (rawManifest.developer.name) {
- creator = rawManifest.developer.name;
- }
- if (rawManifest.developer.url) {
- homepageURL = rawManifest.developer.url;
- }
- }
-
- let result = {
- name: extension.localize(rawManifest.name, aLocale),
- description: extension.localize(rawManifest.description, aLocale),
- creator: extension.localize(creator, aLocale),
- homepageURL: extension.localize(homepageURL, aLocale),
-
- developers: null,
- translators: null,
- contributors: null,
- locales: [aLocale],
- };
- return result;
- }
-
- addon.defaultLocale = getLocale(extension.defaultLocale);
- addon.locales = Array.from(locales.keys(), getLocale);
-
- delete addon.defaultLocale.locales;
-
- addon.targetApplications = [{
- id: WEBEXTENSIONS_ID,
- minVersion: bss.strict_min_version,
- maxVersion: bss.strict_max_version,
- }];
-
- addon.targetPlatforms = [];
- addon.userDisabled = false;
- addon.softDisabled = addon.blocklistState == Blocklist.STATE_SOFTBLOCKED;
-
- return addon;
-});
-
-/**
- * Reads an AddonInternal object from an RDF stream.
- *
- * @param aUri
- * The URI that the manifest is being read from
- * @param aStream
- * An open stream to read the RDF from
- * @return an AddonInternal object
- * @throws if the install manifest in the RDF stream is corrupt or could not
- * be read
- */
-let loadManifestFromRDF = Task.async(function*(aUri, aStream) {
- function getPropertyArray(aDs, aSource, aProperty) {
- let values = [];
- let targets = aDs.GetTargets(aSource, EM_R(aProperty), true);
- while (targets.hasMoreElements())
- values.push(getRDFValue(targets.getNext()));
-
- return values;
- }
-
- /**
- * Reads locale properties from either the main install manifest root or
- * an em:localized section in the install manifest.
- *
- * @param aDs
- * The nsIRDFDatasource to read from
- * @param aSource
- * The nsIRDFResource to read the properties from
- * @param isDefault
- * True if the locale is to be read from the main install manifest
- * root
- * @param aSeenLocales
- * An array of locale names already seen for this install manifest.
- * Any locale names seen as a part of this function will be added to
- * this array
- * @return an object containing the locale properties
- */
- function readLocale(aDs, aSource, isDefault, aSeenLocales) {
- let locale = { };
- if (!isDefault) {
- locale.locales = [];
- let targets = ds.GetTargets(aSource, EM_R("locale"), true);
- while (targets.hasMoreElements()) {
- let localeName = getRDFValue(targets.getNext());
- if (!localeName) {
- logger.warn("Ignoring empty locale in localized properties");
- continue;
- }
- if (aSeenLocales.indexOf(localeName) != -1) {
- logger.warn("Ignoring duplicate locale in localized properties");
- continue;
- }
- aSeenLocales.push(localeName);
- locale.locales.push(localeName);
- }
-
- if (locale.locales.length == 0) {
- logger.warn("Ignoring localized properties with no listed locales");
- return null;
- }
- }
-
- for (let prop of PROP_LOCALE_SINGLE) {
- locale[prop] = getRDFProperty(aDs, aSource, prop);
- }
-
- for (let prop of PROP_LOCALE_MULTI) {
- // Don't store empty arrays
- let props = getPropertyArray(aDs, aSource,
- prop.substring(0, prop.length - 1));
- if (props.length > 0)
- locale[prop] = props;
- }
-
- return locale;
- }
-
- let rdfParser = Cc["@mozilla.org/rdf/xml-parser;1"].
- createInstance(Ci.nsIRDFXMLParser)
- let ds = Cc["@mozilla.org/rdf/datasource;1?name=in-memory-datasource"].
- createInstance(Ci.nsIRDFDataSource);
- let listener = rdfParser.parseAsync(ds, aUri);
- let channel = Cc["@mozilla.org/network/input-stream-channel;1"].
- createInstance(Ci.nsIInputStreamChannel);
- channel.setURI(aUri);
- channel.contentStream = aStream;
- channel.QueryInterface(Ci.nsIChannel);
- channel.contentType = "text/xml";
-
- listener.onStartRequest(channel, null);
-
- try {
- let pos = 0;
- let count = aStream.available();
- while (count > 0) {
- listener.onDataAvailable(channel, null, aStream, pos, count);
- pos += count;
- count = aStream.available();
- }
- listener.onStopRequest(channel, null, Components.results.NS_OK);
- }
- catch (e) {
- listener.onStopRequest(channel, null, e.result);
- throw e;
- }
-
- let root = gRDF.GetResource(RDFURI_INSTALL_MANIFEST_ROOT);
- let addon = new AddonInternal();
- for (let prop of PROP_METADATA) {
- addon[prop] = getRDFProperty(ds, root, prop);
- }
- addon.unpack = getRDFProperty(ds, root, "unpack") == "true";
-
- if (!addon.type) {
- addon.type = addon.internalName ? "theme" : "extension";
- }
- else {
- let type = addon.type;
- addon.type = null;
- for (let name in TYPES) {
- if (TYPES[name] == type) {
- addon.type = name;
- break;
- }
- }
- }
-
- if (!(addon.type in TYPES))
- throw new Error("Install manifest specifies unknown type: " + addon.type);
-
- if (addon.type != "multipackage") {
- if (!addon.id)
- throw new Error("No ID in install manifest");
- if (!gIDTest.test(addon.id))
- throw new Error("Illegal add-on ID " + addon.id);
- if (!addon.version)
- throw new Error("No version in install manifest");
- }
-
- addon.strictCompatibility = !(addon.type in COMPATIBLE_BY_DEFAULT_TYPES) ||
- getRDFProperty(ds, root, "strictCompatibility") == "true";
-
- // Only read these properties for extensions.
- if (addon.type == "extension") {
- addon.bootstrap = getRDFProperty(ds, root, "bootstrap") == "true";
-
- let mpcValue = getRDFProperty(ds, root, "multiprocessCompatible");
- addon.multiprocessCompatible = mpcValue == "true";
- addon.mpcOptedOut = mpcValue == "false";
-
- addon.hasEmbeddedWebExtension = getRDFProperty(ds, root, "hasEmbeddedWebExtension") == "true";
-
- if (addon.optionsType &&
- addon.optionsType != AddonManager.OPTIONS_TYPE_DIALOG &&
- addon.optionsType != AddonManager.OPTIONS_TYPE_INLINE &&
- addon.optionsType != AddonManager.OPTIONS_TYPE_TAB &&
- addon.optionsType != AddonManager.OPTIONS_TYPE_INLINE_INFO) {
- throw new Error("Install manifest specifies unknown type: " + addon.optionsType);
- }
-
- if (addon.hasEmbeddedWebExtension) {
- let uri = NetUtil.newURI("webextension/manifest.json", null, aUri);
- let embeddedAddon = yield loadManifestFromWebManifest(uri);
- if (embeddedAddon.optionsURL) {
- if (addon.optionsType || addon.optionsURL)
- logger.warn(`Addon ${addon.id} specifies optionsType or optionsURL ` +
- `in both install.rdf and manifest.json`);
-
- addon.optionsURL = embeddedAddon.optionsURL;
- addon.optionsType = embeddedAddon.optionsType;
- }
- }
- }
- else {
- // Some add-on types are always restartless.
- if (RESTARTLESS_TYPES.has(addon.type)) {
- addon.bootstrap = true;
- }
-
- // Only extensions are allowed to provide an optionsURL, optionsType or aboutURL. For
- // all other types they are silently ignored
- addon.optionsURL = null;
- addon.optionsType = null;
- addon.aboutURL = null;
-
- if (addon.type == "theme") {
- if (!addon.internalName)
- throw new Error("Themes must include an internalName property");
- addon.skinnable = getRDFProperty(ds, root, "skinnable") == "true";
- }
- }
-
- addon.defaultLocale = readLocale(ds, root, true);
-
- let seenLocales = [];
- addon.locales = [];
- let targets = ds.GetTargets(root, EM_R("localized"), true);
- while (targets.hasMoreElements()) {
- let target = targets.getNext().QueryInterface(Ci.nsIRDFResource);
- let locale = readLocale(ds, target, false, seenLocales);
- if (locale)
- addon.locales.push(locale);
- }
-
- let dependencies = new Set();
- targets = ds.GetTargets(root, EM_R("dependency"), true);
- while (targets.hasMoreElements()) {
- let target = targets.getNext().QueryInterface(Ci.nsIRDFResource);
- let id = getRDFProperty(ds, target, "id");
- dependencies.add(id);
- }
- addon.dependencies = Object.freeze(Array.from(dependencies));
-
- let seenApplications = [];
- addon.targetApplications = [];
- targets = ds.GetTargets(root, EM_R("targetApplication"), true);
- while (targets.hasMoreElements()) {
- let target = targets.getNext().QueryInterface(Ci.nsIRDFResource);
- let targetAppInfo = {};
- for (let prop of PROP_TARGETAPP) {
- targetAppInfo[prop] = getRDFProperty(ds, target, prop);
- }
- if (!targetAppInfo.id || !targetAppInfo.minVersion ||
- !targetAppInfo.maxVersion) {
- logger.warn("Ignoring invalid targetApplication entry in install manifest");
- continue;
- }
- if (seenApplications.indexOf(targetAppInfo.id) != -1) {
- logger.warn("Ignoring duplicate targetApplication entry for " + targetAppInfo.id +
- " in install manifest");
- continue;
- }
- seenApplications.push(targetAppInfo.id);
- addon.targetApplications.push(targetAppInfo);
- }
-
- // Note that we don't need to check for duplicate targetPlatform entries since
- // the RDF service coalesces them for us.
- let targetPlatforms = getPropertyArray(ds, root, "targetPlatform");
- addon.targetPlatforms = [];
- for (let targetPlatform of targetPlatforms) {
- let platform = {
- os: null,
- abi: null
- };
-
- let pos = targetPlatform.indexOf("_");
- if (pos != -1) {
- platform.os = targetPlatform.substring(0, pos);
- platform.abi = targetPlatform.substring(pos + 1);
- }
- else {
- platform.os = targetPlatform;
- }
-
- addon.targetPlatforms.push(platform);
- }
-
- // A theme's userDisabled value is true if the theme is not the selected skin
- // or if there is an active lightweight theme. We ignore whether softblocking
- // is in effect since it would change the active theme.
- if (addon.type == "theme") {
- addon.userDisabled = !!LightweightThemeManager.currentTheme ||
- addon.internalName != XPIProvider.selectedSkin;
- }
- else if (addon.type == "experiment") {
- // Experiments are disabled by default. It is up to the Experiments Manager
- // to enable them (it drives installation).
- addon.userDisabled = true;
- }
- else {
- addon.userDisabled = false;
- }
-
- addon.softDisabled = addon.blocklistState == Blocklist.STATE_SOFTBLOCKED;
- addon.applyBackgroundUpdates = AddonManager.AUTOUPDATE_DEFAULT;
-
- // Experiments are managed and updated through an external "experiments
- // manager." So disable some built-in mechanisms.
- if (addon.type == "experiment") {
- addon.applyBackgroundUpdates = AddonManager.AUTOUPDATE_DISABLE;
- addon.updateURL = null;
- addon.updateKey = null;
- }
-
- // icons will be filled by the calling function
- addon.icons = {};
-
- return addon;
-});
-
-function defineSyncGUID(aAddon) {
- // Define .syncGUID as a lazy property which is also settable
- Object.defineProperty(aAddon, "syncGUID", {
- get: () => {
- // Generate random GUID used for Sync.
- let guid = Cc["@mozilla.org/uuid-generator;1"]
- .getService(Ci.nsIUUIDGenerator)
- .generateUUID().toString();
-
- delete aAddon.syncGUID;
- aAddon.syncGUID = guid;
- return guid;
- },
- set: (val) => {
- delete aAddon.syncGUID;
- aAddon.syncGUID = val;
- },
- configurable: true,
- enumerable: true,
- });
-}
-
-// Generate a unique ID based on the path to this temporary add-on location.
-function generateTemporaryInstallID(aFile) {
- const hasher = Cc["@mozilla.org/security/hash;1"]
- .createInstance(Ci.nsICryptoHash);
- hasher.init(hasher.SHA1);
- const data = new TextEncoder().encode(aFile.path);
- // Make it so this ID cannot be guessed.
- const sess = TEMP_INSTALL_ID_GEN_SESSION;
- hasher.update(sess, sess.length);
- hasher.update(data, data.length);
- let id = `${getHashStringForCrypto(hasher)}@temporary-addon`;
- logger.info(`Generated temp id ${id} (${sess.join("")}) for ${aFile.path}`);
- return id;
-}
-
-/**
- * Loads an AddonInternal object from an add-on extracted in a directory.
- *
- * @param aDir
- * The nsIFile directory holding the add-on
- * @return an AddonInternal object
- * @throws if the directory does not contain a valid install manifest
- */
-var loadManifestFromDir = Task.async(function*(aDir, aInstallLocation) {
- function getFileSize(aFile) {
- if (aFile.isSymlink())
- return 0;
-
- if (!aFile.isDirectory())
- return aFile.fileSize;
-
- let size = 0;
- let entries = aFile.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
- let entry;
- while ((entry = entries.nextFile))
- size += getFileSize(entry);
- entries.close();
- return size;
- }
-
- function* loadFromRDF(aUri) {
- let fis = Cc["@mozilla.org/network/file-input-stream;1"].
- createInstance(Ci.nsIFileInputStream);
- fis.init(aUri.file, -1, -1, false);
- let bis = Cc["@mozilla.org/network/buffered-input-stream;1"].
- createInstance(Ci.nsIBufferedInputStream);
- bis.init(fis, 4096);
- try {
- var addon = yield loadManifestFromRDF(aUri, bis);
- } finally {
- bis.close();
- fis.close();
- }
-
- let iconFile = aDir.clone();
- iconFile.append("icon.png");
-
- if (iconFile.exists()) {
- addon.icons[32] = "icon.png";
- addon.icons[48] = "icon.png";
- }
-
- let icon64File = aDir.clone();
- icon64File.append("icon64.png");
-
- if (icon64File.exists()) {
- addon.icons[64] = "icon64.png";
- }
-
- let file = aDir.clone();
- file.append("chrome.manifest");
- let chromeManifest = ChromeManifestParser.parseSync(Services.io.newFileURI(file));
- addon.hasBinaryComponents = ChromeManifestParser.hasType(chromeManifest,
- "binary-component");
- return addon;
- }
-
- let file = getManifestFileForDir(aDir);
- if (!file) {
- throw new Error("Directory " + aDir.path + " does not contain a valid " +
- "install manifest");
- }
-
- let uri = Services.io.newFileURI(file).QueryInterface(Ci.nsIFileURL);
-
- let addon;
- if (file.leafName == FILE_WEB_MANIFEST) {
- addon = yield loadManifestFromWebManifest(uri);
- if (!addon.id) {
- if (aInstallLocation == TemporaryInstallLocation) {
- addon.id = generateTemporaryInstallID(aDir);
- } else {
- addon.id = aDir.leafName;
- }
- }
- } else {
- addon = yield loadFromRDF(uri);
- }
-
- addon._sourceBundle = aDir.clone();
- addon._installLocation = aInstallLocation;
- addon.size = getFileSize(aDir);
- addon.signedState = yield verifyDirSignedState(aDir, addon)
- .then(({signedState}) => signedState);
- addon.appDisabled = !isUsableAddon(addon);
-
- defineSyncGUID(addon);
-
- return addon;
-});
-
-/**
- * Loads an AddonInternal object from an nsIZipReader for an add-on.
- *
- * @param aZipReader
- * An open nsIZipReader for the add-on's files
- * @return an AddonInternal object
- * @throws if the XPI file does not contain a valid install manifest
- */
-var loadManifestFromZipReader = Task.async(function*(aZipReader, aInstallLocation) {
- function* loadFromRDF(aUri) {
- let zis = aZipReader.getInputStream(entry);
- let bis = Cc["@mozilla.org/network/buffered-input-stream;1"].
- createInstance(Ci.nsIBufferedInputStream);
- bis.init(zis, 4096);
- try {
- var addon = yield loadManifestFromRDF(aUri, bis);
- } finally {
- bis.close();
- zis.close();
- }
-
- if (aZipReader.hasEntry("icon.png")) {
- addon.icons[32] = "icon.png";
- addon.icons[48] = "icon.png";
- }
-
- if (aZipReader.hasEntry("icon64.png")) {
- addon.icons[64] = "icon64.png";
- }
-
- // Binary components can only be loaded from unpacked addons.
- if (addon.unpack) {
- let uri = buildJarURI(aZipReader.file, "chrome.manifest");
- let chromeManifest = ChromeManifestParser.parseSync(uri);
- addon.hasBinaryComponents = ChromeManifestParser.hasType(chromeManifest,
- "binary-component");
- } else {
- addon.hasBinaryComponents = false;
- }
-
- return addon;
- }
-
- let entry = getManifestEntryForZipReader(aZipReader);
- if (!entry) {
- throw new Error("File " + aZipReader.file.path + " does not contain a valid " +
- "install manifest");
- }
-
- let uri = buildJarURI(aZipReader.file, entry);
-
- let isWebExtension = (entry == FILE_WEB_MANIFEST);
-
- let addon = isWebExtension ?
- yield loadManifestFromWebManifest(uri) :
- yield loadFromRDF(uri);
-
- addon._sourceBundle = aZipReader.file;
- addon._installLocation = aInstallLocation;
-
- addon.size = 0;
- let entries = aZipReader.findEntries(null);
- while (entries.hasMore())
- addon.size += aZipReader.getEntry(entries.getNext()).realSize;
-
- let {signedState, cert} = yield verifyZipSignedState(aZipReader.file, addon);
- addon.signedState = signedState;
- if (isWebExtension && !addon.id) {
- if (cert) {
- addon.id = cert.commonName;
- if (!gIDTest.test(addon.id)) {
- throw new Error(`Webextension is signed with an invalid id (${addon.id})`);
- }
- }
- if (!addon.id && aInstallLocation == TemporaryInstallLocation) {
- addon.id = generateTemporaryInstallID(aZipReader.file);
- }
- }
- addon.appDisabled = !isUsableAddon(addon);
-
- defineSyncGUID(addon);
-
- return addon;
-});
-
-/**
- * Loads an AddonInternal object from an add-on in an XPI file.
- *
- * @param aXPIFile
- * An nsIFile pointing to the add-on's XPI file
- * @return an AddonInternal object
- * @throws if the XPI file does not contain a valid install manifest
- */
-var loadManifestFromZipFile = Task.async(function*(aXPIFile, aInstallLocation) {
- let zipReader = Cc["@mozilla.org/libjar/zip-reader;1"].
- createInstance(Ci.nsIZipReader);
- try {
- zipReader.open(aXPIFile);
-
- // Can't return this promise because that will make us close the zip reader
- // before it has finished loading the manifest. Wait for the result and then
- // return.
- let manifest = yield loadManifestFromZipReader(zipReader, aInstallLocation);
- return manifest;
- }
- finally {
- zipReader.close();
- }
-});
-
-function loadManifestFromFile(aFile, aInstallLocation) {
- if (aFile.isFile())
- return loadManifestFromZipFile(aFile, aInstallLocation);
- return loadManifestFromDir(aFile, aInstallLocation);
-}
-
-/**
- * A synchronous method for loading an add-on's manifest. This should only ever
- * be used during startup or a sync load of the add-ons DB
- */
-function syncLoadManifestFromFile(aFile, aInstallLocation) {
- let success = undefined;
- let result = null;
-
- loadManifestFromFile(aFile, aInstallLocation).then(val => {
- success = true;
- result = val;
- }, val => {
- success = false;
- result = val
- });
-
- let thread = Services.tm.currentThread;
-
- while (success === undefined)
- thread.processNextEvent(true);
-
- if (!success)
- throw result;
- return result;
-}
-
-/**
- * Gets an nsIURI for a file within another file, either a directory or an XPI
- * file. If aFile is a directory then this will return a file: URI, if it is an
- * XPI file then it will return a jar: URI.
- *
- * @param aFile
- * The file containing the resources, must be either a directory or an
- * XPI file
- * @param aPath
- * The path to find the resource at, "/" separated. If aPath is empty
- * then the uri to the root of the contained files will be returned
- * @return an nsIURI pointing at the resource
- */
-function getURIForResourceInFile(aFile, aPath) {
- if (aFile.isDirectory()) {
- let resource = aFile.clone();
- if (aPath)
- aPath.split("/").forEach(part => resource.append(part));
-
- return NetUtil.newURI(resource);
- }
-
- return buildJarURI(aFile, aPath);
-}
-
-/**
- * Creates a jar: URI for a file inside a ZIP file.
- *
- * @param aJarfile
- * The ZIP file as an nsIFile
- * @param aPath
- * The path inside the ZIP file
- * @return an nsIURI for the file
- */
-function buildJarURI(aJarfile, aPath) {
- let uri = Services.io.newFileURI(aJarfile);
- uri = "jar:" + uri.spec + "!/" + aPath;
- return NetUtil.newURI(uri);
-}
-
-/**
- * Sends local and remote notifications to flush a JAR file cache entry
- *
- * @param aJarFile
- * The ZIP/XPI/JAR file as a nsIFile
- */
-function flushJarCache(aJarFile) {
- Services.obs.notifyObservers(aJarFile, "flush-cache-entry", null);
- Services.mm.broadcastAsyncMessage(MSG_JAR_FLUSH, aJarFile.path);
-}
-
-function flushChromeCaches() {
- // Init this, so it will get the notification.
- Services.obs.notifyObservers(null, "startupcache-invalidate", null);
- // Flush message manager cached scripts
- Services.obs.notifyObservers(null, "message-manager-flush-caches", null);
- // Also dispatch this event to child processes
- Services.mm.broadcastAsyncMessage(MSG_MESSAGE_MANAGER_CACHES_FLUSH, null);
-}
-
-/**
- * Creates and returns a new unique temporary file. The caller should delete
- * the file when it is no longer needed.
- *
- * @return an nsIFile that points to a randomly named, initially empty file in
- * the OS temporary files directory
- */
-function getTemporaryFile() {
- let file = FileUtils.getDir(KEY_TEMPDIR, []);
- let random = Math.random().toString(36).replace(/0./, '').substr(-3);
- file.append("tmp-" + random + ".xpi");
- file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
-
- return file;
-}
-
-/**
- * Verifies that a zip file's contents are all signed by the same principal.
- * Directory entries and anything in the META-INF directory are not checked.
- *
- * @param aZip
- * A nsIZipReader to check
- * @param aCertificate
- * The nsIX509Cert to compare against
- * @return true if all the contents that should be signed were signed by the
- * principal
- */
-function verifyZipSigning(aZip, aCertificate) {
- var count = 0;
- var entries = aZip.findEntries(null);
- while (entries.hasMore()) {
- var entry = entries.getNext();
- // Nothing in META-INF is in the manifest.
- if (entry.substr(0, 9) == "META-INF/")
- continue;
- // Directory entries aren't in the manifest.
- if (entry.substr(-1) == "/")
- continue;
- count++;
- var entryCertificate = aZip.getSigningCert(entry);
- if (!entryCertificate || !aCertificate.equals(entryCertificate)) {
- return false;
- }
- }
- return aZip.manifestEntriesCount == count;
-}
-
-/**
- * Returns the signedState for a given return code and certificate by verifying
- * it against the expected ID.
- */
-function getSignedStatus(aRv, aCert, aAddonID) {
- let expectedCommonName = aAddonID;
- if (aAddonID && aAddonID.length > 64) {
- let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
- createInstance(Ci.nsIScriptableUnicodeConverter);
- converter.charset = "UTF-8";
- let data = converter.convertToByteArray(aAddonID, {});
-
- let crypto = Cc["@mozilla.org/security/hash;1"].
- createInstance(Ci.nsICryptoHash);
- crypto.init(Ci.nsICryptoHash.SHA256);
- crypto.update(data, data.length);
- expectedCommonName = getHashStringForCrypto(crypto);
- }
-
- switch (aRv) {
- case Cr.NS_OK:
- if (expectedCommonName && expectedCommonName != aCert.commonName)
- return AddonManager.SIGNEDSTATE_BROKEN;
-
- let hotfixID = Preferences.get(PREF_EM_HOTFIX_ID, undefined);
- if (hotfixID && hotfixID == aAddonID && Preferences.get(PREF_EM_CERT_CHECKATTRIBUTES, false)) {
- // The hotfix add-on has some more rigorous certificate checks
- try {
- CertUtils.validateCert(aCert,
- CertUtils.readCertPrefs(PREF_EM_HOTFIX_CERTS));
- }
- catch (e) {
- logger.warn("The hotfix add-on was not signed by the expected " +
- "certificate and so will not be installed.", e);
- return AddonManager.SIGNEDSTATE_BROKEN;
- }
- }
-
- if (aCert.organizationalUnit == "Mozilla Components")
- return AddonManager.SIGNEDSTATE_SYSTEM;
-
- return /preliminary/i.test(aCert.organizationalUnit)
- ? AddonManager.SIGNEDSTATE_PRELIMINARY
- : AddonManager.SIGNEDSTATE_SIGNED;
- case Cr.NS_ERROR_SIGNED_JAR_NOT_SIGNED:
- return AddonManager.SIGNEDSTATE_MISSING;
- case Cr.NS_ERROR_SIGNED_JAR_MANIFEST_INVALID:
- case Cr.NS_ERROR_SIGNED_JAR_ENTRY_INVALID:
- case Cr.NS_ERROR_SIGNED_JAR_ENTRY_MISSING:
- case Cr.NS_ERROR_SIGNED_JAR_ENTRY_TOO_LARGE:
- case Cr.NS_ERROR_SIGNED_JAR_UNSIGNED_ENTRY:
- case Cr.NS_ERROR_SIGNED_JAR_MODIFIED_ENTRY:
- return AddonManager.SIGNEDSTATE_BROKEN;
- default:
- // Any other error indicates that either the add-on isn't signed or it
- // is signed by a signature that doesn't chain to the trusted root.
- return AddonManager.SIGNEDSTATE_UNKNOWN;
- }
-}
-
-function shouldVerifySignedState(aAddon) {
- // Updated system add-ons should always have their signature checked
- if (aAddon._installLocation.name == KEY_APP_SYSTEM_ADDONS)
- return true;
-
- // We don't care about signatures for default system add-ons
- if (aAddon._installLocation.name == KEY_APP_SYSTEM_DEFAULTS)
- return false;
-
- // Hotfixes should always have their signature checked
- let hotfixID = Preferences.get(PREF_EM_HOTFIX_ID, undefined);
- if (hotfixID && aAddon.id == hotfixID)
- return true;
-
- // Otherwise only check signatures if signing is enabled and the add-on is one
- // of the signed types.
- return ADDON_SIGNING && SIGNED_TYPES.has(aAddon.type);
-}
-
-let gCertDB = Cc["@mozilla.org/security/x509certdb;1"]
- .getService(Ci.nsIX509CertDB);
-
-/**
- * Verifies that a zip file's contents are all correctly signed by an
- * AMO-issued certificate
- *
- * @param aFile
- * the xpi file to check
- * @param aAddon
- * the add-on object to verify
- * @return a Promise that resolves to an object with properties:
- * signedState: an AddonManager.SIGNEDSTATE_* constant
- * cert: an nsIX509Cert
- */
-function verifyZipSignedState(aFile, aAddon) {
- if (!shouldVerifySignedState(aAddon))
- return Promise.resolve({
- signedState: AddonManager.SIGNEDSTATE_NOT_REQUIRED,
- cert: null
- });
-
- let root = Ci.nsIX509CertDB.AddonsPublicRoot;
- if (!REQUIRE_SIGNING && Preferences.get(PREF_XPI_SIGNATURES_DEV_ROOT, false))
- root = Ci.nsIX509CertDB.AddonsStageRoot;
-
- return new Promise(resolve => {
- let callback = {
- openSignedAppFileFinished: function(aRv, aZipReader, aCert) {
- if (aZipReader)
- aZipReader.close();
- resolve({
- signedState: getSignedStatus(aRv, aCert, aAddon.id),
- cert: aCert
- });
- }
- };
- // This allows the certificate DB to get the raw JS callback object so the
- // test code can pass through objects that XPConnect would reject.
- callback.wrappedJSObject = callback;
-
- gCertDB.openSignedAppFileAsync(root, aFile, callback);
- });
-}
-
-/**
- * Verifies that a directory's contents are all correctly signed by an
- * AMO-issued certificate
- *
- * @param aDir
- * the directory to check
- * @param aAddon
- * the add-on object to verify
- * @return a Promise that resolves to an object with properties:
- * signedState: an AddonManager.SIGNEDSTATE_* constant
- * cert: an nsIX509Cert
- */
-function verifyDirSignedState(aDir, aAddon) {
- if (!shouldVerifySignedState(aAddon))
- return Promise.resolve({
- signedState: AddonManager.SIGNEDSTATE_NOT_REQUIRED,
- cert: null,
- });
-
- let root = Ci.nsIX509CertDB.AddonsPublicRoot;
- if (!REQUIRE_SIGNING && Preferences.get(PREF_XPI_SIGNATURES_DEV_ROOT, false))
- root = Ci.nsIX509CertDB.AddonsStageRoot;
-
- return new Promise(resolve => {
- let callback = {
- verifySignedDirectoryFinished: function(aRv, aCert) {
- resolve({
- signedState: getSignedStatus(aRv, aCert, aAddon.id),
- cert: null,
- });
- }
- };
- // This allows the certificate DB to get the raw JS callback object so the
- // test code can pass through objects that XPConnect would reject.
- callback.wrappedJSObject = callback;
-
- gCertDB.verifySignedDirectoryAsync(root, aDir, callback);
- });
-}
-
-/**
- * Verifies that a bundle's contents are all correctly signed by an
- * AMO-issued certificate
- *
- * @param aBundle
- * the nsIFile for the bundle to check, either a directory or zip file
- * @param aAddon
- * the add-on object to verify
- * @return a Promise that resolves to an AddonManager.SIGNEDSTATE_* constant.
- */
-function verifyBundleSignedState(aBundle, aAddon) {
- let promise = aBundle.isFile() ? verifyZipSignedState(aBundle, aAddon)
- : verifyDirSignedState(aBundle, aAddon);
- return promise.then(({signedState}) => signedState);
-}
-
-/**
- * Replaces %...% strings in an addon url (update and updateInfo) with
- * appropriate values.
- *
- * @param aAddon
- * The AddonInternal representing the add-on
- * @param aUri
- * The uri to escape
- * @param aUpdateType
- * An optional number representing the type of update, only applicable
- * when creating a url for retrieving an update manifest
- * @param aAppVersion
- * The optional application version to use for %APP_VERSION%
- * @return the appropriately escaped uri.
- */
-function escapeAddonURI(aAddon, aUri, aUpdateType, aAppVersion)
-{
- let uri = AddonManager.escapeAddonURI(aAddon, aUri, aAppVersion);
-
- // If there is an updateType then replace the UPDATE_TYPE string
- if (aUpdateType)
- uri = uri.replace(/%UPDATE_TYPE%/g, aUpdateType);
-
- // If this add-on has compatibility information for either the current
- // application or toolkit then replace the ITEM_MAXAPPVERSION with the
- // maxVersion
- let app = aAddon.matchingTargetApplication;
- if (app)
- var maxVersion = app.maxVersion;
- else
- maxVersion = "";
- uri = uri.replace(/%ITEM_MAXAPPVERSION%/g, maxVersion);
-
- let compatMode = "normal";
- if (!AddonManager.checkCompatibility)
- compatMode = "ignore";
- else if (AddonManager.strictCompatibility)
- compatMode = "strict";
- uri = uri.replace(/%COMPATIBILITY_MODE%/g, compatMode);
-
- return uri;
-}
-
-function removeAsync(aFile) {
- return Task.spawn(function*() {
- let info = null;
- try {
- info = yield OS.File.stat(aFile.path);
- if (info.isDir)
- yield OS.File.removeDir(aFile.path);
- else
- yield OS.File.remove(aFile.path);
- }
- catch (e) {
- if (!(e instanceof OS.File.Error) || ! e.becauseNoSuchFile)
- throw e;
- // The file has already gone away
- return;
- }
- });
-}
-
-/**
- * Recursively removes a directory or file fixing permissions when necessary.
- *
- * @param aFile
- * The nsIFile to remove
- */
-function recursiveRemove(aFile) {
- let isDir = null;
-
- try {
- isDir = aFile.isDirectory();
- }
- catch (e) {
- // If the file has already gone away then don't worry about it, this can
- // happen on OSX where the resource fork is automatically moved with the
- // data fork for the file. See bug 733436.
- if (e.result == Cr.NS_ERROR_FILE_TARGET_DOES_NOT_EXIST)
- return;
- if (e.result == Cr.NS_ERROR_FILE_NOT_FOUND)
- return;
-
- throw e;
- }
-
- setFilePermissions(aFile, isDir ? FileUtils.PERMS_DIRECTORY
- : FileUtils.PERMS_FILE);
-
- try {
- aFile.remove(true);
- return;
- }
- catch (e) {
- if (!aFile.isDirectory() || aFile.isSymlink()) {
- logger.error("Failed to remove file " + aFile.path, e);
- throw e;
- }
- }
-
- // Use a snapshot of the directory contents to avoid possible issues with
- // iterating over a directory while removing files from it (the YAFFS2
- // embedded filesystem has this issue, see bug 772238), and to remove
- // normal files before their resource forks on OSX (see bug 733436).
- let entries = getDirectoryEntries(aFile, true);
- entries.forEach(recursiveRemove);
-
- try {
- aFile.remove(true);
- }
- catch (e) {
- logger.error("Failed to remove empty directory " + aFile.path, e);
- throw e;
- }
-}
-
-/**
- * Returns the timestamp and leaf file name of the most recently modified
- * entry in a directory,
- * or simply the file's own timestamp if it is not a directory.
- * Also returns the total number of items (directories and files) visited in the scan
- *
- * @param aFile
- * A non-null nsIFile object
- * @return [File Name, Epoch time, items visited], as described above.
- */
-function recursiveLastModifiedTime(aFile) {
- try {
- let modTime = aFile.lastModifiedTime;
- let fileName = aFile.leafName;
- if (aFile.isFile())
- return [fileName, modTime, 1];
-
- if (aFile.isDirectory()) {
- let entries = aFile.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
- let entry;
- let totalItems = 1;
- while ((entry = entries.nextFile)) {
- let [subName, subTime, items] = recursiveLastModifiedTime(entry);
- totalItems += items;
- if (subTime > modTime) {
- modTime = subTime;
- fileName = subName;
- }
- }
- entries.close();
- return [fileName, modTime, totalItems];
- }
- }
- catch (e) {
- logger.warn("Problem getting last modified time for " + aFile.path, e);
- }
-
- // If the file is something else, just ignore it.
- return ["", 0, 0];
-}
-
-/**
- * Gets a snapshot of directory entries.
- *
- * @param aDir
- * Directory to look at
- * @param aSortEntries
- * True to sort entries by filename
- * @return An array of nsIFile, or an empty array if aDir is not a readable directory
- */
-function getDirectoryEntries(aDir, aSortEntries) {
- let dirEnum;
- try {
- dirEnum = aDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
- let entries = [];
- while (dirEnum.hasMoreElements())
- entries.push(dirEnum.nextFile);
-
- if (aSortEntries) {
- entries.sort(function(a, b) {
- return a.path > b.path ? -1 : 1;
- });
- }
-
- return entries
- }
- catch (e) {
- logger.warn("Can't iterate directory " + aDir.path, e);
- return [];
- }
- finally {
- if (dirEnum) {
- dirEnum.close();
- }
- }
-}
-
-/**
- * Record a bit of per-addon telemetry
- * @param aAddon the addon to record
- */
-function recordAddonTelemetry(aAddon) {
- let locale = aAddon.defaultLocale;
- if (locale) {
- if (locale.name)
- XPIProvider.setTelemetry(aAddon.id, "name", locale.name);
- if (locale.creator)
- XPIProvider.setTelemetry(aAddon.id, "creator", locale.creator);
- }
-}
-
-/**
- * The on-disk state of an individual XPI, created from an Object
- * as stored in the 'extensions.xpiState' pref.
- */
-function XPIState(saved) {
- for (let [short, long] of XPIState.prototype.fields) {
- if (short in saved) {
- this[long] = saved[short];
- }
- }
-}
-
-XPIState.prototype = {
- fields: [['d', 'descriptor'],
- ['e', 'enabled'],
- ['v', 'version'],
- ['st', 'scanTime'],
- ['mt', 'manifestTime']],
- /**
- * Return the last modified time, based on enabled/disabled
- */
- get mtime() {
- if (!this.enabled && ('manifestTime' in this) && this.manifestTime > this.scanTime) {
- return this.manifestTime;
- }
- return this.scanTime;
- },
-
- toJSON() {
- let json = {};
- for (let [short, long] of XPIState.prototype.fields) {
- if (long in this) {
- json[short] = this[long];
- }
- }
- return json;
- },
-
- /**
- * Update the last modified time for an add-on on disk.
- * @param aFile: nsIFile path of the add-on.
- * @param aId: The add-on ID.
- * @return True if the time stamp has changed.
- */
- getModTime(aFile, aId) {
- let changed = false;
- let scanStarted = Cu.now();
- // For an unknown or enabled add-on, we do a full recursive scan.
- if (!('scanTime' in this) || this.enabled) {
- logger.debug('getModTime: Recursive scan of ' + aId);
- let [modFile, modTime, items] = recursiveLastModifiedTime(aFile);
- XPIProvider._mostRecentlyModifiedFile[aId] = modFile;
- XPIProvider.setTelemetry(aId, "scan_items", items);
- if (modTime != this.scanTime) {
- this.scanTime = modTime;
- changed = true;
- }
- }
- // if the add-on is disabled, modified time is the install manifest time, if
- // any. If no manifest exists, we assume this is a packed .xpi and use
- // the time stamp of {path}
- try {
- // Get the install manifest update time, if any.
- let maniFile = getManifestFileForDir(aFile);
- if (!(aId in XPIProvider._mostRecentlyModifiedFile)) {
- XPIProvider._mostRecentlyModifiedFile[aId] = maniFile.leafName;
- }
- let maniTime = maniFile.lastModifiedTime;
- if (maniTime != this.manifestTime) {
- this.manifestTime = maniTime;
- changed = true;
- }
- } catch (e) {
- // No manifest
- delete this.manifestTime;
- try {
- let dtime = aFile.lastModifiedTime;
- if (dtime != this.scanTime) {
- changed = true;
- this.scanTime = dtime;
- }
- } catch (e) {
- logger.warn("Can't get modified time of ${file}: ${e}", {file: aFile.path, e: e});
- changed = true;
- this.scanTime = 0;
- }
- }
- // Record duration of file-modified check
- XPIProvider.setTelemetry(aId, "scan_MS", Math.round(Cu.now() - scanStarted));
-
- return changed;
- },
-
- /**
- * Update the XPIState to match an XPIDatabase entry; if 'enabled' is changed to true,
- * update the last-modified time. This should probably be made async, but for now we
- * don't want to maintain parallel sync and async versions of the scan.
- * Caller is responsible for doing XPIStates.save() if necessary.
- * @param aDBAddon The DBAddonInternal for this add-on.
- * @param aUpdated The add-on was updated, so we must record new modified time.
- */
- syncWithDB(aDBAddon, aUpdated = false) {
- logger.debug("Updating XPIState for " + JSON.stringify(aDBAddon));
- // If the add-on changes from disabled to enabled, we should re-check the modified time.
- // If this is a newly found add-on, it won't have an 'enabled' field but we
- // did a full recursive scan in that case, so we don't need to do it again.
- // We don't use aDBAddon.active here because it's not updated until after restart.
- let mustGetMod = (aDBAddon.visible && !aDBAddon.disabled && !this.enabled);
- this.enabled = (aDBAddon.visible && !aDBAddon.disabled);
- this.version = aDBAddon.version;
- // XXX Eventually also copy bootstrap, etc.
- if (aUpdated || mustGetMod) {
- this.getModTime(new nsIFile(this.descriptor), aDBAddon.id);
- if (this.scanTime != aDBAddon.updateDate) {
- aDBAddon.updateDate = this.scanTime;
- XPIDatabase.saveChanges();
- }
- }
- },
-};
-
-// Constructor for an ES6 Map that knows how to convert itself into a
-// regular object for toJSON().
-function SerializableMap() {
- let m = new Map();
- m.toJSON = function() {
- let out = {}
- for (let [key, val] of m) {
- out[key] = val;
- }
- return out;
- };
- return m;
-}
-
-/**
- * Keeps track of the state of XPI add-ons on the file system.
- */
-this.XPIStates = {
- // Map(location name -> Map(add-on ID -> XPIState))
- db: null,
-
- get size() {
- if (!this.db) {
- return 0;
- }
- let count = 0;
- for (let location of this.db.values()) {
- count += location.size;
- }
- return count;
- },
-
- /**
- * Load extension state data from preferences.
- */
- loadExtensionState() {
- let state = {};
-
- // Clear out old directory state cache.
- Preferences.reset(PREF_INSTALL_CACHE);
-
- let cache = Preferences.get(PREF_XPI_STATE, "{}");
- try {
- state = JSON.parse(cache);
- } catch (e) {
- logger.warn("Error parsing extensions.xpiState ${state}: ${error}",
- {state: cache, error: e});
- }
- logger.debug("Loaded add-on state from prefs: ${}", state);
- return state;
- },
-
- /**
- * Walk through all install locations, highest priority first,
- * comparing the on-disk state of extensions to what is stored in prefs.
- * @return true if anything has changed.
- */
- getInstallState() {
- let oldState = this.loadExtensionState();
- let changed = false;
- this.db = new SerializableMap();
-
- for (let location of XPIProvider.installLocations) {
- // The list of add-on like file/directory names in the install location.
- let addons = location.getAddonLocations();
- // The results of scanning this location.
- let foundAddons = new SerializableMap();
-
- // What our old state thinks should be in this location.
- let locState = {};
- if (location.name in oldState) {
- locState = oldState[location.name];
- // We've seen this location.
- delete oldState[location.name];
- }
-
- for (let [id, file] of addons) {
- if (!(id in locState)) {
- logger.debug("New add-on ${id} in ${location}", {id: id, location: location.name});
- let xpiState = new XPIState({d: file.persistentDescriptor});
- changed = xpiState.getModTime(file, id) || changed;
- foundAddons.set(id, xpiState);
- } else {
- let xpiState = new XPIState(locState[id]);
- // We found this add-on in the file system
- delete locState[id];
-
- changed = xpiState.getModTime(file, id) || changed;
-
- if (file.persistentDescriptor != xpiState.descriptor) {
- xpiState.descriptor = file.persistentDescriptor;
- changed = true;
- }
- if (changed) {
- logger.debug("Changed add-on ${id} in ${location}", {id: id, location: location.name});
- }
- else {
- logger.debug("Existing add-on ${id} in ${location}", {id: id, location: location.name});
- }
- foundAddons.set(id, xpiState);
- }
- XPIProvider.setTelemetry(id, "location", location.name);
- }
-
- // Anything left behind in oldState was removed from the file system.
- for (let id in locState) {
- changed = true;
- break;
- }
- // If we found anything, add this location to our database.
- if (foundAddons.size != 0) {
- this.db.set(location.name, foundAddons);
- }
- }
-
- // If there's anything left in oldState, an install location that held add-ons
- // was removed from the browser configuration.
- for (let location in oldState) {
- changed = true;
- break;
- }
-
- logger.debug("getInstallState changed: ${rv}, state: ${state}",
- {rv: changed, state: this.db});
- return changed;
- },
-
- /**
- * Get the Map of XPI states for a particular location.
- * @param aLocation The name of the install location.
- * @return Map (id -> XPIState) or null if there are no add-ons in the location.
- */
- getLocation(aLocation) {
- return this.db.get(aLocation);
- },
-
- /**
- * Get the XPI state for a specific add-on in a location.
- * If the state is not in our cache, return null.
- * @param aLocation The name of the location where the add-on is installed.
- * @param aId The add-on ID
- * @return The XPIState entry for the add-on, or null.
- */
- getAddon(aLocation, aId) {
- let location = this.db.get(aLocation);
- if (!location) {
- return null;
- }
- return location.get(aId);
- },
-
- /**
- * Find the highest priority location of an add-on by ID and return the
- * location and the XPIState.
- * @param aId The add-on ID
- * @return [locationName, XPIState] if the add-on is found, [undefined, undefined]
- * if the add-on is not found.
- */
- findAddon(aId) {
- // Fortunately the Map iterator returns in order of insertion, which is
- // also our highest -> lowest priority order.
- for (let [name, location] of this.db) {
- if (location.has(aId)) {
- return [name, location.get(aId)];
- }
- }
- return [undefined, undefined];
- },
-
- /**
- * Add a new XPIState for an add-on and synchronize it with the DBAddonInternal.
- * @param aAddon DBAddonInternal for the new add-on.
- */
- addAddon(aAddon) {
- let location = this.db.get(aAddon.location);
- if (!location) {
- // First add-on in this location.
- location = new SerializableMap();
- this.db.set(aAddon.location, location);
- }
- logger.debug("XPIStates adding add-on ${id} in ${location}: ${descriptor}", aAddon);
- let xpiState = new XPIState({d: aAddon.descriptor});
- location.set(aAddon.id, xpiState);
- xpiState.syncWithDB(aAddon, true);
- XPIProvider.setTelemetry(aAddon.id, "location", aAddon.location);
- },
-
- /**
- * Save the current state of installed add-ons.
- * XXX this *totally* should be a .json file using DeferredSave...
- */
- save() {
- let cache = JSON.stringify(this.db);
- Services.prefs.setCharPref(PREF_XPI_STATE, cache);
- },
-
- /**
- * Remove the XPIState for an add-on and save the new state.
- * @param aLocation The name of the add-on location.
- * @param aId The ID of the add-on.
- */
- removeAddon(aLocation, aId) {
- logger.debug("Removing XPIState for " + aLocation + ":" + aId);
- let location = this.db.get(aLocation);
- if (!location) {
- return;
- }
- location.delete(aId);
- if (location.size == 0) {
- this.db.delete(aLocation);
- }
- this.save();
- },
-};
-
-this.XPIProvider = {
- get name() {
- return "XPIProvider";
- },
-
- // An array of known install locations
- installLocations: null,
- // A dictionary of known install locations by name
- installLocationsByName: null,
- // An array of currently active AddonInstalls
- installs: null,
- // The default skin for the application
- defaultSkin: "classic/1.0",
- // The current skin used by the application
- currentSkin: null,
- // The selected skin to be used by the application when it is restarted. This
- // will be the same as currentSkin when it is the skin to be used when the
- // application is restarted
- selectedSkin: null,
- // The value of the minCompatibleAppVersion preference
- minCompatibleAppVersion: null,
- // The value of the minCompatiblePlatformVersion preference
- minCompatiblePlatformVersion: null,
- // A dictionary of the file descriptors for bootstrappable add-ons by ID
- bootstrappedAddons: {},
- // A Map of active addons to their bootstrapScope by ID
- activeAddons: new Map(),
- // True if the platform could have activated extensions
- extensionsActive: false,
- // True if all of the add-ons found during startup were installed in the
- // application install location
- allAppGlobal: true,
- // A string listing the enabled add-ons for annotating crash reports
- enabledAddons: null,
- // Keep track of startup phases for telemetry
- runPhase: XPI_STARTING,
- // Keep track of the newest file in each add-on, in case we want to
- // report it to telemetry.
- _mostRecentlyModifiedFile: {},
- // Per-addon telemetry information
- _telemetryDetails: {},
- // A Map from an add-on install to its ID
- _addonFileMap: new Map(),
- // Flag to know if ToolboxProcess.jsm has already been loaded by someone or not
- _toolboxProcessLoaded: false,
- // Have we started shutting down bootstrap add-ons?
- _closing: false,
-
- /**
- * Returns an array of the add-on values in `bootstrappedAddons`,
- * sorted so that all of an add-on's dependencies appear in the array
- * before itself.
- *
- * @returns {Array<object>}
- * A sorted array of add-on objects. Each value is a copy of the
- * corresponding value in the `bootstrappedAddons` object, with an
- * additional `id` property, which corresponds to the key in that
- * object, which is the same as the add-ons ID.
- */
- sortBootstrappedAddons: function() {
- let addons = {};
-
- // Sort the list of IDs so that the ordering is deterministic.
- for (let id of Object.keys(this.bootstrappedAddons).sort()) {
- addons[id] = Object.assign({id}, this.bootstrappedAddons[id]);
- }
-
- let res = new Set();
- let seen = new Set();
-
- let add = addon => {
- seen.add(addon.id);
-
- for (let id of addon.dependencies || []) {
- if (id in addons && !seen.has(id)) {
- add(addons[id]);
- }
- }
-
- res.add(addon.id);
- }
-
- Object.values(addons).forEach(add);
-
- return Array.from(res, id => addons[id]);
- },
-
- /*
- * Set a value in the telemetry hash for a given ID
- */
- setTelemetry: function(aId, aName, aValue) {
- if (!this._telemetryDetails[aId])
- this._telemetryDetails[aId] = {};
- this._telemetryDetails[aId][aName] = aValue;
- },
-
- // Keep track of in-progress operations that support cancel()
- _inProgress: [],
-
- doing: function(aCancellable) {
- this._inProgress.push(aCancellable);
- },
-
- done: function(aCancellable) {
- let i = this._inProgress.indexOf(aCancellable);
- if (i != -1) {
- this._inProgress.splice(i, 1);
- return true;
- }
- return false;
- },
-
- cancelAll: function() {
- // Cancelling one may alter _inProgress, so don't use a simple iterator
- while (this._inProgress.length > 0) {
- let c = this._inProgress.shift();
- try {
- c.cancel();
- }
- catch (e) {
- logger.warn("Cancel failed", e);
- }
- }
- },
-
- /**
- * Adds or updates a URI mapping for an Addon.id.
- *
- * Mappings should not be removed at any point. This is so that the mappings
- * will be still valid after an add-on gets disabled or uninstalled, as
- * consumers may still have URIs of (leaked) resources they want to map.
- */
- _addURIMapping: function(aID, aFile) {
- logger.info("Mapping " + aID + " to " + aFile.path);
- this._addonFileMap.set(aID, aFile.path);
-
- AddonPathService.insertPath(aFile.path, aID);
- },
-
- /**
- * Resolve a URI back to physical file.
- *
- * Of course, this works only for URIs pointing to local resources.
- *
- * @param aURI
- * URI to resolve
- * @return
- * resolved nsIFileURL
- */
- _resolveURIToFile: function(aURI) {
- switch (aURI.scheme) {
- case "jar":
- case "file":
- if (aURI instanceof Ci.nsIJARURI) {
- return this._resolveURIToFile(aURI.JARFile);
- }
- return aURI;
-
- case "chrome":
- aURI = ChromeRegistry.convertChromeURL(aURI);
- return this._resolveURIToFile(aURI);
-
- case "resource":
- aURI = Services.io.newURI(ResProtocolHandler.resolveURI(aURI), null,
- null);
- return this._resolveURIToFile(aURI);
-
- case "view-source":
- aURI = Services.io.newURI(aURI.path, null, null);
- return this._resolveURIToFile(aURI);
-
- case "about":
- if (aURI.spec == "about:blank") {
- // Do not attempt to map about:blank
- return null;
- }
-
- let chan;
- try {
- chan = NetUtil.newChannel({
- uri: aURI,
- loadUsingSystemPrincipal: true
- });
- }
- catch (ex) {
- return null;
- }
- // Avoid looping
- if (chan.URI.equals(aURI)) {
- return null;
- }
- // We want to clone the channel URI to avoid accidentially keeping
- // unnecessary references to the channel or implementation details
- // around.
- return this._resolveURIToFile(chan.URI.clone());
-
- default:
- return null;
- }
- },
-
- /**
- * Starts the XPI provider initializes the install locations and prefs.
- *
- * @param aAppChanged
- * A tri-state value. Undefined means the current profile was created
- * for this session, true means the profile already existed but was
- * last used with an application with a different version number,
- * false means that the profile was last used by this version of the
- * application.
- * @param aOldAppVersion
- * The version of the application last run with this profile or null
- * if it is a new profile or the version is unknown
- * @param aOldPlatformVersion
- * The version of the platform last run with this profile or null
- * if it is a new profile or the version is unknown
- */
- startup: function(aAppChanged, aOldAppVersion, aOldPlatformVersion) {
- function addDirectoryInstallLocation(aName, aKey, aPaths, aScope, aLocked) {
- try {
- var dir = FileUtils.getDir(aKey, aPaths);
- }
- catch (e) {
- // Some directories aren't defined on some platforms, ignore them
- logger.debug("Skipping unavailable install location " + aName);
- return;
- }
-
- try {
- var location = aLocked ? new DirectoryInstallLocation(aName, dir, aScope)
- : new MutableDirectoryInstallLocation(aName, dir, aScope);
- }
- catch (e) {
- logger.warn("Failed to add directory install location " + aName, e);
- return;
- }
-
- XPIProvider.installLocations.push(location);
- XPIProvider.installLocationsByName[location.name] = location;
- }
-
- function addSystemAddonInstallLocation(aName, aKey, aPaths, aScope) {
- try {
- var dir = FileUtils.getDir(aKey, aPaths);
- }
- catch (e) {
- // Some directories aren't defined on some platforms, ignore them
- logger.debug("Skipping unavailable install location " + aName);
- return;
- }
-
- try {
- var location = new SystemAddonInstallLocation(aName, dir, aScope, aAppChanged !== false);
- }
- catch (e) {
- logger.warn("Failed to add system add-on install location " + aName, e);
- return;
- }
-
- XPIProvider.installLocations.push(location);
- XPIProvider.installLocationsByName[location.name] = location;
- }
-
- function addRegistryInstallLocation(aName, aRootkey, aScope) {
- try {
- var location = new WinRegInstallLocation(aName, aRootkey, aScope);
- }
- catch (e) {
- logger.warn("Failed to add registry install location " + aName, e);
- return;
- }
-
- XPIProvider.installLocations.push(location);
- XPIProvider.installLocationsByName[location.name] = location;
- }
-
- try {
- AddonManagerPrivate.recordTimestamp("XPI_startup_begin");
-
- logger.debug("startup");
- this.runPhase = XPI_STARTING;
- this.installs = new Set();
- this.installLocations = [];
- this.installLocationsByName = {};
- // Hook for tests to detect when saving database at shutdown time fails
- this._shutdownError = null;
- // Clear this at startup for xpcshell test restarts
- this._telemetryDetails = {};
- // Register our details structure with AddonManager
- AddonManagerPrivate.setTelemetryDetails("XPI", this._telemetryDetails);
-
- let hasRegistry = ("nsIWindowsRegKey" in Ci);
-
- let enabledScopes = Preferences.get(PREF_EM_ENABLED_SCOPES,
- AddonManager.SCOPE_ALL);
-
- // These must be in order of priority, highest to lowest,
- // for processFileChanges etc. to work
-
- XPIProvider.installLocations.push(TemporaryInstallLocation);
- XPIProvider.installLocationsByName[TemporaryInstallLocation.name] =
- TemporaryInstallLocation;
-
- // The profile location is always enabled
- addDirectoryInstallLocation(KEY_APP_PROFILE, KEY_PROFILEDIR,
- [DIR_EXTENSIONS],
- AddonManager.SCOPE_PROFILE, false);
-
- addSystemAddonInstallLocation(KEY_APP_SYSTEM_ADDONS, KEY_PROFILEDIR,
- [DIR_SYSTEM_ADDONS],
- AddonManager.SCOPE_PROFILE);
-
- addDirectoryInstallLocation(KEY_APP_SYSTEM_DEFAULTS, KEY_APP_FEATURES,
- [], AddonManager.SCOPE_PROFILE, true);
-
- if (enabledScopes & AddonManager.SCOPE_USER) {
- addDirectoryInstallLocation(KEY_APP_SYSTEM_USER, "XREUSysExt",
- [Services.appinfo.ID],
- AddonManager.SCOPE_USER, true);
- if (hasRegistry) {
- addRegistryInstallLocation("winreg-app-user",
- Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
- AddonManager.SCOPE_USER);
- }
- }
-
- addDirectoryInstallLocation(KEY_APP_GLOBAL, KEY_ADDON_APP_DIR,
- [DIR_EXTENSIONS],
- AddonManager.SCOPE_APPLICATION, true);
-
- if (enabledScopes & AddonManager.SCOPE_SYSTEM) {
- addDirectoryInstallLocation(KEY_APP_SYSTEM_SHARE, "XRESysSExtPD",
- [Services.appinfo.ID],
- AddonManager.SCOPE_SYSTEM, true);
- addDirectoryInstallLocation(KEY_APP_SYSTEM_LOCAL, "XRESysLExtPD",
- [Services.appinfo.ID],
- AddonManager.SCOPE_SYSTEM, true);
- if (hasRegistry) {
- addRegistryInstallLocation("winreg-app-global",
- Ci.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE,
- AddonManager.SCOPE_SYSTEM);
- }
- }
-
- let defaultPrefs = new Preferences({ defaultBranch: true });
- this.defaultSkin = defaultPrefs.get(PREF_GENERAL_SKINS_SELECTEDSKIN,
- "classic/1.0");
- this.currentSkin = Preferences.get(PREF_GENERAL_SKINS_SELECTEDSKIN,
- this.defaultSkin);
- this.selectedSkin = this.currentSkin;
- this.applyThemeChange();
-
- this.minCompatibleAppVersion = Preferences.get(PREF_EM_MIN_COMPAT_APP_VERSION,
- null);
- this.minCompatiblePlatformVersion = Preferences.get(PREF_EM_MIN_COMPAT_PLATFORM_VERSION,
- null);
- this.enabledAddons = "";
-
- Services.prefs.addObserver(PREF_EM_MIN_COMPAT_APP_VERSION, this, false);
- Services.prefs.addObserver(PREF_EM_MIN_COMPAT_PLATFORM_VERSION, this, false);
- if (!REQUIRE_SIGNING)
- Services.prefs.addObserver(PREF_XPI_SIGNATURES_REQUIRED, this, false);
- Services.obs.addObserver(this, NOTIFICATION_FLUSH_PERMISSIONS, false);
-
- // Cu.isModuleLoaded can fail here for external XUL apps where there is
- // no chrome.manifest that defines resource://devtools.
- if (ResProtocolHandler.hasSubstitution("devtools")) {
- if (Cu.isModuleLoaded("resource://devtools/client/framework/ToolboxProcess.jsm")) {
- // If BrowserToolboxProcess is already loaded, set the boolean to true
- // and do whatever is needed
- this._toolboxProcessLoaded = true;
- BrowserToolboxProcess.on("connectionchange",
- this.onDebugConnectionChange.bind(this));
- } else {
- // Else, wait for it to load
- Services.obs.addObserver(this, NOTIFICATION_TOOLBOXPROCESS_LOADED, false);
- }
- }
-
- let flushCaches = this.checkForChanges(aAppChanged, aOldAppVersion,
- aOldPlatformVersion);
-
- // Changes to installed extensions may have changed which theme is selected
- this.applyThemeChange();
-
- AddonManagerPrivate.markProviderSafe(this);
-
- if (aAppChanged && !this.allAppGlobal &&
- Preferences.get(PREF_EM_SHOW_MISMATCH_UI, true)) {
- let addonsToUpdate = this.shouldForceUpdateCheck(aAppChanged);
- if (addonsToUpdate) {
- this.showUpgradeUI(addonsToUpdate);
- flushCaches = true;
- }
- }
-
- if (flushCaches) {
- Services.obs.notifyObservers(null, "startupcache-invalidate", null);
- // UI displayed early in startup (like the compatibility UI) may have
- // caused us to cache parts of the skin or locale in memory. These must
- // be flushed to allow extension provided skins and locales to take full
- // effect
- Services.obs.notifyObservers(null, "chrome-flush-skin-caches", null);
- Services.obs.notifyObservers(null, "chrome-flush-caches", null);
- }
-
- this.enabledAddons = Preferences.get(PREF_EM_ENABLED_ADDONS, "");
-
- if ("nsICrashReporter" in Ci &&
- Services.appinfo instanceof Ci.nsICrashReporter) {
- // Annotate the crash report with relevant add-on information.
- try {
- Services.appinfo.annotateCrashReport("Theme", this.currentSkin);
- } catch (e) { }
- try {
- Services.appinfo.annotateCrashReport("EMCheckCompatibility",
- AddonManager.checkCompatibility);
- } catch (e) { }
- this.addAddonsToCrashReporter();
- }
-
- try {
- AddonManagerPrivate.recordTimestamp("XPI_bootstrap_addons_begin");
-
- for (let addon of this.sortBootstrappedAddons()) {
- try {
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- file.persistentDescriptor = addon.descriptor;
- let reason = BOOTSTRAP_REASONS.APP_STARTUP;
- // Eventually set INSTALLED reason when a bootstrap addon
- // is dropped in profile folder and automatically installed
- if (AddonManager.getStartupChanges(AddonManager.STARTUP_CHANGE_INSTALLED)
- .indexOf(addon.id) !== -1)
- reason = BOOTSTRAP_REASONS.ADDON_INSTALL;
- this.callBootstrapMethod(createAddonDetails(addon.id, addon),
- file, "startup", reason);
- }
- catch (e) {
- logger.error("Failed to load bootstrap addon " + addon.id + " from " +
- addon.descriptor, e);
- }
- }
- AddonManagerPrivate.recordTimestamp("XPI_bootstrap_addons_end");
- }
- catch (e) {
- logger.error("bootstrap startup failed", e);
- AddonManagerPrivate.recordException("XPI-BOOTSTRAP", "startup failed", e);
- }
-
- // Let these shutdown a little earlier when they still have access to most
- // of XPCOM
- Services.obs.addObserver({
- observe: function(aSubject, aTopic, aData) {
- XPIProvider._closing = true;
- for (let addon of XPIProvider.sortBootstrappedAddons().reverse()) {
- // If no scope has been loaded for this add-on then there is no need
- // to shut it down (should only happen when a bootstrapped add-on is
- // pending enable)
- if (!XPIProvider.activeAddons.has(addon.id))
- continue;
-
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- file.persistentDescriptor = addon.descriptor;
- let addonDetails = createAddonDetails(addon.id, addon);
-
- // If the add-on was pending disable then shut it down and remove it
- // from the persisted data.
- if (addon.disable) {
- XPIProvider.callBootstrapMethod(addonDetails, file, "shutdown",
- BOOTSTRAP_REASONS.ADDON_DISABLE);
- delete XPIProvider.bootstrappedAddons[addon.id];
- }
- else {
- XPIProvider.callBootstrapMethod(addonDetails, file, "shutdown",
- BOOTSTRAP_REASONS.APP_SHUTDOWN);
- }
- }
- Services.obs.removeObserver(this, "quit-application-granted");
- }
- }, "quit-application-granted", false);
-
- // Detect final-ui-startup for telemetry reporting
- Services.obs.addObserver({
- observe: function(aSubject, aTopic, aData) {
- AddonManagerPrivate.recordTimestamp("XPI_finalUIStartup");
- XPIProvider.runPhase = XPI_AFTER_UI_STARTUP;
- Services.obs.removeObserver(this, "final-ui-startup");
- }
- }, "final-ui-startup", false);
-
- AddonManagerPrivate.recordTimestamp("XPI_startup_end");
-
- this.extensionsActive = true;
- this.runPhase = XPI_BEFORE_UI_STARTUP;
-
- let timerManager = Cc["@mozilla.org/updates/timer-manager;1"].
- getService(Ci.nsIUpdateTimerManager);
- timerManager.registerTimer("xpi-signature-verification", () => {
- this.verifySignatures();
- }, XPI_SIGNATURE_CHECK_PERIOD);
- }
- catch (e) {
- logger.error("startup failed", e);
- AddonManagerPrivate.recordException("XPI", "startup failed", e);
- }
- },
-
- /**
- * Shuts down the database and releases all references.
- * Return: Promise{integer} resolves / rejects with the result of
- * flushing the XPI Database if it was loaded,
- * 0 otherwise.
- */
- shutdown: function() {
- logger.debug("shutdown");
-
- // Stop anything we were doing asynchronously
- this.cancelAll();
-
- this.bootstrappedAddons = {};
- this.activeAddons.clear();
- this.enabledAddons = null;
- this.allAppGlobal = true;
-
- // If there are pending operations then we must update the list of active
- // add-ons
- if (Preferences.get(PREF_PENDING_OPERATIONS, false)) {
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_pending_ops", 1);
- XPIDatabase.updateActiveAddons();
- Services.prefs.setBoolPref(PREF_PENDING_OPERATIONS,
- !XPIDatabase.writeAddonsList());
- }
-
- this.installs = null;
- this.installLocations = null;
- this.installLocationsByName = null;
-
- // This is needed to allow xpcshell tests to simulate a restart
- this.extensionsActive = false;
- this._addonFileMap.clear();
-
- if (gLazyObjectsLoaded) {
- let done = XPIDatabase.shutdown();
- done.then(
- ret => {
- logger.debug("Notifying XPI shutdown observers");
- Services.obs.notifyObservers(null, "xpi-provider-shutdown", null);
- },
- err => {
- logger.debug("Notifying XPI shutdown observers");
- this._shutdownError = err;
- Services.obs.notifyObservers(null, "xpi-provider-shutdown", err);
- }
- );
- return done;
- }
- logger.debug("Notifying XPI shutdown observers");
- Services.obs.notifyObservers(null, "xpi-provider-shutdown", null);
- return undefined;
- },
-
- /**
- * Applies any pending theme change to the preferences.
- */
- applyThemeChange: function() {
- if (!Preferences.get(PREF_DSS_SWITCHPENDING, false))
- return;
-
- // Tell the Chrome Registry which Skin to select
- try {
- this.selectedSkin = Preferences.get(PREF_DSS_SKIN_TO_SELECT);
- Services.prefs.setCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN,
- this.selectedSkin);
- Services.prefs.clearUserPref(PREF_DSS_SKIN_TO_SELECT);
- logger.debug("Changed skin to " + this.selectedSkin);
- this.currentSkin = this.selectedSkin;
- }
- catch (e) {
- logger.error("Error applying theme change", e);
- }
- Services.prefs.clearUserPref(PREF_DSS_SWITCHPENDING);
- },
-
- /**
- * If the application has been upgraded and there are add-ons outside the
- * application directory then we may need to synchronize compatibility
- * information but only if the mismatch UI isn't disabled.
- *
- * @returns False if no update check is needed, otherwise an array of add-on
- * IDs to check for updates. Array may be empty if no add-ons can be/need
- * to be updated, but the metadata check needs to be performed.
- */
- shouldForceUpdateCheck: function(aAppChanged) {
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_metadata_age", AddonRepository.metadataAge());
-
- let startupChanges = AddonManager.getStartupChanges(AddonManager.STARTUP_CHANGE_DISABLED);
- logger.debug("shouldForceUpdateCheck startupChanges: " + startupChanges.toSource());
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_startup_disabled", startupChanges.length);
-
- let forceUpdate = [];
- if (startupChanges.length > 0) {
- let addons = XPIDatabase.getAddons();
- for (let addon of addons) {
- if ((startupChanges.indexOf(addon.id) != -1) &&
- (addon.permissions() & AddonManager.PERM_CAN_UPGRADE) &&
- !addon.isCompatible) {
- logger.debug("shouldForceUpdateCheck: can upgrade disabled add-on " + addon.id);
- forceUpdate.push(addon.id);
- }
- }
- }
-
- if (AddonRepository.isMetadataStale()) {
- logger.debug("shouldForceUpdateCheck: metadata is stale");
- return forceUpdate;
- }
- if (forceUpdate.length > 0) {
- return forceUpdate;
- }
-
- return false;
- },
-
- /**
- * Shows the "Compatibility Updates" UI.
- *
- * @param aAddonIDs
- * Array opf addon IDs that were disabled by the application update, and
- * should therefore be checked for updates.
- */
- showUpgradeUI: function(aAddonIDs) {
- logger.debug("XPI_showUpgradeUI: " + aAddonIDs.toSource());
- Services.telemetry.getHistogramById("ADDON_MANAGER_UPGRADE_UI_SHOWN").add(1);
-
- // Flip a flag to indicate that we interrupted startup with an interactive prompt
- Services.startup.interrupted = true;
-
- var variant = Cc["@mozilla.org/variant;1"].
- createInstance(Ci.nsIWritableVariant);
- variant.setFromVariant(aAddonIDs);
-
- // This *must* be modal as it has to block startup.
- var features = "chrome,centerscreen,dialog,titlebar,modal";
- var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
- getService(Ci.nsIWindowWatcher);
- ww.openWindow(null, URI_EXTENSION_UPDATE_DIALOG, "", features, variant);
-
- // Ensure any changes to the add-ons list are flushed to disk
- Services.prefs.setBoolPref(PREF_PENDING_OPERATIONS,
- !XPIDatabase.writeAddonsList());
- },
-
- updateSystemAddons: Task.async(function*() {
- let systemAddonLocation = XPIProvider.installLocationsByName[KEY_APP_SYSTEM_ADDONS];
- if (!systemAddonLocation)
- return;
-
- // Don't do anything in safe mode
- if (Services.appinfo.inSafeMode)
- return;
-
- // Download the list of system add-ons
- let url = Preferences.get(PREF_SYSTEM_ADDON_UPDATE_URL, null);
- if (!url) {
- yield systemAddonLocation.cleanDirectories();
- return;
- }
-
- url = UpdateUtils.formatUpdateURL(url);
-
- logger.info(`Starting system add-on update check from ${url}.`);
- let res = yield ProductAddonChecker.getProductAddonList(url);
-
- // If there was no list then do nothing.
- if (!res || !res.gmpAddons) {
- logger.info("No system add-ons list was returned.");
- yield systemAddonLocation.cleanDirectories();
- return;
- }
-
- let addonList = new Map(
- res.gmpAddons.map(spec => [spec.id, { spec, path: null, addon: null }]));
-
- let getAddonsInLocation = (location) => {
- return new Promise(resolve => {
- XPIDatabase.getAddonsInLocation(location, resolve);
- });
- };
-
- let setMatches = (wanted, existing) => {
- if (wanted.size != existing.size)
- return false;
-
- for (let [id, addon] of existing) {
- let wantedInfo = wanted.get(id);
-
- if (!wantedInfo)
- return false;
- if (wantedInfo.spec.version != addon.version)
- return false;
- }
-
- return true;
- };
-
- // If this matches the current set in the profile location then do nothing.
- let updatedAddons = addonMap(yield getAddonsInLocation(KEY_APP_SYSTEM_ADDONS));
- if (setMatches(addonList, updatedAddons)) {
- logger.info("Retaining existing updated system add-ons.");
- yield systemAddonLocation.cleanDirectories();
- return;
- }
-
- // If this matches the current set in the default location then reset the
- // updated set.
- let defaultAddons = addonMap(yield getAddonsInLocation(KEY_APP_SYSTEM_DEFAULTS));
- if (setMatches(addonList, defaultAddons)) {
- logger.info("Resetting system add-ons.");
- systemAddonLocation.resetAddonSet();
- yield systemAddonLocation.cleanDirectories();
- return;
- }
-
- // Download all the add-ons
- let downloadAddon = Task.async(function*(item) {
- try {
- let sourceAddon = updatedAddons.get(item.spec.id);
- if (sourceAddon && sourceAddon.version == item.spec.version) {
- // Copying the file to a temporary location has some benefits. If the
- // file is locked and cannot be read then we'll fall back to
- // downloading a fresh copy. It also means we don't have to remember
- // whether to delete the temporary copy later.
- try {
- let path = OS.Path.join(OS.Constants.Path.tmpDir, "tmpaddon");
- let unique = yield OS.File.openUnique(path);
- unique.file.close();
- yield OS.File.copy(sourceAddon._sourceBundle.path, unique.path);
- // Make sure to update file modification times so this is detected
- // as a new add-on.
- yield OS.File.setDates(unique.path);
- item.path = unique.path;
- }
- catch (e) {
- logger.warn(`Failed make temporary copy of ${sourceAddon._sourceBundle.path}.`, e);
- }
- }
- if (!item.path) {
- item.path = yield ProductAddonChecker.downloadAddon(item.spec);
- }
- item.addon = yield loadManifestFromFile(nsIFile(item.path), systemAddonLocation);
- }
- catch (e) {
- logger.error(`Failed to download system add-on ${item.spec.id}`, e);
- }
- });
- yield Promise.all(Array.from(addonList.values()).map(downloadAddon));
-
- // The download promises all resolve regardless, now check if they all
- // succeeded
- let validateAddon = (item) => {
- if (item.spec.id != item.addon.id) {
- logger.warn(`Downloaded system add-on expected to be ${item.spec.id} but was ${item.addon.id}.`);
- return false;
- }
-
- if (item.spec.version != item.addon.version) {
- logger.warn(`Expected system add-on ${item.spec.id} to be version ${item.spec.version} but was ${item.addon.version}.`);
- return false;
- }
-
- if (!systemAddonLocation.isValidAddon(item.addon))
- return false;
-
- return true;
- }
-
- if (!Array.from(addonList.values()).every(item => item.path && item.addon && validateAddon(item))) {
- throw new Error("Rejecting updated system add-on set that either could not " +
- "be downloaded or contained unusable add-ons.");
- }
-
- // Install into the install location
- logger.info("Installing new system add-on set");
- yield systemAddonLocation.installAddonSet(Array.from(addonList.values())
- .map(a => a.addon));
- }),
-
- /**
- * Verifies that all installed add-ons are still correctly signed.
- */
- verifySignatures: function() {
- XPIDatabase.getAddonList(a => true, (addons) => {
- Task.spawn(function*() {
- let changes = {
- enabled: [],
- disabled: []
- };
-
- for (let addon of addons) {
- // The add-on might have vanished, we'll catch that on the next startup
- if (!addon._sourceBundle.exists())
- continue;
-
- let signedState = yield verifyBundleSignedState(addon._sourceBundle, addon);
-
- if (signedState != addon.signedState) {
- addon.signedState = signedState;
- AddonManagerPrivate.callAddonListeners("onPropertyChanged",
- addon.wrapper,
- ["signedState"]);
- }
-
- let disabled = XPIProvider.updateAddonDisabledState(addon);
- if (disabled !== undefined)
- changes[disabled ? "disabled" : "enabled"].push(addon.id);
- }
-
- XPIDatabase.saveChanges();
-
- Services.obs.notifyObservers(null, "xpi-signature-changed", JSON.stringify(changes));
- }).then(null, err => {
- logger.error("XPI_verifySignature: " + err);
- })
- });
- },
-
- /**
- * Persists changes to XPIProvider.bootstrappedAddons to its store (a pref).
- */
- persistBootstrappedAddons: function() {
- // Experiments are disabled upon app load, so don't persist references.
- let filtered = {};
- for (let id in this.bootstrappedAddons) {
- let entry = this.bootstrappedAddons[id];
- if (entry.type == "experiment") {
- continue;
- }
-
- filtered[id] = entry;
- }
-
- Services.prefs.setCharPref(PREF_BOOTSTRAP_ADDONS,
- JSON.stringify(filtered));
- },
-
- /**
- * Adds a list of currently active add-ons to the next crash report.
- */
- addAddonsToCrashReporter: function() {
- if (!("nsICrashReporter" in Ci) ||
- !(Services.appinfo instanceof Ci.nsICrashReporter))
- return;
-
- // In safe mode no add-ons are loaded so we should not include them in the
- // crash report
- if (Services.appinfo.inSafeMode)
- return;
-
- let data = this.enabledAddons;
- for (let id in this.bootstrappedAddons) {
- data += (data ? "," : "") + encodeURIComponent(id) + ":" +
- encodeURIComponent(this.bootstrappedAddons[id].version);
- }
-
- try {
- Services.appinfo.annotateCrashReport("Add-ons", data);
- }
- catch (e) { }
-
- let TelemetrySession =
- Cu.import("resource://gre/modules/TelemetrySession.jsm", {}).TelemetrySession;
- TelemetrySession.setAddOns(data);
- },
-
- /**
- * Check the staging directories of install locations for any add-ons to be
- * installed or add-ons to be uninstalled.
- *
- * @param aManifests
- * A dictionary to add detected install manifests to for the purpose
- * of passing through updated compatibility information
- * @return true if an add-on was installed or uninstalled
- */
- processPendingFileChanges: function(aManifests) {
- let changed = false;
- for (let location of this.installLocations) {
- aManifests[location.name] = {};
- // We can't install or uninstall anything in locked locations
- if (location.locked) {
- continue;
- }
-
- let stagingDir = location.getStagingDir();
-
- try {
- if (!stagingDir || !stagingDir.exists() || !stagingDir.isDirectory())
- continue;
- }
- catch (e) {
- logger.warn("Failed to find staging directory", e);
- continue;
- }
-
- let seenFiles = [];
- // Use a snapshot of the directory contents to avoid possible issues with
- // iterating over a directory while removing files from it (the YAFFS2
- // embedded filesystem has this issue, see bug 772238), and to remove
- // normal files before their resource forks on OSX (see bug 733436).
- let stagingDirEntries = getDirectoryEntries(stagingDir, true);
- for (let stageDirEntry of stagingDirEntries) {
- let id = stageDirEntry.leafName;
-
- let isDir;
- try {
- isDir = stageDirEntry.isDirectory();
- }
- catch (e) {
- if (e.result != Cr.NS_ERROR_FILE_TARGET_DOES_NOT_EXIST)
- throw e;
- // If the file has already gone away then don't worry about it, this
- // can happen on OSX where the resource fork is automatically moved
- // with the data fork for the file. See bug 733436.
- continue;
- }
-
- if (!isDir) {
- if (id.substring(id.length - 4).toLowerCase() == ".xpi") {
- id = id.substring(0, id.length - 4);
- }
- else {
- if (id.substring(id.length - 5).toLowerCase() != ".json") {
- logger.warn("Ignoring file: " + stageDirEntry.path);
- seenFiles.push(stageDirEntry.leafName);
- }
- continue;
- }
- }
-
- // Check that the directory's name is a valid ID.
- if (!gIDTest.test(id)) {
- logger.warn("Ignoring directory whose name is not a valid add-on ID: " +
- stageDirEntry.path);
- seenFiles.push(stageDirEntry.leafName);
- continue;
- }
-
- changed = true;
-
- if (isDir) {
- // Check if the directory contains an install manifest.
- let manifest = getManifestFileForDir(stageDirEntry);
-
- // If the install manifest doesn't exist uninstall this add-on in this
- // install location.
- if (!manifest) {
- logger.debug("Processing uninstall of " + id + " in " + location.name);
-
- try {
- let addonFile = location.getLocationForID(id);
- let addonToUninstall = syncLoadManifestFromFile(addonFile, location);
- if (addonToUninstall.bootstrap) {
- this.callBootstrapMethod(addonToUninstall, addonToUninstall._sourceBundle,
- "uninstall", BOOTSTRAP_REASONS.ADDON_UNINSTALL);
- }
- }
- catch (e) {
- logger.warn("Failed to call uninstall for " + id, e);
- }
-
- try {
- location.uninstallAddon(id);
- seenFiles.push(stageDirEntry.leafName);
- }
- catch (e) {
- logger.error("Failed to uninstall add-on " + id + " in " + location.name, e);
- }
- // The file check later will spot the removal and cleanup the database
- continue;
- }
- }
-
- aManifests[location.name][id] = null;
- let existingAddonID = id;
-
- let jsonfile = stagingDir.clone();
- jsonfile.append(id + ".json");
- // Assume this was a foreign install if there is no cached metadata file
- let foreignInstall = !jsonfile.exists();
- let addon;
-
- try {
- addon = syncLoadManifestFromFile(stageDirEntry, location);
- }
- catch (e) {
- logger.error("Unable to read add-on manifest from " + stageDirEntry.path, e);
- // This add-on can't be installed so just remove it now
- seenFiles.push(stageDirEntry.leafName);
- seenFiles.push(jsonfile.leafName);
- continue;
- }
-
- if (mustSign(addon.type) &&
- addon.signedState <= AddonManager.SIGNEDSTATE_MISSING) {
- logger.warn("Refusing to install staged add-on " + id + " with signed state " + addon.signedState);
- seenFiles.push(stageDirEntry.leafName);
- seenFiles.push(jsonfile.leafName);
- continue;
- }
-
- // Check for a cached metadata for this add-on, it may contain updated
- // compatibility information
- if (!foreignInstall) {
- logger.debug("Found updated metadata for " + id + " in " + location.name);
- let fis = Cc["@mozilla.org/network/file-input-stream;1"].
- createInstance(Ci.nsIFileInputStream);
- let json = Cc["@mozilla.org/dom/json;1"].
- createInstance(Ci.nsIJSON);
-
- try {
- fis.init(jsonfile, -1, 0, 0);
- let metadata = json.decodeFromStream(fis, jsonfile.fileSize);
- addon.importMetadata(metadata);
-
- // Pass this through to addMetadata so it knows this add-on was
- // likely installed through the UI
- aManifests[location.name][id] = addon;
- }
- catch (e) {
- // If some data can't be recovered from the cached metadata then it
- // is unlikely to be a problem big enough to justify throwing away
- // the install, just log an error and continue
- logger.error("Unable to read metadata from " + jsonfile.path, e);
- }
- finally {
- fis.close();
- }
- }
- seenFiles.push(jsonfile.leafName);
-
- existingAddonID = addon.existingAddonID || id;
-
- var oldBootstrap = null;
- logger.debug("Processing install of " + id + " in " + location.name);
- if (existingAddonID in this.bootstrappedAddons) {
- try {
- var existingAddon = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- existingAddon.persistentDescriptor = this.bootstrappedAddons[existingAddonID].descriptor;
- if (existingAddon.exists()) {
- oldBootstrap = this.bootstrappedAddons[existingAddonID];
-
- // We'll be replacing a currently active bootstrapped add-on so
- // call its uninstall method
- let newVersion = addon.version;
- let oldVersion = oldBootstrap.version;
- let uninstallReason = Services.vc.compare(oldVersion, newVersion) < 0 ?
- BOOTSTRAP_REASONS.ADDON_UPGRADE :
- BOOTSTRAP_REASONS.ADDON_DOWNGRADE;
-
- this.callBootstrapMethod(createAddonDetails(existingAddonID, oldBootstrap),
- existingAddon, "uninstall", uninstallReason,
- { newVersion: newVersion });
- this.unloadBootstrapScope(existingAddonID);
- flushChromeCaches();
- }
- }
- catch (e) {
- }
- }
-
- try {
- addon._sourceBundle = location.installAddon({
- id,
- source: stageDirEntry,
- existingAddonID
- });
- }
- catch (e) {
- logger.error("Failed to install staged add-on " + id + " in " + location.name,
- e);
- // Re-create the staged install
- new StagedAddonInstall(location, stageDirEntry, addon);
- // Make sure not to delete the cached manifest json file
- seenFiles.pop();
-
- delete aManifests[location.name][id];
-
- if (oldBootstrap) {
- // Re-install the old add-on
- this.callBootstrapMethod(createAddonDetails(existingAddonID, oldBootstrap),
- existingAddon, "install",
- BOOTSTRAP_REASONS.ADDON_INSTALL);
- }
- continue;
- }
- }
-
- try {
- location.cleanStagingDir(seenFiles);
- }
- catch (e) {
- // Non-critical, just saves some perf on startup if we clean this up.
- logger.debug("Error cleaning staging dir " + stagingDir.path, e);
- }
- }
- return changed;
- },
-
- /**
- * Installs any add-ons located in the extensions directory of the
- * application's distribution specific directory into the profile unless a
- * newer version already exists or the user has previously uninstalled the
- * distributed add-on.
- *
- * @param aManifests
- * A dictionary to add new install manifests to to save having to
- * reload them later
- * @param aAppChanged
- * See checkForChanges
- * @return true if any new add-ons were installed
- */
- installDistributionAddons: function(aManifests, aAppChanged) {
- let distroDir;
- try {
- distroDir = FileUtils.getDir(KEY_APP_DISTRIBUTION, [DIR_EXTENSIONS]);
- }
- catch (e) {
- return false;
- }
-
- if (!distroDir.exists())
- return false;
-
- if (!distroDir.isDirectory())
- return false;
-
- let changed = false;
- let profileLocation = this.installLocationsByName[KEY_APP_PROFILE];
-
- let entries = distroDir.directoryEntries
- .QueryInterface(Ci.nsIDirectoryEnumerator);
- let entry;
- while ((entry = entries.nextFile)) {
-
- let id = entry.leafName;
-
- if (entry.isFile()) {
- if (id.substring(id.length - 4).toLowerCase() == ".xpi") {
- id = id.substring(0, id.length - 4);
- }
- else {
- logger.debug("Ignoring distribution add-on that isn't an XPI: " + entry.path);
- continue;
- }
- }
- else if (!entry.isDirectory()) {
- logger.debug("Ignoring distribution add-on that isn't a file or directory: " +
- entry.path);
- continue;
- }
-
- if (!gIDTest.test(id)) {
- logger.debug("Ignoring distribution add-on whose name is not a valid add-on ID: " +
- entry.path);
- continue;
- }
-
- /* If this is not an upgrade and we've already handled this extension
- * just continue */
- if (!aAppChanged && Preferences.isSet(PREF_BRANCH_INSTALLED_ADDON + id)) {
- continue;
- }
-
- let addon;
- try {
- addon = syncLoadManifestFromFile(entry, profileLocation);
- }
- catch (e) {
- logger.warn("File entry " + entry.path + " contains an invalid add-on", e);
- continue;
- }
-
- if (addon.id != id) {
- logger.warn("File entry " + entry.path + " contains an add-on with an " +
- "incorrect ID")
- continue;
- }
-
- let existingEntry = null;
- try {
- existingEntry = profileLocation.getLocationForID(id);
- }
- catch (e) {
- }
-
- if (existingEntry) {
- let existingAddon;
- try {
- existingAddon = syncLoadManifestFromFile(existingEntry, profileLocation);
-
- if (Services.vc.compare(addon.version, existingAddon.version) <= 0)
- continue;
- }
- catch (e) {
- // Bad add-on in the profile so just proceed and install over the top
- logger.warn("Profile contains an add-on with a bad or missing install " +
- "manifest at " + existingEntry.path + ", overwriting", e);
- }
- }
- else if (Preferences.get(PREF_BRANCH_INSTALLED_ADDON + id, false)) {
- continue;
- }
-
- // Install the add-on
- try {
- addon._sourceBundle = profileLocation.installAddon({ id, source: entry, action: "copy" });
- logger.debug("Installed distribution add-on " + id);
-
- Services.prefs.setBoolPref(PREF_BRANCH_INSTALLED_ADDON + id, true)
-
- // aManifests may contain a copy of a newly installed add-on's manifest
- // and we'll have overwritten that so instead cache our install manifest
- // which will later be put into the database in processFileChanges
- if (!(KEY_APP_PROFILE in aManifests))
- aManifests[KEY_APP_PROFILE] = {};
- aManifests[KEY_APP_PROFILE][id] = addon;
- changed = true;
- }
- catch (e) {
- logger.error("Failed to install distribution add-on " + entry.path, e);
- }
- }
-
- entries.close();
-
- return changed;
- },
-
- /**
- * Imports the xpinstall permissions from preferences into the permissions
- * manager for the user to change later.
- */
- importPermissions: function() {
- PermissionsUtils.importFromPrefs(PREF_XPI_PERMISSIONS_BRANCH,
- XPI_PERMISSION);
- },
-
- getDependentAddons: function(aAddon) {
- return Array.from(XPIDatabase.getAddons())
- .filter(addon => addon.dependencies.includes(aAddon.id));
- },
-
- /**
- * Checks for any changes that have occurred since the last time the
- * application was launched.
- *
- * @param aAppChanged
- * A tri-state value. Undefined means the current profile was created
- * for this session, true means the profile already existed but was
- * last used with an application with a different version number,
- * false means that the profile was last used by this version of the
- * application.
- * @param aOldAppVersion
- * The version of the application last run with this profile or null
- * if it is a new profile or the version is unknown
- * @param aOldPlatformVersion
- * The version of the platform last run with this profile or null
- * if it is a new profile or the version is unknown
- * @return true if a change requiring a restart was detected
- */
- checkForChanges: function(aAppChanged, aOldAppVersion,
- aOldPlatformVersion) {
- logger.debug("checkForChanges");
-
- // Keep track of whether and why we need to open and update the database at
- // startup time.
- let updateReasons = [];
- if (aAppChanged) {
- updateReasons.push("appChanged");
- }
-
- // Load the list of bootstrapped add-ons first so processFileChanges can
- // modify it
- // XXX eventually get rid of bootstrappedAddons
- try {
- this.bootstrappedAddons = JSON.parse(Preferences.get(PREF_BOOTSTRAP_ADDONS,
- "{}"));
- } catch (e) {
- logger.warn("Error parsing enabled bootstrapped extensions cache", e);
- }
-
- // First install any new add-ons into the locations, if there are any
- // changes then we must update the database with the information in the
- // install locations
- let manifests = {};
- let updated = this.processPendingFileChanges(manifests);
- if (updated) {
- updateReasons.push("pendingFileChanges");
- }
-
- // This will be true if the previous session made changes that affect the
- // active state of add-ons but didn't commit them properly (normally due
- // to the application crashing)
- let hasPendingChanges = Preferences.get(PREF_PENDING_OPERATIONS);
- if (hasPendingChanges) {
- updateReasons.push("hasPendingChanges");
- }
-
- // If the application has changed then check for new distribution add-ons
- if (Preferences.get(PREF_INSTALL_DISTRO_ADDONS, true))
- {
- updated = this.installDistributionAddons(manifests, aAppChanged);
- if (updated) {
- updateReasons.push("installDistributionAddons");
- }
- }
-
- // Telemetry probe added around getInstallState() to check perf
- let telemetryCaptureTime = Cu.now();
- let installChanged = XPIStates.getInstallState();
- let telemetry = Services.telemetry;
- telemetry.getHistogramById("CHECK_ADDONS_MODIFIED_MS").add(Math.round(Cu.now() - telemetryCaptureTime));
- if (installChanged) {
- updateReasons.push("directoryState");
- }
-
- let haveAnyAddons = (XPIStates.size > 0);
-
- // If the schema appears to have changed then we should update the database
- if (DB_SCHEMA != Preferences.get(PREF_DB_SCHEMA, 0)) {
- // If we don't have any add-ons, just update the pref, since we don't need to
- // write the database
- if (!haveAnyAddons) {
- logger.debug("Empty XPI database, setting schema version preference to " + DB_SCHEMA);
- Services.prefs.setIntPref(PREF_DB_SCHEMA, DB_SCHEMA);
- }
- else {
- updateReasons.push("schemaChanged");
- }
- }
-
- // If the database doesn't exist and there are add-ons installed then we
- // must update the database however if there are no add-ons then there is
- // no need to update the database.
- let dbFile = FileUtils.getFile(KEY_PROFILEDIR, [FILE_DATABASE], true);
- if (!dbFile.exists() && haveAnyAddons) {
- updateReasons.push("needNewDatabase");
- }
-
- // XXX This will go away when we fold bootstrappedAddons into XPIStates.
- if (updateReasons.length == 0) {
- let bootstrapDescriptors = new Set(Object.keys(this.bootstrappedAddons)
- .map(b => this.bootstrappedAddons[b].descriptor));
-
- for (let location of XPIStates.db.values()) {
- for (let state of location.values()) {
- bootstrapDescriptors.delete(state.descriptor);
- }
- }
-
- if (bootstrapDescriptors.size > 0) {
- logger.warn("Bootstrap state is invalid (missing add-ons: "
- + Array.from(bootstrapDescriptors).join(", ") + ")");
- updateReasons.push("missingBootstrapAddon");
- }
- }
-
- // Catch and log any errors during the main startup
- try {
- let extensionListChanged = false;
- // If the database needs to be updated then open it and then update it
- // from the filesystem
- if (updateReasons.length > 0) {
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_startup_load_reasons", updateReasons);
- XPIDatabase.syncLoadDB(false);
- try {
- extensionListChanged = XPIDatabaseReconcile.processFileChanges(manifests,
- aAppChanged,
- aOldAppVersion,
- aOldPlatformVersion,
- updateReasons.includes("schemaChanged"));
- }
- catch (e) {
- logger.error("Failed to process extension changes at startup", e);
- }
- }
-
- if (aAppChanged) {
- // When upgrading the app and using a custom skin make sure it is still
- // compatible otherwise switch back the default
- if (this.currentSkin != this.defaultSkin) {
- let oldSkin = XPIDatabase.getVisibleAddonForInternalName(this.currentSkin);
- if (!oldSkin || oldSkin.disabled)
- this.enableDefaultTheme();
- }
-
- // When upgrading remove the old extensions cache to force older
- // versions to rescan the entire list of extensions
- let oldCache = FileUtils.getFile(KEY_PROFILEDIR, [FILE_OLD_CACHE], true);
- try {
- if (oldCache.exists())
- oldCache.remove(true);
- }
- catch (e) {
- logger.warn("Unable to remove old extension cache " + oldCache.path, e);
- }
- }
-
- // If the application crashed before completing any pending operations then
- // we should perform them now.
- if (extensionListChanged || hasPendingChanges) {
- logger.debug("Updating database with changes to installed add-ons");
- XPIDatabase.updateActiveAddons();
- Services.prefs.setBoolPref(PREF_PENDING_OPERATIONS,
- !XPIDatabase.writeAddonsList());
- Services.prefs.setCharPref(PREF_BOOTSTRAP_ADDONS,
- JSON.stringify(this.bootstrappedAddons));
- return true;
- }
-
- logger.debug("No changes found");
- }
- catch (e) {
- logger.error("Error during startup file checks", e);
- }
-
- // Check that the add-ons list still exists
- let addonsList = FileUtils.getFile(KEY_PROFILEDIR, [FILE_XPI_ADDONS_LIST],
- true);
- // the addons list file should exist if and only if we have add-ons installed
- if (addonsList.exists() != haveAnyAddons) {
- logger.debug("Add-ons list is invalid, rebuilding");
- XPIDatabase.writeAddonsList();
- }
-
- return false;
- },
-
- /**
- * Called to test whether this provider supports installing a particular
- * mimetype.
- *
- * @param aMimetype
- * The mimetype to check for
- * @return true if the mimetype is application/x-xpinstall
- */
- supportsMimetype: function(aMimetype) {
- return aMimetype == "application/x-xpinstall";
- },
-
- /**
- * Called to test whether installing XPI add-ons is enabled.
- *
- * @return true if installing is enabled
- */
- isInstallEnabled: function() {
- // Default to enabled if the preference does not exist
- return Preferences.get(PREF_XPI_ENABLED, true);
- },
-
- /**
- * Called to test whether installing XPI add-ons by direct URL requests is
- * whitelisted.
- *
- * @return true if installing by direct requests is whitelisted
- */
- isDirectRequestWhitelisted: function() {
- // Default to whitelisted if the preference does not exist.
- return Preferences.get(PREF_XPI_DIRECT_WHITELISTED, true);
- },
-
- /**
- * Called to test whether installing XPI add-ons from file referrers is
- * whitelisted.
- *
- * @return true if installing from file referrers is whitelisted
- */
- isFileRequestWhitelisted: function() {
- // Default to whitelisted if the preference does not exist.
- return Preferences.get(PREF_XPI_FILE_WHITELISTED, true);
- },
-
- /**
- * Called to test whether installing XPI add-ons from a URI is allowed.
- *
- * @param aInstallingPrincipal
- * The nsIPrincipal that initiated the install
- * @return true if installing is allowed
- */
- isInstallAllowed: function(aInstallingPrincipal) {
- if (!this.isInstallEnabled())
- return false;
-
- let uri = aInstallingPrincipal.URI;
-
- // Direct requests without a referrer are either whitelisted or blocked.
- if (!uri)
- return this.isDirectRequestWhitelisted();
-
- // Local referrers can be whitelisted.
- if (this.isFileRequestWhitelisted() &&
- (uri.schemeIs("chrome") || uri.schemeIs("file")))
- return true;
-
- this.importPermissions();
-
- let permission = Services.perms.testPermissionFromPrincipal(aInstallingPrincipal, XPI_PERMISSION);
- if (permission == Ci.nsIPermissionManager.DENY_ACTION)
- return false;
-
- let requireWhitelist = Preferences.get(PREF_XPI_WHITELIST_REQUIRED, true);
- if (requireWhitelist && (permission != Ci.nsIPermissionManager.ALLOW_ACTION))
- return false;
-
- let requireSecureOrigin = Preferences.get(PREF_INSTALL_REQUIRESECUREORIGIN, true);
- let safeSchemes = ["https", "chrome", "file"];
- if (requireSecureOrigin && safeSchemes.indexOf(uri.scheme) == -1)
- return false;
-
- return true;
- },
-
- /**
- * Called to get an AddonInstall to download and install an add-on from a URL.
- *
- * @param aUrl
- * The URL to be installed
- * @param aHash
- * A hash for the install
- * @param aName
- * A name for the install
- * @param aIcons
- * Icon URLs for the install
- * @param aVersion
- * A version for the install
- * @param aBrowser
- * The browser performing the install
- * @param aCallback
- * A callback to pass the AddonInstall to
- */
- getInstallForURL: function(aUrl, aHash, aName, aIcons, aVersion, aBrowser,
- aCallback) {
- createDownloadInstall(function(aInstall) {
- aCallback(aInstall.wrapper);
- }, aUrl, aHash, aName, aIcons, aVersion, aBrowser);
- },
-
- /**
- * Called to get an AddonInstall to install an add-on from a local file.
- *
- * @param aFile
- * The file to be installed
- * @param aCallback
- * A callback to pass the AddonInstall to
- */
- getInstallForFile: function(aFile, aCallback) {
- createLocalInstall(aFile).then(install => {
- aCallback(install ? install.wrapper : null);
- });
- },
-
- /**
- * Temporarily installs add-on from a local XPI file or directory.
- * As this is intended for development, the signature is not checked and
- * the add-on does not persist on application restart.
- *
- * @param aFile
- * An nsIFile for the unpacked add-on directory or XPI file.
- *
- * @return See installAddonFromLocation return value.
- */
- installTemporaryAddon: function(aFile) {
- return this.installAddonFromLocation(aFile, TemporaryInstallLocation);
- },
-
- /**
- * Permanently installs add-on from a local XPI file or directory.
- * The signature is checked but the add-on persist on application restart.
- *
- * @param aFile
- * An nsIFile for the unpacked add-on directory or XPI file.
- *
- * @return See installAddonFromLocation return value.
- */
- installAddonFromSources: Task.async(function*(aFile) {
- let location = XPIProvider.installLocationsByName[KEY_APP_PROFILE];
- return this.installAddonFromLocation(aFile, location, "proxy");
- }),
-
- /**
- * Installs add-on from a local XPI file or directory.
- *
- * @param aFile
- * An nsIFile for the unpacked add-on directory or XPI file.
- * @param aInstallLocation
- * Define a custom install location object to use for the install.
- * @param aInstallAction
- * Optional action mode to use when installing the addon
- * (see MutableDirectoryInstallLocation.installAddon)
- *
- * @return a Promise that resolves to an Addon object on success, or rejects
- * if the add-on is not a valid restartless add-on or if the
- * same ID is already installed.
- */
- installAddonFromLocation: Task.async(function*(aFile, aInstallLocation, aInstallAction) {
- if (aFile.exists() && aFile.isFile()) {
- flushJarCache(aFile);
- }
- let addon = yield loadManifestFromFile(aFile, aInstallLocation);
-
- aInstallLocation.installAddon({ id: addon.id, source: aFile, action: aInstallAction });
-
- if (addon.appDisabled) {
- let message = `Add-on ${addon.id} is not compatible with application version.`;
-
- let app = addon.matchingTargetApplication;
- if (app) {
- if (app.minVersion) {
- message += ` add-on minVersion: ${app.minVersion}.`;
- }
- if (app.maxVersion) {
- message += ` add-on maxVersion: ${app.maxVersion}.`;
- }
- }
- throw new Error(message);
- }
-
- if (!addon.bootstrap) {
- throw new Error("Only restartless (bootstrap) add-ons"
- + " can be installed from sources:", addon.id);
- }
- let installReason = BOOTSTRAP_REASONS.ADDON_INSTALL;
- let oldAddon = yield new Promise(
- resolve => XPIDatabase.getVisibleAddonForID(addon.id, resolve));
- if (oldAddon) {
- if (!oldAddon.bootstrap) {
- logger.warn("Non-restartless Add-on is already installed", addon.id);
- throw new Error("Non-restartless add-on with ID "
- + oldAddon.id + " is already installed");
- }
- else {
- logger.warn("Addon with ID " + oldAddon.id + " already installed,"
- + " older version will be disabled");
-
- let existingAddonID = oldAddon.id;
- let existingAddon = oldAddon._sourceBundle;
-
- // We'll be replacing a currently active bootstrapped add-on so
- // call its uninstall method
- let newVersion = addon.version;
- let oldVersion = oldAddon.version;
- if (Services.vc.compare(newVersion, oldVersion) >= 0) {
- installReason = BOOTSTRAP_REASONS.ADDON_UPGRADE;
- } else {
- installReason = BOOTSTRAP_REASONS.ADDON_DOWNGRADE;
- }
- let uninstallReason = installReason;
-
- if (oldAddon.active) {
- XPIProvider.callBootstrapMethod(oldAddon, existingAddon,
- "shutdown", uninstallReason,
- { newVersion });
- }
- this.callBootstrapMethod(oldAddon, existingAddon,
- "uninstall", uninstallReason, { newVersion });
- this.unloadBootstrapScope(existingAddonID);
- flushChromeCaches();
- }
- }
-
- let file = addon._sourceBundle;
-
- XPIProvider._addURIMapping(addon.id, file);
- XPIProvider.callBootstrapMethod(addon, file, "install", installReason);
- addon.state = AddonManager.STATE_INSTALLED;
- logger.debug("Install of temporary addon in " + aFile.path + " completed.");
- addon.visible = true;
- addon.enabled = true;
- addon.active = true;
-
- addon = XPIDatabase.addAddonMetadata(addon, file.persistentDescriptor);
-
- XPIStates.addAddon(addon);
- XPIDatabase.saveChanges();
- XPIStates.save();
-
- AddonManagerPrivate.callAddonListeners("onInstalling", addon.wrapper,
- false);
- XPIProvider.callBootstrapMethod(addon, file, "startup",
- BOOTSTRAP_REASONS.ADDON_ENABLE);
- AddonManagerPrivate.callInstallListeners("onExternalInstall",
- null, addon.wrapper,
- oldAddon ? oldAddon.wrapper : null,
- false);
- AddonManagerPrivate.callAddonListeners("onInstalled", addon.wrapper);
-
- return addon.wrapper;
- }),
-
- /**
- * Returns an Addon corresponding to an instance ID.
- * @param aInstanceID
- * An Addon Instance ID
- * @return {Promise}
- * @resolves The found Addon or null if no such add-on exists.
- * @rejects Never
- * @throws if the aInstanceID argument is not specified
- */
- getAddonByInstanceID: function(aInstanceID) {
- if (!aInstanceID || typeof aInstanceID != "symbol")
- throw Components.Exception("aInstanceID must be a Symbol()",
- Cr.NS_ERROR_INVALID_ARG);
-
- for (let [id, val] of this.activeAddons) {
- if (aInstanceID == val.instanceID) {
- if (val.safeWrapper) {
- return Promise.resolve(val.safeWrapper);
- }
-
- return new Promise(resolve => {
- this.getAddonByID(id, function(addon) {
- val.safeWrapper = new PrivateWrapper(addon);
- resolve(val.safeWrapper);
- });
- });
- }
- }
-
- return Promise.resolve(null);
- },
-
- /**
- * Removes an AddonInstall from the list of active installs.
- *
- * @param install
- * The AddonInstall to remove
- */
- removeActiveInstall: function(aInstall) {
- this.installs.delete(aInstall);
- },
-
- /**
- * Called to get an Addon with a particular ID.
- *
- * @param aId
- * The ID of the add-on to retrieve
- * @param aCallback
- * A callback to pass the Addon to
- */
- getAddonByID: function(aId, aCallback) {
- XPIDatabase.getVisibleAddonForID (aId, function(aAddon) {
- aCallback(aAddon ? aAddon.wrapper : null);
- });
- },
-
- /**
- * Called to get Addons of a particular type.
- *
- * @param aTypes
- * An array of types to fetch. Can be null to get all types.
- * @param aCallback
- * A callback to pass an array of Addons to
- */
- getAddonsByTypes: function(aTypes, aCallback) {
- let typesToGet = getAllAliasesForTypes(aTypes);
-
- XPIDatabase.getVisibleAddons(typesToGet, function(aAddons) {
- aCallback(aAddons.map(a => a.wrapper));
- });
- },
-
- /**
- * Obtain an Addon having the specified Sync GUID.
- *
- * @param aGUID
- * String GUID of add-on to retrieve
- * @param aCallback
- * A callback to pass the Addon to. Receives null if not found.
- */
- getAddonBySyncGUID: function(aGUID, aCallback) {
- XPIDatabase.getAddonBySyncGUID(aGUID, function(aAddon) {
- aCallback(aAddon ? aAddon.wrapper : null);
- });
- },
-
- /**
- * Called to get Addons that have pending operations.
- *
- * @param aTypes
- * An array of types to fetch. Can be null to get all types
- * @param aCallback
- * A callback to pass an array of Addons to
- */
- getAddonsWithOperationsByTypes: function(aTypes, aCallback) {
- let typesToGet = getAllAliasesForTypes(aTypes);
-
- XPIDatabase.getVisibleAddonsWithPendingOperations(typesToGet, function(aAddons) {
- let results = aAddons.map(a => a.wrapper);
- for (let install of XPIProvider.installs) {
- if (install.state == AddonManager.STATE_INSTALLED &&
- !(install.addon.inDatabase))
- results.push(install.addon.wrapper);
- }
- aCallback(results);
- });
- },
-
- /**
- * Called to get the current AddonInstalls, optionally limiting to a list of
- * types.
- *
- * @param aTypes
- * An array of types or null to get all types
- * @param aCallback
- * A callback to pass the array of AddonInstalls to
- */
- getInstallsByTypes: function(aTypes, aCallback) {
- let results = [...this.installs];
- if (aTypes) {
- results = results.filter(install => {
- return aTypes.includes(getExternalType(install.type));
- });
- }
-
- aCallback(results.map(install => install.wrapper));
- },
-
- /**
- * Synchronously map a URI to the corresponding Addon ID.
- *
- * Mappable URIs are limited to in-application resources belonging to the
- * add-on, such as Javascript compartments, XUL windows, XBL bindings, etc.
- * but do not include URIs from meta data, such as the add-on homepage.
- *
- * @param aURI
- * nsIURI to map or null
- * @return string containing the Addon ID
- * @see AddonManager.mapURIToAddonID
- * @see amIAddonManager.mapURIToAddonID
- */
- mapURIToAddonID: function(aURI) {
- // Returns `null` instead of empty string if the URI can't be mapped.
- return AddonPathService.mapURIToAddonId(aURI) || null;
- },
-
- /**
- * Called when a new add-on has been enabled when only one add-on of that type
- * can be enabled.
- *
- * @param aId
- * The ID of the newly enabled add-on
- * @param aType
- * The type of the newly enabled add-on
- * @param aPendingRestart
- * true if the newly enabled add-on will only become enabled after a
- * restart
- */
- addonChanged: function(aId, aType, aPendingRestart) {
- // We only care about themes in this provider
- if (aType != "theme")
- return;
-
- if (!aId) {
- // Fallback to the default theme when no theme was enabled
- this.enableDefaultTheme();
- return;
- }
-
- // Look for the previously enabled theme and find the internalName of the
- // currently selected theme
- let previousTheme = null;
- let newSkin = this.defaultSkin;
- let addons = XPIDatabase.getAddonsByType("theme");
- for (let theme of addons) {
- if (!theme.visible)
- return;
- if (theme.id == aId)
- newSkin = theme.internalName;
- else if (theme.userDisabled == false && !theme.pendingUninstall)
- previousTheme = theme;
- }
-
- if (aPendingRestart) {
- Services.prefs.setBoolPref(PREF_DSS_SWITCHPENDING, true);
- Services.prefs.setCharPref(PREF_DSS_SKIN_TO_SELECT, newSkin);
- }
- else if (newSkin == this.currentSkin) {
- try {
- Services.prefs.clearUserPref(PREF_DSS_SWITCHPENDING);
- }
- catch (e) { }
- try {
- Services.prefs.clearUserPref(PREF_DSS_SKIN_TO_SELECT);
- }
- catch (e) { }
- }
- else {
- Services.prefs.setCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN, newSkin);
- this.currentSkin = newSkin;
- }
- this.selectedSkin = newSkin;
-
- // Flush the preferences to disk so they don't get out of sync with the
- // database
- Services.prefs.savePrefFile(null);
-
- // Mark the previous theme as disabled. This won't cause recursion since
- // only enabled calls notifyAddonChanged.
- if (previousTheme)
- this.updateAddonDisabledState(previousTheme, true);
- },
-
- /**
- * Update the appDisabled property for all add-ons.
- */
- updateAddonAppDisabledStates: function() {
- let addons = XPIDatabase.getAddons();
- for (let addon of addons) {
- this.updateAddonDisabledState(addon);
- }
- },
-
- /**
- * Update the repositoryAddon property for all add-ons.
- *
- * @param aCallback
- * Function to call when operation is complete.
- */
- updateAddonRepositoryData: function(aCallback) {
- XPIDatabase.getVisibleAddons(null, aAddons => {
- let pending = aAddons.length;
- logger.debug("updateAddonRepositoryData found " + pending + " visible add-ons");
- if (pending == 0) {
- aCallback();
- return;
- }
-
- function notifyComplete() {
- if (--pending == 0)
- aCallback();
- }
-
- for (let addon of aAddons) {
- AddonRepository.getCachedAddonByID(addon.id, aRepoAddon => {
- if (aRepoAddon) {
- logger.debug("updateAddonRepositoryData got info for " + addon.id);
- addon._repositoryAddon = aRepoAddon;
- addon.compatibilityOverrides = aRepoAddon.compatibilityOverrides;
- this.updateAddonDisabledState(addon);
- }
-
- notifyComplete();
- });
- }
- });
- },
-
- /**
- * When the previously selected theme is removed this method will be called
- * to enable the default theme.
- */
- enableDefaultTheme: function() {
- logger.debug("Activating default theme");
- let addon = XPIDatabase.getVisibleAddonForInternalName(this.defaultSkin);
- if (addon) {
- if (addon.userDisabled) {
- this.updateAddonDisabledState(addon, false);
- }
- else if (!this.extensionsActive) {
- // During startup we may end up trying to enable the default theme when
- // the database thinks it is already enabled (see f.e. bug 638847). In
- // this case just force the theme preferences to be correct
- Services.prefs.setCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN,
- addon.internalName);
- this.currentSkin = this.selectedSkin = addon.internalName;
- Preferences.reset(PREF_DSS_SKIN_TO_SELECT);
- Preferences.reset(PREF_DSS_SWITCHPENDING);
- }
- else {
- logger.warn("Attempting to activate an already active default theme");
- }
- }
- else {
- logger.warn("Unable to activate the default theme");
- }
- },
-
- onDebugConnectionChange: function(aEvent, aWhat, aConnection) {
- if (aWhat != "opened")
- return;
-
- for (let [id, val] of this.activeAddons) {
- aConnection.setAddonOptions(
- id, { global: val.debugGlobal || val.bootstrapScope });
- }
- },
-
- /**
- * Notified when a preference we're interested in has changed.
- *
- * @see nsIObserver
- */
- observe: function(aSubject, aTopic, aData) {
- if (aTopic == NOTIFICATION_FLUSH_PERMISSIONS) {
- if (!aData || aData == XPI_PERMISSION) {
- this.importPermissions();
- }
- return;
- }
- else if (aTopic == NOTIFICATION_TOOLBOXPROCESS_LOADED) {
- Services.obs.removeObserver(this, NOTIFICATION_TOOLBOXPROCESS_LOADED, false);
- this._toolboxProcessLoaded = true;
- BrowserToolboxProcess.on("connectionchange",
- this.onDebugConnectionChange.bind(this));
- }
-
- if (aTopic == "nsPref:changed") {
- switch (aData) {
- case PREF_EM_MIN_COMPAT_APP_VERSION:
- this.minCompatibleAppVersion = Preferences.get(PREF_EM_MIN_COMPAT_APP_VERSION,
- null);
- this.updateAddonAppDisabledStates();
- break;
- case PREF_EM_MIN_COMPAT_PLATFORM_VERSION:
- this.minCompatiblePlatformVersion = Preferences.get(PREF_EM_MIN_COMPAT_PLATFORM_VERSION,
- null);
- this.updateAddonAppDisabledStates();
- break;
- case PREF_XPI_SIGNATURES_REQUIRED:
- this.updateAddonAppDisabledStates();
- break;
- }
- }
- },
-
- /**
- * Tests whether enabling an add-on will require a restart.
- *
- * @param aAddon
- * The add-on to test
- * @return true if the operation requires a restart
- */
- enableRequiresRestart: function(aAddon) {
- // If the platform couldn't have activated extensions then we can make
- // changes without any restart.
- if (!this.extensionsActive)
- return false;
-
- // If the application is in safe mode then any change can be made without
- // restarting
- if (Services.appinfo.inSafeMode)
- return false;
-
- // Anything that is active is already enabled
- if (aAddon.active)
- return false;
-
- if (aAddon.type == "theme") {
- // If dynamic theme switching is enabled then switching themes does not
- // require a restart
- if (Preferences.get(PREF_EM_DSS_ENABLED))
- return false;
-
- // If the theme is already the theme in use then no restart is necessary.
- // This covers the case where the default theme is in use but a
- // lightweight theme is considered active.
- return aAddon.internalName != this.currentSkin;
- }
-
- return !aAddon.bootstrap;
- },
-
- /**
- * Tests whether disabling an add-on will require a restart.
- *
- * @param aAddon
- * The add-on to test
- * @return true if the operation requires a restart
- */
- disableRequiresRestart: function(aAddon) {
- // If the platform couldn't have activated up extensions then we can make
- // changes without any restart.
- if (!this.extensionsActive)
- return false;
-
- // If the application is in safe mode then any change can be made without
- // restarting
- if (Services.appinfo.inSafeMode)
- return false;
-
- // Anything that isn't active is already disabled
- if (!aAddon.active)
- return false;
-
- if (aAddon.type == "theme") {
- // If dynamic theme switching is enabled then switching themes does not
- // require a restart
- if (Preferences.get(PREF_EM_DSS_ENABLED))
- return false;
-
- // Non-default themes always require a restart to disable since it will
- // be switching from one theme to another or to the default theme and a
- // lightweight theme.
- if (aAddon.internalName != this.defaultSkin)
- return true;
-
- // The default theme requires a restart to disable if we are in the
- // process of switching to a different theme. Note that this makes the
- // disabled flag of operationsRequiringRestart incorrect for the default
- // theme (it will be false most of the time). Bug 520124 would be required
- // to fix it. For the UI this isn't a problem since we never try to
- // disable or uninstall the default theme.
- return this.selectedSkin != this.currentSkin;
- }
-
- return !aAddon.bootstrap;
- },
-
- /**
- * Tests whether installing an add-on will require a restart.
- *
- * @param aAddon
- * The add-on to test
- * @return true if the operation requires a restart
- */
- installRequiresRestart: function(aAddon) {
- // If the platform couldn't have activated up extensions then we can make
- // changes without any restart.
- if (!this.extensionsActive)
- return false;
-
- // If the application is in safe mode then any change can be made without
- // restarting
- if (Services.appinfo.inSafeMode)
- return false;
-
- // Add-ons that are already installed don't require a restart to install.
- // This wouldn't normally be called for an already installed add-on (except
- // for forming the operationsRequiringRestart flags) so is really here as
- // a safety measure.
- if (aAddon.inDatabase)
- return false;
-
- // If we have an AddonInstall for this add-on then we can see if there is
- // an existing installed add-on with the same ID
- if ("_install" in aAddon && aAddon._install) {
- // If there is an existing installed add-on and uninstalling it would
- // require a restart then installing the update will also require a
- // restart
- let existingAddon = aAddon._install.existingAddon;
- if (existingAddon && this.uninstallRequiresRestart(existingAddon))
- return true;
- }
-
- // If the add-on is not going to be active after installation then it
- // doesn't require a restart to install.
- if (aAddon.disabled)
- return false;
-
- // Themes will require a restart (even if dynamic switching is enabled due
- // to some caching issues) and non-bootstrapped add-ons will require a
- // restart
- return aAddon.type == "theme" || !aAddon.bootstrap;
- },
-
- /**
- * Tests whether uninstalling an add-on will require a restart.
- *
- * @param aAddon
- * The add-on to test
- * @return true if the operation requires a restart
- */
- uninstallRequiresRestart: function(aAddon) {
- // If the platform couldn't have activated up extensions then we can make
- // changes without any restart.
- if (!this.extensionsActive)
- return false;
-
- // If the application is in safe mode then any change can be made without
- // restarting
- if (Services.appinfo.inSafeMode)
- return false;
-
- // If the add-on can be disabled without a restart then it can also be
- // uninstalled without a restart
- return this.disableRequiresRestart(aAddon);
- },
-
- /**
- * Loads a bootstrapped add-on's bootstrap.js into a sandbox and the reason
- * values as constants in the scope. This will also add information about the
- * add-on to the bootstrappedAddons dictionary and notify the crash reporter
- * that new add-ons have been loaded.
- *
- * @param aId
- * The add-on's ID
- * @param aFile
- * The nsIFile for the add-on
- * @param aVersion
- * The add-on's version
- * @param aType
- * The type for the add-on
- * @param aMultiprocessCompatible
- * Boolean indicating whether the add-on is compatible with electrolysis.
- * @param aRunInSafeMode
- * Boolean indicating whether the add-on can run in safe mode.
- * @param aDependencies
- * An array of add-on IDs on which this add-on depends.
- * @param hasEmbeddedWebExtension
- * Boolean indicating whether the add-on has an embedded webextension.
- * @return a JavaScript scope
- */
- loadBootstrapScope: function(aId, aFile, aVersion, aType,
- aMultiprocessCompatible, aRunInSafeMode,
- aDependencies, hasEmbeddedWebExtension) {
- // Mark the add-on as active for the crash reporter before loading
- this.bootstrappedAddons[aId] = {
- version: aVersion,
- type: aType,
- descriptor: aFile.persistentDescriptor,
- multiprocessCompatible: aMultiprocessCompatible,
- runInSafeMode: aRunInSafeMode,
- dependencies: aDependencies,
- hasEmbeddedWebExtension,
- };
- this.persistBootstrappedAddons();
- this.addAddonsToCrashReporter();
-
- this.activeAddons.set(aId, {
- debugGlobal: null,
- safeWrapper: null,
- bootstrapScope: null,
- // a Symbol passed to this add-on, which it can use to identify itself
- instanceID: Symbol(aId),
- });
- let activeAddon = this.activeAddons.get(aId);
-
- // Locales only contain chrome and can't have bootstrap scripts
- if (aType == "locale") {
- return;
- }
-
- logger.debug("Loading bootstrap scope from " + aFile.path);
-
- let principal = Cc["@mozilla.org/systemprincipal;1"].
- createInstance(Ci.nsIPrincipal);
- if (!aMultiprocessCompatible && Preferences.get(PREF_INTERPOSITION_ENABLED, false)) {
- let interposition = Cc["@mozilla.org/addons/multiprocess-shims;1"].
- getService(Ci.nsIAddonInterposition);
- Cu.setAddonInterposition(aId, interposition);
- Cu.allowCPOWsInAddon(aId, true);
- }
-
- if (!aFile.exists()) {
- activeAddon.bootstrapScope =
- new Cu.Sandbox(principal, { sandboxName: aFile.path,
- wantGlobalProperties: ["indexedDB"],
- addonId: aId,
- metadata: { addonID: aId } });
- logger.error("Attempted to load bootstrap scope from missing directory " + aFile.path);
- return;
- }
-
- let uri = getURIForResourceInFile(aFile, "bootstrap.js").spec;
- if (aType == "dictionary")
- uri = "resource://gre/modules/addons/SpellCheckDictionaryBootstrap.js"
- else if (aType == "webextension")
- uri = "resource://gre/modules/addons/WebExtensionBootstrap.js"
- else if (aType == "apiextension")
- uri = "resource://gre/modules/addons/APIExtensionBootstrap.js"
-
- activeAddon.bootstrapScope =
- new Cu.Sandbox(principal, { sandboxName: uri,
- wantGlobalProperties: ["indexedDB"],
- addonId: aId,
- metadata: { addonID: aId, URI: uri } });
-
- let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- createInstance(Ci.mozIJSSubScriptLoader);
-
- try {
- // Copy the reason values from the global object into the bootstrap scope.
- for (let name in BOOTSTRAP_REASONS)
- activeAddon.bootstrapScope[name] = BOOTSTRAP_REASONS[name];
-
- // Add other stuff that extensions want.
- const features = [ "Worker", "ChromeWorker" ];
-
- for (let feature of features)
- activeAddon.bootstrapScope[feature] = gGlobalScope[feature];
-
- // Define a console for the add-on
- activeAddon.bootstrapScope["console"] = new ConsoleAPI(
- { consoleID: "addon/" + aId });
-
- // As we don't want our caller to control the JS version used for the
- // bootstrap file, we run loadSubScript within the context of the
- // sandbox with the latest JS version set explicitly.
- activeAddon.bootstrapScope.__SCRIPT_URI_SPEC__ = uri;
- Components.utils.evalInSandbox(
- "Components.classes['@mozilla.org/moz/jssubscript-loader;1'] \
- .createInstance(Components.interfaces.mozIJSSubScriptLoader) \
- .loadSubScript(__SCRIPT_URI_SPEC__);",
- activeAddon.bootstrapScope, "ECMAv5");
- }
- catch (e) {
- logger.warn("Error loading bootstrap.js for " + aId, e);
- }
-
- // Only access BrowserToolboxProcess if ToolboxProcess.jsm has been
- // initialized as otherwise, when it will be initialized, all addons'
- // globals will be added anyways
- if (this._toolboxProcessLoaded) {
- BrowserToolboxProcess.setAddonOptions(aId,
- { global: activeAddon.bootstrapScope });
- }
- },
-
- /**
- * Unloads a bootstrap scope by dropping all references to it and then
- * updating the list of active add-ons with the crash reporter.
- *
- * @param aId
- * The add-on's ID
- */
- unloadBootstrapScope: function(aId) {
- // In case the add-on was not multiprocess-compatible, deregister
- // any interpositions for it.
- Cu.setAddonInterposition(aId, null);
- Cu.allowCPOWsInAddon(aId, false);
-
- this.activeAddons.delete(aId);
- delete this.bootstrappedAddons[aId];
- this.persistBootstrappedAddons();
- this.addAddonsToCrashReporter();
-
- // Only access BrowserToolboxProcess if ToolboxProcess.jsm has been
- // initialized as otherwise, there won't be any addon globals added to it
- if (this._toolboxProcessLoaded) {
- BrowserToolboxProcess.setAddonOptions(aId, { global: null });
- }
- },
-
- /**
- * Calls a bootstrap method for an add-on.
- *
- * @param aAddon
- * An object representing the add-on, with `id`, `type` and `version`
- * @param aFile
- * The nsIFile for the add-on
- * @param aMethod
- * The name of the bootstrap method to call
- * @param aReason
- * The reason flag to pass to the bootstrap's startup method
- * @param aExtraParams
- * An object of additional key/value pairs to pass to the method in
- * the params argument
- */
- callBootstrapMethod: function(aAddon, aFile, aMethod, aReason, aExtraParams) {
- if (!aAddon.id || !aAddon.version || !aAddon.type) {
- throw new Error("aAddon must include an id, version, and type");
- }
-
- // Only run in safe mode if allowed to
- let runInSafeMode = "runInSafeMode" in aAddon ? aAddon.runInSafeMode : canRunInSafeMode(aAddon);
- if (Services.appinfo.inSafeMode && !runInSafeMode)
- return;
-
- let timeStart = new Date();
- if (CHROME_TYPES.has(aAddon.type) && aMethod == "startup") {
- logger.debug("Registering manifest for " + aFile.path);
- Components.manager.addBootstrappedManifestLocation(aFile);
- }
-
- try {
- // Load the scope if it hasn't already been loaded
- let activeAddon = this.activeAddons.get(aAddon.id);
- if (!activeAddon) {
- this.loadBootstrapScope(aAddon.id, aFile, aAddon.version, aAddon.type,
- aAddon.multiprocessCompatible || false,
- runInSafeMode, aAddon.dependencies,
- aAddon.hasEmbeddedWebExtension || false);
- activeAddon = this.activeAddons.get(aAddon.id);
- }
-
- if (aMethod == "startup" || aMethod == "shutdown") {
- if (!aExtraParams) {
- aExtraParams = {};
- }
- aExtraParams["instanceID"] = this.activeAddons.get(aAddon.id).instanceID;
- }
-
- // Nothing to call for locales
- if (aAddon.type == "locale")
- return;
-
- let method = undefined;
- try {
- method = Components.utils.evalInSandbox(`${aMethod};`,
- activeAddon.bootstrapScope, "ECMAv5");
- }
- catch (e) {
- // An exception will be caught if the expected method is not defined.
- // That will be logged below.
- }
-
- if (!method) {
- logger.warn("Add-on " + aAddon.id + " is missing bootstrap method " + aMethod);
- return;
- }
-
- // Extensions are automatically deinitialized in the correct order at shutdown.
- if (aMethod == "shutdown" && aReason != BOOTSTRAP_REASONS.APP_SHUTDOWN) {
- activeAddon.disable = true;
- for (let addon of this.getDependentAddons(aAddon)) {
- if (addon.active)
- this.updateAddonDisabledState(addon);
- }
- }
-
- let params = {
- id: aAddon.id,
- version: aAddon.version,
- installPath: aFile.clone(),
- resourceURI: getURIForResourceInFile(aFile, "")
- };
-
- if (aExtraParams) {
- for (let key in aExtraParams) {
- params[key] = aExtraParams[key];
- }
- }
-
- if (aAddon.hasEmbeddedWebExtension) {
- if (aMethod == "startup") {
- const webExtension = LegacyExtensionsUtils.getEmbeddedExtensionFor(params);
- params.webExtension = {
- startup: () => webExtension.startup(),
- };
- } else if (aMethod == "shutdown") {
- LegacyExtensionsUtils.getEmbeddedExtensionFor(params).shutdown();
- }
- }
-
- logger.debug("Calling bootstrap method " + aMethod + " on " + aAddon.id + " version " +
- aAddon.version);
- try {
- method(params, aReason);
- }
- catch (e) {
- logger.warn("Exception running bootstrap method " + aMethod + " on " + aAddon.id, e);
- }
- }
- finally {
- // Extensions are automatically initialized in the correct order at startup.
- if (aMethod == "startup" && aReason != BOOTSTRAP_REASONS.APP_STARTUP) {
- for (let addon of this.getDependentAddons(aAddon))
- this.updateAddonDisabledState(addon);
- }
-
- if (CHROME_TYPES.has(aAddon.type) && aMethod == "shutdown" && aReason != BOOTSTRAP_REASONS.APP_SHUTDOWN) {
- logger.debug("Removing manifest for " + aFile.path);
- Components.manager.removeBootstrappedManifestLocation(aFile);
-
- let manifest = getURIForResourceInFile(aFile, "chrome.manifest");
- for (let line of ChromeManifestParser.parseSync(manifest)) {
- if (line.type == "resource") {
- ResProtocolHandler.setSubstitution(line.args[0], null);
- }
- }
- }
- this.setTelemetry(aAddon.id, aMethod + "_MS", new Date() - timeStart);
- }
- },
-
- /**
- * Updates the disabled state for an add-on. Its appDisabled property will be
- * calculated and if the add-on is changed the database will be saved and
- * appropriate notifications will be sent out to the registered AddonListeners.
- *
- * @param aAddon
- * The DBAddonInternal to update
- * @param aUserDisabled
- * Value for the userDisabled property. If undefined the value will
- * not change
- * @param aSoftDisabled
- * Value for the softDisabled property. If undefined the value will
- * not change. If true this will force userDisabled to be true
- * @return a tri-state indicating the action taken for the add-on:
- * - undefined: The add-on did not change state
- * - true: The add-on because disabled
- * - false: The add-on became enabled
- * @throws if addon is not a DBAddonInternal
- */
- updateAddonDisabledState: function(aAddon, aUserDisabled, aSoftDisabled) {
- if (!(aAddon.inDatabase))
- throw new Error("Can only update addon states for installed addons.");
- if (aUserDisabled !== undefined && aSoftDisabled !== undefined) {
- throw new Error("Cannot change userDisabled and softDisabled at the " +
- "same time");
- }
-
- if (aUserDisabled === undefined) {
- aUserDisabled = aAddon.userDisabled;
- }
- else if (!aUserDisabled) {
- // If enabling the add-on then remove softDisabled
- aSoftDisabled = false;
- }
-
- // If not changing softDisabled or the add-on is already userDisabled then
- // use the existing value for softDisabled
- if (aSoftDisabled === undefined || aUserDisabled)
- aSoftDisabled = aAddon.softDisabled;
-
- let appDisabled = !isUsableAddon(aAddon);
- // No change means nothing to do here
- if (aAddon.userDisabled == aUserDisabled &&
- aAddon.appDisabled == appDisabled &&
- aAddon.softDisabled == aSoftDisabled)
- return undefined;
-
- let wasDisabled = aAddon.disabled;
- let isDisabled = aUserDisabled || aSoftDisabled || appDisabled;
-
- // If appDisabled changes but addon.disabled doesn't,
- // no onDisabling/onEnabling is sent - so send a onPropertyChanged.
- let appDisabledChanged = aAddon.appDisabled != appDisabled;
-
- // Update the properties in the database.
- XPIDatabase.setAddonProperties(aAddon, {
- userDisabled: aUserDisabled,
- appDisabled: appDisabled,
- softDisabled: aSoftDisabled
- });
-
- let wrapper = aAddon.wrapper;
-
- if (appDisabledChanged) {
- AddonManagerPrivate.callAddonListeners("onPropertyChanged",
- wrapper,
- ["appDisabled"]);
- }
-
- // If the add-on is not visible or the add-on is not changing state then
- // there is no need to do anything else
- if (!aAddon.visible || (wasDisabled == isDisabled))
- return undefined;
-
- // Flag that active states in the database need to be updated on shutdown
- Services.prefs.setBoolPref(PREF_PENDING_OPERATIONS, true);
-
- // Have we just gone back to the current state?
- if (isDisabled != aAddon.active) {
- AddonManagerPrivate.callAddonListeners("onOperationCancelled", wrapper);
- }
- else {
- if (isDisabled) {
- var needsRestart = this.disableRequiresRestart(aAddon);
- AddonManagerPrivate.callAddonListeners("onDisabling", wrapper,
- needsRestart);
- }
- else {
- needsRestart = this.enableRequiresRestart(aAddon);
- AddonManagerPrivate.callAddonListeners("onEnabling", wrapper,
- needsRestart);
- }
-
- if (!needsRestart) {
- XPIDatabase.updateAddonActive(aAddon, !isDisabled);
-
- if (isDisabled) {
- if (aAddon.bootstrap) {
- this.callBootstrapMethod(aAddon, aAddon._sourceBundle, "shutdown",
- BOOTSTRAP_REASONS.ADDON_DISABLE);
- this.unloadBootstrapScope(aAddon.id);
- }
- AddonManagerPrivate.callAddonListeners("onDisabled", wrapper);
- }
- else {
- if (aAddon.bootstrap) {
- this.callBootstrapMethod(aAddon, aAddon._sourceBundle, "startup",
- BOOTSTRAP_REASONS.ADDON_ENABLE);
- }
- AddonManagerPrivate.callAddonListeners("onEnabled", wrapper);
- }
- }
- else if (aAddon.bootstrap) {
- // Something blocked the restartless add-on from enabling or disabling
- // make sure it happens on the next startup
- if (isDisabled) {
- this.bootstrappedAddons[aAddon.id].disable = true;
- }
- else {
- this.bootstrappedAddons[aAddon.id] = {
- version: aAddon.version,
- type: aAddon.type,
- descriptor: aAddon._sourceBundle.persistentDescriptor,
- multiprocessCompatible: aAddon.multiprocessCompatible,
- runInSafeMode: canRunInSafeMode(aAddon),
- dependencies: aAddon.dependencies,
- hasEmbeddedWebExtension: aAddon.hasEmbeddedWebExtension,
- };
- this.persistBootstrappedAddons();
- }
- }
- }
-
- // Sync with XPIStates.
- let xpiState = XPIStates.getAddon(aAddon.location, aAddon.id);
- if (xpiState) {
- xpiState.syncWithDB(aAddon);
- XPIStates.save();
- } else {
- // There should always be an xpiState
- logger.warn("No XPIState for ${id} in ${location}", aAddon);
- }
-
- // Notify any other providers that a new theme has been enabled
- if (aAddon.type == "theme" && !isDisabled)
- AddonManagerPrivate.notifyAddonChanged(aAddon.id, aAddon.type, needsRestart);
-
- return isDisabled;
- },
-
- /**
- * Uninstalls an add-on, immediately if possible or marks it as pending
- * uninstall if not.
- *
- * @param aAddon
- * The DBAddonInternal to uninstall
- * @param aForcePending
- * Force this addon into the pending uninstall state, even if
- * it isn't marked as requiring a restart (used e.g. while the
- * add-on manager is open and offering an "undo" button)
- * @throws if the addon cannot be uninstalled because it is in an install
- * location that does not allow it
- */
- uninstallAddon: function(aAddon, aForcePending) {
- if (!(aAddon.inDatabase))
- throw new Error("Cannot uninstall addon " + aAddon.id + " because it is not installed");
-
- if (aAddon._installLocation.locked)
- throw new Error("Cannot uninstall addon " + aAddon.id
- + " from locked install location " + aAddon._installLocation.name);
-
- // Inactive add-ons don't require a restart to uninstall
- let requiresRestart = this.uninstallRequiresRestart(aAddon);
-
- // if makePending is true, we don't actually apply the uninstall,
- // we just mark the addon as having a pending uninstall
- let makePending = aForcePending || requiresRestart;
-
- if (makePending && aAddon.pendingUninstall)
- throw new Error("Add-on is already marked to be uninstalled");
-
- aAddon._hasResourceCache.clear();
-
- if (aAddon._updateCheck) {
- logger.debug("Cancel in-progress update check for " + aAddon.id);
- aAddon._updateCheck.cancel();
- }
-
- let wasPending = aAddon.pendingUninstall;
-
- if (makePending) {
- // We create an empty directory in the staging directory to indicate
- // that an uninstall is necessary on next startup. Temporary add-ons are
- // automatically uninstalled on shutdown anyway so there is no need to
- // do this for them.
- if (aAddon._installLocation.name != KEY_APP_TEMPORARY) {
- let stage = aAddon._installLocation.getStagingDir();
- stage.append(aAddon.id);
- if (!stage.exists())
- stage.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
- }
-
- XPIDatabase.setAddonProperties(aAddon, {
- pendingUninstall: true
- });
- Services.prefs.setBoolPref(PREF_PENDING_OPERATIONS, true);
- let xpiState = XPIStates.getAddon(aAddon.location, aAddon.id);
- if (xpiState) {
- xpiState.enabled = false;
- XPIStates.save();
- } else {
- logger.warn("Can't find XPI state while uninstalling ${id} from ${location}", aAddon);
- }
- }
-
- // If the add-on is not visible then there is no need to notify listeners.
- if (!aAddon.visible)
- return;
-
- let wrapper = aAddon.wrapper;
-
- // If the add-on wasn't already pending uninstall then notify listeners.
- if (!wasPending) {
- // Passing makePending as the requiresRestart parameter is a little
- // strange as in some cases this operation can complete without a restart
- // so really this is now saying that the uninstall isn't going to happen
- // immediately but will happen later.
- AddonManagerPrivate.callAddonListeners("onUninstalling", wrapper,
- makePending);
- }
-
- // Reveal the highest priority add-on with the same ID
- function revealAddon(aAddon) {
- XPIDatabase.makeAddonVisible(aAddon);
-
- let wrappedAddon = aAddon.wrapper;
- AddonManagerPrivate.callAddonListeners("onInstalling", wrappedAddon, false);
-
- if (!aAddon.disabled && !XPIProvider.enableRequiresRestart(aAddon)) {
- XPIDatabase.updateAddonActive(aAddon, true);
- }
-
- if (aAddon.bootstrap) {
- XPIProvider.callBootstrapMethod(aAddon, aAddon._sourceBundle,
- "install", BOOTSTRAP_REASONS.ADDON_INSTALL);
-
- if (aAddon.active) {
- XPIProvider.callBootstrapMethod(aAddon, aAddon._sourceBundle,
- "startup", BOOTSTRAP_REASONS.ADDON_INSTALL);
- }
- else {
- XPIProvider.unloadBootstrapScope(aAddon.id);
- }
- }
-
- // We always send onInstalled even if a restart is required to enable
- // the revealed add-on
- AddonManagerPrivate.callAddonListeners("onInstalled", wrappedAddon);
- }
-
- function findAddonAndReveal(aId) {
- let [locationName, ] = XPIStates.findAddon(aId);
- if (locationName) {
- XPIDatabase.getAddonInLocation(aId, locationName, revealAddon);
- }
- }
-
- if (!makePending) {
- if (aAddon.bootstrap) {
- if (aAddon.active) {
- this.callBootstrapMethod(aAddon, aAddon._sourceBundle, "shutdown",
- BOOTSTRAP_REASONS.ADDON_UNINSTALL);
- }
-
- this.callBootstrapMethod(aAddon, aAddon._sourceBundle, "uninstall",
- BOOTSTRAP_REASONS.ADDON_UNINSTALL);
- this.unloadBootstrapScope(aAddon.id);
- flushChromeCaches();
- }
- aAddon._installLocation.uninstallAddon(aAddon.id);
- XPIDatabase.removeAddonMetadata(aAddon);
- XPIStates.removeAddon(aAddon.location, aAddon.id);
- AddonManagerPrivate.callAddonListeners("onUninstalled", wrapper);
-
- findAddonAndReveal(aAddon.id);
- }
- else if (aAddon.bootstrap && aAddon.active && !this.disableRequiresRestart(aAddon)) {
- this.callBootstrapMethod(aAddon, aAddon._sourceBundle, "shutdown",
- BOOTSTRAP_REASONS.ADDON_UNINSTALL);
- this.unloadBootstrapScope(aAddon.id);
- XPIDatabase.updateAddonActive(aAddon, false);
- }
-
- // Notify any other providers that a new theme has been enabled
- if (aAddon.type == "theme" && aAddon.active)
- AddonManagerPrivate.notifyAddonChanged(null, aAddon.type, requiresRestart);
- },
-
- /**
- * Cancels the pending uninstall of an add-on.
- *
- * @param aAddon
- * The DBAddonInternal to cancel uninstall for
- */
- cancelUninstallAddon: function(aAddon) {
- if (!(aAddon.inDatabase))
- throw new Error("Can only cancel uninstall for installed addons.");
- if (!aAddon.pendingUninstall)
- throw new Error("Add-on is not marked to be uninstalled");
-
- if (aAddon._installLocation.name != KEY_APP_TEMPORARY)
- aAddon._installLocation.cleanStagingDir([aAddon.id]);
-
- XPIDatabase.setAddonProperties(aAddon, {
- pendingUninstall: false
- });
-
- if (!aAddon.visible)
- return;
-
- Services.prefs.setBoolPref(PREF_PENDING_OPERATIONS, true);
-
- // TODO hide hidden add-ons (bug 557710)
- let wrapper = aAddon.wrapper;
- AddonManagerPrivate.callAddonListeners("onOperationCancelled", wrapper);
-
- if (aAddon.bootstrap && !aAddon.disabled && !this.enableRequiresRestart(aAddon)) {
- this.callBootstrapMethod(aAddon, aAddon._sourceBundle, "startup",
- BOOTSTRAP_REASONS.ADDON_INSTALL);
- XPIDatabase.updateAddonActive(aAddon, true);
- }
-
- // Notify any other providers that this theme is now enabled again.
- if (aAddon.type == "theme" && aAddon.active)
- AddonManagerPrivate.notifyAddonChanged(aAddon.id, aAddon.type, false);
- }
-};
-
-function getHashStringForCrypto(aCrypto) {
- // return the two-digit hexadecimal code for a byte
- let toHexString = charCode => ("0" + charCode.toString(16)).slice(-2);
-
- // convert the binary hash data to a hex string.
- let binary = aCrypto.finish(false);
- let hash = Array.from(binary, c => toHexString(c.charCodeAt(0)))
- return hash.join("").toLowerCase();
-}
-
-/**
- * Base class for objects that manage the installation of an addon.
- * This class isn't instantiated directly, see the derived classes below.
- */
-class AddonInstall {
- /**
- * Instantiates an AddonInstall.
- *
- * @param aInstallLocation
- * The install location the add-on will be installed into
- * @param aUrl
- * The nsIURL to get the add-on from. If this is an nsIFileURL then
- * the add-on will not need to be downloaded
- * @param aHash
- * An optional hash for the add-on
- * @param aExistingAddon
- * The add-on this install will update if known
- */
- constructor(aInstallLocation, aUrl, aHash, aExistingAddon) {
- this.wrapper = new AddonInstallWrapper(this);
- this.installLocation = aInstallLocation;
- this.sourceURI = aUrl;
-
- if (aHash) {
- let hashSplit = aHash.toLowerCase().split(":");
- this.originalHash = {
- algorithm: hashSplit[0],
- data: hashSplit[1]
- };
- }
- this.hash = this.originalHash;
- this.existingAddon = aExistingAddon;
- this.releaseNotesURI = null;
-
- this.listeners = [];
- this.icons = {};
- this.error = 0;
-
- this.progress = 0;
- this.maxProgress = -1;
-
- // Giving each instance of AddonInstall a reference to the logger.
- this.logger = logger;
-
- this.name = null;
- this.type = null;
- this.version = null;
-
- this.file = null;
- this.ownsTempFile = null;
- this.certificate = null;
- this.certName = null;
-
- this.linkedInstalls = null;
- this.addon = null;
- this.state = null;
-
- XPIProvider.installs.add(this);
- }
-
- /**
- * Starts installation of this add-on from whatever state it is currently at
- * if possible.
- *
- * Note this method is overridden to handle additional state in
- * the subclassses below.
- *
- * @throws if installation cannot proceed from the current state
- */
- install() {
- switch (this.state) {
- case AddonManager.STATE_DOWNLOADED:
- this.startInstall();
- break;
- case AddonManager.STATE_POSTPONED:
- logger.debug(`Postponing install of ${this.addon.id}`);
- break;
- case AddonManager.STATE_DOWNLOADING:
- case AddonManager.STATE_CHECKING:
- case AddonManager.STATE_INSTALLING:
- // Installation is already running
- return;
- default:
- throw new Error("Cannot start installing from this state");
- }
- }
-
- /**
- * Cancels installation of this add-on.
- *
- * Note this method is overridden to handle additional state in
- * the subclass DownloadAddonInstall.
- *
- * @throws if installation cannot be cancelled from the current state
- */
- cancel() {
- switch (this.state) {
- case AddonManager.STATE_AVAILABLE:
- case AddonManager.STATE_DOWNLOADED:
- logger.debug("Cancelling download of " + this.sourceURI.spec);
- this.state = AddonManager.STATE_CANCELLED;
- XPIProvider.removeActiveInstall(this);
- AddonManagerPrivate.callInstallListeners("onDownloadCancelled",
- this.listeners, this.wrapper);
- this.removeTemporaryFile();
- break;
- case AddonManager.STATE_INSTALLED:
- logger.debug("Cancelling install of " + this.addon.id);
- let xpi = this.installLocation.getStagingDir();
- xpi.append(this.addon.id + ".xpi");
- flushJarCache(xpi);
- this.installLocation.cleanStagingDir([this.addon.id, this.addon.id + ".xpi",
- this.addon.id + ".json"]);
- this.state = AddonManager.STATE_CANCELLED;
- XPIProvider.removeActiveInstall(this);
-
- if (this.existingAddon) {
- delete this.existingAddon.pendingUpgrade;
- this.existingAddon.pendingUpgrade = null;
- }
-
- AddonManagerPrivate.callAddonListeners("onOperationCancelled", this.addon.wrapper);
-
- AddonManagerPrivate.callInstallListeners("onInstallCancelled",
- this.listeners, this.wrapper);
- break;
- case AddonManager.STATE_POSTPONED:
- logger.debug(`Cancelling postponed install of ${this.addon.id}`);
- this.state = AddonManager.STATE_CANCELLED;
- XPIProvider.removeActiveInstall(this);
- AddonManagerPrivate.callInstallListeners("onInstallCancelled",
- this.listeners, this.wrapper);
- this.removeTemporaryFile();
-
- let stagingDir = this.installLocation.getStagingDir();
- let stagedAddon = stagingDir.clone();
-
- this.unstageInstall(stagedAddon);
- default:
- throw new Error("Cannot cancel install of " + this.sourceURI.spec +
- " from this state (" + this.state + ")");
- }
- }
-
- /**
- * Adds an InstallListener for this instance if the listener is not already
- * registered.
- *
- * @param aListener
- * The InstallListener to add
- */
- addListener(aListener) {
- if (!this.listeners.some(function(i) { return i == aListener; }))
- this.listeners.push(aListener);
- }
-
- /**
- * Removes an InstallListener for this instance if it is registered.
- *
- * @param aListener
- * The InstallListener to remove
- */
- removeListener(aListener) {
- this.listeners = this.listeners.filter(function(i) {
- return i != aListener;
- });
- }
-
- /**
- * Removes the temporary file owned by this AddonInstall if there is one.
- */
- removeTemporaryFile() {
- // Only proceed if this AddonInstall owns its XPI file
- if (!this.ownsTempFile) {
- this.logger.debug("removeTemporaryFile: " + this.sourceURI.spec + " does not own temp file");
- return;
- }
-
- try {
- this.logger.debug("removeTemporaryFile: " + this.sourceURI.spec + " removing temp file " +
- this.file.path);
- this.file.remove(true);
- this.ownsTempFile = false;
- }
- catch (e) {
- this.logger.warn("Failed to remove temporary file " + this.file.path + " for addon " +
- this.sourceURI.spec,
- e);
- }
- }
-
- /**
- * Updates the sourceURI and releaseNotesURI values on the Addon being
- * installed by this AddonInstall instance.
- */
- updateAddonURIs() {
- this.addon.sourceURI = this.sourceURI.spec;
- if (this.releaseNotesURI)
- this.addon.releaseNotesURI = this.releaseNotesURI.spec;
- }
-
- /**
- * Fills out linkedInstalls with AddonInstall instances for the other files
- * in a multi-package XPI.
- *
- * @param aFiles
- * An array of { entryName, file } for each remaining file from the
- * multi-package XPI.
- */
- _createLinkedInstalls(aFiles) {
- return Task.spawn((function*() {
- if (aFiles.length == 0)
- return;
-
- // Create new AddonInstall instances for every remaining file
- if (!this.linkedInstalls)
- this.linkedInstalls = [];
-
- for (let { entryName, file } of aFiles) {
- logger.debug("Creating linked install from " + entryName);
- let install = yield createLocalInstall(file);
-
- // Make the new install own its temporary file
- install.ownsTempFile = true;
-
- this.linkedInstalls.push(install);
-
- // If one of the internal XPIs was multipackage then move its linked
- // installs to the outer install
- if (install.linkedInstalls) {
- this.linkedInstalls.push(...install.linkedInstalls);
- install.linkedInstalls = null;
- }
-
- install.sourceURI = this.sourceURI;
- install.releaseNotesURI = this.releaseNotesURI;
- if (install.state != AddonManager.STATE_DOWNLOAD_FAILED)
- install.updateAddonURIs();
- }
- }).bind(this));
- }
-
- /**
- * Loads add-on manifests from a multi-package XPI file. Each of the
- * XPI and JAR files contained in the XPI will be extracted. Any that
- * do not contain valid add-ons will be ignored. The first valid add-on will
- * be installed by this AddonInstall instance, the rest will have new
- * AddonInstall instances created for them.
- *
- * @param aZipReader
- * An open nsIZipReader for the multi-package XPI's files. This will
- * be closed before this method returns.
- */
- _loadMultipackageManifests(aZipReader) {
- return Task.spawn((function*() {
- let files = [];
- let entries = aZipReader.findEntries("(*.[Xx][Pp][Ii]|*.[Jj][Aa][Rr])");
- while (entries.hasMore()) {
- let entryName = entries.getNext();
- let file = getTemporaryFile();
- try {
- aZipReader.extract(entryName, file);
- files.push({ entryName, file });
- }
- catch (e) {
- logger.warn("Failed to extract " + entryName + " from multi-package " +
- "XPI", e);
- file.remove(false);
- }
- }
-
- aZipReader.close();
-
- if (files.length == 0) {
- return Promise.reject([AddonManager.ERROR_CORRUPT_FILE,
- "Multi-package XPI does not contain any packages to install"]);
- }
-
- let addon = null;
-
- // Find the first file that is a valid install and use it for
- // the add-on that this AddonInstall instance will install.
- for (let { entryName, file } of files) {
- this.removeTemporaryFile();
- try {
- yield this.loadManifest(file);
- logger.debug("Base multi-package XPI install came from " + entryName);
- this.file = file;
- this.ownsTempFile = true;
-
- yield this._createLinkedInstalls(files.filter(f => f.file != file));
- return undefined;
- }
- catch (e) {
- // _createLinkedInstalls will log errors when it tries to process this
- // file
- }
- }
-
- // No valid add-on was found, delete all the temporary files
- for (let { file } of files) {
- try {
- file.remove(true);
- } catch (e) {
- this.logger.warn("Could not remove temp file " + file.path);
- }
- }
-
- return Promise.reject([AddonManager.ERROR_CORRUPT_FILE,
- "Multi-package XPI does not contain any valid packages to install"]);
- }).bind(this));
- }
-
- /**
- * Called after the add-on is a local file and the signature and install
- * manifest can be read.
- *
- * @param aCallback
- * A function to call when the manifest has been loaded
- * @throws if the add-on does not contain a valid install manifest or the
- * XPI is incorrectly signed
- */
- loadManifest(file) {
- return Task.spawn((function*() {
- let zipreader = Cc["@mozilla.org/libjar/zip-reader;1"].
- createInstance(Ci.nsIZipReader);
- try {
- zipreader.open(file);
- }
- catch (e) {
- zipreader.close();
- return Promise.reject([AddonManager.ERROR_CORRUPT_FILE, e]);
- }
-
- try {
- // loadManifestFromZipReader performs the certificate verification for us
- this.addon = yield loadManifestFromZipReader(zipreader, this.installLocation);
- }
- catch (e) {
- zipreader.close();
- return Promise.reject([AddonManager.ERROR_CORRUPT_FILE, e]);
- }
-
- // A multi-package XPI is a container, the add-ons it holds each
- // have their own id. Everything else had better have an id here.
- if (!this.addon.id && this.addon.type != "multipackage") {
- let err = new Error(`Cannot find id for addon ${file.path}`);
- return Promise.reject([AddonManager.ERROR_CORRUPT_FILE, err]);
- }
-
- if (this.existingAddon) {
- // Check various conditions related to upgrades
- if (this.addon.id != this.existingAddon.id) {
- zipreader.close();
- return Promise.reject([AddonManager.ERROR_INCORRECT_ID,
- `Refusing to upgrade addon ${this.existingAddon.id} to different ID {this.addon.id}`]);
- }
-
- if (this.addon.type == "multipackage") {
- zipreader.close();
- return Promise.reject([AddonManager.ERROR_UNEXPECTED_ADDON_TYPE,
- `Refusing to upgrade addon ${this.existingAddon.id} to a multi-package xpi`]);
- }
-
- if (this.existingAddon.type == "webextension" && this.addon.type != "webextension") {
- zipreader.close();
- return Promise.reject([AddonManager.ERROR_UNEXPECTED_ADDON_TYPE,
- "WebExtensions may not be upated to other extension types"]);
- }
- }
-
- if (mustSign(this.addon.type)) {
- if (this.addon.signedState <= AddonManager.SIGNEDSTATE_MISSING) {
- // This add-on isn't properly signed by a signature that chains to the
- // trusted root.
- let state = this.addon.signedState;
- this.addon = null;
- zipreader.close();
-
- if (state == AddonManager.SIGNEDSTATE_MISSING)
- return Promise.reject([AddonManager.ERROR_SIGNEDSTATE_REQUIRED,
- "signature is required but missing"])
-
- return Promise.reject([AddonManager.ERROR_CORRUPT_FILE,
- "signature verification failed"])
- }
- }
- else if (this.addon.signedState == AddonManager.SIGNEDSTATE_UNKNOWN ||
- this.addon.signedState == AddonManager.SIGNEDSTATE_NOT_REQUIRED) {
- // Check object signing certificate, if any
- let x509 = zipreader.getSigningCert(null);
- if (x509) {
- logger.debug("Verifying XPI signature");
- if (verifyZipSigning(zipreader, x509)) {
- this.certificate = x509;
- if (this.certificate.commonName.length > 0) {
- this.certName = this.certificate.commonName;
- } else {
- this.certName = this.certificate.organization;
- }
- } else {
- zipreader.close();
- return Promise.reject([AddonManager.ERROR_CORRUPT_FILE,
- "XPI is incorrectly signed"]);
- }
- }
- }
-
- if (this.addon.type == "multipackage")
- return this._loadMultipackageManifests(zipreader);
-
- zipreader.close();
-
- this.updateAddonURIs();
-
- this.addon._install = this;
- this.name = this.addon.selectedLocale.name || this.addon.defaultLocale.name;
- this.type = this.addon.type;
- this.version = this.addon.version;
-
- // Setting the iconURL to something inside the XPI locks the XPI and
- // makes it impossible to delete on Windows.
-
- // Try to load from the existing cache first
- let repoAddon = yield new Promise(resolve => AddonRepository.getCachedAddonByID(this.addon.id, resolve));
-
- // It wasn't there so try to re-download it
- if (!repoAddon) {
- yield new Promise(resolve => AddonRepository.cacheAddons([this.addon.id], resolve));
- repoAddon = yield new Promise(resolve => AddonRepository.getCachedAddonByID(this.addon.id, resolve));
- }
-
- this.addon._repositoryAddon = repoAddon;
- this.name = this.name || this.addon._repositoryAddon.name;
- this.addon.compatibilityOverrides = repoAddon ?
- repoAddon.compatibilityOverrides :
- null;
- this.addon.appDisabled = !isUsableAddon(this.addon);
- return undefined;
- }).bind(this));
- }
-
- // TODO This relies on the assumption that we are always installing into the
- // highest priority install location so the resulting add-on will be visible
- // overriding any existing copy in another install location (bug 557710).
- /**
- * Installs the add-on into the install location.
- */
- startInstall() {
- this.state = AddonManager.STATE_INSTALLING;
- if (!AddonManagerPrivate.callInstallListeners("onInstallStarted",
- this.listeners, this.wrapper)) {
- this.state = AddonManager.STATE_DOWNLOADED;
- XPIProvider.removeActiveInstall(this);
- AddonManagerPrivate.callInstallListeners("onInstallCancelled",
- this.listeners, this.wrapper)
- return;
- }
-
- // Find and cancel any pending installs for the same add-on in the same
- // install location
- for (let aInstall of XPIProvider.installs) {
- if (aInstall.state == AddonManager.STATE_INSTALLED &&
- aInstall.installLocation == this.installLocation &&
- aInstall.addon.id == this.addon.id) {
- logger.debug("Cancelling previous pending install of " + aInstall.addon.id);
- aInstall.cancel();
- }
- }
-
- let isUpgrade = this.existingAddon &&
- this.existingAddon._installLocation == this.installLocation;
- let requiresRestart = XPIProvider.installRequiresRestart(this.addon);
-
- logger.debug("Starting install of " + this.addon.id + " from " + this.sourceURI.spec);
- AddonManagerPrivate.callAddonListeners("onInstalling",
- this.addon.wrapper,
- requiresRestart);
-
- let stagedAddon = this.installLocation.getStagingDir();
-
- Task.spawn((function*() {
- let installedUnpacked = 0;
-
- yield this.installLocation.requestStagingDir();
-
- // remove any previously staged files
- yield this.unstageInstall(stagedAddon);
-
- stagedAddon.append(this.addon.id);
- stagedAddon.leafName = this.addon.id + ".xpi";
-
- installedUnpacked = yield this.stageInstall(requiresRestart, stagedAddon, isUpgrade);
-
- if (requiresRestart) {
- this.state = AddonManager.STATE_INSTALLED;
- AddonManagerPrivate.callInstallListeners("onInstallEnded",
- this.listeners, this.wrapper,
- this.addon.wrapper);
- }
- else {
- // The install is completed so it should be removed from the active list
- XPIProvider.removeActiveInstall(this);
-
- // Deactivate and remove the old add-on as necessary
- let reason = BOOTSTRAP_REASONS.ADDON_INSTALL;
- if (this.existingAddon) {
- if (Services.vc.compare(this.existingAddon.version, this.addon.version) < 0)
- reason = BOOTSTRAP_REASONS.ADDON_UPGRADE;
- else
- reason = BOOTSTRAP_REASONS.ADDON_DOWNGRADE;
-
- if (this.existingAddon.bootstrap) {
- let file = this.existingAddon._sourceBundle;
- if (this.existingAddon.active) {
- XPIProvider.callBootstrapMethod(this.existingAddon, file,
- "shutdown", reason,
- { newVersion: this.addon.version });
- }
-
- XPIProvider.callBootstrapMethod(this.existingAddon, file,
- "uninstall", reason,
- { newVersion: this.addon.version });
- XPIProvider.unloadBootstrapScope(this.existingAddon.id);
- flushChromeCaches();
- }
-
- if (!isUpgrade && this.existingAddon.active) {
- XPIDatabase.updateAddonActive(this.existingAddon, false);
- }
- }
-
- // Install the new add-on into its final location
- let existingAddonID = this.existingAddon ? this.existingAddon.id : null;
- let file = this.installLocation.installAddon({
- id: this.addon.id,
- source: stagedAddon,
- existingAddonID
- });
-
- // Update the metadata in the database
- this.addon._sourceBundle = file;
- this.addon.visible = true;
-
- if (isUpgrade) {
- this.addon = XPIDatabase.updateAddonMetadata(this.existingAddon, this.addon,
- file.persistentDescriptor);
- let state = XPIStates.getAddon(this.installLocation.name, this.addon.id);
- if (state) {
- state.syncWithDB(this.addon, true);
- } else {
- logger.warn("Unexpected missing XPI state for add-on ${id}", this.addon);
- }
- }
- else {
- this.addon.active = (this.addon.visible && !this.addon.disabled);
- this.addon = XPIDatabase.addAddonMetadata(this.addon, file.persistentDescriptor);
- XPIStates.addAddon(this.addon);
- this.addon.installDate = this.addon.updateDate;
- XPIDatabase.saveChanges();
- }
- XPIStates.save();
-
- let extraParams = {};
- if (this.existingAddon) {
- extraParams.oldVersion = this.existingAddon.version;
- }
-
- if (this.addon.bootstrap) {
- XPIProvider.callBootstrapMethod(this.addon, file, "install",
- reason, extraParams);
- }
-
- AddonManagerPrivate.callAddonListeners("onInstalled",
- this.addon.wrapper);
-
- logger.debug("Install of " + this.sourceURI.spec + " completed.");
- this.state = AddonManager.STATE_INSTALLED;
- AddonManagerPrivate.callInstallListeners("onInstallEnded",
- this.listeners, this.wrapper,
- this.addon.wrapper);
-
- if (this.addon.bootstrap) {
- if (this.addon.active) {
- XPIProvider.callBootstrapMethod(this.addon, file, "startup",
- reason, extraParams);
- }
- else {
- // XXX this makes it dangerous to do some things in onInstallEnded
- // listeners because important cleanup hasn't been done yet
- XPIProvider.unloadBootstrapScope(this.addon.id);
- }
- }
- XPIProvider.setTelemetry(this.addon.id, "unpacked", installedUnpacked);
- recordAddonTelemetry(this.addon);
- }
- }).bind(this)).then(null, (e) => {
- logger.warn(`Failed to install ${this.file.path} from ${this.sourceURI.spec} to ${stagedAddon.path}`, e);
-
- if (stagedAddon.exists())
- recursiveRemove(stagedAddon);
- this.state = AddonManager.STATE_INSTALL_FAILED;
- this.error = AddonManager.ERROR_FILE_ACCESS;
- XPIProvider.removeActiveInstall(this);
- AddonManagerPrivate.callAddonListeners("onOperationCancelled",
- this.addon.wrapper);
- AddonManagerPrivate.callInstallListeners("onInstallFailed",
- this.listeners,
- this.wrapper);
- }).then(() => {
- this.removeTemporaryFile();
- return this.installLocation.releaseStagingDir();
- });
- }
-
- /**
- * Stages an upgrade for next application restart.
- */
- stageInstall(restartRequired, stagedAddon, isUpgrade) {
- return Task.spawn((function*() {
- let stagedJSON = stagedAddon.clone();
- stagedJSON.leafName = this.addon.id + ".json";
-
- let installedUnpacked = 0;
-
- // First stage the file regardless of whether restarting is necessary
- if (this.addon.unpack || Preferences.get(PREF_XPI_UNPACK, false)) {
- logger.debug("Addon " + this.addon.id + " will be installed as " +
- "an unpacked directory");
- stagedAddon.leafName = this.addon.id;
- yield OS.File.makeDir(stagedAddon.path);
- yield ZipUtils.extractFilesAsync(this.file, stagedAddon);
- installedUnpacked = 1;
- }
- else {
- logger.debug(`Addon ${this.addon.id} will be installed as a packed xpi`);
- stagedAddon.leafName = this.addon.id + ".xpi";
-
- yield OS.File.copy(this.file.path, stagedAddon.path);
- }
-
- if (restartRequired) {
- // Point the add-on to its extracted files as the xpi may get deleted
- this.addon._sourceBundle = stagedAddon;
-
- // Cache the AddonInternal as it may have updated compatibility info
- writeStringToFile(stagedJSON, JSON.stringify(this.addon));
-
- logger.debug("Staged install of " + this.addon.id + " from " + this.sourceURI.spec + " ready; waiting for restart.");
- if (isUpgrade) {
- delete this.existingAddon.pendingUpgrade;
- this.existingAddon.pendingUpgrade = this.addon;
- }
- }
-
- return installedUnpacked;
- }).bind(this));
- }
-
- /**
- * Removes any previously staged upgrade.
- */
- unstageInstall(stagedAddon) {
- return Task.spawn((function*() {
- let stagedJSON = stagedAddon.clone();
- let removedAddon = stagedAddon.clone();
-
- stagedJSON.append(this.addon.id + ".json");
-
- if (stagedJSON.exists()) {
- stagedJSON.remove(true);
- }
-
- removedAddon.append(this.addon.id);
- yield removeAsync(removedAddon);
- removedAddon.leafName = this.addon.id + ".xpi";
- yield removeAsync(removedAddon);
- }).bind(this));
- }
-
- /**
- * Postone a pending update, until restart or until the add-on resumes.
- *
- * @param {Function} resumeFunction - a function for the add-on to run
- * when resuming.
- */
- postpone(resumeFunction) {
- return Task.spawn((function*() {
- this.state = AddonManager.STATE_POSTPONED;
-
- let stagingDir = this.installLocation.getStagingDir();
- let stagedAddon = stagingDir.clone();
-
- yield this.installLocation.requestStagingDir();
- yield this.unstageInstall(stagedAddon);
-
- stagedAddon.append(this.addon.id);
- stagedAddon.leafName = this.addon.id + ".xpi";
-
- yield this.stageInstall(true, stagedAddon, true);
-
- AddonManagerPrivate.callInstallListeners("onInstallPostponed",
- this.listeners, this.wrapper)
-
- // upgrade has been staged for restart, provide a way for it to call the
- // resume function.
- if (resumeFunction) {
- let callback = AddonManagerPrivate.getUpgradeListener(this.addon.id);
- if (callback) {
- callback({
- version: this.version,
- install: () => {
- switch (this.state) {
- case AddonManager.STATE_POSTPONED:
- resumeFunction();
- break;
- default:
- logger.warn(`${this.addon.id} cannot resume postponed upgrade from state (${this.state})`);
- break;
- }
- },
- });
- }
- }
- this.installLocation.releaseStagingDir();
- }).bind(this));
- }
-}
-
-class LocalAddonInstall extends AddonInstall {
- /**
- * Initialises this install to be an install from a local file.
- *
- * @returns Promise
- * A Promise that resolves when the object is ready to use.
- */
- init() {
- return Task.spawn((function*() {
- this.file = this.sourceURI.QueryInterface(Ci.nsIFileURL).file;
-
- if (!this.file.exists()) {
- logger.warn("XPI file " + this.file.path + " does not exist");
- this.state = AddonManager.STATE_DOWNLOAD_FAILED;
- this.error = AddonManager.ERROR_NETWORK_FAILURE;
- XPIProvider.removeActiveInstall(this);
- return;
- }
-
- this.state = AddonManager.STATE_DOWNLOADED;
- this.progress = this.file.fileSize;
- this.maxProgress = this.file.fileSize;
-
- if (this.hash) {
- let crypto = Cc["@mozilla.org/security/hash;1"].
- createInstance(Ci.nsICryptoHash);
- try {
- crypto.initWithString(this.hash.algorithm);
- }
- catch (e) {
- logger.warn("Unknown hash algorithm '" + this.hash.algorithm + "' for addon " + this.sourceURI.spec, e);
- this.state = AddonManager.STATE_DOWNLOAD_FAILED;
- this.error = AddonManager.ERROR_INCORRECT_HASH;
- XPIProvider.removeActiveInstall(this);
- return;
- }
-
- let fis = Cc["@mozilla.org/network/file-input-stream;1"].
- createInstance(Ci.nsIFileInputStream);
- fis.init(this.file, -1, -1, false);
- crypto.updateFromStream(fis, this.file.fileSize);
- let calculatedHash = getHashStringForCrypto(crypto);
- if (calculatedHash != this.hash.data) {
- logger.warn("File hash (" + calculatedHash + ") did not match provided hash (" +
- this.hash.data + ")");
- this.state = AddonManager.STATE_DOWNLOAD_FAILED;
- this.error = AddonManager.ERROR_INCORRECT_HASH;
- XPIProvider.removeActiveInstall(this);
- return;
- }
- }
-
- try {
- yield this.loadManifest(this.file);
- } catch ([error, message]) {
- logger.warn("Invalid XPI", message);
- this.state = AddonManager.STATE_DOWNLOAD_FAILED;
- this.error = error;
- XPIProvider.removeActiveInstall(this);
- AddonManagerPrivate.callInstallListeners("onNewInstall",
- this.listeners,
- this.wrapper);
- return;
- }
-
- let addon = yield new Promise(resolve => {
- XPIDatabase.getVisibleAddonForID(this.addon.id, resolve);
- });
-
- this.existingAddon = addon;
- if (addon)
- applyBlocklistChanges(addon, this.addon);
- this.addon.updateDate = Date.now();
- this.addon.installDate = addon ? addon.installDate : this.addon.updateDate;
-
- if (!this.addon.isCompatible) {
- this.state = AddonManager.STATE_CHECKING;
-
- yield new Promise(resolve => {
- new UpdateChecker(this.addon, {
- onUpdateFinished: aAddon => {
- this.state = AddonManager.STATE_DOWNLOADED;
- AddonManagerPrivate.callInstallListeners("onNewInstall",
- this.listeners,
- this.wrapper);
- resolve();
- }
- }, AddonManager.UPDATE_WHEN_ADDON_INSTALLED);
- });
- }
- else {
- AddonManagerPrivate.callInstallListeners("onNewInstall",
- this.listeners,
- this.wrapper);
-
- }
- }).bind(this));
- }
-
- install() {
- if (this.state == AddonManager.STATE_DOWNLOAD_FAILED) {
- // For a local install, this state means that verification of the
- // file failed (e.g., the hash or signature or manifest contents
- // were invalid). It doesn't make sense to retry anything in this
- // case but we have callers who don't know if their AddonInstall
- // object is a local file or a download so accomodate them here.
- AddonManagerPrivate.callInstallListeners("onDownloadFailed",
- this.listeners, this.wrapper);
- return;
- }
- super.install();
- }
-}
-
-class DownloadAddonInstall extends AddonInstall {
- /**
- * Instantiates a DownloadAddonInstall
- *
- * @param installLocation
- * The InstallLocation the add-on will be installed into
- * @param url
- * The nsIURL to get the add-on from
- * @param name
- * An optional name for the add-on
- * @param hash
- * An optional hash for the add-on
- * @param existingAddon
- * The add-on this install will update if known
- * @param browser
- * The browser performing the install, used to display
- * authentication prompts.
- * @param type
- * An optional type for the add-on
- * @param icons
- * Optional icons for the add-on
- * @param version
- * An optional version for the add-on
- */
- constructor(installLocation, url, hash, existingAddon, browser,
- name, type, icons, version) {
- super(installLocation, url, hash, existingAddon);
-
- this.browser = browser;
-
- this.state = AddonManager.STATE_AVAILABLE;
- this.name = name;
- this.type = type;
- this.version = version;
- this.icons = icons;
-
- this.stream = null;
- this.crypto = null;
- this.badCertHandler = null;
- this.restartDownload = false;
-
- AddonManagerPrivate.callInstallListeners("onNewInstall", this.listeners,
- this.wrapper);
- }
-
- install() {
- switch (this.state) {
- case AddonManager.STATE_AVAILABLE:
- this.startDownload();
- break;
- case AddonManager.STATE_DOWNLOAD_FAILED:
- case AddonManager.STATE_INSTALL_FAILED:
- case AddonManager.STATE_CANCELLED:
- this.removeTemporaryFile();
- this.state = AddonManager.STATE_AVAILABLE;
- this.error = 0;
- this.progress = 0;
- this.maxProgress = -1;
- this.hash = this.originalHash;
- this.startDownload();
- break;
- default:
- super.install();
- }
- }
-
- cancel() {
- if (this.state == AddonManager.STATE_DOWNLOADING) {
- if (this.channel) {
- logger.debug("Cancelling download of " + this.sourceURI.spec);
- this.channel.cancel(Cr.NS_BINDING_ABORTED);
- }
- } else {
- super.cancel();
- }
- }
-
- observe(aSubject, aTopic, aData) {
- // Network is going offline
- this.cancel();
- }
-
- /**
- * Starts downloading the add-on's XPI file.
- */
- startDownload() {
- this.state = AddonManager.STATE_DOWNLOADING;
- if (!AddonManagerPrivate.callInstallListeners("onDownloadStarted",
- this.listeners, this.wrapper)) {
- logger.debug("onDownloadStarted listeners cancelled installation of addon " + this.sourceURI.spec);
- this.state = AddonManager.STATE_CANCELLED;
- XPIProvider.removeActiveInstall(this);
- AddonManagerPrivate.callInstallListeners("onDownloadCancelled",
- this.listeners, this.wrapper)
- return;
- }
-
- // If a listener changed our state then do not proceed with the download
- if (this.state != AddonManager.STATE_DOWNLOADING)
- return;
-
- if (this.channel) {
- // A previous download attempt hasn't finished cleaning up yet, signal
- // that it should restart when complete
- logger.debug("Waiting for previous download to complete");
- this.restartDownload = true;
- return;
- }
-
- this.openChannel();
- }
-
- openChannel() {
- this.restartDownload = false;
-
- try {
- this.file = getTemporaryFile();
- this.ownsTempFile = true;
- this.stream = Cc["@mozilla.org/network/file-output-stream;1"].
- createInstance(Ci.nsIFileOutputStream);
- this.stream.init(this.file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE |
- FileUtils.MODE_TRUNCATE, FileUtils.PERMS_FILE, 0);
- }
- catch (e) {
- logger.warn("Failed to start download for addon " + this.sourceURI.spec, e);
- this.state = AddonManager.STATE_DOWNLOAD_FAILED;
- this.error = AddonManager.ERROR_FILE_ACCESS;
- XPIProvider.removeActiveInstall(this);
- AddonManagerPrivate.callInstallListeners("onDownloadFailed",
- this.listeners, this.wrapper);
- return;
- }
-
- let listener = Cc["@mozilla.org/network/stream-listener-tee;1"].
- createInstance(Ci.nsIStreamListenerTee);
- listener.init(this, this.stream);
- try {
- let requireBuiltIn = Preferences.get(PREF_INSTALL_REQUIREBUILTINCERTS, true);
- this.badCertHandler = new CertUtils.BadCertHandler(!requireBuiltIn);
-
- this.channel = NetUtil.newChannel({
- uri: this.sourceURI,
- loadUsingSystemPrincipal: true
- });
- this.channel.notificationCallbacks = this;
- if (this.channel instanceof Ci.nsIHttpChannel) {
- this.channel.setRequestHeader("Moz-XPI-Update", "1", true);
- if (this.channel instanceof Ci.nsIHttpChannelInternal)
- this.channel.forceAllowThirdPartyCookie = true;
- }
- this.channel.asyncOpen2(listener);
-
- Services.obs.addObserver(this, "network:offline-about-to-go-offline", false);
- }
- catch (e) {
- logger.warn("Failed to start download for addon " + this.sourceURI.spec, e);
- this.state = AddonManager.STATE_DOWNLOAD_FAILED;
- this.error = AddonManager.ERROR_NETWORK_FAILURE;
- XPIProvider.removeActiveInstall(this);
- AddonManagerPrivate.callInstallListeners("onDownloadFailed",
- this.listeners, this.wrapper);
- }
- }
-
- /**
- * Update the crypto hasher with the new data and call the progress listeners.
- *
- * @see nsIStreamListener
- */
- onDataAvailable(aRequest, aContext, aInputstream, aOffset, aCount) {
- this.crypto.updateFromStream(aInputstream, aCount);
- this.progress += aCount;
- if (!AddonManagerPrivate.callInstallListeners("onDownloadProgress",
- this.listeners, this.wrapper)) {
- // TODO cancel the download and make it available again (bug 553024)
- }
- }
-
- /**
- * Check the redirect response for a hash of the target XPI and verify that
- * we don't end up on an insecure channel.
- *
- * @see nsIChannelEventSink
- */
- asyncOnChannelRedirect(aOldChannel, aNewChannel, aFlags, aCallback) {
- if (!this.hash && aOldChannel.originalURI.schemeIs("https") &&
- aOldChannel instanceof Ci.nsIHttpChannel) {
- try {
- let hashStr = aOldChannel.getResponseHeader("X-Target-Digest");
- let hashSplit = hashStr.toLowerCase().split(":");
- this.hash = {
- algorithm: hashSplit[0],
- data: hashSplit[1]
- };
- }
- catch (e) {
- }
- }
-
- // Verify that we don't end up on an insecure channel if we haven't got a
- // hash to verify with (see bug 537761 for discussion)
- if (!this.hash)
- this.badCertHandler.asyncOnChannelRedirect(aOldChannel, aNewChannel, aFlags, aCallback);
- else
- aCallback.onRedirectVerifyCallback(Cr.NS_OK);
-
- this.channel = aNewChannel;
- }
-
- /**
- * This is the first chance to get at real headers on the channel.
- *
- * @see nsIStreamListener
- */
- onStartRequest(aRequest, aContext) {
- this.crypto = Cc["@mozilla.org/security/hash;1"].
- createInstance(Ci.nsICryptoHash);
- if (this.hash) {
- try {
- this.crypto.initWithString(this.hash.algorithm);
- }
- catch (e) {
- logger.warn("Unknown hash algorithm '" + this.hash.algorithm + "' for addon " + this.sourceURI.spec, e);
- this.state = AddonManager.STATE_DOWNLOAD_FAILED;
- this.error = AddonManager.ERROR_INCORRECT_HASH;
- XPIProvider.removeActiveInstall(this);
- AddonManagerPrivate.callInstallListeners("onDownloadFailed",
- this.listeners, this.wrapper);
- aRequest.cancel(Cr.NS_BINDING_ABORTED);
- return;
- }
- }
- else {
- // We always need something to consume data from the inputstream passed
- // to onDataAvailable so just create a dummy cryptohasher to do that.
- this.crypto.initWithString("sha1");
- }
-
- this.progress = 0;
- if (aRequest instanceof Ci.nsIChannel) {
- try {
- this.maxProgress = aRequest.contentLength;
- }
- catch (e) {
- }
- logger.debug("Download started for " + this.sourceURI.spec + " to file " +
- this.file.path);
- }
- }
-
- /**
- * The download is complete.
- *
- * @see nsIStreamListener
- */
- onStopRequest(aRequest, aContext, aStatus) {
- this.stream.close();
- this.channel = null;
- this.badCerthandler = null;
- Services.obs.removeObserver(this, "network:offline-about-to-go-offline");
-
- // If the download was cancelled then update the state and send events
- if (aStatus == Cr.NS_BINDING_ABORTED) {
- if (this.state == AddonManager.STATE_DOWNLOADING) {
- logger.debug("Cancelled download of " + this.sourceURI.spec);
- this.state = AddonManager.STATE_CANCELLED;
- XPIProvider.removeActiveInstall(this);
- AddonManagerPrivate.callInstallListeners("onDownloadCancelled",
- this.listeners, this.wrapper);
- // If a listener restarted the download then there is no need to
- // remove the temporary file
- if (this.state != AddonManager.STATE_CANCELLED)
- return;
- }
-
- this.removeTemporaryFile();
- if (this.restartDownload)
- this.openChannel();
- return;
- }
-
- logger.debug("Download of " + this.sourceURI.spec + " completed.");
-
- if (Components.isSuccessCode(aStatus)) {
- if (!(aRequest instanceof Ci.nsIHttpChannel) || aRequest.requestSucceeded) {
- if (!this.hash && (aRequest instanceof Ci.nsIChannel)) {
- try {
- CertUtils.checkCert(aRequest,
- !Preferences.get(PREF_INSTALL_REQUIREBUILTINCERTS, true));
- }
- catch (e) {
- this.downloadFailed(AddonManager.ERROR_NETWORK_FAILURE, e);
- return;
- }
- }
-
- // convert the binary hash data to a hex string.
- let calculatedHash = getHashStringForCrypto(this.crypto);
- this.crypto = null;
- if (this.hash && calculatedHash != this.hash.data) {
- this.downloadFailed(AddonManager.ERROR_INCORRECT_HASH,
- "Downloaded file hash (" + calculatedHash +
- ") did not match provided hash (" + this.hash.data + ")");
- return;
- }
-
- this.loadManifest(this.file).then(() => {
- if (this.addon.isCompatible) {
- this.downloadCompleted();
- }
- else {
- // TODO Should we send some event here (bug 557716)?
- this.state = AddonManager.STATE_CHECKING;
- new UpdateChecker(this.addon, {
- onUpdateFinished: aAddon => this.downloadCompleted(),
- }, AddonManager.UPDATE_WHEN_ADDON_INSTALLED);
- }
- }, ([error, message]) => {
- this.removeTemporaryFile();
- this.downloadFailed(error, message);
- });
- }
- else if (aRequest instanceof Ci.nsIHttpChannel) {
- this.downloadFailed(AddonManager.ERROR_NETWORK_FAILURE,
- aRequest.responseStatus + " " +
- aRequest.responseStatusText);
- }
- else {
- this.downloadFailed(AddonManager.ERROR_NETWORK_FAILURE, aStatus);
- }
- }
- else {
- this.downloadFailed(AddonManager.ERROR_NETWORK_FAILURE, aStatus);
- }
- }
-
- /**
- * Notify listeners that the download failed.
- *
- * @param aReason
- * Something to log about the failure
- * @param error
- * The error code to pass to the listeners
- */
- downloadFailed(aReason, aError) {
- logger.warn("Download of " + this.sourceURI.spec + " failed", aError);
- this.state = AddonManager.STATE_DOWNLOAD_FAILED;
- this.error = aReason;
- XPIProvider.removeActiveInstall(this);
- AddonManagerPrivate.callInstallListeners("onDownloadFailed", this.listeners,
- this.wrapper);
-
- // If the listener hasn't restarted the download then remove any temporary
- // file
- if (this.state == AddonManager.STATE_DOWNLOAD_FAILED) {
- logger.debug("downloadFailed: removing temp file for " + this.sourceURI.spec);
- this.removeTemporaryFile();
- }
- else
- logger.debug("downloadFailed: listener changed AddonInstall state for " +
- this.sourceURI.spec + " to " + this.state);
- }
-
- /**
- * Notify listeners that the download completed.
- */
- downloadCompleted() {
- XPIDatabase.getVisibleAddonForID(this.addon.id, aAddon => {
- if (aAddon)
- this.existingAddon = aAddon;
-
- this.state = AddonManager.STATE_DOWNLOADED;
- this.addon.updateDate = Date.now();
-
- if (this.existingAddon) {
- this.addon.existingAddonID = this.existingAddon.id;
- this.addon.installDate = this.existingAddon.installDate;
- applyBlocklistChanges(this.existingAddon, this.addon);
- }
- else {
- this.addon.installDate = this.addon.updateDate;
- }
-
- if (AddonManagerPrivate.callInstallListeners("onDownloadEnded",
- this.listeners,
- this.wrapper)) {
- // If a listener changed our state then do not proceed with the install
- if (this.state != AddonManager.STATE_DOWNLOADED)
- return;
-
- // If an upgrade listener is registered for this add-on, pass control
- // over the upgrade to the add-on.
- if (AddonManagerPrivate.hasUpgradeListener(this.addon.id)) {
- logger.info(`add-on ${this.addon.id} has an upgrade listener, postponing upgrade until restart`);
- let resumeFn = () => {
- logger.info(`${this.addon.id} has resumed a previously postponed upgrade`);
- this.state = AddonManager.STATE_DOWNLOADED;
- this.install();
- }
- this.postpone(resumeFn);
- } else {
- // no upgrade listener present, so proceed with normal install
- this.install();
- if (this.linkedInstalls) {
- for (let install of this.linkedInstalls) {
- if (install.state == AddonManager.STATE_DOWNLOADED)
- install.install();
- }
- }
- }
- }
- });
- }
-
- getInterface(iid) {
- if (iid.equals(Ci.nsIAuthPrompt2)) {
- let win = null;
- if (this.browser) {
- win = this.browser.contentWindow || this.browser.ownerDocument.defaultView;
- }
-
- let factory = Cc["@mozilla.org/prompter;1"].
- getService(Ci.nsIPromptFactory);
- let prompt = factory.getPrompt(win, Ci.nsIAuthPrompt2);
-
- if (this.browser && prompt instanceof Ci.nsILoginManagerPrompter)
- prompt.browser = this.browser;
-
- return prompt;
- }
- else if (iid.equals(Ci.nsIChannelEventSink)) {
- return this;
- }
-
- return this.badCertHandler.getInterface(iid);
- }
-
- /**
- * Postone a pending update, until restart or until the add-on resumes.
- *
- * @param {Function} resumeFn - a function for the add-on to run
- * when resuming.
- */
- postpone(resumeFn) {
- return Task.spawn((function*() {
- this.state = AddonManager.STATE_POSTPONED;
-
- let stagingDir = this.installLocation.getStagingDir();
- let stagedAddon = stagingDir.clone();
-
- yield this.installLocation.requestStagingDir();
- yield this.unstageInstall(stagedAddon);
-
- stagedAddon.append(this.addon.id);
- stagedAddon.leafName = this.addon.id + ".xpi";
-
- yield this.stageInstall(true, stagedAddon, true);
-
- AddonManagerPrivate.callInstallListeners("onInstallPostponed",
- this.listeners, this.wrapper)
-
- // upgrade has been staged for restart, provide a way for it to call the
- // resume function.
- let callback = AddonManagerPrivate.getUpgradeListener(this.addon.id);
- if (callback) {
- callback({
- version: this.version,
- install: () => {
- switch (this.state) {
- case AddonManager.STATE_POSTPONED:
- if (resumeFn) {
- resumeFn();
- }
- break;
- default:
- logger.warn(`${this.addon.id} cannot resume postponed upgrade from state (${this.state})`);
- break;
- }
- },
- });
- }
- // Release the staging directory lock, but since the staging dir is populated
- // it will not be removed until resumed or installed by restart.
- // See also cleanStagingDir()
- this.installLocation.releaseStagingDir();
- }).bind(this));
- }
-}
-
-/**
- * This class exists just for the specific case of staged add-ons that
- * fail to install at startup. When that happens, the add-on remains
- * staged but we want to keep track of it like other installs so that we
- * can clean it up if the same add-on is installed again (see the comment
- * about "pending installs for the same add-on" in AddonInstall.startInstall)
- */
-class StagedAddonInstall extends AddonInstall {
- constructor(installLocation, dir, manifest) {
- super(installLocation, dir);
-
- this.name = manifest.name;
- this.type = manifest.type;
- this.version = manifest.version;
- this.icons = manifest.icons;
- this.releaseNotesURI = manifest.releaseNotesURI ?
- NetUtil.newURI(manifest.releaseNotesURI) :
- null;
- this.sourceURI = manifest.sourceURI ?
- NetUtil.newURI(manifest.sourceURI) :
- null;
- this.file = null;
- this.addon = manifest;
-
- this.state = AddonManager.STATE_INSTALLED;
- }
-}
-
-/**
- * Creates a new AddonInstall to install an add-on from a local file.
- *
- * @param file
- * The file to install
- * @param location
- * The location to install to
- * @returns Promise
- * A Promise that resolves with the new install object.
- */
-function createLocalInstall(file, location) {
- if (!location) {
- location = XPIProvider.installLocationsByName[KEY_APP_PROFILE];
- }
- let url = Services.io.newFileURI(file);
-
- try {
- let install = new LocalAddonInstall(location, url);
- return install.init().then(() => install);
- }
- catch (e) {
- logger.error("Error creating install", e);
- XPIProvider.removeActiveInstall(this);
- return Promise.resolve(null);
- }
-}
-
-/**
- * Creates a new AddonInstall to download and install a URL.
- *
- * @param aCallback
- * The callback to pass the new AddonInstall to
- * @param aUri
- * The URI to download
- * @param aHash
- * A hash for the add-on
- * @param aName
- * A name for the add-on
- * @param aIcons
- * An icon URLs for the add-on
- * @param aVersion
- * A version for the add-on
- * @param aBrowser
- * The browser performing the install
- */
-function createDownloadInstall(aCallback, aUri, aHash, aName, aIcons,
- aVersion, aBrowser) {
- let location = XPIProvider.installLocationsByName[KEY_APP_PROFILE];
- let url = NetUtil.newURI(aUri);
-
- if (url instanceof Ci.nsIFileURL) {
- let install = new LocalAddonInstall(location, url, aHash);
- install.init().then(() => { aCallback(install); });
- } else {
- let install = new DownloadAddonInstall(location, url, aHash, null,
- aBrowser, aName, null, aIcons,
- aVersion);
- aCallback(install);
- }
-}
-
-/**
- * Creates a new AddonInstall for an update.
- *
- * @param aCallback
- * The callback to pass the new AddonInstall to
- * @param aAddon
- * The add-on being updated
- * @param aUpdate
- * The metadata about the new version from the update manifest
- */
-function createUpdate(aCallback, aAddon, aUpdate) {
- let url = NetUtil.newURI(aUpdate.updateURL);
-
- Task.spawn(function*() {
- let install;
- if (url instanceof Ci.nsIFileURL) {
- install = new LocalAddonInstall(aAddon._installLocation, url,
- aUpdate.updateHash, aAddon);
- yield install.init();
- } else {
- install = new DownloadAddonInstall(aAddon._installLocation, url,
- aUpdate.updateHash, aAddon, null,
- aAddon.selectedLocale.name ?
- aAddon.selectedLocale.name : aAddon.defaultLocale.name,
- aAddon.type, aAddon.icons, aUpdate.version);
- }
- try {
- if (aUpdate.updateInfoURL)
- install.releaseNotesURI = NetUtil.newURI(escapeAddonURI(aAddon, aUpdate.updateInfoURL));
- }
- catch (e) {
- // If the releaseNotesURI cannot be parsed then just ignore it.
- }
-
- aCallback(install);
- });
-}
-
-// This map is shared between AddonInstallWrapper and AddonWrapper
-const wrapperMap = new WeakMap();
-let installFor = wrapper => wrapperMap.get(wrapper);
-let addonFor = installFor;
-
-/**
- * Creates a wrapper for an AddonInstall that only exposes the public API
- *
- * @param install
- * The AddonInstall to create a wrapper for
- */
-function AddonInstallWrapper(aInstall) {
- wrapperMap.set(this, aInstall);
-}
-
-AddonInstallWrapper.prototype = {
- get __AddonInstallInternal__() {
- return AppConstants.DEBUG ? installFor(this) : undefined;
- },
-
- get type() {
- return getExternalType(installFor(this).type);
- },
-
- get iconURL() {
- return installFor(this).icons[32];
- },
-
- get existingAddon() {
- let install = installFor(this);
- return install.existingAddon ? install.existingAddon.wrapper : null;
- },
-
- get addon() {
- let install = installFor(this);
- return install.addon ? install.addon.wrapper : null;
- },
-
- get sourceURI() {
- return installFor(this).sourceURI;
- },
-
- get linkedInstalls() {
- let install = installFor(this);
- if (!install.linkedInstalls)
- return null;
- return install.linkedInstalls.map(i => i.wrapper);
- },
-
- install: function() {
- installFor(this).install();
- },
-
- cancel: function() {
- installFor(this).cancel();
- },
-
- addListener: function(listener) {
- installFor(this).addListener(listener);
- },
-
- removeListener: function(listener) {
- installFor(this).removeListener(listener);
- },
-};
-
-["name", "version", "icons", "releaseNotesURI", "file", "state", "error",
- "progress", "maxProgress", "certificate", "certName"].forEach(function(aProp) {
- Object.defineProperty(AddonInstallWrapper.prototype, aProp, {
- get: function() {
- return installFor(this)[aProp];
- },
- enumerable: true,
- });
-});
-
-/**
- * Creates a new update checker.
- *
- * @param aAddon
- * The add-on to check for updates
- * @param aListener
- * An UpdateListener to notify of updates
- * @param aReason
- * The reason for the update check
- * @param aAppVersion
- * An optional application version to check for updates for
- * @param aPlatformVersion
- * An optional platform version to check for updates for
- * @throws if the aListener or aReason arguments are not valid
- */
-function UpdateChecker(aAddon, aListener, aReason, aAppVersion, aPlatformVersion) {
- if (!aListener || !aReason)
- throw Cr.NS_ERROR_INVALID_ARG;
-
- Components.utils.import("resource://gre/modules/addons/AddonUpdateChecker.jsm");
-
- this.addon = aAddon;
- aAddon._updateCheck = this;
- XPIProvider.doing(this);
- this.listener = aListener;
- this.appVersion = aAppVersion;
- this.platformVersion = aPlatformVersion;
- this.syncCompatibility = (aReason == AddonManager.UPDATE_WHEN_NEW_APP_INSTALLED);
-
- let updateURL = aAddon.updateURL;
- if (!updateURL) {
- if (aReason == AddonManager.UPDATE_WHEN_PERIODIC_UPDATE &&
- Services.prefs.getPrefType(PREF_EM_UPDATE_BACKGROUND_URL) == Services.prefs.PREF_STRING) {
- updateURL = Services.prefs.getCharPref(PREF_EM_UPDATE_BACKGROUND_URL);
- } else {
- updateURL = Services.prefs.getCharPref(PREF_EM_UPDATE_URL);
- }
- }
-
- const UPDATE_TYPE_COMPATIBILITY = 32;
- const UPDATE_TYPE_NEWVERSION = 64;
-
- aReason |= UPDATE_TYPE_COMPATIBILITY;
- if ("onUpdateAvailable" in this.listener)
- aReason |= UPDATE_TYPE_NEWVERSION;
-
- let url = escapeAddonURI(aAddon, updateURL, aReason, aAppVersion);
- this._parser = AddonUpdateChecker.checkForUpdates(aAddon.id, aAddon.updateKey,
- url, this);
-}
-
-UpdateChecker.prototype = {
- addon: null,
- listener: null,
- appVersion: null,
- platformVersion: null,
- syncCompatibility: null,
-
- /**
- * Calls a method on the listener passing any number of arguments and
- * consuming any exceptions.
- *
- * @param aMethod
- * The method to call on the listener
- */
- callListener: function(aMethod, ...aArgs) {
- if (!(aMethod in this.listener))
- return;
-
- try {
- this.listener[aMethod].apply(this.listener, aArgs);
- }
- catch (e) {
- logger.warn("Exception calling UpdateListener method " + aMethod, e);
- }
- },
-
- /**
- * Called when AddonUpdateChecker completes the update check
- *
- * @param updates
- * The list of update details for the add-on
- */
- onUpdateCheckComplete: function(aUpdates) {
- XPIProvider.done(this.addon._updateCheck);
- this.addon._updateCheck = null;
- let AUC = AddonUpdateChecker;
-
- let ignoreMaxVersion = false;
- let ignoreStrictCompat = false;
- if (!AddonManager.checkCompatibility) {
- ignoreMaxVersion = true;
- ignoreStrictCompat = true;
- } else if (this.addon.type in COMPATIBLE_BY_DEFAULT_TYPES &&
- !AddonManager.strictCompatibility &&
- !this.addon.strictCompatibility &&
- !this.addon.hasBinaryComponents) {
- ignoreMaxVersion = true;
- }
-
- // Always apply any compatibility update for the current version
- let compatUpdate = AUC.getCompatibilityUpdate(aUpdates, this.addon.version,
- this.syncCompatibility,
- null, null,
- ignoreMaxVersion,
- ignoreStrictCompat);
- // Apply the compatibility update to the database
- if (compatUpdate)
- this.addon.applyCompatibilityUpdate(compatUpdate, this.syncCompatibility);
-
- // If the request is for an application or platform version that is
- // different to the current application or platform version then look for a
- // compatibility update for those versions.
- if ((this.appVersion &&
- Services.vc.compare(this.appVersion, Services.appinfo.version) != 0) ||
- (this.platformVersion &&
- Services.vc.compare(this.platformVersion, Services.appinfo.platformVersion) != 0)) {
- compatUpdate = AUC.getCompatibilityUpdate(aUpdates, this.addon.version,
- false, this.appVersion,
- this.platformVersion,
- ignoreMaxVersion,
- ignoreStrictCompat);
- }
-
- if (compatUpdate)
- this.callListener("onCompatibilityUpdateAvailable", this.addon.wrapper);
- else
- this.callListener("onNoCompatibilityUpdateAvailable", this.addon.wrapper);
-
- function sendUpdateAvailableMessages(aSelf, aInstall) {
- if (aInstall) {
- aSelf.callListener("onUpdateAvailable", aSelf.addon.wrapper,
- aInstall.wrapper);
- }
- else {
- aSelf.callListener("onNoUpdateAvailable", aSelf.addon.wrapper);
- }
- aSelf.callListener("onUpdateFinished", aSelf.addon.wrapper,
- AddonManager.UPDATE_STATUS_NO_ERROR);
- }
-
- let compatOverrides = AddonManager.strictCompatibility ?
- null :
- this.addon.compatibilityOverrides;
-
- let update = AUC.getNewestCompatibleUpdate(aUpdates,
- this.appVersion,
- this.platformVersion,
- ignoreMaxVersion,
- ignoreStrictCompat,
- compatOverrides);
-
- if (update && Services.vc.compare(this.addon.version, update.version) < 0
- && !this.addon._installLocation.locked) {
- for (let currentInstall of XPIProvider.installs) {
- // Skip installs that don't match the available update
- if (currentInstall.existingAddon != this.addon ||
- currentInstall.version != update.version)
- continue;
-
- // If the existing install has not yet started downloading then send an
- // available update notification. If it is already downloading then
- // don't send any available update notification
- if (currentInstall.state == AddonManager.STATE_AVAILABLE) {
- logger.debug("Found an existing AddonInstall for " + this.addon.id);
- sendUpdateAvailableMessages(this, currentInstall);
- }
- else
- sendUpdateAvailableMessages(this, null);
- return;
- }
-
- createUpdate(aInstall => {
- sendUpdateAvailableMessages(this, aInstall);
- }, this.addon, update);
- }
- else {
- sendUpdateAvailableMessages(this, null);
- }
- },
-
- /**
- * Called when AddonUpdateChecker fails the update check
- *
- * @param aError
- * An error status
- */
- onUpdateCheckError: function(aError) {
- XPIProvider.done(this.addon._updateCheck);
- this.addon._updateCheck = null;
- this.callListener("onNoCompatibilityUpdateAvailable", this.addon.wrapper);
- this.callListener("onNoUpdateAvailable", this.addon.wrapper);
- this.callListener("onUpdateFinished", this.addon.wrapper, aError);
- },
-
- /**
- * Called to cancel an in-progress update check
- */
- cancel: function() {
- let parser = this._parser;
- if (parser) {
- this._parser = null;
- // This will call back to onUpdateCheckError with a CANCELLED error
- parser.cancel();
- }
- }
-};
-
-/**
- * The AddonInternal is an internal only representation of add-ons. It may
- * have come from the database (see DBAddonInternal in XPIProviderUtils.jsm)
- * or an install manifest.
- */
-function AddonInternal() {
- this._hasResourceCache = new Map();
-
- XPCOMUtils.defineLazyGetter(this, "wrapper", () => {
- return new AddonWrapper(this);
- });
-}
-
-AddonInternal.prototype = {
- _selectedLocale: null,
- _hasResourceCache: null,
- active: false,
- visible: false,
- userDisabled: false,
- appDisabled: false,
- softDisabled: false,
- sourceURI: null,
- releaseNotesURI: null,
- foreignInstall: false,
- seen: true,
- skinnable: false,
-
- /**
- * @property {Array<string>} dependencies
- * An array of bootstrapped add-on IDs on which this add-on depends.
- * The add-on will remain appDisabled if any of the dependent
- * add-ons is not installed and enabled.
- */
- dependencies: Object.freeze([]),
- hasEmbeddedWebExtension: false,
-
- get selectedLocale() {
- if (this._selectedLocale)
- return this._selectedLocale;
- let locale = Locale.findClosestLocale(this.locales);
- this._selectedLocale = locale ? locale : this.defaultLocale;
- return this._selectedLocale;
- },
-
- get providesUpdatesSecurely() {
- return !!(this.updateKey || !this.updateURL ||
- this.updateURL.substring(0, 6) == "https:");
- },
-
- get isCorrectlySigned() {
- switch (this._installLocation.name) {
- case KEY_APP_SYSTEM_ADDONS:
- // System add-ons must be signed by the system key.
- return this.signedState == AddonManager.SIGNEDSTATE_SYSTEM
-
- case KEY_APP_SYSTEM_DEFAULTS:
- case KEY_APP_TEMPORARY:
- // Temporary and built-in system add-ons do not require signing.
- return true;
-
- case KEY_APP_SYSTEM_SHARE:
- case KEY_APP_SYSTEM_LOCAL:
- // On UNIX platforms except OSX, an additional location for system
- // add-ons exists in /usr/{lib,share}/mozilla/extensions. Add-ons
- // installed there do not require signing.
- if (Services.appinfo.OS != "Darwin")
- return true;
- break;
- }
-
- if (this.signedState === AddonManager.SIGNEDSTATE_NOT_REQUIRED)
- return true;
- return this.signedState > AddonManager.SIGNEDSTATE_MISSING;
- },
-
- get isCompatible() {
- return this.isCompatibleWith();
- },
-
- get disabled() {
- return (this.userDisabled || this.appDisabled || this.softDisabled);
- },
-
- get isPlatformCompatible() {
- if (this.targetPlatforms.length == 0)
- return true;
-
- let matchedOS = false;
-
- // If any targetPlatform matches the OS and contains an ABI then we will
- // only match a targetPlatform that contains both the current OS and ABI
- let needsABI = false;
-
- // Some platforms do not specify an ABI, test against null in that case.
- let abi = null;
- try {
- abi = Services.appinfo.XPCOMABI;
- }
- catch (e) { }
-
- // Something is causing errors in here
- try {
- for (let platform of this.targetPlatforms) {
- if (platform.os == Services.appinfo.OS) {
- if (platform.abi) {
- needsABI = true;
- if (platform.abi === abi)
- return true;
- }
- else {
- matchedOS = true;
- }
- }
- }
- } catch (e) {
- let message = "Problem with addon " + this.id + " targetPlatforms "
- + JSON.stringify(this.targetPlatforms);
- logger.error(message, e);
- AddonManagerPrivate.recordException("XPI", message, e);
- // don't trust this add-on
- return false;
- }
-
- return matchedOS && !needsABI;
- },
-
- isCompatibleWith: function(aAppVersion, aPlatformVersion) {
- let app = this.matchingTargetApplication;
- if (!app)
- return false;
-
- // set reasonable defaults for minVersion and maxVersion
- let minVersion = app.minVersion || "0";
- let maxVersion = app.maxVersion || "*";
-
- if (!aAppVersion)
- aAppVersion = Services.appinfo.version;
- if (!aPlatformVersion)
- aPlatformVersion = Services.appinfo.platformVersion;
-
- let version;
- if (app.id == Services.appinfo.ID)
- version = aAppVersion;
- else if (app.id == TOOLKIT_ID)
- version = aPlatformVersion
- else if (app.id == WEBEXTENSIONS_ID)
- version = WEBEXTENSIONS_VERSION
-
- // Only extensions and dictionaries can be compatible by default; themes
- // and language packs always use strict compatibility checking.
- if (this.type in COMPATIBLE_BY_DEFAULT_TYPES &&
- !AddonManager.strictCompatibility && !this.strictCompatibility &&
- !this.hasBinaryComponents) {
-
- // The repository can specify compatibility overrides.
- // Note: For now, only blacklisting is supported by overrides.
- if (this._repositoryAddon &&
- this._repositoryAddon.compatibilityOverrides) {
- let overrides = this._repositoryAddon.compatibilityOverrides;
- let override = AddonRepository.findMatchingCompatOverride(this.version,
- overrides);
- if (override && override.type == "incompatible")
- return false;
- }
-
- // Extremely old extensions should not be compatible by default.
- let minCompatVersion;
- if (app.id == Services.appinfo.ID)
- minCompatVersion = XPIProvider.minCompatibleAppVersion;
- else if (app.id == TOOLKIT_ID || app.id == WEBEXTENSIONS_ID)
- minCompatVersion = XPIProvider.minCompatiblePlatformVersion;
-
- if (minCompatVersion &&
- Services.vc.compare(minCompatVersion, maxVersion) > 0)
- return false;
-
- return Services.vc.compare(version, minVersion) >= 0;
- }
-
- return (Services.vc.compare(version, minVersion) >= 0) &&
- (Services.vc.compare(version, maxVersion) <= 0)
- },
-
- get matchingTargetApplication() {
- let app = null;
- for (let targetApp of this.targetApplications) {
- if (targetApp.id == Services.appinfo.ID)
- return targetApp;
- if (targetApp.id == TOOLKIT_ID || targetApp.id == WEBEXTENSIONS_ID)
- app = targetApp;
- }
- return app;
- },
-
- get blocklistState() {
- let staticItem = findMatchingStaticBlocklistItem(this);
- if (staticItem)
- return staticItem.level;
-
- return Blocklist.getAddonBlocklistState(this.wrapper);
- },
-
- get blocklistURL() {
- let staticItem = findMatchingStaticBlocklistItem(this);
- if (staticItem) {
- let url = Services.urlFormatter.formatURLPref("extensions.blocklist.itemURL");
- return url.replace(/%blockID%/g, staticItem.blockID);
- }
-
- return Blocklist.getAddonBlocklistURL(this.wrapper);
- },
-
- applyCompatibilityUpdate: function(aUpdate, aSyncCompatibility) {
- for (let targetApp of this.targetApplications) {
- for (let updateTarget of aUpdate.targetApplications) {
- if (targetApp.id == updateTarget.id && (aSyncCompatibility ||
- Services.vc.compare(targetApp.maxVersion, updateTarget.maxVersion) < 0)) {
- targetApp.minVersion = updateTarget.minVersion;
- targetApp.maxVersion = updateTarget.maxVersion;
- }
- }
- }
- if (aUpdate.multiprocessCompatible !== undefined)
- this.multiprocessCompatible = aUpdate.multiprocessCompatible;
- this.appDisabled = !isUsableAddon(this);
- },
-
- /**
- * getDataDirectory tries to execute the callback with two arguments:
- * 1) the path of the data directory within the profile,
- * 2) any exception generated from trying to build it.
- */
- getDataDirectory: function(callback) {
- let parentPath = OS.Path.join(OS.Constants.Path.profileDir, "extension-data");
- let dirPath = OS.Path.join(parentPath, this.id);
-
- Task.spawn(function*() {
- yield OS.File.makeDir(parentPath, {ignoreExisting: true});
- yield OS.File.makeDir(dirPath, {ignoreExisting: true});
- }).then(() => callback(dirPath, null),
- e => callback(dirPath, e));
- },
-
- /**
- * toJSON is called by JSON.stringify in order to create a filtered version
- * of this object to be serialized to a JSON file. A new object is returned
- * with copies of all non-private properties. Functions, getters and setters
- * are not copied.
- *
- * @param aKey
- * The key that this object is being serialized as in the JSON.
- * Unused here since this is always the main object serialized
- *
- * @return an object containing copies of the properties of this object
- * ignoring private properties, functions, getters and setters
- */
- toJSON: function(aKey) {
- let obj = {};
- for (let prop in this) {
- // Ignore the wrapper property
- if (prop == "wrapper")
- continue;
-
- // Ignore private properties
- if (prop.substring(0, 1) == "_")
- continue;
-
- // Ignore getters
- if (this.__lookupGetter__(prop))
- continue;
-
- // Ignore setters
- if (this.__lookupSetter__(prop))
- continue;
-
- // Ignore functions
- if (typeof this[prop] == "function")
- continue;
-
- obj[prop] = this[prop];
- }
-
- return obj;
- },
-
- /**
- * When an add-on install is pending its metadata will be cached in a file.
- * This method reads particular properties of that metadata that may be newer
- * than that in the install manifest, like compatibility information.
- *
- * @param aObj
- * A JS object containing the cached metadata
- */
- importMetadata: function(aObj) {
- for (let prop of PENDING_INSTALL_METADATA) {
- if (!(prop in aObj))
- continue;
-
- this[prop] = aObj[prop];
- }
-
- // Compatibility info may have changed so update appDisabled
- this.appDisabled = !isUsableAddon(this);
- },
-
- permissions: function() {
- let permissions = 0;
-
- // Add-ons that aren't installed cannot be modified in any way
- if (!(this.inDatabase))
- return permissions;
-
- if (!this.appDisabled) {
- if (this.userDisabled || this.softDisabled) {
- permissions |= AddonManager.PERM_CAN_ENABLE;
- }
- else if (this.type != "theme") {
- permissions |= AddonManager.PERM_CAN_DISABLE;
- }
- }
-
- // Add-ons that are in locked install locations, or are pending uninstall
- // cannot be upgraded or uninstalled
- if (!this._installLocation.locked && !this.pendingUninstall) {
- // Experiments cannot be upgraded.
- // System add-on upgrades are triggered through a different mechanism (see updateSystemAddons())
- let isSystem = (this._installLocation.name == KEY_APP_SYSTEM_DEFAULTS ||
- this._installLocation.name == KEY_APP_SYSTEM_ADDONS);
- // Add-ons that are installed by a file link cannot be upgraded.
- if (this.type != "experiment" &&
- !this._installLocation.isLinkedAddon(this.id) && !isSystem) {
- permissions |= AddonManager.PERM_CAN_UPGRADE;
- }
-
- permissions |= AddonManager.PERM_CAN_UNINSTALL;
- }
-
- return permissions;
- },
-};
-
-/**
- * The AddonWrapper wraps an Addon to provide the data visible to consumers of
- * the public API.
- */
-function AddonWrapper(aAddon) {
- wrapperMap.set(this, aAddon);
-}
-
-AddonWrapper.prototype = {
- get __AddonInternal__() {
- return AppConstants.DEBUG ? addonFor(this) : undefined;
- },
-
- get seen() {
- return addonFor(this).seen;
- },
-
- get hasEmbeddedWebExtension() {
- return addonFor(this).hasEmbeddedWebExtension;
- },
-
- markAsSeen: function() {
- addonFor(this).seen = true;
- XPIDatabase.saveChanges();
- },
-
- get type() {
- return getExternalType(addonFor(this).type);
- },
-
- get isWebExtension() {
- return addonFor(this).type == "webextension";
- },
-
- get temporarilyInstalled() {
- return addonFor(this)._installLocation == TemporaryInstallLocation;
- },
-
- get aboutURL() {
- return this.isActive ? addonFor(this)["aboutURL"] : null;
- },
-
- get optionsURL() {
- if (!this.isActive) {
- return null;
- }
-
- let addon = addonFor(this);
- if (addon.optionsURL) {
- if (this.isWebExtension || this.hasEmbeddedWebExtension) {
- // The internal object's optionsURL property comes from the addons
- // DB and should be a relative URL. However, extensions with
- // options pages installed before bug 1293721 was fixed got absolute
- // URLs in the addons db. This code handles both cases.
- let base = ExtensionManagement.getURLForExtension(addon.id);
- if (!base) {
- return null;
- }
- return new URL(addon.optionsURL, base).href;
- }
- return addon.optionsURL;
- }
-
- if (this.hasResource("options.xul"))
- return this.getResourceURI("options.xul").spec;
-
- return null;
- },
-
- get optionsType() {
- if (!this.isActive)
- return null;
-
- let addon = addonFor(this);
- let hasOptionsXUL = this.hasResource("options.xul");
- let hasOptionsURL = !!this.optionsURL;
-
- if (addon.optionsType) {
- switch (parseInt(addon.optionsType, 10)) {
- case AddonManager.OPTIONS_TYPE_DIALOG:
- case AddonManager.OPTIONS_TYPE_TAB:
- return hasOptionsURL ? addon.optionsType : null;
- case AddonManager.OPTIONS_TYPE_INLINE:
- case AddonManager.OPTIONS_TYPE_INLINE_INFO:
- case AddonManager.OPTIONS_TYPE_INLINE_BROWSER:
- return (hasOptionsXUL || hasOptionsURL) ? addon.optionsType : null;
- }
- return null;
- }
-
- if (hasOptionsXUL)
- return AddonManager.OPTIONS_TYPE_INLINE;
-
- if (hasOptionsURL)
- return AddonManager.OPTIONS_TYPE_DIALOG;
-
- return null;
- },
-
- get iconURL() {
- return AddonManager.getPreferredIconURL(this, 48);
- },
-
- get icon64URL() {
- return AddonManager.getPreferredIconURL(this, 64);
- },
-
- get icons() {
- let addon = addonFor(this);
- let icons = {};
-
- if (addon._repositoryAddon) {
- for (let size in addon._repositoryAddon.icons) {
- icons[size] = addon._repositoryAddon.icons[size];
- }
- }
-
- if (addon.icons) {
- for (let size in addon.icons) {
- icons[size] = this.getResourceURI(addon.icons[size]).spec;
- }
- } else {
- // legacy add-on that did not update its icon data yet
- if (this.hasResource("icon.png")) {
- icons[32] = icons[48] = this.getResourceURI("icon.png").spec;
- }
- if (this.hasResource("icon64.png")) {
- icons[64] = this.getResourceURI("icon64.png").spec;
- }
- }
-
- if (this.isActive && addon.iconURL) {
- icons[32] = addon.iconURL;
- icons[48] = addon.iconURL;
- }
-
- if (this.isActive && addon.icon64URL) {
- icons[64] = addon.icon64URL;
- }
-
- Object.freeze(icons);
- return icons;
- },
-
- get screenshots() {
- let addon = addonFor(this);
- let repositoryAddon = addon._repositoryAddon;
- if (repositoryAddon && ("screenshots" in repositoryAddon)) {
- let repositoryScreenshots = repositoryAddon.screenshots;
- if (repositoryScreenshots && repositoryScreenshots.length > 0)
- return repositoryScreenshots;
- }
-
- if (addon.type == "theme" && this.hasResource("preview.png")) {
- let url = this.getResourceURI("preview.png").spec;
- return [new AddonManagerPrivate.AddonScreenshot(url)];
- }
-
- return null;
- },
-
- get applyBackgroundUpdates() {
- return addonFor(this).applyBackgroundUpdates;
- },
- set applyBackgroundUpdates(val) {
- let addon = addonFor(this);
- if (this.type == "experiment") {
- logger.warn("Setting applyBackgroundUpdates on an experiment is not supported.");
- return addon.applyBackgroundUpdates;
- }
-
- if (val != AddonManager.AUTOUPDATE_DEFAULT &&
- val != AddonManager.AUTOUPDATE_DISABLE &&
- val != AddonManager.AUTOUPDATE_ENABLE) {
- val = val ? AddonManager.AUTOUPDATE_DEFAULT :
- AddonManager.AUTOUPDATE_DISABLE;
- }
-
- if (val == addon.applyBackgroundUpdates)
- return val;
-
- XPIDatabase.setAddonProperties(addon, {
- applyBackgroundUpdates: val
- });
- AddonManagerPrivate.callAddonListeners("onPropertyChanged", this, ["applyBackgroundUpdates"]);
-
- return val;
- },
-
- set syncGUID(val) {
- let addon = addonFor(this);
- if (addon.syncGUID == val)
- return val;
-
- if (addon.inDatabase)
- XPIDatabase.setAddonSyncGUID(addon, val);
-
- addon.syncGUID = val;
-
- return val;
- },
-
- get install() {
- let addon = addonFor(this);
- if (!("_install" in addon) || !addon._install)
- return null;
- return addon._install.wrapper;
- },
-
- get pendingUpgrade() {
- let addon = addonFor(this);
- return addon.pendingUpgrade ? addon.pendingUpgrade.wrapper : null;
- },
-
- get scope() {
- let addon = addonFor(this);
- if (addon._installLocation)
- return addon._installLocation.scope;
-
- return AddonManager.SCOPE_PROFILE;
- },
-
- get pendingOperations() {
- let addon = addonFor(this);
- let pending = 0;
- if (!(addon.inDatabase)) {
- // Add-on is pending install if there is no associated install (shouldn't
- // happen here) or if the install is in the process of or has successfully
- // completed the install. If an add-on is pending install then we ignore
- // any other pending operations.
- if (!addon._install || addon._install.state == AddonManager.STATE_INSTALLING ||
- addon._install.state == AddonManager.STATE_INSTALLED)
- return AddonManager.PENDING_INSTALL;
- }
- else if (addon.pendingUninstall) {
- // If an add-on is pending uninstall then we ignore any other pending
- // operations
- return AddonManager.PENDING_UNINSTALL;
- }
-
- if (addon.active && addon.disabled)
- pending |= AddonManager.PENDING_DISABLE;
- else if (!addon.active && !addon.disabled)
- pending |= AddonManager.PENDING_ENABLE;
-
- if (addon.pendingUpgrade)
- pending |= AddonManager.PENDING_UPGRADE;
-
- return pending;
- },
-
- get operationsRequiringRestart() {
- let addon = addonFor(this);
- let ops = 0;
- if (XPIProvider.installRequiresRestart(addon))
- ops |= AddonManager.OP_NEEDS_RESTART_INSTALL;
- if (XPIProvider.uninstallRequiresRestart(addon))
- ops |= AddonManager.OP_NEEDS_RESTART_UNINSTALL;
- if (XPIProvider.enableRequiresRestart(addon))
- ops |= AddonManager.OP_NEEDS_RESTART_ENABLE;
- if (XPIProvider.disableRequiresRestart(addon))
- ops |= AddonManager.OP_NEEDS_RESTART_DISABLE;
-
- return ops;
- },
-
- get isDebuggable() {
- return this.isActive && addonFor(this).bootstrap;
- },
-
- get permissions() {
- return addonFor(this).permissions();
- },
-
- get isActive() {
- let addon = addonFor(this);
- if (!addon.active)
- return false;
- if (!Services.appinfo.inSafeMode)
- return true;
- return addon.bootstrap && canRunInSafeMode(addon);
- },
-
- get userDisabled() {
- let addon = addonFor(this);
- return addon.softDisabled || addon.userDisabled;
- },
- set userDisabled(val) {
- let addon = addonFor(this);
- if (val == this.userDisabled) {
- return val;
- }
-
- if (addon.inDatabase) {
- if (addon.type == "theme" && val) {
- if (addon.internalName == XPIProvider.defaultSkin)
- throw new Error("Cannot disable the default theme");
- XPIProvider.enableDefaultTheme();
- }
- else {
- // hidden and system add-ons should not be user disasbled,
- // as there is no UI to re-enable them.
- if (this.hidden) {
- throw new Error(`Cannot disable hidden add-on ${addon.id}`);
- }
- XPIProvider.updateAddonDisabledState(addon, val);
- }
- }
- else {
- addon.userDisabled = val;
- // When enabling remove the softDisabled flag
- if (!val)
- addon.softDisabled = false;
- }
-
- return val;
- },
-
- set softDisabled(val) {
- let addon = addonFor(this);
- if (val == addon.softDisabled)
- return val;
-
- if (addon.inDatabase) {
- // When softDisabling a theme just enable the active theme
- if (addon.type == "theme" && val && !addon.userDisabled) {
- if (addon.internalName == XPIProvider.defaultSkin)
- throw new Error("Cannot disable the default theme");
- XPIProvider.enableDefaultTheme();
- }
- else {
- XPIProvider.updateAddonDisabledState(addon, undefined, val);
- }
- }
- else if (!addon.userDisabled) {
- // Only set softDisabled if not already disabled
- addon.softDisabled = val;
- }
-
- return val;
- },
-
- get hidden() {
- let addon = addonFor(this);
- if (addon._installLocation.name == KEY_APP_TEMPORARY)
- return false;
-
- return (addon._installLocation.name == KEY_APP_SYSTEM_DEFAULTS ||
- addon._installLocation.name == KEY_APP_SYSTEM_ADDONS);
- },
-
- get isSystem() {
- let addon = addonFor(this);
- return (addon._installLocation.name == KEY_APP_SYSTEM_DEFAULTS ||
- addon._installLocation.name == KEY_APP_SYSTEM_ADDONS);
- },
-
- // Returns true if Firefox Sync should sync this addon. Only non-hotfixes
- // directly in the profile are considered syncable.
- get isSyncable() {
- let addon = addonFor(this);
- let hotfixID = Preferences.get(PREF_EM_HOTFIX_ID, undefined);
- if (hotfixID && hotfixID == addon.id) {
- return false;
- }
- return (addon._installLocation.name == KEY_APP_PROFILE);
- },
-
- isCompatibleWith: function(aAppVersion, aPlatformVersion) {
- return addonFor(this).isCompatibleWith(aAppVersion, aPlatformVersion);
- },
-
- uninstall: function(alwaysAllowUndo) {
- let addon = addonFor(this);
- XPIProvider.uninstallAddon(addon, alwaysAllowUndo);
- },
-
- cancelUninstall: function() {
- let addon = addonFor(this);
- XPIProvider.cancelUninstallAddon(addon);
- },
-
- findUpdates: function(aListener, aReason, aAppVersion, aPlatformVersion) {
- // Short-circuit updates for experiments because updates are handled
- // through the Experiments Manager.
- if (this.type == "experiment") {
- AddonManagerPrivate.callNoUpdateListeners(this, aListener, aReason,
- aAppVersion, aPlatformVersion);
- return;
- }
-
- new UpdateChecker(addonFor(this), aListener, aReason, aAppVersion, aPlatformVersion);
- },
-
- // Returns true if there was an update in progress, false if there was no update to cancel
- cancelUpdate: function() {
- let addon = addonFor(this);
- if (addon._updateCheck) {
- addon._updateCheck.cancel();
- return true;
- }
- return false;
- },
-
- hasResource: function(aPath) {
- let addon = addonFor(this);
- if (addon._hasResourceCache.has(aPath))
- return addon._hasResourceCache.get(aPath);
-
- let bundle = addon._sourceBundle.clone();
-
- // Bundle may not exist any more if the addon has just been uninstalled,
- // but explicitly first checking .exists() results in unneeded file I/O.
- try {
- var isDir = bundle.isDirectory();
- } catch (e) {
- addon._hasResourceCache.set(aPath, false);
- return false;
- }
-
- if (isDir) {
- if (aPath)
- aPath.split("/").forEach(part => bundle.append(part));
- let result = bundle.exists();
- addon._hasResourceCache.set(aPath, result);
- return result;
- }
-
- let zipReader = Cc["@mozilla.org/libjar/zip-reader;1"].
- createInstance(Ci.nsIZipReader);
- try {
- zipReader.open(bundle);
- let result = zipReader.hasEntry(aPath);
- addon._hasResourceCache.set(aPath, result);
- return result;
- }
- catch (e) {
- addon._hasResourceCache.set(aPath, false);
- return false;
- }
- finally {
- zipReader.close();
- }
- },
-
- /**
- * Reloads the add-on.
- *
- * For temporarily installed add-ons, this uninstalls and re-installs the
- * add-on. Otherwise, the addon is disabled and then re-enabled, and the cache
- * is flushed.
- *
- * @return Promise
- */
- reload: function() {
- return new Promise((resolve) => {
- const addon = addonFor(this);
-
- logger.debug(`reloading add-on ${addon.id}`);
-
- if (!this.temporarilyInstalled) {
- let addonFile = addon.getResourceURI;
- XPIProvider.updateAddonDisabledState(addon, true);
- Services.obs.notifyObservers(addonFile, "flush-cache-entry", null);
- XPIProvider.updateAddonDisabledState(addon, false)
- resolve();
- } else {
- // This function supports re-installing an existing add-on.
- resolve(AddonManager.installTemporaryAddon(addon._sourceBundle));
- }
- });
- },
-
- /**
- * Returns a URI to the selected resource or to the add-on bundle if aPath
- * is null. URIs to the bundle will always be file: URIs. URIs to resources
- * will be file: URIs if the add-on is unpacked or jar: URIs if the add-on is
- * still an XPI file.
- *
- * @param aPath
- * The path in the add-on to get the URI for or null to get a URI to
- * the file or directory the add-on is installed as.
- * @return an nsIURI
- */
- getResourceURI: function(aPath) {
- let addon = addonFor(this);
- if (!aPath)
- return NetUtil.newURI(addon._sourceBundle);
-
- return getURIForResourceInFile(addon._sourceBundle, aPath);
- }
-};
-
-/**
- * The PrivateWrapper is used to expose certain functionality only when being
- * called with the add-on instanceID, disallowing other add-ons to access it.
- */
-function PrivateWrapper(aAddon) {
- AddonWrapper.call(this, aAddon);
-}
-
-PrivateWrapper.prototype = Object.create(AddonWrapper.prototype);
-Object.assign(PrivateWrapper.prototype, {
- addonId() {
- return this.id;
- },
-
- /**
- * Retrieves the preferred global context to be used from the
- * add-on debugging window.
- *
- * @returns global
- * The object set as global context. Must be a window object.
- */
- getDebugGlobal(global) {
- let activeAddon = XPIProvider.activeAddons.get(this.id);
- if (activeAddon) {
- return activeAddon.debugGlobal;
- }
-
- return null;
- },
-
- /**
- * Defines a global context to be used in the console
- * of the add-on debugging window.
- *
- * @param global
- * The object to set as global context. Must be a window object.
- */
- setDebugGlobal(global) {
- if (!global) {
- // If the new global is null, notify the listeners regardless
- // from the current state of the addon.
- // NOTE: this happen after the addon has been disabled and
- // the global will never be set to null otherwise.
- AddonManagerPrivate.callAddonListeners("onPropertyChanged",
- addonFor(this),
- ["debugGlobal"]);
- } else {
- let activeAddon = XPIProvider.activeAddons.get(this.id);
- if (activeAddon) {
- let globalChanged = activeAddon.debugGlobal != global;
- activeAddon.debugGlobal = global;
-
- if (globalChanged) {
- AddonManagerPrivate.callAddonListeners("onPropertyChanged",
- addonFor(this),
- ["debugGlobal"]);
- }
- }
- }
- }
-});
-
-function chooseValue(aAddon, aObj, aProp) {
- let repositoryAddon = aAddon._repositoryAddon;
- let objValue = aObj[aProp];
-
- if (repositoryAddon && (aProp in repositoryAddon) &&
- (objValue === undefined || objValue === null)) {
- return [repositoryAddon[aProp], true];
- }
-
- return [objValue, false];
-}
-
-function defineAddonWrapperProperty(name, getter) {
- Object.defineProperty(AddonWrapper.prototype, name, {
- get: getter,
- enumerable: true,
- });
-}
-
-["id", "syncGUID", "version", "isCompatible", "isPlatformCompatible",
- "providesUpdatesSecurely", "blocklistState", "blocklistURL", "appDisabled",
- "softDisabled", "skinnable", "size", "foreignInstall", "hasBinaryComponents",
- "strictCompatibility", "compatibilityOverrides", "updateURL", "dependencies",
- "getDataDirectory", "multiprocessCompatible", "signedState", "mpcOptedOut",
- "isCorrectlySigned"].forEach(function(aProp) {
- defineAddonWrapperProperty(aProp, function() {
- let addon = addonFor(this);
- return (aProp in addon) ? addon[aProp] : undefined;
- });
-});
-
-["fullDescription", "developerComments", "eula", "supportURL",
- "contributionURL", "contributionAmount", "averageRating", "reviewCount",
- "reviewURL", "totalDownloads", "weeklyDownloads", "dailyUsers",
- "repositoryStatus"].forEach(function(aProp) {
- defineAddonWrapperProperty(aProp, function() {
- let addon = addonFor(this);
- if (addon._repositoryAddon)
- return addon._repositoryAddon[aProp];
-
- return null;
- });
-});
-
-["installDate", "updateDate"].forEach(function(aProp) {
- defineAddonWrapperProperty(aProp, function() {
- return new Date(addonFor(this)[aProp]);
- });
-});
-
-["sourceURI", "releaseNotesURI"].forEach(function(aProp) {
- defineAddonWrapperProperty(aProp, function() {
- let addon = addonFor(this);
-
- // Temporary Installed Addons do not have a "sourceURI",
- // But we can use the "_sourceBundle" as an alternative,
- // which points to the path of the addon xpi installed
- // or its source dir (if it has been installed from a
- // directory).
- if (aProp == "sourceURI" && this.temporarilyInstalled) {
- return Services.io.newFileURI(addon._sourceBundle);
- }
-
- let [target, fromRepo] = chooseValue(addon, addon, aProp);
- if (!target)
- return null;
- if (fromRepo)
- return target;
- return NetUtil.newURI(target);
- });
-});
-
-PROP_LOCALE_SINGLE.forEach(function(aProp) {
- defineAddonWrapperProperty(aProp, function() {
- let addon = addonFor(this);
- // Override XPI creator if repository creator is defined
- if (aProp == "creator" &&
- addon._repositoryAddon && addon._repositoryAddon.creator) {
- return addon._repositoryAddon.creator;
- }
-
- let result = null;
-
- if (addon.active) {
- try {
- let pref = PREF_EM_EXTENSION_FORMAT + addon.id + "." + aProp;
- let value = Preferences.get(pref, null, Ci.nsIPrefLocalizedString);
- if (value)
- result = value;
- }
- catch (e) {
- }
- }
-
- let rest;
- if (result == null)
- [result, ...rest] = chooseValue(addon, addon.selectedLocale, aProp);
-
- if (aProp == "creator")
- return result ? new AddonManagerPrivate.AddonAuthor(result) : null;
-
- if (aProp == "name")
- return result ? result : addon.defaultLocale.name;
-
- return result;
- });
-});
-
-PROP_LOCALE_MULTI.forEach(function(aProp) {
- defineAddonWrapperProperty(aProp, function() {
- let addon = addonFor(this);
- let results = null;
- let usedRepository = false;
-
- if (addon.active) {
- let pref = PREF_EM_EXTENSION_FORMAT + addon.id + "." +
- aProp.substring(0, aProp.length - 1);
- let list = Services.prefs.getChildList(pref, {});
- if (list.length > 0) {
- list.sort();
- results = [];
- for (let childPref of list) {
- let value = Preferences.get(childPref, null, Ci.nsIPrefLocalizedString);
- if (value)
- results.push(value);
- }
- }
- }
-
- if (results == null)
- [results, usedRepository] = chooseValue(addon, addon.selectedLocale, aProp);
-
- if (results && !usedRepository) {
- results = results.map(function(aResult) {
- return new AddonManagerPrivate.AddonAuthor(aResult);
- });
- }
-
- return results;
- });
-});
-
-/**
- * An object which identifies a directory install location for add-ons. The
- * location consists of a directory which contains the add-ons installed in the
- * location.
- *
- * Each add-on installed in the location is either a directory containing the
- * add-on's files or a text file containing an absolute path to the directory
- * containing the add-ons files. The directory or text file must have the same
- * name as the add-on's ID.
- *
- * @param aName
- * The string identifier for the install location
- * @param aDirectory
- * The nsIFile directory for the install location
- * @param aScope
- * The scope of add-ons installed in this location
- */
-function DirectoryInstallLocation(aName, aDirectory, aScope) {
- this._name = aName;
- this.locked = true;
- this._directory = aDirectory;
- this._scope = aScope
- this._IDToFileMap = {};
- this._linkedAddons = [];
-
- if (!aDirectory || !aDirectory.exists())
- return;
- if (!aDirectory.isDirectory())
- throw new Error("Location must be a directory.");
-
- this._readAddons();
-}
-
-DirectoryInstallLocation.prototype = {
- _name : "",
- _directory : null,
- _IDToFileMap : null, // mapping from add-on ID to nsIFile
-
- /**
- * Reads a directory linked to in a file.
- *
- * @param file
- * The file containing the directory path
- * @return An nsIFile object representing the linked directory.
- */
- _readDirectoryFromFile: function(aFile) {
- let linkedDirectory;
- if (aFile.isSymlink()) {
- linkedDirectory = aFile.clone();
- try {
- linkedDirectory.normalize();
- } catch (e) {
- logger.warn("Symbolic link " + aFile.path + " points to a path" +
- " which does not exist");
- return null;
- }
- }
- else {
- let fis = Cc["@mozilla.org/network/file-input-stream;1"].
- createInstance(Ci.nsIFileInputStream);
- fis.init(aFile, -1, -1, false);
- let line = { value: "" };
- if (fis instanceof Ci.nsILineInputStream)
- fis.readLine(line);
- fis.close();
- if (line.value) {
- linkedDirectory = Cc["@mozilla.org/file/local;1"].
- createInstance(Ci.nsIFile);
-
- try {
- linkedDirectory.initWithPath(line.value);
- }
- catch (e) {
- linkedDirectory.setRelativeDescriptor(aFile.parent, line.value);
- }
- }
- }
-
- if (linkedDirectory) {
- if (!linkedDirectory.exists()) {
- logger.warn("File pointer " + aFile.path + " points to " + linkedDirectory.path +
- " which does not exist");
- return null;
- }
-
- if (!linkedDirectory.isDirectory()) {
- logger.warn("File pointer " + aFile.path + " points to " + linkedDirectory.path +
- " which is not a directory");
- return null;
- }
-
- return linkedDirectory;
- }
-
- logger.warn("File pointer " + aFile.path + " does not contain a path");
- return null;
- },
-
- /**
- * Finds all the add-ons installed in this location.
- */
- _readAddons: function() {
- // Use a snapshot of the directory contents to avoid possible issues with
- // iterating over a directory while removing files from it (the YAFFS2
- // embedded filesystem has this issue, see bug 772238).
- let entries = getDirectoryEntries(this._directory);
- for (let entry of entries) {
- let id = entry.leafName;
-
- if (id == DIR_STAGE || id == DIR_TRASH)
- continue;
-
- let directLoad = false;
- if (entry.isFile() &&
- id.substring(id.length - 4).toLowerCase() == ".xpi") {
- directLoad = true;
- id = id.substring(0, id.length - 4);
- }
-
- if (!gIDTest.test(id)) {
- logger.debug("Ignoring file entry whose name is not a valid add-on ID: " +
- entry.path);
- continue;
- }
-
- if (!directLoad && (entry.isFile() || entry.isSymlink())) {
- let newEntry = this._readDirectoryFromFile(entry);
- if (!newEntry) {
- logger.debug("Deleting stale pointer file " + entry.path);
- try {
- entry.remove(true);
- }
- catch (e) {
- logger.warn("Failed to remove stale pointer file " + entry.path, e);
- // Failing to remove the stale pointer file is ignorable
- }
- continue;
- }
-
- entry = newEntry;
- this._linkedAddons.push(id);
- }
-
- this._IDToFileMap[id] = entry;
- XPIProvider._addURIMapping(id, entry);
- }
- },
-
- /**
- * Gets the name of this install location.
- */
- get name() {
- return this._name;
- },
-
- /**
- * Gets the scope of this install location.
- */
- get scope() {
- return this._scope;
- },
-
- /**
- * Gets an array of nsIFiles for add-ons installed in this location.
- */
- getAddonLocations: function() {
- let locations = new Map();
- for (let id in this._IDToFileMap) {
- locations.set(id, this._IDToFileMap[id].clone());
- }
- return locations;
- },
-
- /**
- * Gets the directory that the add-on with the given ID is installed in.
- *
- * @param aId
- * The ID of the add-on
- * @return The nsIFile
- * @throws if the ID does not match any of the add-ons installed
- */
- getLocationForID: function(aId) {
- if (aId in this._IDToFileMap)
- return this._IDToFileMap[aId].clone();
- throw new Error("Unknown add-on ID " + aId);
- },
-
- /**
- * Returns true if the given addon was installed in this location by a text
- * file pointing to its real path.
- *
- * @param aId
- * The ID of the addon
- */
- isLinkedAddon: function(aId) {
- return this._linkedAddons.indexOf(aId) != -1;
- }
-};
-
-/**
- * An extension of DirectoryInstallLocation which adds methods to installing
- * and removing add-ons from the directory at runtime.
- *
- * @param aName
- * The string identifier for the install location
- * @param aDirectory
- * The nsIFile directory for the install location
- * @param aScope
- * The scope of add-ons installed in this location
- */
-function MutableDirectoryInstallLocation(aName, aDirectory, aScope) {
- DirectoryInstallLocation.call(this, aName, aDirectory, aScope);
- this.locked = false;
- this._stagingDirLock = 0;
-}
-
-MutableDirectoryInstallLocation.prototype = Object.create(DirectoryInstallLocation.prototype);
-Object.assign(MutableDirectoryInstallLocation.prototype, {
- /**
- * Gets the staging directory to put add-ons that are pending install and
- * uninstall into.
- *
- * @return an nsIFile
- */
- getStagingDir: function() {
- let dir = this._directory.clone();
- dir.append(DIR_STAGE);
- return dir;
- },
-
- requestStagingDir: function() {
- this._stagingDirLock++;
-
- if (this._stagingDirPromise)
- return this._stagingDirPromise;
-
- OS.File.makeDir(this._directory.path);
- let stagepath = OS.Path.join(this._directory.path, DIR_STAGE);
- return this._stagingDirPromise = OS.File.makeDir(stagepath).then(null, (e) => {
- if (e instanceof OS.File.Error && e.becauseExists)
- return;
- logger.error("Failed to create staging directory", e);
- throw e;
- });
- },
-
- releaseStagingDir: function() {
- this._stagingDirLock--;
-
- if (this._stagingDirLock == 0) {
- this._stagingDirPromise = null;
- this.cleanStagingDir();
- }
-
- return Promise.resolve();
- },
-
- /**
- * Removes the specified files or directories in the staging directory and
- * then if the staging directory is empty attempts to remove it.
- *
- * @param aLeafNames
- * An array of file or directory to remove from the directory, the
- * array may be empty
- */
- cleanStagingDir: function(aLeafNames = []) {
- let dir = this.getStagingDir();
-
- for (let name of aLeafNames) {
- let file = dir.clone();
- file.append(name);
- recursiveRemove(file);
- }
-
- if (this._stagingDirLock > 0)
- return;
-
- let dirEntries = dir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
- try {
- if (dirEntries.nextFile)
- return;
- }
- finally {
- dirEntries.close();
- }
-
- try {
- setFilePermissions(dir, FileUtils.PERMS_DIRECTORY);
- dir.remove(false);
- }
- catch (e) {
- logger.warn("Failed to remove staging dir", e);
- // Failing to remove the staging directory is ignorable
- }
- },
-
- /**
- * Returns a directory that is normally on the same filesystem as the rest of
- * the install location and can be used for temporarily storing files during
- * safe move operations. Calling this method will delete the existing trash
- * directory and its contents.
- *
- * @return an nsIFile
- */
- getTrashDir: function() {
- let trashDir = this._directory.clone();
- trashDir.append(DIR_TRASH);
- let trashDirExists = trashDir.exists();
- try {
- if (trashDirExists)
- recursiveRemove(trashDir);
- trashDirExists = false;
- } catch (e) {
- logger.warn("Failed to remove trash directory", e);
- }
- if (!trashDirExists)
- trashDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
-
- return trashDir;
- },
-
- /**
- * Installs an add-on into the install location.
- *
- * @param id
- * The ID of the add-on to install
- * @param source
- * The source nsIFile to install from
- * @param existingAddonID
- * The ID of an existing add-on to uninstall at the same time
- * @param action
- * What to we do with the given source file:
- * "move"
- * Default action, the source files will be moved to the new
- * location,
- * "copy"
- * The source files will be copied,
- * "proxy"
- * A "proxy file" is going to refer to the source file path
- * @return an nsIFile indicating where the add-on was installed to
- */
- installAddon: function({ id, source, existingAddonID, action = "move" }) {
- let trashDir = this.getTrashDir();
-
- let transaction = new SafeInstallOperation();
-
- let moveOldAddon = aId => {
- let file = this._directory.clone();
- file.append(aId);
-
- if (file.exists())
- transaction.moveUnder(file, trashDir);
-
- file = this._directory.clone();
- file.append(aId + ".xpi");
- if (file.exists()) {
- flushJarCache(file);
- transaction.moveUnder(file, trashDir);
- }
- }
-
- // If any of these operations fails the finally block will clean up the
- // temporary directory
- try {
- moveOldAddon(id);
- if (existingAddonID && existingAddonID != id) {
- moveOldAddon(existingAddonID);
-
- {
- // Move the data directories.
- /* XXX ajvincent We can't use OS.File: installAddon isn't compatible
- * with Promises, nor is SafeInstallOperation. Bug 945540 has been filed
- * for porting to OS.File.
- */
- let oldDataDir = FileUtils.getDir(
- KEY_PROFILEDIR, ["extension-data", existingAddonID], false, true
- );
-
- if (oldDataDir.exists()) {
- let newDataDir = FileUtils.getDir(
- KEY_PROFILEDIR, ["extension-data", id], false, true
- );
- if (newDataDir.exists()) {
- let trashData = trashDir.clone();
- trashData.append("data-directory");
- transaction.moveUnder(newDataDir, trashData);
- }
-
- transaction.moveTo(oldDataDir, newDataDir);
- }
- }
- }
-
- if (action == "copy") {
- transaction.copy(source, this._directory);
- }
- else if (action == "move") {
- if (source.isFile())
- flushJarCache(source);
-
- transaction.moveUnder(source, this._directory);
- }
- // Do nothing for the proxy file as we sideload an addon permanently
- }
- finally {
- // It isn't ideal if this cleanup fails but it isn't worth rolling back
- // the install because of it.
- try {
- recursiveRemove(trashDir);
- }
- catch (e) {
- logger.warn("Failed to remove trash directory when installing " + id, e);
- }
- }
-
- let newFile = this._directory.clone();
-
- if (action == "proxy") {
- // When permanently installing sideloaded addon, we just put a proxy file
- // refering to the addon sources
- newFile.append(id);
-
- writeStringToFile(newFile, source.path);
- } else {
- newFile.append(source.leafName);
- }
-
- try {
- newFile.lastModifiedTime = Date.now();
- } catch (e) {
- logger.warn("failed to set lastModifiedTime on " + newFile.path, e);
- }
- this._IDToFileMap[id] = newFile;
- XPIProvider._addURIMapping(id, newFile);
-
- if (existingAddonID && existingAddonID != id &&
- existingAddonID in this._IDToFileMap) {
- delete this._IDToFileMap[existingAddonID];
- }
-
- return newFile;
- },
-
- /**
- * Uninstalls an add-on from this location.
- *
- * @param aId
- * The ID of the add-on to uninstall
- * @throws if the ID does not match any of the add-ons installed
- */
- uninstallAddon: function(aId) {
- let file = this._IDToFileMap[aId];
- if (!file) {
- logger.warn("Attempted to remove " + aId + " from " +
- this._name + " but it was already gone");
- return;
- }
-
- file = this._directory.clone();
- file.append(aId);
- if (!file.exists())
- file.leafName += ".xpi";
-
- if (!file.exists()) {
- logger.warn("Attempted to remove " + aId + " from " +
- this._name + " but it was already gone");
-
- delete this._IDToFileMap[aId];
- return;
- }
-
- let trashDir = this.getTrashDir();
-
- if (file.leafName != aId) {
- logger.debug("uninstallAddon: flushing jar cache " + file.path + " for addon " + aId);
- flushJarCache(file);
- }
-
- let transaction = new SafeInstallOperation();
-
- try {
- transaction.moveUnder(file, trashDir);
- }
- finally {
- // It isn't ideal if this cleanup fails, but it is probably better than
- // rolling back the uninstall at this point
- try {
- recursiveRemove(trashDir);
- }
- catch (e) {
- logger.warn("Failed to remove trash directory when uninstalling " + aId, e);
- }
- }
-
- delete this._IDToFileMap[aId];
- },
-});
-
-/**
- * An object which identifies a directory install location for system add-ons
- * upgrades.
- *
- * The location consists of a directory which contains the add-ons installed.
- *
- * @param aName
- * The string identifier for the install location
- * @param aDirectory
- * The nsIFile directory for the install location
- * @param aScope
- * The scope of add-ons installed in this location
- * @param aResetSet
- * True to throw away the current add-on set
- */
-function SystemAddonInstallLocation(aName, aDirectory, aScope, aResetSet) {
- this._baseDir = aDirectory;
- this._nextDir = null;
-
- this._stagingDirLock = 0;
-
- if (aResetSet)
- this.resetAddonSet();
-
- this._addonSet = this._loadAddonSet();
-
- this._directory = null;
- if (this._addonSet.directory) {
- this._directory = aDirectory.clone();
- this._directory.append(this._addonSet.directory);
- logger.info("SystemAddonInstallLocation scanning directory " + this._directory.path);
- }
- else {
- logger.info("SystemAddonInstallLocation directory is missing");
- }
-
- DirectoryInstallLocation.call(this, aName, this._directory, aScope);
- this.locked = false;
-}
-
-SystemAddonInstallLocation.prototype = Object.create(DirectoryInstallLocation.prototype);
-Object.assign(SystemAddonInstallLocation.prototype, {
- /**
- * Removes the specified files or directories in the staging directory and
- * then if the staging directory is empty attempts to remove it.
- *
- * @param aLeafNames
- * An array of file or directory to remove from the directory, the
- * array may be empty
- */
- cleanStagingDir: function(aLeafNames = []) {
- let dir = this.getStagingDir();
-
- for (let name of aLeafNames) {
- let file = dir.clone();
- file.append(name);
- recursiveRemove(file);
- }
-
- if (this._stagingDirLock > 0)
- return;
-
- let dirEntries = dir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
- try {
- if (dirEntries.nextFile)
- return;
- }
- finally {
- dirEntries.close();
- }
-
- try {
- setFilePermissions(dir, FileUtils.PERMS_DIRECTORY);
- dir.remove(false);
- }
- catch (e) {
- logger.warn("Failed to remove staging dir", e);
- // Failing to remove the staging directory is ignorable
- }
- },
-
- /**
- * Gets the staging directory to put add-ons that are pending install and
- * uninstall into.
- *
- * @return {nsIFile} - staging directory for system add-on upgrades.
- */
- getStagingDir: function() {
- this._addonSet = this._loadAddonSet();
- let dir = null;
- if (this._addonSet.directory) {
- this._directory = this._baseDir.clone();
- this._directory.append(this._addonSet.directory);
- dir = this._directory.clone();
- dir.append(DIR_STAGE);
- }
- else {
- logger.info("SystemAddonInstallLocation directory is missing");
- }
-
- return dir;
- },
-
- requestStagingDir: function() {
- this._stagingDirLock++;
- if (this._stagingDirPromise)
- return this._stagingDirPromise;
-
- this._addonSet = this._loadAddonSet();
- if (this._addonSet.directory) {
- this._directory = this._baseDir.clone();
- this._directory.append(this._addonSet.directory);
- }
-
- OS.File.makeDir(this._directory.path);
- let stagepath = OS.Path.join(this._directory.path, DIR_STAGE);
- return this._stagingDirPromise = OS.File.makeDir(stagepath).then(null, (e) => {
- if (e instanceof OS.File.Error && e.becauseExists)
- return;
- logger.error("Failed to create staging directory", e);
- throw e;
- });
- },
-
- releaseStagingDir: function() {
- this._stagingDirLock--;
-
- if (this._stagingDirLock == 0) {
- this._stagingDirPromise = null;
- this.cleanStagingDir();
- }
-
- return Promise.resolve();
- },
-
- /**
- * Reads the current set of system add-ons
- */
- _loadAddonSet: function() {
- try {
- let setStr = Preferences.get(PREF_SYSTEM_ADDON_SET, null);
- if (setStr) {
- let addonSet = JSON.parse(setStr);
- if ((typeof addonSet == "object") && addonSet.schema == 1)
- return addonSet;
- }
- }
- catch (e) {
- logger.error("Malformed system add-on set, resetting.");
- }
-
- return { schema: 1, addons: {} };
- },
-
- /**
- * Saves the current set of system add-ons
- *
- * @param {Object} aAddonSet - object containing schema, directory and set
- * of system add-on IDs and versions.
- */
- _saveAddonSet: function(aAddonSet) {
- Preferences.set(PREF_SYSTEM_ADDON_SET, JSON.stringify(aAddonSet));
- },
-
- getAddonLocations: function() {
- // Updated system add-ons are ignored in safe mode
- if (Services.appinfo.inSafeMode)
- return new Map();
-
- let addons = DirectoryInstallLocation.prototype.getAddonLocations.call(this);
-
- // Strip out any unexpected add-ons from the list
- for (let id of addons.keys()) {
- if (!(id in this._addonSet.addons))
- addons.delete(id);
- }
-
- return addons;
- },
-
- /**
- * Tests whether updated system add-ons are expected.
- */
- isActive: function() {
- return this._directory != null;
- },
-
- isValidAddon: function(aAddon) {
- if (aAddon.appDisabled) {
- logger.warn(`System add-on ${aAddon.id} isn't compatible with the application.`);
- return false;
- }
-
- if (aAddon.unpack) {
- logger.warn(`System add-on ${aAddon.id} isn't a packed add-on.`);
- return false;
- }
-
- if (!aAddon.bootstrap) {
- logger.warn(`System add-on ${aAddon.id} isn't restartless.`);
- return false;
- }
-
- if (!aAddon.multiprocessCompatible) {
- logger.warn(`System add-on ${aAddon.id} isn't multiprocess compatible.`);
- return false;
- }
-
- return true;
- },
-
- /**
- * Tests whether the loaded add-on information matches what is expected.
- */
- isValid: function(aAddons) {
- for (let id of Object.keys(this._addonSet.addons)) {
- if (!aAddons.has(id)) {
- logger.warn(`Expected add-on ${id} is missing from the system add-on location.`);
- return false;
- }
-
- let addon = aAddons.get(id);
- if (addon.version != this._addonSet.addons[id].version) {
- logger.warn(`Expected system add-on ${id} to be version ${this._addonSet.addons[id].version} but was ${addon.version}.`);
- return false;
- }
-
- if (!this.isValidAddon(addon))
- return false;
- }
-
- return true;
- },
-
- /**
- * Resets the add-on set so on the next startup the default set will be used.
- */
- resetAddonSet: function() {
-
- if (this._addonSet) {
- logger.info("Removing all system add-on upgrades.");
-
- // remove everything from the pref first, if uninstall
- // fails then at least they will not be re-activated on
- // next restart.
- this._saveAddonSet({ schema: 1, addons: {} });
-
- for (let id of Object.keys(this._addonSet.addons)) {
- AddonManager.getAddonByID(id, addon => {
- if (addon) {
- addon.uninstall();
- }
- });
- }
- }
- },
-
- /**
- * Removes any directories not currently in use or pending use after a
- * restart. Any errors that happen here don't really matter as we'll attempt
- * to cleanup again next time.
- */
- cleanDirectories: Task.async(function*() {
-
- // System add-ons directory does not exist
- if (!(yield OS.File.exists(this._baseDir.path))) {
- return;
- }
-
- let iterator;
- try {
- iterator = new OS.File.DirectoryIterator(this._baseDir.path);
- }
- catch (e) {
- logger.error("Failed to clean updated system add-ons directories.", e);
- return;
- }
-
- try {
- let entries = [];
-
- yield iterator.forEach(entry => {
- // Skip the directory currently in use
- if (this._directory && this._directory.path == entry.path)
- return;
-
- // Skip the next directory
- if (this._nextDir && this._nextDir.path == entry.path)
- return;
-
- entries.push(entry);
- });
-
- for (let entry of entries) {
- if (entry.isDir) {
- yield OS.File.removeDir(entry.path, {
- ignoreAbsent: true,
- ignorePermissions: true,
- });
- }
- else {
- yield OS.File.remove(entry.path, {
- ignoreAbsent: true,
- });
- }
- }
- }
- catch (e) {
- logger.error("Failed to clean updated system add-ons directories.", e);
- }
- finally {
- iterator.close();
- }
- }),
-
- /**
- * Installs a new set of system add-ons into the location and updates the
- * add-on set in prefs.
- *
- * @param {Array} aAddons - An array of addons to install.
- */
- installAddonSet: Task.async(function*(aAddons) {
- // Make sure the base dir exists
- yield OS.File.makeDir(this._baseDir.path, { ignoreExisting: true });
-
- let addonSet = this._loadAddonSet();
-
- // Remove any add-ons that are no longer part of the set.
- for (let addonID of Object.keys(addonSet.addons)) {
- if (!aAddons.includes(addonID)) {
- AddonManager.getAddonByID(addonID, a => a.uninstall());
- }
- }
-
- let newDir = this._baseDir.clone();
-
- let uuidGen = Cc["@mozilla.org/uuid-generator;1"].
- getService(Ci.nsIUUIDGenerator);
- newDir.append("blank");
-
- while (true) {
- newDir.leafName = uuidGen.generateUUID().toString();
-
- try {
- yield OS.File.makeDir(newDir.path, { ignoreExisting: false });
- break;
- }
- catch (e) {
- logger.debug("Could not create new system add-on updates dir, retrying", e);
- }
- }
-
- // Record the new upgrade directory.
- let state = { schema: 1, directory: newDir.leafName, addons: {} };
- this._saveAddonSet(state);
-
- this._nextDir = newDir;
- let location = this;
-
- let installs = [];
- for (let addon of aAddons) {
- let install = yield createLocalInstall(addon._sourceBundle, location);
- installs.push(install);
- }
-
- let installAddon = Task.async(function*(install) {
- // Make the new install own its temporary file.
- install.ownsTempFile = true;
- install.install();
- });
-
- let postponeAddon = Task.async(function*(install) {
- let resumeFn;
- if (AddonManagerPrivate.hasUpgradeListener(install.addon.id)) {
- logger.info(`system add-on ${install.addon.id} has an upgrade listener, postponing upgrade set until restart`);
- resumeFn = () => {
- logger.info(`${install.addon.id} has resumed a previously postponed addon set`);
- install.installLocation.resumeAddonSet(installs);
- }
- }
- yield install.postpone(resumeFn);
- });
-
- let previousState;
-
- try {
- // All add-ons in position, create the new state and store it in prefs
- state = { schema: 1, directory: newDir.leafName, addons: {} };
- for (let addon of aAddons) {
- state.addons[addon.id] = {
- version: addon.version
- }
- }
-
- previousState = this._loadAddonSet();
- this._saveAddonSet(state);
-
- let blockers = aAddons.filter(
- addon => AddonManagerPrivate.hasUpgradeListener(addon.id)
- );
-
- if (blockers.length > 0) {
- yield waitForAllPromises(installs.map(postponeAddon));
- } else {
- yield waitForAllPromises(installs.map(installAddon));
- }
- }
- catch (e) {
- // Roll back to previous upgrade set (if present) on restart.
- if (previousState) {
- this._saveAddonSet(previousState);
- }
- // Otherwise, roll back to built-in set on restart.
- // TODO try to do these restartlessly
- this.resetAddonSet();
-
- try {
- yield OS.File.removeDir(newDir.path, { ignorePermissions: true });
- }
- catch (e) {
- logger.warn(`Failed to remove failed system add-on directory ${newDir.path}.`, e);
- }
- throw e;
- }
- }),
-
- /**
- * Resumes upgrade of a previously-delayed add-on set.
- */
- resumeAddonSet: Task.async(function*(installs) {
- let resumeAddon = Task.async(function*(install) {
- install.state = AddonManager.STATE_DOWNLOADED;
- install.installLocation.releaseStagingDir();
- install.install();
- });
-
- let addonSet = this._loadAddonSet();
- let addonIDs = Object.keys(addonSet.addons);
-
- let blockers = installs.filter(
- install => AddonManagerPrivate.hasUpgradeListener(install.addon.id)
- );
-
- if (blockers.length > 1) {
- logger.warn("Attempted to resume system add-on install but upgrade blockers are still present");
- } else {
- yield waitForAllPromises(installs.map(resumeAddon));
- }
- }),
-
- /**
- * Returns a directory that is normally on the same filesystem as the rest of
- * the install location and can be used for temporarily storing files during
- * safe move operations. Calling this method will delete the existing trash
- * directory and its contents.
- *
- * @return an nsIFile
- */
- getTrashDir: function() {
- let trashDir = this._directory.clone();
- trashDir.append(DIR_TRASH);
- let trashDirExists = trashDir.exists();
- try {
- if (trashDirExists)
- recursiveRemove(trashDir);
- trashDirExists = false;
- } catch (e) {
- logger.warn("Failed to remove trash directory", e);
- }
- if (!trashDirExists)
- trashDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
-
- return trashDir;
- },
-
- /**
- * Installs an add-on into the install location.
- *
- * @param id
- * The ID of the add-on to install
- * @param source
- * The source nsIFile to install from
- * @return an nsIFile indicating where the add-on was installed to
- */
- installAddon: function({id, source}) {
- let trashDir = this.getTrashDir();
- let transaction = new SafeInstallOperation();
-
- // If any of these operations fails the finally block will clean up the
- // temporary directory
- try {
- if (source.isFile()) {
- flushJarCache(source);
- }
-
- transaction.moveUnder(source, this._directory);
- }
- finally {
- // It isn't ideal if this cleanup fails but it isn't worth rolling back
- // the install because of it.
- try {
- recursiveRemove(trashDir);
- }
- catch (e) {
- logger.warn("Failed to remove trash directory when installing " + id, e);
- }
- }
-
- let newFile = this._directory.clone();
- newFile.append(source.leafName);
-
- try {
- newFile.lastModifiedTime = Date.now();
- } catch (e) {
- logger.warn("failed to set lastModifiedTime on " + newFile.path, e);
- }
- this._IDToFileMap[id] = newFile;
- XPIProvider._addURIMapping(id, newFile);
-
- return newFile;
- },
-
- // old system add-on upgrade dirs get automatically removed
- uninstallAddon: (aAddon) => {},
-});
-
-/**
- * An object which identifies an install location for temporary add-ons.
- */
-const TemporaryInstallLocation = {
- locked: false,
- name: KEY_APP_TEMPORARY,
- scope: AddonManager.SCOPE_TEMPORARY,
- getAddonLocations: () => [],
- isLinkedAddon: () => false,
- installAddon: () => {},
- uninstallAddon: (aAddon) => {},
- getStagingDir: () => {},
-}
-
-/**
- * An object that identifies a registry install location for add-ons. The location
- * consists of a registry key which contains string values mapping ID to the
- * path where an add-on is installed
- *
- * @param aName
- * The string identifier of this Install Location.
- * @param aRootKey
- * The root key (one of the ROOT_KEY_ values from nsIWindowsRegKey).
- * @param scope
- * The scope of add-ons installed in this location
- */
-function WinRegInstallLocation(aName, aRootKey, aScope) {
- this.locked = true;
- this._name = aName;
- this._rootKey = aRootKey;
- this._scope = aScope;
- this._IDToFileMap = {};
-
- let path = this._appKeyPath + "\\Extensions";
- let key = Cc["@mozilla.org/windows-registry-key;1"].
- createInstance(Ci.nsIWindowsRegKey);
-
- // Reading the registry may throw an exception, and that's ok. In error
- // cases, we just leave ourselves in the empty state.
- try {
- key.open(this._rootKey, path, Ci.nsIWindowsRegKey.ACCESS_READ);
- }
- catch (e) {
- return;
- }
-
- this._readAddons(key);
- key.close();
-}
-
-WinRegInstallLocation.prototype = {
- _name : "",
- _rootKey : null,
- _scope : null,
- _IDToFileMap : null, // mapping from ID to nsIFile
-
- /**
- * Retrieves the path of this Application's data key in the registry.
- */
- get _appKeyPath() {
- let appVendor = Services.appinfo.vendor;
- let appName = Services.appinfo.name;
-
- // XXX Thunderbird doesn't specify a vendor string
- if (AppConstants.MOZ_APP_NAME == "thunderbird" && appVendor == "")
- appVendor = "Mozilla";
-
- // XULRunner-based apps may intentionally not specify a vendor
- if (appVendor != "")
- appVendor += "\\";
-
- return "SOFTWARE\\" + appVendor + appName;
- },
-
- /**
- * Read the registry and build a mapping between ID and path for each
- * installed add-on.
- *
- * @param key
- * The key that contains the ID to path mapping
- */
- _readAddons: function(aKey) {
- let count = aKey.valueCount;
- for (let i = 0; i < count; ++i) {
- let id = aKey.getValueName(i);
-
- let file = new nsIFile(aKey.readStringValue(id));
-
- if (!file.exists()) {
- logger.warn("Ignoring missing add-on in " + file.path);
- continue;
- }
-
- this._IDToFileMap[id] = file;
- XPIProvider._addURIMapping(id, file);
- }
- },
-
- /**
- * Gets the name of this install location.
- */
- get name() {
- return this._name;
- },
-
- /**
- * Gets the scope of this install location.
- */
- get scope() {
- return this._scope;
- },
-
- /**
- * Gets an array of nsIFiles for add-ons installed in this location.
- */
- getAddonLocations: function() {
- let locations = new Map();
- for (let id in this._IDToFileMap) {
- locations.set(id, this._IDToFileMap[id].clone());
- }
- return locations;
- },
-
- /**
- * @see DirectoryInstallLocation
- */
- isLinkedAddon: function(aId) {
- return true;
- }
-};
-
-var addonTypes = [
- new AddonManagerPrivate.AddonType("extension", URI_EXTENSION_STRINGS,
- STRING_TYPE_NAME,
- AddonManager.VIEW_TYPE_LIST, 4000,
- AddonManager.TYPE_SUPPORTS_UNDO_RESTARTLESS_UNINSTALL),
- new AddonManagerPrivate.AddonType("theme", URI_EXTENSION_STRINGS,
- STRING_TYPE_NAME,
- AddonManager.VIEW_TYPE_LIST, 5000),
- new AddonManagerPrivate.AddonType("dictionary", URI_EXTENSION_STRINGS,
- STRING_TYPE_NAME,
- AddonManager.VIEW_TYPE_LIST, 7000,
- AddonManager.TYPE_UI_HIDE_EMPTY | AddonManager.TYPE_SUPPORTS_UNDO_RESTARTLESS_UNINSTALL),
- new AddonManagerPrivate.AddonType("locale", URI_EXTENSION_STRINGS,
- STRING_TYPE_NAME,
- AddonManager.VIEW_TYPE_LIST, 8000,
- AddonManager.TYPE_UI_HIDE_EMPTY | AddonManager.TYPE_SUPPORTS_UNDO_RESTARTLESS_UNINSTALL),
-];
-
-// We only register experiments support if the application supports them.
-// Ideally, we would install an observer to watch the pref. Installing
-// an observer for this pref is not necessary here and may be buggy with
-// regards to registering this XPIProvider twice.
-if (Preferences.get("experiments.supported", false)) {
- addonTypes.push(
- new AddonManagerPrivate.AddonType("experiment",
- URI_EXTENSION_STRINGS,
- STRING_TYPE_NAME,
- AddonManager.VIEW_TYPE_LIST, 11000,
- AddonManager.TYPE_UI_HIDE_EMPTY | AddonManager.TYPE_SUPPORTS_UNDO_RESTARTLESS_UNINSTALL));
-}
-
-AddonManagerPrivate.registerProvider(XPIProvider, addonTypes);
diff --git a/toolkit/mozapps/webextensions/internal/XPIProviderUtils.js b/toolkit/mozapps/webextensions/internal/XPIProviderUtils.js
deleted file mode 100644
index 63ff6d8c8..000000000
--- a/toolkit/mozapps/webextensions/internal/XPIProviderUtils.js
+++ /dev/null
@@ -1,2239 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// These are injected from XPIProvider.jsm
-/* globals ADDON_SIGNING, SIGNED_TYPES, BOOTSTRAP_REASONS, DB_SCHEMA,
- AddonInternal, XPIProvider, XPIStates, syncLoadManifestFromFile,
- isUsableAddon, recordAddonTelemetry, applyBlocklistChanges,
- flushChromeCaches, canRunInSafeMode*/
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-var Cu = Components.utils;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/AddonManager.jsm");
-/* globals AddonManagerPrivate*/
-Cu.import("resource://gre/modules/Preferences.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "AddonRepository",
- "resource://gre/modules/addons/AddonRepository.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "DeferredSave",
- "resource://gre/modules/DeferredSave.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "OS",
- "resource://gre/modules/osfile.jsm");
-XPCOMUtils.defineLazyServiceGetter(this, "Blocklist",
- "@mozilla.org/extensions/blocklist;1",
- Ci.nsIBlocklistService);
-
-Cu.import("resource://gre/modules/Log.jsm");
-const LOGGER_ID = "addons.xpi-utils";
-
-const nsIFile = Components.Constructor("@mozilla.org/file/local;1", "nsIFile");
-
-// Create a new logger for use by the Addons XPI Provider Utils
-// (Requires AddonManager.jsm)
-var logger = Log.repository.getLogger(LOGGER_ID);
-
-const KEY_PROFILEDIR = "ProfD";
-const FILE_DATABASE = "extensions.sqlite";
-const FILE_JSON_DB = "extensions.json";
-const FILE_OLD_DATABASE = "extensions.rdf";
-const FILE_XPI_ADDONS_LIST = "extensions.ini";
-
-// The last version of DB_SCHEMA implemented in SQLITE
-const LAST_SQLITE_DB_SCHEMA = 14;
-const PREF_DB_SCHEMA = "extensions.databaseSchema";
-const PREF_PENDING_OPERATIONS = "extensions.pendingOperations";
-const PREF_EM_ENABLED_ADDONS = "extensions.enabledAddons";
-const PREF_EM_DSS_ENABLED = "extensions.dss.enabled";
-const PREF_EM_AUTO_DISABLED_SCOPES = "extensions.autoDisableScopes";
-const PREF_E10S_BLOCKED_BY_ADDONS = "extensions.e10sBlockedByAddons";
-const PREF_E10S_HAS_NONEXEMPT_ADDON = "extensions.e10s.rollout.hasAddon";
-
-const KEY_APP_PROFILE = "app-profile";
-const KEY_APP_SYSTEM_ADDONS = "app-system-addons";
-const KEY_APP_SYSTEM_DEFAULTS = "app-system-defaults";
-const KEY_APP_GLOBAL = "app-global";
-
-// Properties that only exist in the database
-const DB_METADATA = ["syncGUID",
- "installDate",
- "updateDate",
- "size",
- "sourceURI",
- "releaseNotesURI",
- "applyBackgroundUpdates"];
-const DB_BOOL_METADATA = ["visible", "active", "userDisabled", "appDisabled",
- "pendingUninstall", "bootstrap", "skinnable",
- "softDisabled", "isForeignInstall",
- "hasBinaryComponents", "strictCompatibility"];
-
-// Properties to save in JSON file
-const PROP_JSON_FIELDS = ["id", "syncGUID", "location", "version", "type",
- "internalName", "updateURL", "updateKey", "optionsURL",
- "optionsType", "aboutURL", "icons", "iconURL", "icon64URL",
- "defaultLocale", "visible", "active", "userDisabled",
- "appDisabled", "pendingUninstall", "descriptor", "installDate",
- "updateDate", "applyBackgroundUpdates", "bootstrap",
- "skinnable", "size", "sourceURI", "releaseNotesURI",
- "softDisabled", "foreignInstall", "hasBinaryComponents",
- "strictCompatibility", "locales", "targetApplications",
- "targetPlatforms", "multiprocessCompatible", "signedState",
- "seen", "dependencies", "hasEmbeddedWebExtension", "mpcOptedOut"];
-
-// Properties that should be migrated where possible from an old database. These
-// shouldn't include properties that can be read directly from install.rdf files
-// or calculated
-const DB_MIGRATE_METADATA= ["installDate", "userDisabled", "softDisabled",
- "sourceURI", "applyBackgroundUpdates",
- "releaseNotesURI", "foreignInstall", "syncGUID"];
-
-// Time to wait before async save of XPI JSON database, in milliseconds
-const ASYNC_SAVE_DELAY_MS = 20;
-
-const PREFIX_ITEM_URI = "urn:mozilla:item:";
-const RDFURI_ITEM_ROOT = "urn:mozilla:item:root"
-const PREFIX_NS_EM = "http://www.mozilla.org/2004/em-rdf#";
-
-XPCOMUtils.defineLazyServiceGetter(this, "gRDF", "@mozilla.org/rdf/rdf-service;1",
- Ci.nsIRDFService);
-
-function EM_R(aProperty) {
- return gRDF.GetResource(PREFIX_NS_EM + aProperty);
-}
-
-/**
- * Converts an RDF literal, resource or integer into a string.
- *
- * @param aLiteral
- * The RDF object to convert
- * @return a string if the object could be converted or null
- */
-function getRDFValue(aLiteral) {
- if (aLiteral instanceof Ci.nsIRDFLiteral)
- return aLiteral.Value;
- if (aLiteral instanceof Ci.nsIRDFResource)
- return aLiteral.Value;
- if (aLiteral instanceof Ci.nsIRDFInt)
- return aLiteral.Value;
- return null;
-}
-
-/**
- * Gets an RDF property as a string
- *
- * @param aDs
- * The RDF datasource to read the property from
- * @param aResource
- * The RDF resource to read the property from
- * @param aProperty
- * The property to read
- * @return a string if the property existed or null
- */
-function getRDFProperty(aDs, aResource, aProperty) {
- return getRDFValue(aDs.GetTarget(aResource, EM_R(aProperty), true));
-}
-
-/**
- * Asynchronously fill in the _repositoryAddon field for one addon
- */
-function getRepositoryAddon(aAddon, aCallback) {
- if (!aAddon) {
- aCallback(aAddon);
- return;
- }
- function completeAddon(aRepositoryAddon) {
- aAddon._repositoryAddon = aRepositoryAddon;
- aAddon.compatibilityOverrides = aRepositoryAddon ?
- aRepositoryAddon.compatibilityOverrides :
- null;
- aCallback(aAddon);
- }
- AddonRepository.getCachedAddonByID(aAddon.id, completeAddon);
-}
-
-/**
- * Wrap an API-supplied function in an exception handler to make it safe to call
- */
-function makeSafe(aCallback) {
- return function(...aArgs) {
- try {
- aCallback(...aArgs);
- }
- catch (ex) {
- logger.warn("XPI Database callback failed", ex);
- }
- }
-}
-
-/**
- * A helper method to asynchronously call a function on an array
- * of objects, calling a callback when function(x) has been gathered
- * for every element of the array.
- * WARNING: not currently error-safe; if the async function does not call
- * our internal callback for any of the array elements, asyncMap will not
- * call the callback parameter.
- *
- * @param aObjects
- * The array of objects to process asynchronously
- * @param aMethod
- * Function with signature function(object, function(f_of_object))
- * @param aCallback
- * Function with signature f([aMethod(object)]), called when all values
- * are available
- */
-function asyncMap(aObjects, aMethod, aCallback) {
- var resultsPending = aObjects.length;
- var results = []
- if (resultsPending == 0) {
- aCallback(results);
- return;
- }
-
- function asyncMap_gotValue(aIndex, aValue) {
- results[aIndex] = aValue;
- if (--resultsPending == 0) {
- aCallback(results);
- }
- }
-
- aObjects.map(function(aObject, aIndex, aArray) {
- try {
- aMethod(aObject, function(aResult) {
- asyncMap_gotValue(aIndex, aResult);
- });
- }
- catch (e) {
- logger.warn("Async map function failed", e);
- asyncMap_gotValue(aIndex, undefined);
- }
- });
-}
-
-/**
- * A generator to synchronously return result rows from an mozIStorageStatement.
- *
- * @param aStatement
- * The statement to execute
- */
-function* resultRows(aStatement) {
- try {
- while (stepStatement(aStatement))
- yield aStatement.row;
- }
- finally {
- aStatement.reset();
- }
-}
-
-/**
- * A helper function to log an SQL error.
- *
- * @param aError
- * The storage error code associated with the error
- * @param aErrorString
- * An error message
- */
-function logSQLError(aError, aErrorString) {
- logger.error("SQL error " + aError + ": " + aErrorString);
-}
-
-/**
- * A helper function to log any errors that occur during async statements.
- *
- * @param aError
- * A mozIStorageError to log
- */
-function asyncErrorLogger(aError) {
- logSQLError(aError.result, aError.message);
-}
-
-/**
- * A helper function to step a statement synchronously and log any error that
- * occurs.
- *
- * @param aStatement
- * A mozIStorageStatement to execute
- */
-function stepStatement(aStatement) {
- try {
- return aStatement.executeStep();
- }
- catch (e) {
- logSQLError(XPIDatabase.connection.lastError,
- XPIDatabase.connection.lastErrorString);
- throw e;
- }
-}
-
-/**
- * Copies properties from one object to another. If no target object is passed
- * a new object will be created and returned.
- *
- * @param aObject
- * An object to copy from
- * @param aProperties
- * An array of properties to be copied
- * @param aTarget
- * An optional target object to copy the properties to
- * @return the object that the properties were copied onto
- */
-function copyProperties(aObject, aProperties, aTarget) {
- if (!aTarget)
- aTarget = {};
- aProperties.forEach(function(aProp) {
- if (aProp in aObject)
- aTarget[aProp] = aObject[aProp];
- });
- return aTarget;
-}
-
-/**
- * Copies properties from a mozIStorageRow to an object. If no target object is
- * passed a new object will be created and returned.
- *
- * @param aRow
- * A mozIStorageRow to copy from
- * @param aProperties
- * An array of properties to be copied
- * @param aTarget
- * An optional target object to copy the properties to
- * @return the object that the properties were copied onto
- */
-function copyRowProperties(aRow, aProperties, aTarget) {
- if (!aTarget)
- aTarget = {};
- aProperties.forEach(function(aProp) {
- aTarget[aProp] = aRow.getResultByName(aProp);
- });
- return aTarget;
-}
-
-/**
- * The DBAddonInternal is a special AddonInternal that has been retrieved from
- * the database. The constructor will initialize the DBAddonInternal with a set
- * of fields, which could come from either the JSON store or as an
- * XPIProvider.AddonInternal created from an addon's manifest
- * @constructor
- * @param aLoaded
- * Addon data fields loaded from JSON or the addon manifest.
- */
-function DBAddonInternal(aLoaded) {
- AddonInternal.call(this);
-
- copyProperties(aLoaded, PROP_JSON_FIELDS, this);
-
- if (!this.dependencies)
- this.dependencies = [];
- Object.freeze(this.dependencies);
-
- if (aLoaded._installLocation) {
- this._installLocation = aLoaded._installLocation;
- this.location = aLoaded._installLocation.name;
- }
- else if (aLoaded.location) {
- this._installLocation = XPIProvider.installLocationsByName[this.location];
- }
-
- this._key = this.location + ":" + this.id;
-
- if (!aLoaded._sourceBundle) {
- throw new Error("Expected passed argument to contain a descriptor");
- }
-
- this._sourceBundle = aLoaded._sourceBundle;
-
- XPCOMUtils.defineLazyGetter(this, "pendingUpgrade", function() {
- for (let install of XPIProvider.installs) {
- if (install.state == AddonManager.STATE_INSTALLED &&
- !(install.addon.inDatabase) &&
- install.addon.id == this.id &&
- install.installLocation == this._installLocation) {
- delete this.pendingUpgrade;
- return this.pendingUpgrade = install.addon;
- }
- }
- return null;
- });
-}
-
-DBAddonInternal.prototype = Object.create(AddonInternal.prototype);
-Object.assign(DBAddonInternal.prototype, {
- applyCompatibilityUpdate: function(aUpdate, aSyncCompatibility) {
- let wasCompatible = this.isCompatible;
-
- this.targetApplications.forEach(function(aTargetApp) {
- aUpdate.targetApplications.forEach(function(aUpdateTarget) {
- if (aTargetApp.id == aUpdateTarget.id && (aSyncCompatibility ||
- Services.vc.compare(aTargetApp.maxVersion, aUpdateTarget.maxVersion) < 0)) {
- aTargetApp.minVersion = aUpdateTarget.minVersion;
- aTargetApp.maxVersion = aUpdateTarget.maxVersion;
- XPIDatabase.saveChanges();
- }
- });
- });
- if (aUpdate.multiprocessCompatible !== undefined &&
- aUpdate.multiprocessCompatible != this.multiprocessCompatible) {
- this.multiprocessCompatible = aUpdate.multiprocessCompatible;
- XPIDatabase.saveChanges();
- }
-
- if (wasCompatible != this.isCompatible)
- XPIProvider.updateAddonDisabledState(this);
- },
-
- toJSON: function() {
- let jsonData = copyProperties(this, PROP_JSON_FIELDS);
-
- // Experiments are serialized as disabled so they aren't run on the next
- // startup.
- if (this.type == "experiment") {
- jsonData.userDisabled = true;
- jsonData.active = false;
- }
-
- return jsonData;
- },
-
- get inDatabase() {
- return true;
- }
-});
-
-/**
- * Internal interface: find an addon from an already loaded addonDB
- */
-function _findAddon(addonDB, aFilter) {
- for (let addon of addonDB.values()) {
- if (aFilter(addon)) {
- return addon;
- }
- }
- return null;
-}
-
-/**
- * Internal interface to get a filtered list of addons from a loaded addonDB
- */
-function _filterDB(addonDB, aFilter) {
- return Array.from(addonDB.values()).filter(aFilter);
-}
-
-this.XPIDatabase = {
- // true if the database connection has been opened
- initialized: false,
- // The database file
- jsonFile: FileUtils.getFile(KEY_PROFILEDIR, [FILE_JSON_DB], true),
- // Migration data loaded from an old version of the database.
- migrateData: null,
- // Active add-on directories loaded from extensions.ini and prefs at startup.
- activeBundles: null,
-
- // Saved error object if we fail to read an existing database
- _loadError: null,
-
- // Error reported by our most recent attempt to read or write the database, if any
- get lastError() {
- if (this._loadError)
- return this._loadError;
- if (this._deferredSave)
- return this._deferredSave.lastError;
- return null;
- },
-
- /**
- * Mark the current stored data dirty, and schedule a flush to disk
- */
- saveChanges: function() {
- if (!this.initialized) {
- throw new Error("Attempt to use XPI database when it is not initialized");
- }
-
- if (XPIProvider._closing) {
- // use an Error here so we get a stack trace.
- let err = new Error("XPI database modified after shutdown began");
- logger.warn(err);
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_late_stack", Log.stackTrace(err));
- }
-
- if (!this._deferredSave) {
- this._deferredSave = new DeferredSave(this.jsonFile.path,
- () => JSON.stringify(this),
- ASYNC_SAVE_DELAY_MS);
- }
-
- let promise = this._deferredSave.saveChanges();
- if (!this._schemaVersionSet) {
- this._schemaVersionSet = true;
- promise = promise.then(
- count => {
- // Update the XPIDB schema version preference the first time we successfully
- // save the database.
- logger.debug("XPI Database saved, setting schema version preference to " + DB_SCHEMA);
- Services.prefs.setIntPref(PREF_DB_SCHEMA, DB_SCHEMA);
- // Reading the DB worked once, so we don't need the load error
- this._loadError = null;
- },
- error => {
- // Need to try setting the schema version again later
- this._schemaVersionSet = false;
- // this._deferredSave.lastError has the most recent error so we don't
- // need this any more
- this._loadError = null;
-
- throw error;
- });
- }
-
- promise.catch(error => {
- logger.warn("Failed to save XPI database", error);
- });
- },
-
- flush: function() {
- // handle the "in memory only" and "saveChanges never called" cases
- if (!this._deferredSave) {
- return Promise.resolve(0);
- }
-
- return this._deferredSave.flush();
- },
-
- /**
- * Converts the current internal state of the XPI addon database to
- * a JSON.stringify()-ready structure
- */
- toJSON: function() {
- if (!this.addonDB) {
- // We never loaded the database?
- throw new Error("Attempt to save database without loading it first");
- }
-
- let toSave = {
- schemaVersion: DB_SCHEMA,
- addons: [...this.addonDB.values()]
- };
- return toSave;
- },
-
- /**
- * Pull upgrade information from an existing SQLITE database
- *
- * @return false if there is no SQLITE database
- * true and sets this.migrateData to null if the SQLITE DB exists
- * but does not contain useful information
- * true and sets this.migrateData to
- * {location: {id1:{addon1}, id2:{addon2}}, location2:{...}, ...}
- * if there is useful information
- */
- getMigrateDataFromSQLITE: function() {
- let connection = null;
- let dbfile = FileUtils.getFile(KEY_PROFILEDIR, [FILE_DATABASE], true);
- // Attempt to open the database
- try {
- connection = Services.storage.openUnsharedDatabase(dbfile);
- }
- catch (e) {
- logger.warn("Failed to open sqlite database " + dbfile.path + " for upgrade", e);
- return null;
- }
- logger.debug("Migrating data from sqlite");
- let migrateData = this.getMigrateDataFromDatabase(connection);
- connection.close();
- return migrateData;
- },
-
- /**
- * Synchronously opens and reads the database file, upgrading from old
- * databases or making a new DB if needed.
- *
- * The possibilities, in order of priority, are:
- * 1) Perfectly good, up to date database
- * 2) Out of date JSON database needs to be upgraded => upgrade
- * 3) JSON database exists but is mangled somehow => build new JSON
- * 4) no JSON DB, but a useable SQLITE db we can upgrade from => upgrade
- * 5) useless SQLITE DB => build new JSON
- * 6) useable RDF DB => upgrade
- * 7) useless RDF DB => build new JSON
- * 8) Nothing at all => build new JSON
- * @param aRebuildOnError
- * A boolean indicating whether add-on information should be loaded
- * from the install locations if the database needs to be rebuilt.
- * (if false, caller is XPIProvider.checkForChanges() which will rebuild)
- */
- syncLoadDB: function(aRebuildOnError) {
- this.migrateData = null;
- let fstream = null;
- let data = "";
- try {
- let readTimer = AddonManagerPrivate.simpleTimer("XPIDB_syncRead_MS");
- logger.debug("Opening XPI database " + this.jsonFile.path);
- fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].
- createInstance(Components.interfaces.nsIFileInputStream);
- fstream.init(this.jsonFile, -1, 0, 0);
- let cstream = null;
- try {
- cstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"].
- createInstance(Components.interfaces.nsIConverterInputStream);
- cstream.init(fstream, "UTF-8", 0, 0);
-
- let str = {};
- let read = 0;
- do {
- read = cstream.readString(0xffffffff, str); // read as much as we can and put it in str.value
- data += str.value;
- } while (read != 0);
-
- readTimer.done();
- this.parseDB(data, aRebuildOnError);
- }
- catch (e) {
- logger.error("Failed to load XPI JSON data from profile", e);
- let rebuildTimer = AddonManagerPrivate.simpleTimer("XPIDB_rebuildReadFailed_MS");
- this.rebuildDatabase(aRebuildOnError);
- rebuildTimer.done();
- }
- finally {
- if (cstream)
- cstream.close();
- }
- }
- catch (e) {
- if (e.result === Cr.NS_ERROR_FILE_NOT_FOUND) {
- this.upgradeDB(aRebuildOnError);
- }
- else {
- this.rebuildUnreadableDB(e, aRebuildOnError);
- }
- }
- finally {
- if (fstream)
- fstream.close();
- }
- // If an async load was also in progress, resolve that promise with our DB;
- // otherwise create a resolved promise
- if (this._dbPromise) {
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_overlapped_load", 1);
- this._dbPromise.resolve(this.addonDB);
- }
- else
- this._dbPromise = Promise.resolve(this.addonDB);
- },
-
- /**
- * Parse loaded data, reconstructing the database if the loaded data is not valid
- * @param aRebuildOnError
- * If true, synchronously reconstruct the database from installed add-ons
- */
- parseDB: function(aData, aRebuildOnError) {
- let parseTimer = AddonManagerPrivate.simpleTimer("XPIDB_parseDB_MS");
- try {
- // dump("Loaded JSON:\n" + aData + "\n");
- let inputAddons = JSON.parse(aData);
- // Now do some sanity checks on our JSON db
- if (!("schemaVersion" in inputAddons) || !("addons" in inputAddons)) {
- parseTimer.done();
- // Content of JSON file is bad, need to rebuild from scratch
- logger.error("bad JSON file contents");
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_startupError", "badJSON");
- let rebuildTimer = AddonManagerPrivate.simpleTimer("XPIDB_rebuildBadJSON_MS");
- this.rebuildDatabase(aRebuildOnError);
- rebuildTimer.done();
- return;
- }
- if (inputAddons.schemaVersion != DB_SCHEMA) {
- // Handle mismatched JSON schema version. For now, we assume
- // compatibility for JSON data, though we throw away any fields we
- // don't know about (bug 902956)
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_startupError",
- "schemaMismatch-" + inputAddons.schemaVersion);
- logger.debug("JSON schema mismatch: expected " + DB_SCHEMA +
- ", actual " + inputAddons.schemaVersion);
- // When we rev the schema of the JSON database, we need to make sure we
- // force the DB to save so that the DB_SCHEMA value in the JSON file and
- // the preference are updated.
- }
- // If we got here, we probably have good data
- // Make AddonInternal instances from the loaded data and save them
- let addonDB = new Map();
- for (let loadedAddon of inputAddons.addons) {
- loadedAddon._sourceBundle = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- try {
- loadedAddon._sourceBundle.persistentDescriptor = loadedAddon.descriptor;
- }
- catch (e) {
- // We can fail here when the descriptor is invalid, usually from the
- // wrong OS
- logger.warn("Could not find source bundle for add-on " + loadedAddon.id, e);
- }
-
- let newAddon = new DBAddonInternal(loadedAddon);
- addonDB.set(newAddon._key, newAddon);
- }
- parseTimer.done();
- this.addonDB = addonDB;
- logger.debug("Successfully read XPI database");
- this.initialized = true;
- }
- catch (e) {
- // If we catch and log a SyntaxError from the JSON
- // parser, the xpcshell test harness fails the test for us: bug 870828
- parseTimer.done();
- if (e.name == "SyntaxError") {
- logger.error("Syntax error parsing saved XPI JSON data");
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_startupError", "syntax");
- }
- else {
- logger.error("Failed to load XPI JSON data from profile", e);
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_startupError", "other");
- }
- let rebuildTimer = AddonManagerPrivate.simpleTimer("XPIDB_rebuildReadFailed_MS");
- this.rebuildDatabase(aRebuildOnError);
- rebuildTimer.done();
- }
- },
-
- /**
- * Upgrade database from earlier (sqlite or RDF) version if available
- */
- upgradeDB: function(aRebuildOnError) {
- let upgradeTimer = AddonManagerPrivate.simpleTimer("XPIDB_upgradeDB_MS");
- try {
- let schemaVersion = Services.prefs.getIntPref(PREF_DB_SCHEMA);
- if (schemaVersion <= LAST_SQLITE_DB_SCHEMA) {
- // we should have an older SQLITE database
- logger.debug("Attempting to upgrade from SQLITE database");
- this.migrateData = this.getMigrateDataFromSQLITE();
- }
- else {
- // we've upgraded before but the JSON file is gone, fall through
- // and rebuild from scratch
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_startupError", "dbMissing");
- }
- }
- catch (e) {
- // No schema version pref means either a really old upgrade (RDF) or
- // a new profile
- this.migrateData = this.getMigrateDataFromRDF();
- }
-
- this.rebuildDatabase(aRebuildOnError);
- upgradeTimer.done();
- },
-
- /**
- * Reconstruct when the DB file exists but is unreadable
- * (for example because read permission is denied)
- */
- rebuildUnreadableDB: function(aError, aRebuildOnError) {
- let rebuildTimer = AddonManagerPrivate.simpleTimer("XPIDB_rebuildUnreadableDB_MS");
- logger.warn("Extensions database " + this.jsonFile.path +
- " exists but is not readable; rebuilding", aError);
- // Remember the error message until we try and write at least once, so
- // we know at shutdown time that there was a problem
- this._loadError = aError;
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_startupError", "unreadable");
- this.rebuildDatabase(aRebuildOnError);
- rebuildTimer.done();
- },
-
- /**
- * Open and read the XPI database asynchronously, upgrading if
- * necessary. If any DB load operation fails, we need to
- * synchronously rebuild the DB from the installed extensions.
- *
- * @return Promise<Map> resolves to the Map of loaded JSON data stored
- * in this.addonDB; never rejects.
- */
- asyncLoadDB: function() {
- // Already started (and possibly finished) loading
- if (this._dbPromise) {
- return this._dbPromise;
- }
-
- logger.debug("Starting async load of XPI database " + this.jsonFile.path);
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_async_load", XPIProvider.runPhase);
- let readOptions = {
- outExecutionDuration: 0
- };
- return this._dbPromise = OS.File.read(this.jsonFile.path, null, readOptions).then(
- byteArray => {
- logger.debug("Async JSON file read took " + readOptions.outExecutionDuration + " MS");
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_asyncRead_MS",
- readOptions.outExecutionDuration);
- if (this._addonDB) {
- logger.debug("Synchronous load completed while waiting for async load");
- return this.addonDB;
- }
- logger.debug("Finished async read of XPI database, parsing...");
- let decodeTimer = AddonManagerPrivate.simpleTimer("XPIDB_decode_MS");
- let decoder = new TextDecoder();
- let data = decoder.decode(byteArray);
- decodeTimer.done();
- this.parseDB(data, true);
- return this.addonDB;
- })
- .then(null,
- error => {
- if (this._addonDB) {
- logger.debug("Synchronous load completed while waiting for async load");
- return this.addonDB;
- }
- if (error.becauseNoSuchFile) {
- this.upgradeDB(true);
- }
- else {
- // it's there but unreadable
- this.rebuildUnreadableDB(error, true);
- }
- return this.addonDB;
- });
- },
-
- /**
- * Rebuild the database from addon install directories. If this.migrateData
- * is available, uses migrated information for settings on the addons found
- * during rebuild
- * @param aRebuildOnError
- * A boolean indicating whether add-on information should be loaded
- * from the install locations if the database needs to be rebuilt.
- * (if false, caller is XPIProvider.checkForChanges() which will rebuild)
- */
- rebuildDatabase: function(aRebuildOnError) {
- this.addonDB = new Map();
- this.initialized = true;
-
- if (XPIStates.size == 0) {
- // No extensions installed, so we're done
- logger.debug("Rebuilding XPI database with no extensions");
- return;
- }
-
- // If there is no migration data then load the list of add-on directories
- // that were active during the last run
- if (!this.migrateData)
- this.activeBundles = this.getActiveBundles();
-
- if (aRebuildOnError) {
- logger.warn("Rebuilding add-ons database from installed extensions.");
- try {
- XPIDatabaseReconcile.processFileChanges({}, false);
- }
- catch (e) {
- logger.error("Failed to rebuild XPI database from installed extensions", e);
- }
- // Make sure to update the active add-ons and add-ons list on shutdown
- Services.prefs.setBoolPref(PREF_PENDING_OPERATIONS, true);
- }
- },
-
- /**
- * Gets the list of file descriptors of active extension directories or XPI
- * files from the add-ons list. This must be loaded from disk since the
- * directory service gives no easy way to get both directly. This list doesn't
- * include themes as preferences already say which theme is currently active
- *
- * @return an array of persistent descriptors for the directories
- */
- getActiveBundles: function() {
- let bundles = [];
-
- // non-bootstrapped extensions
- let addonsList = FileUtils.getFile(KEY_PROFILEDIR, [FILE_XPI_ADDONS_LIST],
- true);
-
- if (!addonsList.exists())
- // XXX Irving believes this is broken in the case where there is no
- // extensions.ini but there are bootstrap extensions (e.g. Android)
- return null;
-
- try {
- let iniFactory = Cc["@mozilla.org/xpcom/ini-parser-factory;1"]
- .getService(Ci.nsIINIParserFactory);
- let parser = iniFactory.createINIParser(addonsList);
- let keys = parser.getKeys("ExtensionDirs");
-
- while (keys.hasMore())
- bundles.push(parser.getString("ExtensionDirs", keys.getNext()));
- }
- catch (e) {
- logger.warn("Failed to parse extensions.ini", e);
- return null;
- }
-
- // Also include the list of active bootstrapped extensions
- for (let id in XPIProvider.bootstrappedAddons)
- bundles.push(XPIProvider.bootstrappedAddons[id].descriptor);
-
- return bundles;
- },
-
- /**
- * Retrieves migration data from the old extensions.rdf database.
- *
- * @return an object holding information about what add-ons were previously
- * userDisabled and any updated compatibility information
- */
- getMigrateDataFromRDF: function(aDbWasMissing) {
-
- // Migrate data from extensions.rdf
- let rdffile = FileUtils.getFile(KEY_PROFILEDIR, [FILE_OLD_DATABASE], true);
- if (!rdffile.exists())
- return null;
-
- logger.debug("Migrating data from " + FILE_OLD_DATABASE);
- let migrateData = {};
-
- try {
- let ds = gRDF.GetDataSourceBlocking(Services.io.newFileURI(rdffile).spec);
- let root = Cc["@mozilla.org/rdf/container;1"].
- createInstance(Ci.nsIRDFContainer);
- root.Init(ds, gRDF.GetResource(RDFURI_ITEM_ROOT));
- let elements = root.GetElements();
-
- while (elements.hasMoreElements()) {
- let source = elements.getNext().QueryInterface(Ci.nsIRDFResource);
-
- let location = getRDFProperty(ds, source, "installLocation");
- if (location) {
- if (!(location in migrateData))
- migrateData[location] = {};
- let id = source.ValueUTF8.substring(PREFIX_ITEM_URI.length);
- migrateData[location][id] = {
- version: getRDFProperty(ds, source, "version"),
- userDisabled: false,
- targetApplications: []
- }
-
- let disabled = getRDFProperty(ds, source, "userDisabled");
- if (disabled == "true" || disabled == "needs-disable")
- migrateData[location][id].userDisabled = true;
-
- let targetApps = ds.GetTargets(source, EM_R("targetApplication"),
- true);
- while (targetApps.hasMoreElements()) {
- let targetApp = targetApps.getNext()
- .QueryInterface(Ci.nsIRDFResource);
- let appInfo = {
- id: getRDFProperty(ds, targetApp, "id")
- };
-
- let minVersion = getRDFProperty(ds, targetApp, "updatedMinVersion");
- if (minVersion) {
- appInfo.minVersion = minVersion;
- appInfo.maxVersion = getRDFProperty(ds, targetApp, "updatedMaxVersion");
- }
- else {
- appInfo.minVersion = getRDFProperty(ds, targetApp, "minVersion");
- appInfo.maxVersion = getRDFProperty(ds, targetApp, "maxVersion");
- }
- migrateData[location][id].targetApplications.push(appInfo);
- }
- }
- }
- }
- catch (e) {
- logger.warn("Error reading " + FILE_OLD_DATABASE, e);
- migrateData = null;
- }
-
- return migrateData;
- },
-
- /**
- * Retrieves migration data from a database that has an older or newer schema.
- *
- * @return an object holding information about what add-ons were previously
- * userDisabled and any updated compatibility information
- */
- getMigrateDataFromDatabase: function(aConnection) {
- let migrateData = {};
-
- // Attempt to migrate data from a different (even future!) version of the
- // database
- try {
- var stmt = aConnection.createStatement("PRAGMA table_info(addon)");
-
- const REQUIRED = ["internal_id", "id", "location", "userDisabled",
- "installDate", "version"];
-
- let reqCount = 0;
- let props = [];
- for (let row of resultRows(stmt)) {
- if (REQUIRED.indexOf(row.name) != -1) {
- reqCount++;
- props.push(row.name);
- }
- else if (DB_METADATA.indexOf(row.name) != -1) {
- props.push(row.name);
- }
- else if (DB_BOOL_METADATA.indexOf(row.name) != -1) {
- props.push(row.name);
- }
- }
-
- if (reqCount < REQUIRED.length) {
- logger.error("Unable to read anything useful from the database");
- return null;
- }
- stmt.finalize();
-
- stmt = aConnection.createStatement("SELECT " + props.join(",") + " FROM addon");
- for (let row of resultRows(stmt)) {
- if (!(row.location in migrateData))
- migrateData[row.location] = {};
- let addonData = {
- targetApplications: []
- }
- migrateData[row.location][row.id] = addonData;
-
- props.forEach(function(aProp) {
- if (aProp == "isForeignInstall")
- addonData.foreignInstall = (row[aProp] == 1);
- if (DB_BOOL_METADATA.indexOf(aProp) != -1)
- addonData[aProp] = row[aProp] == 1;
- else
- addonData[aProp] = row[aProp];
- })
- }
-
- var taStmt = aConnection.createStatement("SELECT id, minVersion, " +
- "maxVersion FROM " +
- "targetApplication WHERE " +
- "addon_internal_id=:internal_id");
-
- for (let location in migrateData) {
- for (let id in migrateData[location]) {
- taStmt.params.internal_id = migrateData[location][id].internal_id;
- delete migrateData[location][id].internal_id;
- for (let row of resultRows(taStmt)) {
- migrateData[location][id].targetApplications.push({
- id: row.id,
- minVersion: row.minVersion,
- maxVersion: row.maxVersion
- });
- }
- }
- }
- }
- catch (e) {
- // An error here means the schema is too different to read
- logger.error("Error migrating data", e);
- return null;
- }
- finally {
- if (taStmt)
- taStmt.finalize();
- if (stmt)
- stmt.finalize();
- }
-
- return migrateData;
- },
-
- /**
- * Shuts down the database connection and releases all cached objects.
- * Return: Promise{integer} resolves / rejects with the result of the DB
- * flush after the database is flushed and
- * all cleanup is done
- */
- shutdown: function() {
- logger.debug("shutdown");
- if (this.initialized) {
- // If our last database I/O had an error, try one last time to save.
- if (this.lastError)
- this.saveChanges();
-
- this.initialized = false;
-
- if (this._deferredSave) {
- AddonManagerPrivate.recordSimpleMeasure(
- "XPIDB_saves_total", this._deferredSave.totalSaves);
- AddonManagerPrivate.recordSimpleMeasure(
- "XPIDB_saves_overlapped", this._deferredSave.overlappedSaves);
- AddonManagerPrivate.recordSimpleMeasure(
- "XPIDB_saves_late", this._deferredSave.dirty ? 1 : 0);
- }
-
- // Return a promise that any pending writes of the DB are complete and we
- // are finished cleaning up
- let flushPromise = this.flush();
- flushPromise.then(null, error => {
- logger.error("Flush of XPI database failed", error);
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_shutdownFlush_failed", 1);
- // If our last attempt to read or write the DB failed, force a new
- // extensions.ini to be written to disk on the next startup
- Services.prefs.setBoolPref(PREF_PENDING_OPERATIONS, true);
- })
- .then(count => {
- // Clear out the cached addons data loaded from JSON
- delete this.addonDB;
- delete this._dbPromise;
- // same for the deferred save
- delete this._deferredSave;
- // re-enable the schema version setter
- delete this._schemaVersionSet;
- });
- return flushPromise;
- }
- return Promise.resolve(0);
- },
-
- /**
- * Asynchronously list all addons that match the filter function
- * @param aFilter
- * Function that takes an addon instance and returns
- * true if that addon should be included in the selected array
- * @param aCallback
- * Called back with an array of addons matching aFilter
- * or an empty array if none match
- */
- getAddonList: function(aFilter, aCallback) {
- this.asyncLoadDB().then(
- addonDB => {
- let addonList = _filterDB(addonDB, aFilter);
- asyncMap(addonList, getRepositoryAddon, makeSafe(aCallback));
- })
- .then(null,
- error => {
- logger.error("getAddonList failed", error);
- makeSafe(aCallback)([]);
- });
- },
-
- /**
- * (Possibly asynchronously) get the first addon that matches the filter function
- * @param aFilter
- * Function that takes an addon instance and returns
- * true if that addon should be selected
- * @param aCallback
- * Called back with the addon, or null if no matching addon is found
- */
- getAddon: function(aFilter, aCallback) {
- return this.asyncLoadDB().then(
- addonDB => {
- getRepositoryAddon(_findAddon(addonDB, aFilter), makeSafe(aCallback));
- })
- .then(null,
- error => {
- logger.error("getAddon failed", error);
- makeSafe(aCallback)(null);
- });
- },
-
- /**
- * Asynchronously gets an add-on with a particular ID in a particular
- * install location.
- *
- * @param aId
- * The ID of the add-on to retrieve
- * @param aLocation
- * The name of the install location
- * @param aCallback
- * A callback to pass the DBAddonInternal to
- */
- getAddonInLocation: function(aId, aLocation, aCallback) {
- this.asyncLoadDB().then(
- addonDB => getRepositoryAddon(addonDB.get(aLocation + ":" + aId),
- makeSafe(aCallback)));
- },
-
- /**
- * Asynchronously get all the add-ons in a particular install location.
- *
- * @param aLocation
- * The name of the install location
- * @param aCallback
- * A callback to pass the array of DBAddonInternals to
- */
- getAddonsInLocation: function(aLocation, aCallback) {
- this.getAddonList(aAddon => aAddon._installLocation.name == aLocation, aCallback);
- },
-
- /**
- * Asynchronously gets the add-on with the specified ID that is visible.
- *
- * @param aId
- * The ID of the add-on to retrieve
- * @param aCallback
- * A callback to pass the DBAddonInternal to
- */
- getVisibleAddonForID: function(aId, aCallback) {
- this.getAddon(aAddon => ((aAddon.id == aId) && aAddon.visible),
- aCallback);
- },
-
- /**
- * Asynchronously gets the visible add-ons, optionally restricting by type.
- *
- * @param aTypes
- * An array of types to include or null to include all types
- * @param aCallback
- * A callback to pass the array of DBAddonInternals to
- */
- getVisibleAddons: function(aTypes, aCallback) {
- this.getAddonList(aAddon => (aAddon.visible &&
- (!aTypes || (aTypes.length == 0) ||
- (aTypes.indexOf(aAddon.type) > -1))),
- aCallback);
- },
-
- /**
- * Synchronously gets all add-ons of a particular type.
- *
- * @param aType
- * The type of add-on to retrieve
- * @return an array of DBAddonInternals
- */
- getAddonsByType: function(aType) {
- if (!this.addonDB) {
- // jank-tastic! Must synchronously load DB if the theme switches from
- // an XPI theme to a lightweight theme before the DB has loaded,
- // because we're called from sync XPIProvider.addonChanged
- logger.warn("Synchronous load of XPI database due to getAddonsByType(" + aType + ")");
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_lateOpen_byType", XPIProvider.runPhase);
- this.syncLoadDB(true);
- }
- return _filterDB(this.addonDB, aAddon => (aAddon.type == aType));
- },
-
- /**
- * Synchronously gets an add-on with a particular internalName.
- *
- * @param aInternalName
- * The internalName of the add-on to retrieve
- * @return a DBAddonInternal
- */
- getVisibleAddonForInternalName: function(aInternalName) {
- if (!this.addonDB) {
- // This may be called when the DB hasn't otherwise been loaded
- logger.warn("Synchronous load of XPI database due to getVisibleAddonForInternalName");
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_lateOpen_forInternalName",
- XPIProvider.runPhase);
- this.syncLoadDB(true);
- }
-
- return _findAddon(this.addonDB,
- aAddon => aAddon.visible &&
- (aAddon.internalName == aInternalName));
- },
-
- /**
- * Asynchronously gets all add-ons with pending operations.
- *
- * @param aTypes
- * The types of add-ons to retrieve or null to get all types
- * @param aCallback
- * A callback to pass the array of DBAddonInternal to
- */
- getVisibleAddonsWithPendingOperations: function(aTypes, aCallback) {
- this.getAddonList(
- aAddon => (aAddon.visible &&
- (aAddon.pendingUninstall ||
- // Logic here is tricky. If we're active but disabled,
- // we're pending disable; !active && !disabled, we're pending enable
- (aAddon.active == aAddon.disabled)) &&
- (!aTypes || (aTypes.length == 0) || (aTypes.indexOf(aAddon.type) > -1))),
- aCallback);
- },
-
- /**
- * Asynchronously get an add-on by its Sync GUID.
- *
- * @param aGUID
- * Sync GUID of add-on to fetch
- * @param aCallback
- * A callback to pass the DBAddonInternal record to. Receives null
- * if no add-on with that GUID is found.
- *
- */
- getAddonBySyncGUID: function(aGUID, aCallback) {
- this.getAddon(aAddon => aAddon.syncGUID == aGUID,
- aCallback);
- },
-
- /**
- * Synchronously gets all add-ons in the database.
- * This is only called from the preference observer for the default
- * compatibility version preference, so we can return an empty list if
- * we haven't loaded the database yet.
- *
- * @return an array of DBAddonInternals
- */
- getAddons: function() {
- if (!this.addonDB) {
- return [];
- }
- return _filterDB(this.addonDB, aAddon => true);
- },
-
- /**
- * Synchronously adds an AddonInternal's metadata to the database.
- *
- * @param aAddon
- * AddonInternal to add
- * @param aDescriptor
- * The file descriptor of the add-on
- * @return The DBAddonInternal that was added to the database
- */
- addAddonMetadata: function(aAddon, aDescriptor) {
- if (!this.addonDB) {
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_lateOpen_addMetadata",
- XPIProvider.runPhase);
- this.syncLoadDB(false);
- }
-
- let newAddon = new DBAddonInternal(aAddon);
- newAddon.descriptor = aDescriptor;
- this.addonDB.set(newAddon._key, newAddon);
- if (newAddon.visible) {
- this.makeAddonVisible(newAddon);
- }
-
- this.saveChanges();
- return newAddon;
- },
-
- /**
- * Synchronously updates an add-on's metadata in the database. Currently just
- * removes and recreates.
- *
- * @param aOldAddon
- * The DBAddonInternal to be replaced
- * @param aNewAddon
- * The new AddonInternal to add
- * @param aDescriptor
- * The file descriptor of the add-on
- * @return The DBAddonInternal that was added to the database
- */
- updateAddonMetadata: function(aOldAddon, aNewAddon, aDescriptor) {
- this.removeAddonMetadata(aOldAddon);
- aNewAddon.syncGUID = aOldAddon.syncGUID;
- aNewAddon.installDate = aOldAddon.installDate;
- aNewAddon.applyBackgroundUpdates = aOldAddon.applyBackgroundUpdates;
- aNewAddon.foreignInstall = aOldAddon.foreignInstall;
- aNewAddon.seen = aOldAddon.seen;
- aNewAddon.active = (aNewAddon.visible && !aNewAddon.disabled && !aNewAddon.pendingUninstall);
-
- // addAddonMetadata does a saveChanges()
- return this.addAddonMetadata(aNewAddon, aDescriptor);
- },
-
- /**
- * Synchronously removes an add-on from the database.
- *
- * @param aAddon
- * The DBAddonInternal being removed
- */
- removeAddonMetadata: function(aAddon) {
- this.addonDB.delete(aAddon._key);
- this.saveChanges();
- },
-
- /**
- * Synchronously marks a DBAddonInternal as visible marking all other
- * instances with the same ID as not visible.
- *
- * @param aAddon
- * The DBAddonInternal to make visible
- */
- makeAddonVisible: function(aAddon) {
- logger.debug("Make addon " + aAddon._key + " visible");
- for (let [, otherAddon] of this.addonDB) {
- if ((otherAddon.id == aAddon.id) && (otherAddon._key != aAddon._key)) {
- logger.debug("Hide addon " + otherAddon._key);
- otherAddon.visible = false;
- otherAddon.active = false;
- }
- }
- aAddon.visible = true;
- this.saveChanges();
- },
-
- /**
- * Synchronously sets properties for an add-on.
- *
- * @param aAddon
- * The DBAddonInternal being updated
- * @param aProperties
- * A dictionary of properties to set
- */
- setAddonProperties: function(aAddon, aProperties) {
- for (let key in aProperties) {
- aAddon[key] = aProperties[key];
- }
- this.saveChanges();
- },
-
- /**
- * Synchronously sets the Sync GUID for an add-on.
- * Only called when the database is already loaded.
- *
- * @param aAddon
- * The DBAddonInternal being updated
- * @param aGUID
- * GUID string to set the value to
- * @throws if another addon already has the specified GUID
- */
- setAddonSyncGUID: function(aAddon, aGUID) {
- // Need to make sure no other addon has this GUID
- function excludeSyncGUID(otherAddon) {
- return (otherAddon._key != aAddon._key) && (otherAddon.syncGUID == aGUID);
- }
- let otherAddon = _findAddon(this.addonDB, excludeSyncGUID);
- if (otherAddon) {
- throw new Error("Addon sync GUID conflict for addon " + aAddon._key +
- ": " + otherAddon._key + " already has GUID " + aGUID);
- }
- aAddon.syncGUID = aGUID;
- this.saveChanges();
- },
-
- /**
- * Synchronously updates an add-on's active flag in the database.
- *
- * @param aAddon
- * The DBAddonInternal to update
- */
- updateAddonActive: function(aAddon, aActive) {
- logger.debug("Updating active state for add-on " + aAddon.id + " to " + aActive);
-
- aAddon.active = aActive;
- this.saveChanges();
- },
-
- /**
- * Synchronously calculates and updates all the active flags in the database.
- */
- updateActiveAddons: function() {
- if (!this.addonDB) {
- logger.warn("updateActiveAddons called when DB isn't loaded");
- // force the DB to load
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_lateOpen_updateActive",
- XPIProvider.runPhase);
- this.syncLoadDB(true);
- }
- logger.debug("Updating add-on states");
- for (let [, addon] of this.addonDB) {
- let newActive = (addon.visible && !addon.disabled && !addon.pendingUninstall);
- if (newActive != addon.active) {
- addon.active = newActive;
- this.saveChanges();
- }
- }
- },
-
- /**
- * Writes out the XPI add-ons list for the platform to read.
- * @return true if the file was successfully updated, false otherwise
- */
- writeAddonsList: function() {
- if (!this.addonDB) {
- // force the DB to load
- AddonManagerPrivate.recordSimpleMeasure("XPIDB_lateOpen_writeList",
- XPIProvider.runPhase);
- this.syncLoadDB(true);
- }
- Services.appinfo.invalidateCachesOnRestart();
-
- let addonsList = FileUtils.getFile(KEY_PROFILEDIR, [FILE_XPI_ADDONS_LIST],
- true);
- let enabledAddons = [];
- let text = "[ExtensionDirs]\r\n";
- let count = 0;
- let fullCount = 0;
-
- let activeAddons = _filterDB(
- this.addonDB,
- aAddon => aAddon.active && !aAddon.bootstrap && (aAddon.type != "theme"));
-
- for (let row of activeAddons) {
- text += "Extension" + (count++) + "=" + row.descriptor + "\r\n";
- enabledAddons.push(encodeURIComponent(row.id) + ":" +
- encodeURIComponent(row.version));
- }
- fullCount += count;
-
- // The selected skin may come from an inactive theme (the default theme
- // when a lightweight theme is applied for example)
- text += "\r\n[ThemeDirs]\r\n";
-
- let dssEnabled = false;
- try {
- dssEnabled = Services.prefs.getBoolPref(PREF_EM_DSS_ENABLED);
- } catch (e) {}
-
- let themes = [];
- if (dssEnabled) {
- themes = _filterDB(this.addonDB, aAddon => aAddon.type == "theme");
- }
- else {
- let activeTheme = _findAddon(
- this.addonDB,
- aAddon => (aAddon.type == "theme") &&
- (aAddon.internalName == XPIProvider.selectedSkin));
- if (activeTheme) {
- themes.push(activeTheme);
- }
- }
-
- if (themes.length > 0) {
- count = 0;
- for (let row of themes) {
- text += "Extension" + (count++) + "=" + row.descriptor + "\r\n";
- enabledAddons.push(encodeURIComponent(row.id) + ":" +
- encodeURIComponent(row.version));
- }
- fullCount += count;
- }
-
- text += "\r\n[MultiprocessIncompatibleExtensions]\r\n";
-
- count = 0;
- for (let row of activeAddons) {
- if (!row.multiprocessCompatible) {
- text += "Extension" + (count++) + "=" + row.id + "\r\n";
- }
- }
-
- if (fullCount > 0) {
- logger.debug("Writing add-ons list");
-
- try {
- let addonsListTmp = FileUtils.getFile(KEY_PROFILEDIR, [FILE_XPI_ADDONS_LIST + ".tmp"],
- true);
- var fos = FileUtils.openFileOutputStream(addonsListTmp);
- fos.write(text, text.length);
- fos.close();
- addonsListTmp.moveTo(addonsListTmp.parent, FILE_XPI_ADDONS_LIST);
-
- Services.prefs.setCharPref(PREF_EM_ENABLED_ADDONS, enabledAddons.join(","));
- }
- catch (e) {
- logger.error("Failed to write add-ons list to profile directory", e);
- return false;
- }
- }
- else {
- if (addonsList.exists()) {
- logger.debug("Deleting add-ons list");
- try {
- addonsList.remove(false);
- }
- catch (e) {
- logger.error("Failed to remove " + addonsList.path, e);
- return false;
- }
- }
-
- Services.prefs.clearUserPref(PREF_EM_ENABLED_ADDONS);
- }
- return true;
- }
-};
-
-this.XPIDatabaseReconcile = {
- /**
- * Returns a map of ID -> add-on. When the same add-on ID exists in multiple
- * install locations the highest priority location is chosen.
- */
- flattenByID(addonMap, hideLocation) {
- let map = new Map();
-
- for (let installLocation of XPIProvider.installLocations) {
- if (installLocation.name == hideLocation)
- continue;
-
- let locationMap = addonMap.get(installLocation.name);
- if (!locationMap)
- continue;
-
- for (let [id, addon] of locationMap) {
- if (!map.has(id))
- map.set(id, addon);
- }
- }
-
- return map;
- },
-
- /**
- * Finds the visible add-ons from the map.
- */
- getVisibleAddons(addonMap) {
- let map = new Map();
-
- for (let [location, addons] of addonMap) {
- for (let [id, addon] of addons) {
- if (!addon.visible)
- continue;
-
- if (map.has(id)) {
- logger.warn("Previous database listed more than one visible add-on with id " + id);
- continue;
- }
-
- map.set(id, addon);
- }
- }
-
- return map;
- },
-
- /**
- * Called to add the metadata for an add-on in one of the install locations
- * to the database. This can be called in three different cases. Either an
- * add-on has been dropped into the location from outside of Firefox, or
- * an add-on has been installed through the application, or the database
- * has been upgraded or become corrupt and add-on data has to be reloaded
- * into it.
- *
- * @param aInstallLocation
- * The install location containing the add-on
- * @param aId
- * The ID of the add-on
- * @param aAddonState
- * The new state of the add-on
- * @param aNewAddon
- * The manifest for the new add-on if it has already been loaded
- * @param aOldAppVersion
- * The version of the application last run with this profile or null
- * if it is a new profile or the version is unknown
- * @param aOldPlatformVersion
- * The version of the platform last run with this profile or null
- * if it is a new profile or the version is unknown
- * @param aMigrateData
- * If during startup the database had to be upgraded this will
- * contain data that used to be held about this add-on
- * @return a boolean indicating if flushing caches is required to complete
- * changing this add-on
- */
- addMetadata(aInstallLocation, aId, aAddonState, aNewAddon, aOldAppVersion,
- aOldPlatformVersion, aMigrateData) {
- logger.debug("New add-on " + aId + " installed in " + aInstallLocation.name);
-
- // If we had staged data for this add-on or we aren't recovering from a
- // corrupt database and we don't have migration data for this add-on then
- // this must be a new install.
- let isNewInstall = (!!aNewAddon) || (!XPIDatabase.activeBundles && !aMigrateData);
-
- // If it's a new install and we haven't yet loaded the manifest then it
- // must be something dropped directly into the install location
- let isDetectedInstall = isNewInstall && !aNewAddon;
-
- // Load the manifest if necessary and sanity check the add-on ID
- try {
- if (!aNewAddon) {
- // Load the manifest from the add-on.
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- file.persistentDescriptor = aAddonState.descriptor;
- aNewAddon = syncLoadManifestFromFile(file, aInstallLocation);
- }
- // The add-on in the manifest should match the add-on ID.
- if (aNewAddon.id != aId) {
- throw new Error("Invalid addon ID: expected addon ID " + aId +
- ", found " + aNewAddon.id + " in manifest");
- }
- }
- catch (e) {
- logger.warn("addMetadata: Add-on " + aId + " is invalid", e);
-
- // Remove the invalid add-on from the install location if the install
- // location isn't locked, no restart will be necessary
- if (aInstallLocation.isLinkedAddon(aId))
- logger.warn("Not uninstalling invalid item because it is a proxy file");
- else if (aInstallLocation.locked)
- logger.warn("Could not uninstall invalid item from locked install location");
- else
- aInstallLocation.uninstallAddon(aId);
- return null;
- }
-
- // Update the AddonInternal properties.
- aNewAddon.installDate = aAddonState.mtime;
- aNewAddon.updateDate = aAddonState.mtime;
-
- // Assume that add-ons in the system add-ons install location aren't
- // foreign and should default to enabled.
- aNewAddon.foreignInstall = isDetectedInstall &&
- aInstallLocation.name != KEY_APP_SYSTEM_ADDONS &&
- aInstallLocation.name != KEY_APP_SYSTEM_DEFAULTS;
-
- // appDisabled depends on whether the add-on is a foreignInstall so update
- aNewAddon.appDisabled = !isUsableAddon(aNewAddon);
-
- if (aMigrateData) {
- // If there is migration data then apply it.
- logger.debug("Migrating data from old database");
-
- DB_MIGRATE_METADATA.forEach(function(aProp) {
- // A theme's disabled state is determined by the selected theme
- // preference which is read in loadManifestFromRDF
- if (aProp == "userDisabled" && aNewAddon.type == "theme")
- return;
-
- if (aProp in aMigrateData)
- aNewAddon[aProp] = aMigrateData[aProp];
- });
-
- // Force all non-profile add-ons to be foreignInstalls since they can't
- // have been installed through the API
- aNewAddon.foreignInstall |= aInstallLocation.name != KEY_APP_PROFILE;
-
- // Some properties should only be migrated if the add-on hasn't changed.
- // The version property isn't a perfect check for this but covers the
- // vast majority of cases.
- if (aMigrateData.version == aNewAddon.version) {
- logger.debug("Migrating compatibility info");
- if ("targetApplications" in aMigrateData)
- aNewAddon.applyCompatibilityUpdate(aMigrateData, true);
- }
-
- // Since the DB schema has changed make sure softDisabled is correct
- applyBlocklistChanges(aNewAddon, aNewAddon, aOldAppVersion,
- aOldPlatformVersion);
- }
-
- // The default theme is never a foreign install
- if (aNewAddon.type == "theme" && aNewAddon.internalName == XPIProvider.defaultSkin)
- aNewAddon.foreignInstall = false;
-
- if (isDetectedInstall && aNewAddon.foreignInstall) {
- // If the add-on is a foreign install and is in a scope where add-ons
- // that were dropped in should default to disabled then disable it
- let disablingScopes = Preferences.get(PREF_EM_AUTO_DISABLED_SCOPES, 0);
- if (aInstallLocation.scope & disablingScopes) {
- logger.warn("Disabling foreign installed add-on " + aNewAddon.id + " in "
- + aInstallLocation.name);
- aNewAddon.userDisabled = true;
-
- // If we don't have an old app version then this is a new profile in
- // which case just mark any sideloaded add-ons as already seen.
- aNewAddon.seen = !aOldAppVersion;
- }
- }
-
- return XPIDatabase.addAddonMetadata(aNewAddon, aAddonState.descriptor);
- },
-
- /**
- * Called when an add-on has been removed.
- *
- * @param aOldAddon
- * The AddonInternal as it appeared the last time the application
- * ran
- * @return a boolean indicating if flushing caches is required to complete
- * changing this add-on
- */
- removeMetadata(aOldAddon) {
- // This add-on has disappeared
- logger.debug("Add-on " + aOldAddon.id + " removed from " + aOldAddon.location);
- XPIDatabase.removeAddonMetadata(aOldAddon);
- },
-
- /**
- * Updates an add-on's metadata and determines if a restart of the
- * application is necessary. This is called when either the add-on's
- * install directory path or last modified time has changed.
- *
- * @param aInstallLocation
- * The install location containing the add-on
- * @param aOldAddon
- * The AddonInternal as it appeared the last time the application
- * ran
- * @param aAddonState
- * The new state of the add-on
- * @param aNewAddon
- * The manifest for the new add-on if it has already been loaded
- * @return a boolean indicating if flushing caches is required to complete
- * changing this add-on
- */
- updateMetadata(aInstallLocation, aOldAddon, aAddonState, aNewAddon) {
- logger.debug("Add-on " + aOldAddon.id + " modified in " + aInstallLocation.name);
-
- try {
- // If there isn't an updated install manifest for this add-on then load it.
- if (!aNewAddon) {
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- file.persistentDescriptor = aAddonState.descriptor;
- aNewAddon = syncLoadManifestFromFile(file, aInstallLocation);
- applyBlocklistChanges(aOldAddon, aNewAddon);
-
- // Carry over any pendingUninstall state to add-ons modified directly
- // in the profile. This is important when the attempt to remove the
- // add-on in processPendingFileChanges failed and caused an mtime
- // change to the add-ons files.
- aNewAddon.pendingUninstall = aOldAddon.pendingUninstall;
- }
-
- // The ID in the manifest that was loaded must match the ID of the old
- // add-on.
- if (aNewAddon.id != aOldAddon.id)
- throw new Error("Incorrect id in install manifest for existing add-on " + aOldAddon.id);
- }
- catch (e) {
- logger.warn("updateMetadata: Add-on " + aOldAddon.id + " is invalid", e);
- XPIDatabase.removeAddonMetadata(aOldAddon);
- XPIStates.removeAddon(aOldAddon.location, aOldAddon.id);
- if (!aInstallLocation.locked)
- aInstallLocation.uninstallAddon(aOldAddon.id);
- else
- logger.warn("Could not uninstall invalid item from locked install location");
-
- return null;
- }
-
- // Set the additional properties on the new AddonInternal
- aNewAddon.updateDate = aAddonState.mtime;
-
- // Update the database
- return XPIDatabase.updateAddonMetadata(aOldAddon, aNewAddon, aAddonState.descriptor);
- },
-
- /**
- * Updates an add-on's descriptor for when the add-on has moved in the
- * filesystem but hasn't changed in any other way.
- *
- * @param aInstallLocation
- * The install location containing the add-on
- * @param aOldAddon
- * The AddonInternal as it appeared the last time the application
- * ran
- * @param aAddonState
- * The new state of the add-on
- * @return a boolean indicating if flushing caches is required to complete
- * changing this add-on
- */
- updateDescriptor(aInstallLocation, aOldAddon, aAddonState) {
- logger.debug("Add-on " + aOldAddon.id + " moved to " + aAddonState.descriptor);
- aOldAddon.descriptor = aAddonState.descriptor;
- aOldAddon._sourceBundle.persistentDescriptor = aAddonState.descriptor;
-
- return aOldAddon;
- },
-
- /**
- * Called when no change has been detected for an add-on's metadata but the
- * application has changed so compatibility may have changed.
- *
- * @param aInstallLocation
- * The install location containing the add-on
- * @param aOldAddon
- * The AddonInternal as it appeared the last time the application
- * ran
- * @param aAddonState
- * The new state of the add-on
- * @param aOldAppVersion
- * The version of the application last run with this profile or null
- * if it is a new profile or the version is unknown
- * @param aOldPlatformVersion
- * The version of the platform last run with this profile or null
- * if it is a new profile or the version is unknown
- * @param aReloadMetadata
- * A boolean which indicates whether metadata should be reloaded from
- * the addon manifests. Default to false.
- * @return the new addon.
- */
- updateCompatibility(aInstallLocation, aOldAddon, aAddonState, aOldAppVersion,
- aOldPlatformVersion, aReloadMetadata) {
- logger.debug("Updating compatibility for add-on " + aOldAddon.id + " in " + aInstallLocation.name);
-
- // If updating from a version of the app that didn't support signedState
- // then fetch that property now
- if (aOldAddon.signedState === undefined && ADDON_SIGNING &&
- SIGNED_TYPES.has(aOldAddon.type)) {
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- file.persistentDescriptor = aAddonState.descriptor;
- let manifest = syncLoadManifestFromFile(file, aInstallLocation);
- aOldAddon.signedState = manifest.signedState;
- }
-
- // May be updating from a version of the app that didn't support all the
- // properties of the currently-installed add-ons.
- if (aReloadMetadata) {
- let file = new nsIFile()
- file.persistentDescriptor = aAddonState.descriptor;
- let manifest = syncLoadManifestFromFile(file, aInstallLocation);
-
- // Avoid re-reading these properties from manifest,
- // use existing addon instead.
- // TODO - consider re-scanning for targetApplications.
- let remove = ["syncGUID", "foreignInstall", "visible", "active",
- "userDisabled", "applyBackgroundUpdates", "sourceURI",
- "releaseNotesURI", "targetApplications"];
-
- let props = PROP_JSON_FIELDS.filter(a => !remove.includes(a));
- copyProperties(manifest, props, aOldAddon);
- }
-
- // This updates the addon's JSON cached data in place
- applyBlocklistChanges(aOldAddon, aOldAddon, aOldAppVersion,
- aOldPlatformVersion);
- aOldAddon.appDisabled = !isUsableAddon(aOldAddon);
-
- return aOldAddon;
- },
-
- /**
- * Compares the add-ons that are currently installed to those that were
- * known to be installed when the application last ran and applies any
- * changes found to the database. Also sends "startupcache-invalidate" signal to
- * observerservice if it detects that data may have changed.
- * Always called after XPIProviderUtils.js and extensions.json have been loaded.
- *
- * @param aManifests
- * A dictionary of cached AddonInstalls for add-ons that have been
- * installed
- * @param aUpdateCompatibility
- * true to update add-ons appDisabled property when the application
- * version has changed
- * @param aOldAppVersion
- * The version of the application last run with this profile or null
- * if it is a new profile or the version is unknown
- * @param aOldPlatformVersion
- * The version of the platform last run with this profile or null
- * if it is a new profile or the version is unknown
- * @param aSchemaChange
- * The schema has changed and all add-on manifests should be re-read.
- * @return a boolean indicating if a change requiring flushing the caches was
- * detected
- */
- processFileChanges(aManifests, aUpdateCompatibility, aOldAppVersion, aOldPlatformVersion,
- aSchemaChange) {
- let loadedManifest = (aInstallLocation, aId) => {
- if (!(aInstallLocation.name in aManifests))
- return null;
- if (!(aId in aManifests[aInstallLocation.name]))
- return null;
- return aManifests[aInstallLocation.name][aId];
- };
-
- // Add-ons loaded from the database can have an uninitialized _sourceBundle
- // if the descriptor was invalid. Swallow that error and say they don't exist.
- let exists = (aAddon) => {
- try {
- return aAddon._sourceBundle.exists();
- }
- catch (e) {
- if (e.result == Cr.NS_ERROR_NOT_INITIALIZED)
- return false;
- throw e;
- }
- };
-
- // Get the previous add-ons from the database and put them into maps by location
- let previousAddons = new Map();
- for (let a of XPIDatabase.getAddons()) {
- let locationAddonMap = previousAddons.get(a.location);
- if (!locationAddonMap) {
- locationAddonMap = new Map();
- previousAddons.set(a.location, locationAddonMap);
- }
- locationAddonMap.set(a.id, a);
- }
-
- // Build the list of current add-ons into similar maps. When add-ons are still
- // present we re-use the add-on objects from the database and update their
- // details directly
- let currentAddons = new Map();
- for (let installLocation of XPIProvider.installLocations) {
- let locationAddonMap = new Map();
- currentAddons.set(installLocation.name, locationAddonMap);
-
- // Get all the on-disk XPI states for this location, and keep track of which
- // ones we see in the database.
- let states = XPIStates.getLocation(installLocation.name);
-
- // Iterate through the add-ons installed the last time the application
- // ran
- let dbAddons = previousAddons.get(installLocation.name);
- if (dbAddons) {
- for (let [id, oldAddon] of dbAddons) {
- // Check if the add-on is still installed
- let xpiState = states && states.get(id);
- if (xpiState) {
- // Here the add-on was present in the database and on disk
- recordAddonTelemetry(oldAddon);
-
- // Check if the add-on has been changed outside the XPI provider
- if (oldAddon.updateDate != xpiState.mtime) {
- // Did time change in the wrong direction?
- if (xpiState.mtime < oldAddon.updateDate) {
- XPIProvider.setTelemetry(oldAddon.id, "olderFile", {
- name: XPIProvider._mostRecentlyModifiedFile[id],
- mtime: xpiState.mtime,
- oldtime: oldAddon.updateDate
- });
- } else {
- XPIProvider.setTelemetry(oldAddon.id, "modifiedFile",
- XPIProvider._mostRecentlyModifiedFile[id]);
- }
- }
-
- // The add-on has changed if the modification time has changed, if
- // we have an updated manifest for it, or if the schema version has
- // changed.
- //
- // Also reload the metadata for add-ons in the application directory
- // when the application version has changed.
- let newAddon = loadedManifest(installLocation, id);
- if (newAddon || oldAddon.updateDate != xpiState.mtime ||
- (aUpdateCompatibility && (installLocation.name == KEY_APP_GLOBAL ||
- installLocation.name == KEY_APP_SYSTEM_DEFAULTS))) {
- newAddon = this.updateMetadata(installLocation, oldAddon, xpiState, newAddon);
- }
- else if (oldAddon.descriptor != xpiState.descriptor) {
- newAddon = this.updateDescriptor(installLocation, oldAddon, xpiState);
- }
- // Check compatility when the application version and/or schema
- // version has changed. A schema change also reloads metadata from
- // the manifests.
- else if (aUpdateCompatibility || aSchemaChange) {
- newAddon = this.updateCompatibility(installLocation, oldAddon, xpiState,
- aOldAppVersion, aOldPlatformVersion,
- aSchemaChange);
- }
- else {
- // No change
- newAddon = oldAddon;
- }
-
- if (newAddon)
- locationAddonMap.set(newAddon.id, newAddon);
- }
- else {
- // The add-on is in the DB, but not in xpiState (and thus not on disk).
- this.removeMetadata(oldAddon);
- }
- }
- }
-
- // Any add-on in our current location that we haven't seen needs to
- // be added to the database.
- // Get the migration data for this install location so we can include that as
- // we add, in case this is a database upgrade or rebuild.
- let locMigrateData = {};
- if (XPIDatabase.migrateData && installLocation.name in XPIDatabase.migrateData)
- locMigrateData = XPIDatabase.migrateData[installLocation.name];
-
- if (states) {
- for (let [id, xpiState] of states) {
- if (locationAddonMap.has(id))
- continue;
- let migrateData = id in locMigrateData ? locMigrateData[id] : null;
- let newAddon = loadedManifest(installLocation, id);
- let addon = this.addMetadata(installLocation, id, xpiState, newAddon,
- aOldAppVersion, aOldPlatformVersion, migrateData);
- if (addon)
- locationAddonMap.set(addon.id, addon);
- }
- }
- }
-
- // previousAddons may contain locations where the database contains add-ons
- // but the browser is no longer configured to use that location. The metadata
- // for those add-ons must be removed from the database.
- for (let [locationName, addons] of previousAddons) {
- if (!currentAddons.has(locationName)) {
- for (let [id, oldAddon] of addons)
- this.removeMetadata(oldAddon);
- }
- }
-
- // Validate the updated system add-ons
- let systemAddonLocation = XPIProvider.installLocationsByName[KEY_APP_SYSTEM_ADDONS];
- let addons = currentAddons.get(KEY_APP_SYSTEM_ADDONS) || new Map();
-
- let hideLocation;
-
- if (!systemAddonLocation.isValid(addons)) {
- // Hide the system add-on updates if any are invalid.
- logger.info("One or more updated system add-ons invalid, falling back to defaults.");
- hideLocation = KEY_APP_SYSTEM_ADDONS;
- }
-
- let previousVisible = this.getVisibleAddons(previousAddons);
- let currentVisible = this.flattenByID(currentAddons, hideLocation);
- let sawActiveTheme = false;
- XPIProvider.bootstrappedAddons = {};
-
- // Pass over the new set of visible add-ons, record any changes that occured
- // during startup and call bootstrap install/uninstall scripts as necessary
- for (let [id, currentAddon] of currentVisible) {
- let previousAddon = previousVisible.get(id);
-
- // Note if any visible add-on is not in the application install location
- if (currentAddon._installLocation.name != KEY_APP_GLOBAL)
- XPIProvider.allAppGlobal = false;
-
- let isActive = !currentAddon.disabled;
- let wasActive = previousAddon ? previousAddon.active : currentAddon.active
-
- if (!previousAddon) {
- // If we had a manifest for this add-on it was a staged install and
- // so wasn't something recovered from a corrupt database
- let wasStaged = !!loadedManifest(currentAddon._installLocation, id);
-
- // We might be recovering from a corrupt database, if so use the
- // list of known active add-ons to update the new add-on
- if (!wasStaged && XPIDatabase.activeBundles) {
- // For themes we know which is active by the current skin setting
- if (currentAddon.type == "theme")
- isActive = currentAddon.internalName == XPIProvider.currentSkin;
- else
- isActive = XPIDatabase.activeBundles.indexOf(currentAddon.descriptor) != -1;
-
- // If the add-on wasn't active and it isn't already disabled in some way
- // then it was probably either softDisabled or userDisabled
- if (!isActive && !currentAddon.disabled) {
- // If the add-on is softblocked then assume it is softDisabled
- if (currentAddon.blocklistState == Blocklist.STATE_SOFTBLOCKED)
- currentAddon.softDisabled = true;
- else
- currentAddon.userDisabled = true;
- }
- }
- else {
- // This is a new install
- if (currentAddon.foreignInstall)
- AddonManagerPrivate.addStartupChange(AddonManager.STARTUP_CHANGE_INSTALLED, id);
-
- if (currentAddon.bootstrap) {
- AddonManagerPrivate.addStartupChange(AddonManager.STARTUP_CHANGE_INSTALLED, id);
- // Visible bootstrapped add-ons need to have their install method called
- XPIProvider.callBootstrapMethod(currentAddon, currentAddon._sourceBundle,
- "install", BOOTSTRAP_REASONS.ADDON_INSTALL);
- if (!isActive)
- XPIProvider.unloadBootstrapScope(currentAddon.id);
- }
- }
- }
- else {
- if (previousAddon !== currentAddon) {
- // This is an add-on that has changed, either the metadata was reloaded
- // or the version in a different location has become visible
- AddonManagerPrivate.addStartupChange(AddonManager.STARTUP_CHANGE_CHANGED, id);
-
- let installReason = Services.vc.compare(previousAddon.version, currentAddon.version) < 0 ?
- BOOTSTRAP_REASONS.ADDON_UPGRADE :
- BOOTSTRAP_REASONS.ADDON_DOWNGRADE;
-
- // If the previous add-on was in a different path, bootstrapped
- // and still exists then call its uninstall method.
- if (previousAddon.bootstrap && previousAddon._installLocation &&
- exists(previousAddon) &&
- currentAddon._sourceBundle.path != previousAddon._sourceBundle.path) {
-
- XPIProvider.callBootstrapMethod(previousAddon, previousAddon._sourceBundle,
- "uninstall", installReason,
- { newVersion: currentAddon.version });
- XPIProvider.unloadBootstrapScope(previousAddon.id);
- }
-
- // Make sure to flush the cache when an old add-on has gone away
- flushChromeCaches();
-
- if (currentAddon.bootstrap) {
- // Visible bootstrapped add-ons need to have their install method called
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- file.persistentDescriptor = currentAddon._sourceBundle.persistentDescriptor;
- XPIProvider.callBootstrapMethod(currentAddon, file,
- "install", installReason,
- { oldVersion: previousAddon.version });
- if (currentAddon.disabled)
- XPIProvider.unloadBootstrapScope(currentAddon.id);
- }
- }
-
- if (isActive != wasActive) {
- let change = isActive ? AddonManager.STARTUP_CHANGE_ENABLED
- : AddonManager.STARTUP_CHANGE_DISABLED;
- AddonManagerPrivate.addStartupChange(change, id);
- }
- }
-
- XPIDatabase.makeAddonVisible(currentAddon);
- currentAddon.active = isActive;
-
- // Make sure the bootstrap information is up to date for this ID
- if (currentAddon.bootstrap && currentAddon.active) {
- XPIProvider.bootstrappedAddons[id] = {
- version: currentAddon.version,
- type: currentAddon.type,
- descriptor: currentAddon._sourceBundle.persistentDescriptor,
- multiprocessCompatible: currentAddon.multiprocessCompatible,
- runInSafeMode: canRunInSafeMode(currentAddon),
- dependencies: currentAddon.dependencies,
- hasEmbeddedWebExtension: currentAddon.hasEmbeddedWebExtension,
- };
- }
-
- if (currentAddon.active && currentAddon.internalName == XPIProvider.selectedSkin)
- sawActiveTheme = true;
- }
-
- // Pass over the set of previously visible add-ons that have now gone away
- // and record the change.
- for (let [id, previousAddon] of previousVisible) {
- if (currentVisible.has(id))
- continue;
-
- // This add-on vanished
-
- // If the previous add-on was bootstrapped and still exists then call its
- // uninstall method.
- if (previousAddon.bootstrap && exists(previousAddon)) {
- XPIProvider.callBootstrapMethod(previousAddon, previousAddon._sourceBundle,
- "uninstall", BOOTSTRAP_REASONS.ADDON_UNINSTALL);
- XPIProvider.unloadBootstrapScope(previousAddon.id);
- }
- AddonManagerPrivate.addStartupChange(AddonManager.STARTUP_CHANGE_UNINSTALLED, id);
-
- // Make sure to flush the cache when an old add-on has gone away
- flushChromeCaches();
- }
-
- // Make sure add-ons from hidden locations are marked invisible and inactive
- let locationAddonMap = currentAddons.get(hideLocation);
- if (locationAddonMap) {
- for (let addon of locationAddonMap.values()) {
- addon.visible = false;
- addon.active = false;
- }
- }
-
- // If a custom theme is selected and it wasn't seen in the new list of
- // active add-ons then enable the default theme
- if (XPIProvider.selectedSkin != XPIProvider.defaultSkin && !sawActiveTheme) {
- logger.info("Didn't see selected skin " + XPIProvider.selectedSkin);
- XPIProvider.enableDefaultTheme();
- }
-
- // Finally update XPIStates to match everything
- for (let [locationName, locationAddonMap] of currentAddons) {
- for (let [id, addon] of locationAddonMap) {
- let xpiState = XPIStates.getAddon(locationName, id);
- xpiState.syncWithDB(addon);
- }
- }
- XPIStates.save();
-
- XPIProvider.persistBootstrappedAddons();
-
- // Clear out any cached migration data.
- XPIDatabase.migrateData = null;
- XPIDatabase.saveChanges();
-
- return true;
- },
-}
diff --git a/toolkit/mozapps/webextensions/internal/moz.build b/toolkit/mozapps/webextensions/internal/moz.build
deleted file mode 100644
index 8f1e4fea6..000000000
--- a/toolkit/mozapps/webextensions/internal/moz.build
+++ /dev/null
@@ -1,31 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# 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/.
-
-EXTRA_JS_MODULES.addons += [
- '../../extensions/internal/AddonLogging.jsm',
- '../../extensions/internal/Content.js',
- '../../extensions/internal/ProductAddonChecker.jsm',
- '../../extensions/internal/SpellCheckDictionaryBootstrap.js',
- 'AddonRepository.jsm',
- 'AddonRepository_SQLiteMigrator.jsm',
- 'APIExtensionBootstrap.js',
- 'GMPProvider.jsm',
- 'LightweightThemeImageOptimizer.jsm',
- 'WebExtensionBootstrap.js',
- 'XPIProvider.jsm',
- 'XPIProviderUtils.js',
-]
-
-# Don't ship unused providers on Android
-if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'android':
- EXTRA_JS_MODULES.addons += [
- 'PluginProvider.jsm',
- ]
-
-EXTRA_PP_JS_MODULES.addons += [
- '../../extensions/internal/AddonUpdateChecker.jsm',
- 'AddonConstants.jsm',
-]
diff --git a/toolkit/mozapps/webextensions/jar.mn b/toolkit/mozapps/webextensions/jar.mn
deleted file mode 100644
index 0c63396cc..000000000
--- a/toolkit/mozapps/webextensions/jar.mn
+++ /dev/null
@@ -1,35 +0,0 @@
-# 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/.
-
-toolkit.jar:
-#ifndef MOZ_FENNEC
-% content mozapps %content/mozapps/
-* content/mozapps/extensions/extensions.xul (content/extensions.xul)
- content/mozapps/extensions/extensions.css (content/extensions.css)
-* content/mozapps/extensions/extensions.js (content/extensions.js)
-* content/mozapps/extensions/extensions.xml (content/extensions.xml)
- content/mozapps/extensions/updateinfo.xsl (../extensions/content/updateinfo.xsl)
- content/mozapps/extensions/about.xul (../extensions/content/about.xul)
- content/mozapps/extensions/about.js (content/about.js)
- content/mozapps/extensions/list.xul (../extensions/content/list.xul)
- content/mozapps/extensions/list.js (../extensions/content/list.js)
- content/mozapps/extensions/blocklist.xul (../extensions/content/blocklist.xul)
- content/mozapps/extensions/blocklist.js (../extensions/content/blocklist.js)
- content/mozapps/extensions/blocklist.css (../extensions/content/blocklist.css)
- content/mozapps/extensions/blocklist.xml (../extensions/content/blocklist.xml)
-* content/mozapps/extensions/update.xul (content/update.xul)
- content/mozapps/extensions/update.js (content/update.js)
- content/mozapps/extensions/eula.xul (../extensions/content/eula.xul)
- content/mozapps/extensions/eula.js (content/eula.js)
- content/mozapps/extensions/newaddon.xul (content/newaddon.xul)
-* content/mozapps/extensions/newaddon.js (../extensions/content/newaddon.js)
- content/mozapps/extensions/pluginPrefs.xul (../extensions/content/pluginPrefs.xul)
- content/mozapps/extensions/gmpPrefs.xul (../extensions/content/gmpPrefs.xul)
- content/mozapps/extensions/OpenH264-license.txt (../extensions/content/OpenH264-license.txt)
-#endif
- content/mozapps/extensions/setting.xml (content/setting.xml)
- content/mozapps/xpinstall/xpinstallConfirm.xul (../extensions/content/xpinstallConfirm.xul)
- content/mozapps/xpinstall/xpinstallConfirm.js (../extensions/content/xpinstallConfirm.js)
- content/mozapps/xpinstall/xpinstallConfirm.css (../extensions/content/xpinstallConfirm.css)
- content/mozapps/xpinstall/xpinstallItem.xml (../extensions/content/xpinstallItem.xml)
diff --git a/toolkit/mozapps/webextensions/moz.build b/toolkit/mozapps/webextensions/moz.build
deleted file mode 100644
index f6e83a355..000000000
--- a/toolkit/mozapps/webextensions/moz.build
+++ /dev/null
@@ -1,57 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# 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/.
-
-DIRS += ['internal']
-
-XPIDL_SOURCES += [
- '../extensions/amIAddonManager.idl',
- '../extensions/amIAddonPathService.idl',
- '../extensions/amIWebInstaller.idl',
- '../extensions/amIWebInstallListener.idl',
-]
-
-XPIDL_MODULE = 'extensions'
-
-EXTRA_COMPONENTS += [
- '../extensions/amContentHandler.js',
- 'addonManager.js',
- 'amInstallTrigger.js',
- 'amWebAPI.js',
- 'amWebInstallListener.js',
-]
-
-EXTRA_PP_COMPONENTS += [
- 'extensions.manifest',
-]
-
-EXTRA_JS_MODULES += [
- '../extensions/ChromeManifestParser.jsm',
- '../extensions/DeferredSave.jsm',
- '../extensions/GMPUtils.jsm',
- 'AddonManager.jsm',
- 'LightweightThemeManager.jsm',
- 'GMPInstallManager.jsm',
-]
-
-JAR_MANIFESTS += ['jar.mn']
-
-EXPORTS.mozilla += [
- 'AddonContentPolicy.h',
- 'AddonManagerWebAPI.h',
- 'AddonPathService.h',
-]
-
-UNIFIED_SOURCES += [
- 'AddonContentPolicy.cpp',
- 'AddonManagerWebAPI.cpp',
- 'AddonPathService.cpp',
-]
-
-LOCAL_INCLUDES += [
- '/dom/base',
-]
-
-FINAL_LIBRARY = 'xul'