icalendar.dart 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. class ICalendar {
  2. final List<ICalendarEvent> _events = [];
  3. void addEvent(
  4. {required String summary,
  5. required String description,
  6. required DateTime startTime,
  7. required DateTime endTime,
  8. required List<dynamic> attendees,
  9. bool allday = false}) {
  10. _events.add(
  11. ICalendarEvent(
  12. summary: summary,
  13. description: description,
  14. startTime: startTime,
  15. endTime: endTime,
  16. attendees: attendees,
  17. allday: allday),
  18. );
  19. }
  20. String serialize() {
  21. final dtstamp = DateTime.now();
  22. final buffer = StringBuffer();
  23. buffer.writeln('BEGIN:VCALENDAR');
  24. buffer.writeln('VERSION:2.0');
  25. buffer.writeln('PRODID:-//Your Organization//Your Product//EN');
  26. for (final event in _events) {
  27. buffer.writeln('BEGIN:VEVENT');
  28. buffer.writeln(
  29. 'UID:${DateTime.now().millisecondsSinceEpoch}-${event.hashCode}');
  30. buffer.writeln('DTSTAMP:${_formatDateTime(dtstamp)}');
  31. buffer.writeln(
  32. 'DTSTART:${event.allday ? _formatDate(event.startTime) : _formatDateTime(event.startTime)}');
  33. buffer.writeln(
  34. 'DTEND:${event.allday ? _formatDate(event.startTime.add(Duration(days: 1))) : _formatDateTime(event.endTime)}');
  35. buffer.writeln('SUMMARY:${event.summary}');
  36. buffer.writeln('DESCRIPTION:${event.description}');
  37. for (final attendee in event.attendees) {
  38. buffer.writeln(
  39. 'ATTENDEE;CN="${attendee.toString()}";ROLE=REQ-PARTICIPANT;RSVP=TRUE:mailto:test@me.com');
  40. }
  41. buffer.writeln('END:VEVENT');
  42. }
  43. buffer.writeln('END:VCALENDAR');
  44. return buffer.toString();
  45. }
  46. String _formatDateTime(DateTime dt) {
  47. return '${dt.toUtc().toString().replaceAll('-', '').replaceAll(':', '').replaceAll(' ', 'T').split('.')[0]}Z';
  48. }
  49. String _formatDate(DateTime dateTime) {
  50. // Extract year, month, and day from the DateTime object
  51. String year = dateTime.year.toString().padLeft(4, '0');
  52. String month = dateTime.month.toString().padLeft(2, '0');
  53. String day = dateTime.day.toString().padLeft(2, '0');
  54. // Combine into the YYYYMMDD format
  55. return '$year$month$day';
  56. }
  57. }
  58. class ICalendarEvent {
  59. final String summary;
  60. final String description;
  61. final DateTime startTime;
  62. final DateTime endTime;
  63. final List<dynamic> attendees;
  64. final bool allday;
  65. ICalendarEvent({
  66. required this.summary,
  67. required this.description,
  68. required this.startTime,
  69. required this.endTime,
  70. required this.attendees,
  71. this.allday = false,
  72. });
  73. }