fromString static method

AtKey fromString(
  1. String key
)

Implementation

static AtKey fromString(String key) {
  var atKey = AtKey();
  var metaData = Metadata();
  if (key.startsWith(AtConstants.atPkamPrivateKey) ||
      key.startsWith(AtConstants.atPkamPublicKey)) {
    atKey.key = key;
    atKey.metadata = metaData;
    return atKey;
  } else if (key.startsWith(AtConstants.atEncryptionPrivateKey)) {
    atKey.key = key.split('@')[0];
    atKey.sharedBy = '@${key.split('@')[1]}';
    atKey.metadata = metaData;
    return atKey;
  }
  //If key does not contain '@'. or key has space, it is not a valid key.
  if (!key.contains('@') || key.contains(' ')) {
    throw InvalidSyntaxException('$key is not well-formed key');
  }
  var keyParts = key.split(':');
  // If key does not contain ':' Ex: phone@bob; then keyParts length is 1
  // where phone is key and @bob is sharedBy
  if (keyParts.length == 1) {
    atKey.sharedBy = '@${keyParts[0].split('@')[1]}';
    atKey.key = keyParts[0].split('@')[0];
  } else {
    // Example key: public:phone@bob
    if (keyParts[0] == 'public') {
      metaData.isPublic = true;
    } else if (keyParts[0] == 'local') {
      atKey.isLocal = true;
    } else if (keyParts[0] == AtConstants.cached) {
      metaData.isCached = true;
      if (keyParts[1] == 'public') {
        metaData.isPublic = true;
        atKey.sharedWith = null; // Example key: cached:public:phone@bob
      } else {
        atKey.sharedWith =
            keyParts[1]; // Example key: cached:@alice:phone@bob
      }
    } else {
      atKey.sharedWith = keyParts[0];
    }

    List<String> keyArr = [];
    if (keyParts[0] == AtConstants.cached) {
      //cached:@alice:phone@bob
      keyArr = keyParts[2].split('@'); //phone@bob ==> 'phone', 'bob'
    } else {
      // @alice:phone@bob
      keyArr = keyParts[1].split('@'); // phone@bob ==> 'phone', 'bob'
    }
    if (keyArr.length == 2) {
      atKey.sharedBy =
          '@${keyArr[1]}'; // keyArr[1] is 'bob' so sharedBy needs to be @bob
      atKey.key = keyArr[0];
    } else {
      atKey.key = keyArr[0];
    }
  }
  //remove namespace
  if (atKey.key.contains('.')) {
    var namespaceIndex = atKey.key.lastIndexOf('.');
    if (namespaceIndex > -1) {
      atKey.namespace = atKey.key.substring(namespaceIndex + 1);
      atKey.key = atKey.key.substring(0, namespaceIndex);
    }
  } else {
    metaData.namespaceAware = false;
  }
  atKey.metadata = metaData;
  return atKey;
}