message: Fix issue where users would be reset to the wrong PL in the case of a deop
diff: @@ -101,7 +101,7 @@ class PowerlevelSyncer {
  // Work out what power levels to give
  const userPowers = [];
  - if (modeToPower[mode] && enabled) { // only give this power if it's +, not -
  + if (modeToPower[mode]) { // only give this power if it's +, not -
  userPowers.push(modeToPower[mode]);
  }
  @@ -152,17 +152,31 @@ class PowerlevelSyncer {
  }
  req.log.info(
  - `onMode: Mode ${mode} received for ${nick} - granting level of ${level} to ${userId}`
  + `onMode: Mode ${mode} received for ${nick}, granting level of ` +
  + `${enabled ? level : 0} to ${userId}`
  );
  const intent = this._ircBridge.getAppServiceBridge().getIntent();
  for (const room of matrixRooms) {
  const powerLevelMap = await (this._getCurrentPowerlevels(room.getId())) || {};
  const users = powerLevelMap.users || {};
  - if (users[userId] === level) {
  + // If the user's present PL is equal to the level, or is 0|undefined and the mode is disabled.
  + if ((users[userId] === level && enabled) || !enabled && !users[userId]) {
  req.log.debug("Not granting PLs, user already has correct PL");
  continue;
  }
  + // If we have a PL for the user, and the PL is higher than the level we want to give the user.
  + if (users[userId] !== undefined && users[userId] > level) {
  + req.log.debug("Not granting PLs, user has a higher existing PL");
  + continue;
  + }
  + // If we hit here, then level is higher than our current level.
  + if (!enabled) {
  + // XXX: Annoyingly we don't know if we can pop down to
  + // voiced level after being de-oped, as we aren't told the full
  + // set of modes.
  + level = 0;
  + }
  try {
  await intent.setPowerLevel(room.getId(), userId, level);
  }
  @@ -342,11 +356,13 @@ class PowerlevelSyncer {
  // the config file).
  const botClient = this._ircBridge.getAppServiceBridge().getIntent().getClient();
  for (const room of matrixRooms) {
  + req.log.info(`Checking moderated status for ${channel}`);
  const roomId = room.getId();
  try {
  const plContent = await this._getCurrentPowerlevels(roomId);
  const eventsDefault = enabled ? 1 : 0;
  if (plContent.events_default === eventsDefault) {
  + req.log.debug(`${channel} already has events_default set to ${eventsDefault}`);
  continue;
  }
  plContent.events_default = eventsDefault;
  