normalizeTarget function

URI? normalizeTarget(
  1. dynamic target, [
  2. String? domain
])

Normalize SIP URI. NOTE: It does not allow a SIP URI without username. Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'. Detects the domain part (if given) and properly hex-escapes the user portion. If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators.

Implementation

URI? normalizeTarget(dynamic target, [String? domain]) {
  // If no target is given then raise an error.
  if (target == null) {
    return null;
    // If a URI instance is given then return it.
  } else if (target is URI) {
    return target;

    // If a string is given split it by '@':
    // - Last fragment is the desired domain.
    // - Otherwise append the given domain argument.
  } else if (target is String) {
    List<String> targetArray = target.split('@');
    String targetUser;
    String targetDomain;

    switch (targetArray.length) {
      case 1:
        if (domain == null) {
          return null;
        }
        targetUser = target;
        targetDomain = domain;
        break;
      case 2:
        targetUser = targetArray[0];
        targetDomain = targetArray[1];
        break;
      default:
        targetUser = targetArray.sublist(0, targetArray.length - 1).join('@');
        targetDomain = targetArray[targetArray.length - 1];
    }

    // Remove the URI scheme (if present).
    targetUser = targetUser.replaceAll(
        RegExp(r'^(sips?|tel):', caseSensitive: false), '');

    // Remove 'tel' visual separators if the user portion just contains 'tel' number symbols.
    if (targetUser.contains(RegExp(r'^[-.()]*\+?[0-9\-.()]+$'))) {
      targetUser = targetUser.replaceAll(RegExp(r'[-.()]'), '');
    }

    // Build the complete SIP URI.
    target = dart_sip_c.SIP + ':' + escapeUser(targetUser) + '@' + targetDomain;

    // Finally parse the resulting URI.
    return URI.parse(target);
  } else {
    return null;
  }
}