LicenseDocument.parse constructor

LicenseDocument.parse(
  1. ByteData data
)

Implementation

factory LicenseDocument.parse(ByteData data) {
  Uint8List list =
      data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
  String text = utf8.decode(list);
  Map jsonObject;
  try {
    jsonObject = json.decode(text);
  } on Exception {
    throw Exception(LcpParsingError.errorDescription(LcpParsingErrors.json));
  }
  String id;
  DateTime issued;
  Uri provider;
  try {
    id = jsonObject["id"];
    issued = DateTime.parse(jsonObject["issued"]);
    provider = Uri.parse(jsonObject["provider"]);
  } on Exception {
    throw Exception(LcpParsingError.errorDescription(LcpParsingErrors.json));
  }

  Encryption encryption = Encryption.parse(jsonObject["encryption"]);
  Links links = Links.parse(jsonObject["links"] as List);

  Rights? rights;
  if (jsonObject.containsKey("rights")) {
    rights = Rights.parse(jsonObject["rights"]);
  }

  User? user;
  if (jsonObject.containsKey("user")) {
    user = User.parse(jsonObject["user"]);
  }

  Signature signature = Signature.parse(jsonObject["signature"]);

  DateTime updated = issued;
  if (jsonObject.containsKey("updated")) {
    var parsedDateTime = DateTime.tryParse(jsonObject["updated"]);
    if (parsedDateTime != null) {
      updated = parsedDateTime;
    }
  }

  if (links.firstWithRel(LicenseRel.hint.val) == null) {
    throw Exception(LcpError.errorDescription(LcpErrorCase.hintLinkNotFound));
  }

  if (links.firstWithRel(LicenseRel.publication.val) == null) {
    throw Exception(
        LcpError.errorDescription(LcpErrorCase.publicationLinkNotFound));
  }
  // TODO What to do if user or rights is null? Can it happen?
  return LicenseDocument._(id, issued, updated, provider, encryption, links,
      rights!, user!, signature, jsonObject, text, data);
}