"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = selectPushKey;

function _open() {
  const data = _interopRequireDefault(require("open"));

  _open = function () {
    return data;
  };

  return data;
}

function _ora() {
  const data = _interopRequireDefault(require("ora"));

  _ora = function () {
    return data;
  };

  return data;
}

function _xdl() {
  const data = require("@expo/xdl");

  _xdl = function () {
    return data;
  };

  return data;
}

function appleApi() {
  const data = _interopRequireWildcard(require("../build/ios/appleApi"));

  appleApi = function () {
    return data;
  };

  return data;
}

function credentials() {
  const data = _interopRequireWildcard(require("../build/ios/credentials"));

  credentials = function () {
    return data;
  };

  return data;
}

function _promptForCredentials() {
  const data = _interopRequireDefault(require("../build/ios/credentials/prompt/promptForCredentials"));

  _promptForCredentials = function () {
    return data;
  };

  return data;
}

function _log() {
  const data = _interopRequireDefault(require("../../log"));

  _log = function () {
    return data;
  };

  return data;
}

function _prompt() {
  const data = _interopRequireDefault(require("../../prompt"));

  _prompt = function () {
    return data;
  };

  return data;
}

function _tagger() {
  const data = require("./tagger");

  _tagger = function () {
    return data;
  };

  return data;
}

function _selectUtils() {
  const data = require("./selectUtils");

  _selectUtils = function () {
    return data;
  };

  return data;
}

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

async function selectPushKey(context, options = {}) {
  const pushKeys = context.username ? await chooseUnrevokedPushKey(context) : [];
  const choices = [...pushKeys]; // autoselect creds if we find valid ones

  if (pushKeys.length > 0 && !options.disableAutoSelectExisting) {
    const autoselectedPushkey = (0, _selectUtils().choosePreferredCreds)(context, pushKeys);
    (0, _log().default)(`Using Push Key: ${autoselectedPushkey.name}`);
    return autoselectedPushkey.value;
  }

  if (!options.disableCreate) {
    choices.push({
      name: '[Create a new key] (Recommended)',
      value: 'GENERATE'
    });
  }

  choices.push({
    name: '[Upload an existing key]',
    value: 'UPLOAD'
  });
  choices.push({
    name: '[Skip. This will disable push notifications.]',
    value: 'SKIP'
  });
  choices.push({
    name: '[Show me more info about these choices] ℹ️',
    value: 'INFO'
  });
  let {
    promptValue
  } = await (0, _prompt().default)({
    type: 'list',
    name: 'promptValue',
    message: 'Select an authentication token signing key to use for push notifications:',
    pageSize: Infinity,
    choices
  });

  if (promptValue === 'GENERATE') {
    return await generatePushKey(context);
  } else if (promptValue === 'UPLOAD') {
    const pushKey = (await (0, _promptForCredentials().default)(context, ['pushKey'])).credentials.pushKey;
    const isValid = await validateUploadedPushKey(context, pushKey);

    if (!isValid) {
      return await selectPushKey(context, {
        disableAutoSelectExisting: true
      });
    } // tag for updating to Expo servers


    (0, _tagger().tagForUpdate)(pushKey);
  } else if (promptValue === 'INFO') {
    (0, _open().default)('https://docs.expo.io/versions/latest/guides/adhoc-builds/#push-key-cli-options');
    return await selectPushKey(context);
  } else if (promptValue === 'SKIP') {
    return null;
  } else {
    return promptValue; // this should be an unrevoked key from the Expo servers
  }
}

