serializeICal function

String serializeICal(
  1. List<EventInput> inputs, {
  2. String prodId = '-//DzCalendar//EN',
  3. String? name,
  4. Instant? stamp,
  5. bool vtimezone = true,
})

Writes inputs as an iCalendar text (CRLF, lines folded at 75 octets). Series keep their rules, EXDATEs and RDATEs; an override (seriesId + recurrenceId) is written under its series' UID with a RECURRENCE-ID.

stamp: the DTSTAMP of every event (default: now). vtimezone: a VTIMEZONE for each zone used (RFC 5545 asks for one; Outlook needs it).

Implementation

String serializeICal(
  List<EventInput> inputs, {
  String prodId = '-//DzCalendar//EN',
  String? name,
  Instant? stamp,
  bool vtimezone = true,
}) {
  final lines = ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:$prodId', 'CALSCALE:GREGORIAN'];
  if (name != null) lines.add('X-WR-CALNAME:${escapeText(name)}');
  final stampText = _utcText(stamp ?? Instant.fromEpochMilliseconds(DateTime.now().millisecondsSinceEpoch));
  final zones = <String, ({int from, int to})>{};
  final body = <String>[];

  for (final e in inputs) {
    final start = _valueOf(e.start);
    if (start == null) continue;
    final end = _valueOf(e.end);
    final out = ['BEGIN:VEVENT'];
    final uid = e.seriesId != null && e.recurrenceId != null ? e.seriesId : e.id;
    if (uid != null) out.add('UID:$uid');
    out.add('DTSTAMP:$stampText');
    // An all-day input given with times is written as dates.
    _Value asDate(_Value x) => e.allDay != true
        ? x
        : switch (x) {
            _Date() => x,
            _Instant(:final v) => _Date(v.wallAt(0).date),
            _Zoned(:final v) || _Floating(:final v) => _Date(v.date),
          };
    final used = <_Value>[];
    void write(String name, _Value? x) {
      if (x == null) return;
      final y = asDate(x);
      used.add(y);
      out.add(_dateLine(name, y));
    }

    write('DTSTART', start);
    if (end != null) {
      write('DTEND', end);
    } else if (e.duration != null) {
      final d = IsoDuration.tryFrom(e.duration);
      if (d != null) out.add('DURATION:$d');
    }
    if (e.recurrenceId != null) write('RECURRENCE-ID', _valueOf(e.recurrenceId));
    final rrule = e.rrule;
    final rules = switch (rrule) {
      String() => [rrule],
      List<Object?>() => [for (final r in rrule) '$r'],
      _ => const <String>[],
    };
    for (final r in rules) {
      out.add('RRULE:${r.replaceFirst(_rrulePrefix, '')}');
    }
    for (final x in e.exdate ?? const <Object?>[]) {
      write('EXDATE', _valueOf(x));
    }
    for (final x in e.rdate ?? const <Object?>[]) {
      write('RDATE', _valueOf(x));
    }
    final title = e.title;
    if (title != null) out.add('SUMMARY:${escapeText(title)}');
    final status = e.status;
    if (status != null) out.add('STATUS:${status.name.toUpperCase()}');
    // A background (closed hours, a maintenance window) takes no one's time where it is imported.
    if (e.busy == false || (e.display == EventDisplay.background && e.busy != true)) out.add('TRANSP:TRANSPARENT');
    final url = e.url;
    if (url != null) out.add('URL:$url');
    final p = e.extendedProps ?? const <String, Object?>{};
    if (p['description'] case final String d) out.add('DESCRIPTION:${escapeText(d)}');
    if (p['location'] case final String l) out.add('LOCATION:${escapeText(l)}');
    if (p['categories'] case final List<Object?> c when c.isNotEmpty) {
      out.add('CATEGORIES:${c.map((x) => escapeText('$x')).join(',')}');
    }
    if (p['organizer'] case final Map<Object?, Object?> org) {
      final n = org['name'];
      final m = org['email'];
      final hasName = n is String && n.isNotEmpty;
      if (hasName || (m is String && m.isNotEmpty)) {
        out.add('ORGANIZER${hasName ? ';CN=${paramValue(n)}' : ''}:mailto:${m is String ? m : ''}');
      }
    }
    out.add('END:VEVENT');
    body.addAll(out);

    // An open series goes on: its zone's rules are written a few years ahead.
    final ahead = rrule != null && !_bounded.hasMatch(rules.join(',')) ? 5 : 1;
    for (final x in used) {
      if (x is! _Zoned) continue;
      final y = x.v.date.year;
      final span = zones[x.zone] ?? (from: y, to: y);
      zones[x.zone] = (from: span.from < y - 1 ? span.from : y - 1, to: span.to > y + ahead ? span.to : y + ahead);
    }
  }

  if (vtimezone) {
    for (final MapEntry(key: zone, value: span) in zones.entries) {
      lines.addAll(_vtimezone(zone, span.from, span.to));
    }
  }
  lines
    ..addAll(body)
    ..add('END:VCALENDAR');
  return lines.map(fold).join();
}