decodeHeader static method

String? decodeHeader(
  1. String? input
)

Decodes the given header input value.

Implementation

static String? decodeHeader(final String? input) {
  if (input == null || input.isEmpty) {
    return input;
  }
  // unwrap any lines:
  var cleaned = input.replaceAll('\r\n ', '');
  // remove any spaces between 2 encoded words:
  final containsEncodedWordsWithSpace = cleaned.contains('?= =?');
  final containsEncodedWordsWithTab = cleaned.contains('?=\t=?');
  final containsEncodedWordsWithoutSpace =
      !containsEncodedWordsWithSpace && cleaned.contains('?==?');
  if (containsEncodedWordsWithSpace ||
      containsEncodedWordsWithTab ||
      containsEncodedWordsWithoutSpace) {
    final match = _headerEncodingExpression.firstMatch(cleaned);
    if (match != null) {
      final sequence = match.group(0) ?? '';
      final separatorIndex = sequence.indexOf('?', 3);
      final endIndex = separatorIndex + 3;
      final startSequence = sequence.substring(0, endIndex);
      final searchText = containsEncodedWordsWithSpace
          ? '?= $startSequence'
          : containsEncodedWordsWithTab
              ? '?=\t$startSequence'
              : '?=$startSequence';
      if (startSequence.endsWith('?B?') || startSequence.endsWith('?b?')) {
        // in base64 encoding there are 2 cases:
        // 1. individual parts can end  with the padding character "=":
        //    - in that case we just remove the
        //      space between the encoded words
        // 2. individual words do not end with a padding character:
        //    - in that case we combine the words
        if (cleaned.contains('=$searchText')) {
          if (containsEncodedWordsWithSpace) {
            cleaned = cleaned.replaceAll('?= =?', '?==?');
          } else if (containsEncodedWordsWithTab) {
            cleaned = cleaned.replaceAll('?=\t=?', '?==?');
          }
        } else {
          cleaned = cleaned.replaceAll(searchText, '');
        }
      } else {
        // "standard case" - just fuse the sequences together
        cleaned = cleaned.replaceAll(searchText, '');
      }
    }
  }
  final buffer = StringBuffer();
  _decodeHeaderImpl(cleaned, buffer);

  return buffer.toString();
}