async function validateUploadedPushKey(context, pushKey) {
  const spinner = (0, _ora().default)(`Checking validity of push key on Apple Developer Portal...`).start();

  const formattedPushKeyArray = _xdl().Credentials.Ios.formatPushKeys([pushKey], {
    provideFullPushKey: true
  });

  const filteredFormattedPushKeyArray = await filterRevokedPushKeys(context, formattedPushKeyArray);
  const isValidPushKey = filteredFormattedPushKeyArray.length > 0;

  if (isValidPushKey) {
    const successMsg = `Successfully validated the Push Key you uploaded against Apple Servers`;
    spinner.succeed(successMsg);
  } else {
    const failureMsg = `The Push Key you uploaded is not valid. Please check that it was not revoked on the Apple Servers. See docs.expo.io/versions/latest/guides/adhoc-builds for more details on uploading your credentials.`;
    spinner.fail(failureMsg);
  }

  return isValidPushKey;
}

async function chooseUnrevokedPushKey(context) {
  const pushKeysOnExpoServer = await _xdl().Credentials.Ios.getExistingPushKeys(context.username, context.team.id, {
    provideFullPushKey: true
  });

  if (pushKeysOnExpoServer.length === 0) {
    return []; // no keys stored on server
  }

  const spinner = (0, _ora().default)(`Checking validity of push keys on Apple Developer Portal...`).start();
  const validPushKeysOnExpoServer = await filterRevokedPushKeys(context, pushKeysOnExpoServer);
  const numValidKeys = validPushKeysOnExpoServer.length;
  const numRevokedKeys = pushKeysOnExpoServer.length - validPushKeysOnExpoServer.length;
  const statusToDisplay = `Push Keys: You have ${numValidKeys} valid and ${numRevokedKeys} revoked push keys on the Expo servers.`;

  if (numValidKeys > 0) {
    spinner.succeed(statusToDisplay);
  } else {
    spinner.warn(statusToDisplay);
  }

  return validPushKeysOnExpoServer;
}

async function filterRevokedPushKeys(context, pushKeys) {
  // if the credentials are valid, check it against apple to make sure it hasnt been revoked
  const pushKeyManager = appleApi().createManagers(context).pushKey;
  const pushKeysOnAppleServer = await pushKeyManager.list();
  const validKeyIdsOnAppleServer = pushKeysOnAppleServer.map(pushKey => pushKey.id);
  const validPushKeysOnExpoServer = pushKeys.filter(pushKey => {
    const apnsKeyId = pushKey.value && pushKey.value.apnsKeyId;
    return validKeyIdsOnAppleServer.includes(apnsKeyId);
  });
  return validPushKeysOnExpoServer;
}

async function generatePushKey(context) {
  const manager = appleApi().createManagers(context).pushKey;

  try {
    const pushKey = await manager.create({}); // tag for updating to Expo servers

    (0, _tagger().tagForUpdate)(pushKey);
    return pushKey;
  } catch (e) {
    if (e.code === 'APPLE_KEYS_TOO_MANY_GENERATED_ERROR') {
      const keys = await manager.list();

      _log().default.warn(`Maximum number (${keys.length}) of keys generated.`);

      const {
        answer
      } = await (0, _prompt().default)({
        type: 'list',
        name: 'answer',
        message: 'Please revoke or reuse an existing key:',
        choices: [{
          key: 'r',
          name: 'Choose which keys to revoke',
          value: 'REVOKE'
        }, {
          key: 'e',
          name: 'Use an existing key',
          value: 'USE_EXISTING'
        }, {
          key: 's',
          name: '[Skip. This will disable push notifications.]',
          value: 'SKIP'
        }, {
          name: '[Show me more info about these choices] ℹ️',
          value: 'INFO'
        }]
      });

      if (answer === 'REVOKE') {
        await credentials().revoke(context, ['pushKey']);
        return await generatePushKey(context);
      } else if (answer === 'USE_EXISTING') {
        return await selectPushKey(context, {
          disableCreate: true,
          disableAutoSelectExisting: true
        });
      } else if (answer === 'SKIP') {
        return null;
      } else if (answer === 'INFO') {
        (0, _open().default)('https://docs.expo.io/versions/latest/guides/adhoc-builds/#push-key-cli-options');
        return await generatePushKey(context);
      }
    }

    throw new Error(e);
  }
}
//# sourceMappingURL=../../__sourcemaps__/commands/client/selectPushKey.js.map