resolveData method

Future<void> resolveData()

Implementation

Future<void> resolveData() async {
  if (json != null) {
    return;
  } else if (base64 != null) {
    json = jsonDecode(utf8.decode(base64Decode(addPaddingToBase64(base64!))));
  } else if (links != null && links!.isNotEmpty) {
    if (hash == null) throw Exception('If links are used hash must be given');

    for (var link in links!) {
      try {
        var res = await get(Uri.parse(link),
            headers: {'Accept': 'application/json'});

        if (res.statusCode == 200) {
          String body = res.body;
          // body should be a json object
          try {
            var baseDecoded = base64Decode(addPaddingToBase64(hash!));
            var data = Uint8List.fromList(utf8.encode(body));

            var correctHash = checkMultiHash(baseDecoded, data);

            if (correctHash) {
              json = jsonDecode(body);
            } else {
              // now check if answer is json-Object with attachment property
              var decoded = jsonDecode(body);
              if (decoded is Map<String, dynamic>) {
                String attachmentJson = decoded['attachment'];

                var attData = Uint8List.fromList(utf8.encode(attachmentJson));
                if (!checkMultiHash(baseDecoded, attData)) {
                  throw Exception(
                      'Hash does not match data (Code: 23482304928)');
                }
                json = jsonDecode(attachmentJson);
              } else if (decoded is List) {
                var attach = decoded.first as Map;
                var attData =
                    Uint8List.fromList(utf8.encode(jsonEncode(attach)));
                if (!checkMultiHash(baseDecoded, attData)) {
                  throw Exception(
                      'Hash does not match data (Code: 23482304928)');
                }
                json = attach;
              }
            }
          } catch (e) {
            throw Exception('Hash is not a valid base64 '
                'encoded multihash ($e) (Code: 34982093)');
          }

          break;
        }
      } catch (e) {
        throw Exception('Cant load link data for $link due to `$e` '
            '(Code: 49382903)');
      }
    }
    if (json == null) throw Exception('No data found');
  } else {
    throw Exception('No data');
  }
}