enableAppLinks method

String enableAppLinks(
  1. String xmlContent,
  2. List<String> domains
)

Enables App Links for specified domains by adding/updating an autoVerify intent-filter. Returns the updated XML content.

Implementation

String enableAppLinks(String xmlContent, List<String> domains) {
  final doc = XmlReader.parse(xmlContent);
  final activity = _findMainActivity(doc);

  // Look for an existing intent-filter with autoVerify="true"
  XmlElement? appLinkFilter;
  for (final child in activity.children) {
    if (child is XmlElement && child.name.local == 'intent-filter') {
      final autoVerify = _getAttributeValue(child, 'autoVerify');
      if (autoVerify == 'true') {
        appLinkFilter = child;
        break;
      }
    }
  }

  if (appLinkFilter == null) {
    // Create new App Link intent filter
    appLinkFilter = XmlElement(XmlName('intent-filter'), [
      XmlAttribute(XmlName('android:autoVerify'), 'true'),
    ], [
      XmlElement(XmlName('action'), [XmlAttribute(XmlName('android:name'), 'android.intent.action.VIEW')]),
      XmlElement(XmlName('category'), [XmlAttribute(XmlName('android:name'), 'android.intent.category.DEFAULT')]),
      XmlElement(XmlName('category'), [XmlAttribute(XmlName('android:name'), 'android.intent.category.BROWSABLE')]),
      XmlElement(XmlName('data'), [XmlAttribute(XmlName('android:scheme'), 'http')]),
      XmlElement(XmlName('data'), [XmlAttribute(XmlName('android:scheme'), 'https')]),
    ]);
    activity.children.add(appLinkFilter);
  }

  // Add missing domains as <data android:host="..." />
  final existingHosts = appLinkFilter.children
      .whereType<XmlElement>()
      .where((el) => el.name.local == 'data')
      .map((el) => _getAttributeValue(el, 'host'))
      .whereType<String>()
      .toSet();

  for (final domain in domains) {
    if (!existingHosts.contains(domain)) {
      appLinkFilter.children.add(
        XmlElement(XmlName('data'), [XmlAttribute(XmlName('android:host'), domain)]),
      );
    }
  }

  return XmlReader.serialize(doc);
}