LegalDocumentData.fromSources constructor

LegalDocumentData.fromSources({
  1. String? metadataJson,
  2. required String privacyPolicyUrl,
  3. String fallbackAppName = '',
  4. String fallbackContactEmail = '',
  5. String fallbackSiteUrl = '',
})

Implementation

factory LegalDocumentData.fromSources({
  String? metadataJson,
  required String privacyPolicyUrl,
  String fallbackAppName = '',
  String fallbackContactEmail = '',
  String fallbackSiteUrl = '',
}) {
  final privacy = _canonicalHttps(privacyPolicyUrl);
  final validPrivacy =
      privacy != null &&
      (privacy.path == '/politica-de-privacidad/' ||
          privacy.path == '/politica-de-privacidad');
  // Match the web generator: an optional invalid canonical falls back to the
  // configured site, which must independently pass the same HTTPS checks.
  final site = validPrivacy ? privacy : _canonicalHttps(fallbackSiteUrl);
  if (site == null) throw const FormatException('Missing legal site URL');
  String name;
  String controller;
  String email;
  String date;
  var color = 0xff111c41;
  if (metadataJson == null) {
    name = fallbackAppName.trim();
    controller = name;
    email = fallbackContactEmail.trim();
    date = '';
  } else {
    final decoded = jsonDecode(metadataJson);
    if (decoded is! Map<String, dynamic>) {
      throw const FormatException('Invalid legal metadata');
    }
    String value(String key) =>
        decoded[key] is String ? (decoded[key] as String).trim() : '';
    controller = value('controllerName');
    // The product's public brand can differ from its legal controller.
    name = fallbackAppName.trim();
    if (name.isEmpty) name = value('appName');
    if (name.isEmpty) name = controller;
    email = value('privacyEmail');
    date = value('updatedAt');
    final parsedDate = DateTime.tryParse(date);
    if (!RegExp(r'^\d{4}-\d{2}-\d{2}$').hasMatch(date) ||
        parsedDate == null ||
        parsedDate.toIso8601String().substring(0, 10) != date) {
      throw const FormatException('Invalid legal revision date');
    }
    final hex = decoded['themeColor'] == null
        ? '#111c41'
        : value('themeColor');
    if (!RegExp(r'^#[a-fA-F0-9]{6}$').hasMatch(hex)) {
      throw const FormatException('Invalid legal theme color');
    }
    color = 0xff000000 | int.parse(hex.substring(1), radix: 16);
  }
  if (name.isEmpty ||
      controller.isEmpty ||
      !RegExp(
        r'^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$',
      ).hasMatch(email)) {
    throw const FormatException('Missing legal identity or contact');
  }
  return LegalDocumentData._(
    appName: name,
    controllerName: controller,
    contactEmail: email,
    updatedAt: date,
    themeColor: color,
    origin: site.replace(path: '/', query: null, fragment: null),
  );
}