getSessionId method

Future<String?> getSessionId({
  1. String? username,
  2. required String password,
})

Implementation

Future<String?> getSessionId({
  String? username,
  required String password,
}) async {
  // AVM documentation (German): https://avm.de/fileadmin/user_upload/Global/Service/Schnittstellen/Session-ID_deutsch_13Nov18.pdf

  /*if (sessionId != null && sessionId.isNotEmpty && sessionId != '0000000000000000') {
    final isSessionIdValid = await get(Uri.parse('$baseUrl/login_sid.lua?sid=$sessionId'), headers: <String, String>{});
    return sessionId;
  }*/

  final challengeMap = await _getChallenge();
  final challenge = challengeMap['challenge'];
  final user = challengeMap['user'];

  /// <md5> ist der MD5 (32 Hexzeichen mit Kleinbuchstaben) von
  /// <challenge>-<klartextpassword>
  final challengeResponse = StringBuffer()
    ..write(challenge)
    ..write('-')
    /*
          md5 = hashlib.md5()
          ..update(challenge.encode('utf-16le'))
          ..update('-'.encode('utf-16le'))
          ..update(password.encode('utf-16le'))
          response = challenge + '-' + md5.hexdigest()
     */
    // require('crypto').createHash('md5').update(Buffer(challenge+'-'+password, 'UTF-16LE')).digest('hex')
    ..write(md5.convert(encodeUtf16le('$challenge-$password')).toString());
  final url = Uri.parse('$baseUrl/login_sid.lua');
  if ((username ?? user) == null) {
    return null;
  }
  final response = (await post(url, body: {
    'response': challengeResponse.toString(),
    'username': username ?? user!,
  })).body;
  final sessionId = extractValueOfXmlTag(xml: response, xmlTag: 'SID');
  if (sessionId != '0000000000000000') {
    this.sessionId = sessionId;
    return sessionId;
  }
  return null;
}