   ]).then(([success]) => success);
    });
  },

  clear(info) {
    return this._checkActivated()
      .then(_ => {
        return this._dropRegistrationsIf(
          record =>
            info.domain == "*" ||
            (record.uri &&
              Services.eTLD.hasRootDomain(record.uri.prePath, info.domain))
        );
      })
      .catch(e => {
        lazy.console.warn(
          "clear: Error dropping subscriptions for domain",
          info.domain,
          e
        );
        return Promise.resolve();
      });
  },

  registration(aPageRecord) {
    lazy.console.debug("registration()");

    return this._getByPageRecord(aPageRecord).then(record => {
      if (!record) {
        return null;
      }
      if (record.isExpired()) {
        return record.quotaChanged().then(isChanged => {
          if (isChanged) {
            return this.dropRegistrationAndNotifyApp(record.keyID).then(
              _ => null
            );
          }
          return null;
        });
      }
      return record.toSubscription();
    });
  },

  _dropExpiredRegistrations() {
    lazy.console.debug("dropExpiredRegistrations()");

    return this._db.getAllExpired().then(records => {
      return Promise.all(
        records.map(record =>
          record
            .quotaChanged()
            .then(isChanged => {
              if (isChanged) {
                // If the user revisited the site, drop the expired push
                // registration and notify the associated service worker.
                this.dropRegistrationAndNotifyApp(record.keyID);
              }
            })
            .catch(error => {
              lazy.console.error(
                "dropExpiredRegistrations: Error dropping registration",
                record.keyID,
                error
              );
            })
        )
      );
    });
  },

  _onPermissionChange(subject, data) {
    lazy.console.debug("onPermissionChange()");

    if (data == "cleared") {
      return this._clearPermissions();
    }

    let permission = subject.QueryInterface(Ci.nsIPermission);
    if (permission.type != "desktop-notification") {
      return Promise.resolve();
    }

    return this._updatePermission(permission, data);
  },

  _clearPermissions() {
    lazy.console.debug("clearPermissions()");

    return this._db.clearIf(record => {
      if (!record.quotaApplies()) {
        // Only drop registrations that are subject to quota.
        return false;
      }
      this._backgroundUnregister(
        record,
        Ci.nsIPushErrorReporter.UNSUBSCRIBE_PERMISSION_REVOKED
      );
      return true;
    });
  },

  _updatePermission(permission, type) {
    lazy.console.debug("updatePermission()");

    let isAllow = permission.capability == Ci.nsIPermissionManager.ALLOW_ACTION;
    let isChange = type == "added" || type == "changed";

    if (isAllow && isChange) {
      // Permission set to "allow". Drop all expired registrations for this
      // site, notify the associated service workers, and reset the quota
      // for active registrations.
      return this._forEachPrincipal(permission.principal, (record, cursor) =>
        this._permissionAllowed(record, cursor)
      );
    } else if (isChange || (isAllow && type == "deleted")) {
      // Permission set to "block" or "always ask," or "allow" permission
      // removed. Expire all registrations for this site.
      return this._forEachPrincipal(permission.principal, (record, cursor) =>
        this._permissionDenied(record, cursor)
      );
    }

    return Promise.resolve();
  },

  _forEachPrincipal(principal, callback) {
    return this._db.forEachOrigin(
      principal.URI.prePath,
      ChromeUtils.originAttributesToSuffix(principal.originAttributes),
      callback
    );
  },

  /**
   * The update function called for each registration record if the push
   * permission is revoked. We only expire the record so we can notify the
   * service worker as soon as the permission is reinstated. If we just
   * deleted the record, the worker wouldn't be notified until the next visit
   * to the site.
   *
   * @param {PushRecord} record The record to expire.
   * @param {IDBCursor} cursor The IndexedDB cursor.
   */
  _permissionDenied(record, cursor) {
    lazy.console.debug("permissionDenied()");

    if (!record.quotaApplies() || record.isExpired()) {
      // Ignore already-expired records.
      return;
    }
    // Drop the registration in the background.
    this._backgroundUnregister(
      record,
      Ci.nsIPushErrorReporter.UNSUBSCRIBE_PERMISSION_REVOKED
    );
    record.setQuota(0);
    cursor.update(record);
  },

  /**
   * The update function called for each registration record if the push
   * permission is granted. If the record has expired, it will be dropped;
   * otherwise, its quota will be reset to the default value.
   *
   * @param {PushRecord} record The record to update.
   * @param {IDBCursor} cursor The IndexedDB cursor.
   */
  _permissionAllowed(record, cursor) {
    lazy.console.debug("permissionAllowed()");

    if (!record.quotaApplies()) {
      return;
    }
    if (record.isExpired()) {
      // If the registration has expired, drop and notify the worker
      // unconditionally.
      this._notifySubscriptionChangeObservers(record);
      cursor.delete();
      return;
    }
    record.resetQuota();
    cursor.update(record);
  },

  /**
   * Drops all matching registrations from the database. Notifies the
   * associated service workers if permission is granted, and removes
   * unexpired registrations from the server.
   *
   * @param {Function} predicate A function called for each record.
   * @returns {Promise} Resolves once the registrations have been dropped.
   */
  _dropRegistrationsIf(predicate) {
    return this._db.clearIf(record => {
      if (!predicate(record)) {
        return false;
      }
      if (record.hasPermission()) {
        // "Clear Recent History" and the Forget button remove permissions
        // before clearing registrations, but it's possible for the worker to
        // resubscribe if the "dom.push.testing.ignorePermission" pref is set.
        this._notifySubscriptionChangeObservers(record);
      }
      if (!record.isExpired()) {
        // Only unregister active registrations, since we already told the
        // server about expired ones.
        this._backgroundUnregister(
          record,
          Ci.nsIPushErrorReporter.UNSUBSCRIBE_MANUAL
        );
      }
      return true;
    });
  },
};
PK