View Javadoc
1   /*
2    * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
3    * Copyright (C) 2010  Mickael Guessant
4    *
5    * This program is free software; you can redistribute it and/or
6    * modify it under the terms of the GNU General Public License
7    * as published by the Free Software Foundation; either version 2
8    * of the License, or (at your option) any later version.
9    *
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with this program; if not, write to the Free Software
17   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18   */
19  package davmail.exchange;
20  
21  import davmail.Settings;
22  import davmail.util.StringUtil;
23  import org.apache.log4j.Logger;
24  
25  import java.io.*;
26  import java.nio.charset.StandardCharsets;
27  import java.text.ParseException;
28  import java.text.SimpleDateFormat;
29  import java.util.*;
30  
31  /**
32   * VCalendar object.
33   */
34  public class VCalendar extends VObject {
35      protected static final Logger LOGGER = Logger.getLogger(VCalendar.class);
36      protected VObject firstVevent;
37      protected VObject vTimezone;
38      protected String email;
39  
40      protected String startTimeZone;
41  
42      /**
43       * Set the start timezone from EWS event.
44       * @param startTimeZone Exchange timezone ID
45       */
46      public void setStartTimeZone(String startTimeZone) {
47          this.startTimeZone = startTimeZone;
48      }
49  
50      /**
51       * Create VCalendar object from reader;
52       *
53       * @param reader    stream reader
54       * @param email     current user email
55       * @param vTimezone user OWA timezone
56       * @throws IOException on error
57       */
58      public VCalendar(BufferedReader reader, String email, VObject vTimezone) throws IOException {
59          super(reader);
60          if (!"VCALENDAR".equals(type)) {
61              throw new IOException("Invalid type: " + type);
62          }
63          this.email = email;
64          // set OWA timezone information
65          if (this.vTimezone == null && vTimezone != null) {
66              setTimezone(vTimezone);
67          }
68      }
69  
70      /**
71       * Create VCalendar object from string;
72       *
73       * @param vCalendarBody item body
74       * @param email         current user email
75       * @param vTimezone     user OWA timezone
76       * @throws IOException on error
77       */
78      public VCalendar(String vCalendarBody, String email, VObject vTimezone) throws IOException {
79          this(new ICSBufferedReader(new StringReader(vCalendarBody)), email, vTimezone);
80      }
81  
82      /**
83       * Create VCalendar object from string;
84       *
85       * @param vCalendarContent item content
86       * @param email            current user email
87       * @param vTimezone        user OWA timezone
88       * @throws IOException on error
89       */
90      public VCalendar(byte[] vCalendarContent, String email, VObject vTimezone) throws IOException {
91          this(new ICSBufferedReader(new InputStreamReader(new ByteArrayInputStream(vCalendarContent), StandardCharsets.UTF_8)), email, vTimezone);
92      }
93  
94      /**
95       * Empty constructor
96       */
97      public VCalendar() {
98          type = "VCALENDAR";
99      }
100 
101     /**
102      * Set timezone on vObject
103      *
104      * @param vTimezone timezone object
105      */
106     public void setTimezone(VObject vTimezone) {
107         if (vObjects == null) {
108             addVObject(vTimezone);
109         } else {
110             vObjects.add(0, vTimezone);
111         }
112         this.vTimezone = vTimezone;
113     }
114 
115     @Override
116     public void addVObject(VObject vObject) {
117         if (firstVevent == null && ("VEVENT".equals(vObject.type) || "VTODO".equals(vObject.type))) {
118             firstVevent = vObject;
119         }
120         if ("VTIMEZONE".equals(vObject.type)) {
121             if (vTimezone == null) {
122                 vTimezone = vObject;
123             } else if (vTimezone.getPropertyValue("TZID").equals(vObject.getPropertyValue("TZID"))){
124                 // drop duplicate TZID definition (Korganizer bug)
125                 vObject = null;
126             }
127         }
128         if (vObject != null) {
129             super.addVObject(vObject);
130         }
131     }
132 
133     protected boolean isAllDay(VObject vObject) {
134         VProperty dtstart = vObject.getProperty("DTSTART");
135         return dtstart != null && dtstart.hasParam("VALUE", "DATE");
136     }
137 
138     protected boolean isCdoAllDay(VObject vObject) {
139         return "TRUE".equals(vObject.getPropertyValue("X-MICROSOFT-CDO-ALLDAYEVENT"));
140     }
141 
142     /**
143      * Check if vCalendar is CDO allday.
144      *
145      * @return true if vCalendar has X-MICROSOFT-CDO-ALLDAYEVENT property set to TRUE
146      */
147     public boolean isCdoAllDay() {
148         return firstVevent != null && isCdoAllDay(firstVevent);
149     }
150 
151     /**
152      * Get email from property value.
153      *
154      * @param property property
155      * @return email value
156      */
157     public String getEmailValue(VProperty property) {
158         if (property == null) {
159             return null;
160         }
161         String propertyValue = property.getValue();
162         if (propertyValue != null && (propertyValue.startsWith("MAILTO:") || propertyValue.startsWith("mailto:"))) {
163             return propertyValue.substring(7);
164         } else {
165             return propertyValue;
166         }
167     }
168 
169     protected String getMethod() {
170         return getPropertyValue("METHOD");
171     }
172 
173     protected void fixVCalendar(boolean fromServer) {
174         // set iCal 4 global X-CALENDARSERVER-ACCESS from CLASS
175         if (fromServer) {
176             setPropertyValue("X-CALENDARSERVER-ACCESS", getCalendarServerAccess());
177         }
178 
179         if (fromServer && "PUBLISH".equals(getPropertyValue("METHOD"))) {
180             removeProperty("METHOD");
181         }
182 
183         // iCal 4 global X-CALENDARSERVER-ACCESS
184         String calendarServerAccess = getPropertyValue("X-CALENDARSERVER-ACCESS");
185 
186         // fix method from iPhone
187         if (!fromServer && getPropertyValue("METHOD") == null) {
188             setPropertyValue("METHOD", "PUBLISH");
189         }
190 
191         // rename TZID for maximum iCal/iPhone compatibility
192         if (fromServer) {
193             // get current tzid
194             VObject vObject = vTimezone;
195             if (vObject != null) {
196                 String currentTzid = vObject.getPropertyValue("TZID");
197                 vObject.setPropertyValue("TZID", fixupTZID(currentTzid));
198             }
199         }
200 
201         if (!fromServer) {
202             fixTimezoneToServer();
203         }
204 
205         // iterate over vObjects
206         for (VObject vObject : vObjects) {
207             if (vObject.isVEvent()) {
208                 if (calendarServerAccess != null) {
209                     vObject.setPropertyValue("CLASS", getEventClass(calendarServerAccess));
210                     // iCal 3, get X-CALENDARSERVER-ACCESS from local VEVENT
211                 } else if (vObject.getPropertyValue("X-CALENDARSERVER-ACCESS") != null) {
212                     vObject.setPropertyValue("CLASS", getEventClass(vObject.getPropertyValue("X-CALENDARSERVER-ACCESS")));
213                 }
214                 if (fromServer) {
215                     // remove organizer line for event without attendees for iPhone
216                     if (vObject.getProperty("ATTENDEE") == null) {
217                         vObject.setPropertyValue("ORGANIZER", null);
218                     }
219                     // detect allday and update date properties
220                     if (isCdoAllDay(vObject)) {
221                         setClientAllday(vObject.getProperty("DTSTART"));
222                         setClientAllday(vObject.getProperty("DTEND"));
223                         setClientAllday(vObject.getProperty("RECURRENCE-ID"));
224                     }
225                     String cdoBusyStatus = vObject.getPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS");
226                     if (cdoBusyStatus != null) {
227                         // we set status only if it's tentative
228                         if ("TENTATIVE".equals(cdoBusyStatus)) {
229                             vObject.setPropertyValue("STATUS", "TENTATIVE");
230                         }
231                         // in all cases, we set the transparency (also called "show time as" in UI)
232                         vObject.setPropertyValue("TRANSP",
233                                 !"FREE".equals(cdoBusyStatus) ? "OPAQUE" : "TRANSPARENT");
234                     }
235 
236                     // Apple iCal doesn't understand this key, and it's entourage
237                     // specific (i.e. not needed by any caldav client): strip it out
238                     vObject.removeProperty("X-ENTOURAGE_UUID");
239 
240                     splitExDate(vObject);
241 
242                     // remove empty properties
243                     if ("".equals(vObject.getPropertyValue("LOCATION"))) {
244                         vObject.removeProperty("LOCATION");
245                     }
246                     if ("".equals(vObject.getPropertyValue("DESCRIPTION"))) {
247                         vObject.removeProperty("DESCRIPTION");
248                     }
249                     if ("".equals(vObject.getPropertyValue("CLASS"))) {
250                         vObject.removeProperty("CLASS");
251                     }
252                     // rename TZIDs
253                     VProperty dtStart = vObject.getProperty("DTSTART");
254                     if (dtStart != null && dtStart.getParam("TZID") != null) {
255                         dtStart.setParam("TZID", fixupTZID(dtStart.getParamValue("TZID")));
256                     }
257                     VProperty dtEnd = vObject.getProperty("DTEND");
258                     if (dtEnd != null && dtEnd.getParam("TZID") != null) {
259                         dtEnd.setParam("TZID", fixupTZID(dtEnd.getParamValue("TZID")));
260                     }
261                     VProperty recurrenceId = vObject.getProperty("RECURRENCE-ID");
262                     if (recurrenceId != null && recurrenceId.getParam("TZID") != null) {
263                         recurrenceId.setParam("TZID", fixupTZID(recurrenceId.getParamValue("TZID")));
264                     }
265                     VProperty exDate = vObject.getProperty("EXDATE");
266                     if (exDate != null && exDate.getParam("TZID") != null) {
267                         exDate.setParam("TZID", fixupTZID(exDate.getParamValue("TZID")));
268                     }
269                     // remove unsupported attachment reference
270                     if (vObject.getProperty("ATTACH") != null) {
271                         List<String> toRemoveValues = null;
272                         List<String> values = vObject.getProperty("ATTACH").getValues();
273                         for (String value : values) {
274                             if (value.contains("CID:")) {
275                                 if (toRemoveValues == null) {
276                                     toRemoveValues = new ArrayList<>();
277                                 }
278                                 toRemoveValues.add(value);
279                             }
280                         }
281                         if (toRemoveValues != null) {
282                             values.removeAll(toRemoveValues);
283                             if (values.isEmpty()) {
284                                 vObject.removeProperty("ATTACH");
285                             }
286                         }
287                     }
288                 } else {
289                     // from client to server
290 
291                     // set Exchange allday flag
292                     vObject.setPropertyValue("X-MICROSOFT-CDO-ALLDAYEVENT", isAllDay(vObject) ? "TRUE" : "FALSE");
293                     // set Exchange busy status from TRANSP property
294                     if (vObject.getPropertyValue("TRANSP") != null) {
295                         vObject.setPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS",
296                                 !"TRANSPARENT".equals(vObject.getPropertyValue("TRANSP")) ? "BUSY" : "FREE");
297                     }
298 
299                     if (isAllDay(vObject)) {
300                         // convert date values to outlook compatible values
301                         setServerAllday(vObject.getProperty("DTSTART"));
302                         setServerAllday(vObject.getProperty("DTEND"));
303                     } else {
304                         fixTzid(vObject.getProperty("DTSTART"));
305                         fixTzid(vObject.getProperty("DTEND"));
306                     }
307                 }
308 
309                 fixAttendees(vObject, fromServer);
310 
311                 fixAlarm(vObject, fromServer);
312             }
313         }
314 
315     }
316 
317     private String fixupTZID(String currentTzid) {
318         // fix TZID with \n (Exchange 2010 bug)
319         if (currentTzid != null && currentTzid.endsWith("\n")) {
320             currentTzid = currentTzid.substring(0, currentTzid.length() - 1);
321         }
322         if (currentTzid != null && currentTzid.indexOf(' ') >= 0) {
323             try {
324                 // map tzid from MIME content
325                 currentTzid = ResourceBundle.getBundle("timezones").getString(currentTzid);
326             } catch (MissingResourceException e) {
327                 // failover to event tzid
328                 if (startTimeZone != null) {
329                     try {
330                         currentTzid = ResourceBundle.getBundle("timezones").getString(startTimeZone);
331                         LOGGER.debug("Timezone " + currentTzid + " resolved via StartTimeZone fallback: " + startTimeZone);
332                     } catch (MissingResourceException e2) {
333                         LOGGER.debug("Timezone " + currentTzid + " not found in rename table, StartTimeZone " + startTimeZone + " also not found");
334                     }
335                 } else {
336                     LOGGER.debug("Timezone " + currentTzid + " not found in rename table");
337                 }
338             }
339         }
340         return currentTzid;
341     }
342 
343     private void fixTimezoneToServer() {
344         if (vTimezone != null && vTimezone.vObjects != null && vTimezone.vObjects.size() > 2) {
345             VObject standard = null;
346             VObject daylight = null;
347             for (VObject vObject : vTimezone.vObjects) {
348                 if ("STANDARD".equals(vObject.type)) {
349                     if (standard == null ||
350                             (vObject.getPropertyValue("DTSTART").compareTo(standard.getPropertyValue("DTSTART")) > 0)) {
351                         standard = vObject;
352                     }
353                 }
354                 if ("DAYLIGHT".equals(vObject.type)) {
355                     if (daylight == null ||
356                             (vObject.getPropertyValue("DTSTART").compareTo(daylight.getPropertyValue("DTSTART")) > 0)) {
357                         daylight = vObject;
358                     }
359                 }
360             }
361             vTimezone.vObjects.clear();
362             vTimezone.vObjects.add(standard);
363             vTimezone.vObjects.add(daylight);
364         }
365         // fix 3569922: quick workaround for broken Israeli Timezone issue
366         if (vTimezone != null && vTimezone.vObjects != null) {
367             for (VObject vObject : vTimezone.vObjects) {
368                 VProperty rrule = vObject.getProperty("RRULE");
369                 if (rrule != null && rrule.getValues().size() == 3 && "BYDAY=-2SU".equals(rrule.getValues().get(1))) {
370                     rrule.getValues().set(1, "BYDAY=4SU");
371                 }
372                 // Fix 555 another broken Israeli timezone
373                 if (rrule != null && rrule.getValues().size() == 4 && "BYDAY=FR".equals(rrule.getValues().get(1))
374                         && "BYMONTHDAY=23,24,25,26,27,28,29".equals(rrule.getValues().get(2))) {
375                     rrule.getValues().set(1, "BYDAY=-1FR");
376                     rrule.getValues().remove(2);
377                 }
378             }
379         }
380 
381         // validate RRULE - COUNT and UNTIL may not occur at once
382         if (vTimezone != null && vTimezone.vObjects != null) {
383             for (VObject vObject : vTimezone.vObjects) {
384                 VProperty rrule = vObject.getProperty("RRULE");
385                 if (rrule != null) {
386                     Map<String, String> rruleValueMap = rrule.getValuesAsMap();
387                     if (rruleValueMap.containsKey("UNTIL") && rruleValueMap.containsKey("COUNT")) {
388                         rrule.removeValue("UNTIL="+rruleValueMap.get("UNTIL"));
389                     }
390                 }
391             }
392         }
393         // end validate RRULE
394 
395         // convert TZID to Exchange time zone id
396         ResourceBundle tzBundle = ResourceBundle.getBundle("exchtimezones");
397         ResourceBundle tzidsBundle = ResourceBundle.getBundle("stdtimezones");
398         for (VObject vObject : vObjects) {
399             if (vObject.isVTimezone()) {
400                 String tzid = vObject.getPropertyValue("TZID");
401                 // check if tzid is a valid Exchange timezone id
402                 if (!tzidsBundle.containsKey(tzid)) {
403                     String exchangeTzid = null;
404                     // try to convert standard timezone id to Exchange timezone id
405                     if (tzBundle.containsKey(tzid)) {
406                         exchangeTzid = tzBundle.getString(tzid);
407                     } else {
408                         // failover, map to a close timezone
409                         for (VObject tzDefinition : vObject.vObjects) {
410                             if ("STANDARD".equals(tzDefinition.type)) {
411                                 exchangeTzid = getTzidFromOffset(tzDefinition.getPropertyValue("TZOFFSETTO"));
412                             }
413                         }
414                     }
415                     if (exchangeTzid != null) {
416                         vObject.setPropertyValue("TZID", exchangeTzid);
417                         // also replace TZID in properties
418                         updateTzid(tzid, exchangeTzid);
419                     }
420                 }
421             }
422         }
423     }
424 
425     protected void updateTzid(String tzid, String newTzid) {
426         for (VObject vObject : vObjects) {
427             if (vObject.isVEvent() || vObject.isVTodo()) {
428                 for (VProperty vProperty : vObject.properties) {
429                     if (tzid.equalsIgnoreCase(vProperty.getParamValue("TZID"))) {
430                         vProperty.setParam("TZID", newTzid);
431                     }
432                 }
433             }
434         }
435     }
436 
437     private void fixTzid(VProperty property) {
438         if (property != null && !property.hasParam("TZID")) {
439             property.addParam("TZID", vTimezone.getPropertyValue("TZID"));
440         }
441     }
442 
443     protected void splitExDate(VObject vObject) {
444         List<VProperty> exDateProperties = vObject.getProperties("EXDATE");
445         if (exDateProperties != null) {
446             for (VProperty property : exDateProperties) {
447                 String value = property.getValue();
448                 if (value.indexOf(',') >= 0) {
449                     // split property
450                     vObject.removeProperty(property);
451                     for (String singleValue : value.split(",")) {
452                         VProperty singleProperty = new VProperty("EXDATE", singleValue);
453                         singleProperty.setParams(property.getParams());
454                         vObject.addProperty(singleProperty);
455                     }
456                 }
457             }
458         }
459     }
460 
461     protected void setServerAllday(VProperty property) {
462         if (vTimezone != null) {
463             // set TZID param
464             if (!property.hasParam("TZID")) {
465                 property.addParam("TZID", vTimezone.getPropertyValue("TZID"));
466             }
467             // remove VALUE
468             property.removeParam("VALUE");
469             String value = property.getValue();
470             if (value.length() != 8) {
471                 LOGGER.warn("Invalid date value in allday event: " + value);
472             }
473             property.setValue(property.getValue() + "T000000");
474         }
475     }
476 
477     protected void setClientAllday(VProperty property) {
478         if (property != null) {
479             // set VALUE=DATE param
480             if (!property.hasParam("VALUE")) {
481                 property.addParam("VALUE", "DATE");
482             }
483             // remove TZID
484             property.removeParam("TZID");
485             String value = property.getValue();
486             if (value.length() != 8) {
487                 // try to convert datetime value to date value
488                 try {
489                     Calendar calendar = Calendar.getInstance();
490                     SimpleDateFormat dateParser = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
491                     calendar.setTime(dateParser.parse(value));
492                     calendar.add(Calendar.HOUR_OF_DAY, 12);
493                     SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
494                     value = dateFormatter.format(calendar.getTime());
495                 } catch (ParseException e) {
496                     LOGGER.warn("Invalid date value in allday event: " + value);
497                 }
498             }
499             property.setValue(value);
500         }
501     }
502 
503     protected void fixAlarm(VObject vObject, boolean fromServer) {
504         if (vObject.vObjects != null) {
505             if (Settings.getBooleanProperty("davmail.caldavDisableReminders", false)) {
506                 ArrayList<VObject> vAlarms = null;
507                 for (VObject vAlarm : vObject.vObjects) {
508                     if ("VALARM".equals(vAlarm.type)) {
509                         if (vAlarms == null) {
510                             vAlarms = new ArrayList<>();
511                         }
512                         vAlarms.add(vAlarm);
513                     }
514                 }
515                 // remove all vAlarms
516                 if (vAlarms != null) {
517                     for (VObject vAlarm : vAlarms) {
518                         vObject.vObjects.remove(vAlarm);
519                     }
520                 }
521 
522             } else {
523                 for (VObject vAlarm : vObject.vObjects) {
524                     if ("VALARM".equals(vAlarm.type)) {
525                         // Exchange may return invalid empty duration P, default to 0 minutes
526                         String trigger = vAlarm.getPropertyValue("TRIGGER");
527                         if (fromServer && trigger != null && "P".equals(trigger)) {
528                             LOGGER.debug("Fixing invalid empty duration trigger to -PT0M");
529                             vAlarm.setPropertyValue("TRIGGER", "-PT0M");
530                         }
531                         String action = vAlarm.getPropertyValue("ACTION");
532                         if (fromServer && "DISPLAY".equals(action)
533                                 // convert DISPLAY to AUDIO only if user defined an alarm sound
534                                 && Settings.getProperty("davmail.caldavAlarmSound") != null) {
535                             // Convert alarm to audio for iCal
536                             vAlarm.setPropertyValue("ACTION", "AUDIO");
537 
538                             if (vAlarm.getPropertyValue("ATTACH") == null) {
539                                 // Add defined sound into the audio alarm
540                                 VProperty vProperty = new VProperty("ATTACH", Settings.getProperty("davmail.caldavAlarmSound"));
541                                 vProperty.addParam("VALUE", "URI");
542                                 vAlarm.addProperty(vProperty);
543                             }
544 
545                         } else if (!fromServer && "AUDIO".equals(action)) {
546                             // Use the alarm action that exchange (and blackberry) understand
547                             // (exchange and blackberry don't understand audio actions)
548                             vAlarm.setPropertyValue("ACTION", "DISPLAY");
549                         }
550                     }
551                 }
552             }
553         }
554     }
555 
556     /**
557      * Replace iCal4 (Snow Leopard) principal paths with mailto expression
558      *
559      * @param value attendee value or ics line
560      * @return fixed value
561      */
562     protected static String replaceIcal4Principal(String value) {
563         final String principalPrefix = "/principals/__uuids__/";
564         final String principalAt = "__AT__";
565         if (value != null && value.contains(principalPrefix) && value.contains(principalAt)) {
566             return "mailto:" +
567                     value.substring(value.indexOf(principalPrefix) + principalPrefix.length(), value.indexOf(principalAt)) +
568                     "@" +
569                     value.substring(value.indexOf(principalAt) + principalAt.length(), value.length() - 1);
570         } else {
571             return value;
572         }
573     }
574 
575     private void fixAttendees(VObject vObject, boolean fromServer) {
576         if (vObject.properties != null) {
577             for (VProperty property : vObject.properties) {
578                 if ("ATTENDEE".equalsIgnoreCase(property.getKey())) {
579                     if (fromServer) {
580                         // If this is coming from the server, strip out RSVP for this
581                         // user as an attendee where the partstat is something other
582                         // than PARTSTAT=NEEDS-ACTION since the RSVP confuses iCal4 into
583                         // thinking the attendee has not replied
584                         if (isCurrentUser(property) && property.hasParam("RSVP", "TRUE")) {
585                             if (!"NEEDS-ACTION".equals(property.getParamValue("PARTSTAT"))) {
586                                 property.removeParam("RSVP");
587                             }
588                         }
589                     } else {
590                         property.setValue(replaceIcal4Principal(property.getValue()));
591                     }
592                 }
593 
594             }
595         }
596 
597     }
598 
599     private boolean isCurrentUser(VProperty property) {
600         return property.getValue() != null && property.getValue().equalsIgnoreCase("mailto:" + email);
601     }
602 
603     /**
604      * Return VTimezone object
605      *
606      * @return VTimezone
607      */
608     public VObject getVTimezone() {
609         return vTimezone;
610     }
611 
612     /**
613      * Convert X-CALENDARSERVER-ACCESS to CLASS.
614      * see <a href="http://svn.calendarserver.org/repository/calendarserver/CalendarServer/trunk/doc/Extensions/caldav-privateevents.txt">caldav-privateevents.txt</a>
615      *
616      * @param calendarServerAccess X-CALENDARSERVER-ACCESS value
617      * @return CLASS value
618      */
619     protected String getEventClass(String calendarServerAccess) {
620         if ("PRIVATE".equalsIgnoreCase(calendarServerAccess)) {
621             return "CONFIDENTIAL";
622         } else if ("CONFIDENTIAL".equalsIgnoreCase(calendarServerAccess) || "RESTRICTED".equalsIgnoreCase(calendarServerAccess)) {
623             return "PRIVATE";
624         } else {
625             return null;
626         }
627     }
628 
629     /**
630      * Convert CLASS to X-CALENDARSERVER-ACCESS.
631      * see <a href="http://svn.calendarserver.org/repository/calendarserver/CalendarServer/trunk/doc/Extensions/caldav-privateevents.txt">caldav-privateevents.txt</a>
632      *
633      * @return X-CALENDARSERVER-ACCESS value
634      */
635     protected String getCalendarServerAccess() {
636         String eventClass = getFirstVeventPropertyValue("CLASS");
637         if ("PRIVATE".equalsIgnoreCase(eventClass)) {
638             return "CONFIDENTIAL";
639         } else if ("CONFIDENTIAL".equalsIgnoreCase(eventClass)) {
640             return "PRIVATE";
641         } else {
642             return null;
643         }
644     }
645 
646     /**
647      * Get property value from first VEVENT in VCALENDAR.
648      *
649      * @param name property name
650      * @return property value
651      */
652     public String getFirstVeventPropertyValue(String name) {
653         if (firstVevent == null) {
654             return null;
655         } else {
656             return firstVevent.getPropertyValue(name);
657         }
658     }
659 
660     protected VProperty getFirstVeventProperty(String name) {
661         if (firstVevent == null) {
662             return null;
663         } else {
664             return firstVevent.getProperty(name);
665         }
666     }
667 
668 
669     /**
670      * Get properties by name from the first VEVENT.
671      *
672      * @param name property name
673      * @return properties
674      */
675     public List<VProperty> getFirstVeventProperties(String name) {
676         if (firstVevent == null) {
677             return null;
678         } else {
679             return firstVevent.getProperties(name);
680         }
681     }
682 
683     /**
684      * Remove VAlarm from VCalendar.
685      */
686     public void removeVAlarm() {
687         if (vObjects != null) {
688             for (VObject vObject : vObjects) {
689                 if ("VEVENT".equals(vObject.type)) {
690                     // As VALARM is the only possible inner object, just drop all objects
691                     if (vObject.vObjects != null) {
692                         vObject.vObjects = null;
693                     }
694                 }
695             }
696         }
697     }
698 
699     /**
700      * Check if VCalendar has a VALARM item.
701      *
702      * @return true if VCalendar has a VALARM
703      */
704     public boolean hasVAlarm() {
705         if (vObjects != null) {
706             for (VObject vObject : vObjects) {
707                 if ("VEVENT".equals(vObject.type)) {
708                     if (vObject.vObjects != null && !vObject.vObjects.isEmpty()) {
709                         return vObject.vObjects.get(0).isVAlarm();
710                     }
711                 }
712             }
713         }
714         return false;
715     }
716 
717     public String getReminderMinutesBeforeStart() {
718         String result = "0";
719         if (vObjects != null) {
720             for (VObject vObject : vObjects) {
721                 if (vObject.vObjects != null && !vObject.vObjects.isEmpty() &&
722                         vObject.vObjects.get(0).isVAlarm()) {
723                     String trigger = vObject.vObjects.get(0).getPropertyValue("TRIGGER");
724                     if (trigger != null) {
725                         if (trigger.startsWith("-PT") && trigger.endsWith("M")) {
726                             result = trigger.substring(3, trigger.length() - 1);
727                         } else if (trigger.startsWith("-PT") && trigger.endsWith("H")) {
728                             result = trigger.substring(3, trigger.length() - 1);
729                             // convert to minutes
730                             result = String.valueOf(Integer.parseInt(result) * 60);
731                         } else if (trigger.startsWith("-P") && trigger.endsWith("D")) {
732                             result = trigger.substring(2, trigger.length() - 1);
733                             // convert to minutes
734                             result = String.valueOf(Integer.parseInt(result) * 60 * 24);
735                         } else if (trigger.startsWith("-P") && trigger.endsWith("W")) {
736                             result = trigger.substring(2, trigger.length() - 1);
737                             // convert to minutes
738                             result = String.valueOf(Integer.parseInt(result) * 60 * 24 * 7);
739                         }
740                     }
741                 }
742             }
743         }
744         return result;
745     }
746 
747 
748     /**
749      * Check if this VCalendar is a meeting.
750      *
751      * @return true if this VCalendar has attendees
752      */
753     public boolean isMeeting() {
754         return getFirstVeventProperty("ATTENDEE") != null;
755     }
756 
757     /**
758      * Check if current user is meeting organizer.
759      *
760      * @return true it user email matched organizer email
761      */
762     public boolean isMeetingOrganizer() {
763         return email.equalsIgnoreCase(getEmailValue(getFirstVeventProperty("ORGANIZER")));
764     }
765 
766     /**
767      * Set property value on first VEVENT.
768      *
769      * @param propertyName  property name
770      * @param propertyValue property value
771      */
772     public void setFirstVeventPropertyValue(String propertyName, String propertyValue) {
773         firstVevent.setPropertyValue(propertyName, propertyValue);
774     }
775 
776     /**
777      * Add property on first VEVENT.
778      *
779      * @param vProperty property object
780      */
781     public void addFirstVeventProperty(VProperty vProperty) {
782         firstVevent.addProperty(vProperty);
783     }
784 
785     /**
786      * Check if this item is a VTODO item
787      *
788      * @return true with VTODO items
789      */
790     public boolean isTodo() {
791         return firstVevent != null && "VTODO".equals(firstVevent.type);
792     }
793 
794     /**
795      * Return calendar mailbox address
796      * @return calendar email
797      */
798     public String getCalendarEmail() {
799         return email;
800     }
801 
802     public void setEmail(String email) {
803         this.email = email;
804     }
805 
806     /**
807      * VCalendar recipients for notifications
808      */
809     public static class Recipients {
810         /**
811          * attendee list
812          */
813         public String attendees;
814 
815         /**
816          * optional attendee list
817          */
818         public String optionalAttendees;
819 
820         /**
821          * vCalendar organizer
822          */
823         public String organizer;
824     }
825 
826     /**
827      * Build recipients value for VCalendar.
828      *
829      * @param isNotification if true, filter recipients that should receive meeting notifications
830      * @return notification/event recipients
831      */
832     public Recipients getRecipients(boolean isNotification) {
833 
834         HashSet<String> attendees = new HashSet<>();
835         HashSet<String> optionalAttendees = new HashSet<>();
836 
837         // get recipients from first VEVENT
838         List<VProperty> attendeeProperties = getFirstVeventProperties("ATTENDEE");
839         if (attendeeProperties != null) {
840             for (VProperty property : attendeeProperties) {
841                 // exclude current user and invalid values from recipients
842                 // also exclude no action attendees
843                 String attendeeEmail = getEmailValue(property);
844                 if (!email.equalsIgnoreCase(attendeeEmail) && attendeeEmail != null && attendeeEmail.indexOf('@') >= 0
845                         // return all attendees for user calendar folder, filter for notifications
846                         && (!isNotification
847                         // notify attendee if reply explicitly requested
848                         || (property.hasParam("RSVP", "TRUE"))
849                         || (
850                         // workaround for iCal bug: do not notify if reply explicitly not requested
851                         !(property.hasParam("RSVP", "FALSE")) &&
852                                 ((property.hasParam("PARTSTAT", "NEEDS-ACTION")
853                                         // need to include other PARTSTATs participants for CANCEL notifications
854                                         || property.hasParam("PARTSTAT", "ACCEPTED")
855                                         || property.hasParam("PARTSTAT", "DECLINED")
856                                         || property.hasParam("PARTSTAT", "TENTATIVE")))
857                 ))) {
858                     if (property.hasParam("ROLE", "OPT-PARTICIPANT")) {
859                         optionalAttendees.add(attendeeEmail);
860                     } else {
861                         attendees.add(attendeeEmail);
862                     }
863                 }
864             }
865         }
866         Recipients recipients = new Recipients();
867         recipients.organizer = getEmailValue(getFirstVeventProperty("ORGANIZER"));
868         recipients.attendees = StringUtil.join(attendees, ", ");
869         recipients.optionalAttendees = StringUtil.join(optionalAttendees, ", ");
870         return recipients;
871     }
872 
873     public String getAttendeeStatus() {
874         String attendeeStatus = null;
875         // iterate over all Vevents to detect meeting response
876         for (VObject vObject : vObjects) {
877             if ("VEVENT".equals(vObject.type)) {
878                 List<VProperty> attendeeProperties = vObject.getProperties("ATTENDEE");
879                 if (attendeeProperties != null) {
880                     for (VProperty property : attendeeProperties) {
881                         if (email.equalsIgnoreCase(getEmailValue(property))) {
882                             String status = property.getParamValue("PARTSTAT");
883                             if (!"NEEDS-ACTION".equals(status)) {
884                                 attendeeStatus = status;
885                             }
886                         }
887                     }
888                 }
889             }
890         }
891         return attendeeStatus;
892     }
893 
894     public HashMap<String, String> getAttendeeOccurrenceStatusMap() throws IOException {
895         HashMap<String, String> attendeeStatusMap = new HashMap<>();
896         // iterate over all Vevents to detect meeting response
897         for (VObject vObject : vObjects) {
898             if ("VEVENT".equals(vObject.type)) {
899                 List<VProperty> attendeeProperties = vObject.getProperties("ATTENDEE");
900                 if (attendeeProperties != null) {
901                     for (VProperty property : attendeeProperties) {
902                         if (email.equalsIgnoreCase(getEmailValue(property))) {
903                             String status = property.getParamValue("PARTSTAT");
904                             if (!"NEEDS-ACTION".equals(status)) {
905                                 VProperty recurrenceIdProperty = vObject.getProperty("RECURRENCE-ID");
906                                 if (recurrenceIdProperty != null) {
907                                     String originalDateZulu = convertCalendarDateToExchangeZulu(
908                                             recurrenceIdProperty.getValue(), recurrenceIdProperty.getParamValue("TZID"));
909                                     attendeeStatusMap.put(originalDateZulu, status);
910                                     LOGGER.debug("Attendee status for " + email + " at " + originalDateZulu + ": " + status);
911                                 } else {
912                                     // this is master vEvent
913                                     attendeeStatusMap.put("master", status);
914                                     LOGGER.debug("Attendee status for " + email + " on master event: " + status);
915                                 }
916                             }
917                         }
918                     }
919                 }
920             }
921         }
922         return attendeeStatusMap;
923     }
924 
925     public boolean isOrganizer() {
926         String organizer = getEmailValue(getFirstVeventProperty("ORGANIZER"));
927         return email.equalsIgnoreCase(organizer);
928     }
929 
930     /**
931      * Get first VEvent
932      *
933      * @return first VEvent
934      */
935     public VObject getFirstVevent() {
936         return firstVevent;
937     }
938 
939     /**
940      * Get recurring VCalendar occurrence exceptions.
941      *
942      * @return event occurrences
943      */
944     public List<VObject> getModifiedOccurrences() {
945         boolean first = true;
946         ArrayList<VObject> results = new ArrayList<>();
947         for (VObject vObject : vObjects) {
948             if ("VEVENT".equals(vObject.type)) {
949                 if (first) {
950                     first = false;
951                 } else {
952                     results.add(vObject);
953                 }
954             }
955         }
956         return results;
957     }
958 
959     /**
960      * Remove recurring VCalendar occurrence exceptions.
961      */
962     public void removeModifiedOccurrences() {
963         vObjects.removeAll(getModifiedOccurrences());
964     }
965 
966     public TimeZone getStandardTimezoneId(String tzid) {
967         String convertedTzid;
968         // convert Exchange TZID to standard timezone
969         try {
970             convertedTzid = ResourceBundle.getBundle("timezones").getString(tzid);
971         } catch (MissingResourceException e) {
972             convertedTzid = tzid;
973             // failover: detect timezone from offset
974             VObject vTimezone = getVTimezone();
975             for (VObject tzDefinition : vTimezone.vObjects) {
976                 if ("STANDARD".equals(tzDefinition.type)) {
977                     convertedTzid = getTzidFromOffset(tzDefinition.getPropertyValue("TZOFFSETTO"));
978                 }
979             }
980             convertedTzid = ResourceBundle.getBundle("timezones").getString(convertedTzid);
981         }
982         return TimeZone.getTimeZone(convertedTzid);
983 
984     }
985 
986     private String getTzidFromOffset(String tzOffset) {
987         if (tzOffset == null) {
988             return null;
989         } else if (tzOffset.length() == 7) {
990             tzOffset = tzOffset.substring(0, 5);
991         }
992         return ResourceBundle.getBundle("tzoffsettimezones").getString(tzOffset);
993     }
994 
995     public String convertCalendarDateToExchangeZulu(String vcalendarDateValue, String tzid) throws IOException {
996         String zuluDateValue = null;
997         TimeZone timeZone;
998         if (tzid == null) {
999             timeZone = ExchangeSession.GMT_TIMEZONE;
1000         } else {
1001             timeZone = getStandardTimezoneId(tzid);
1002         }
1003         if (vcalendarDateValue != null) {
1004             try {
1005                 SimpleDateFormat dateParser;
1006                 if (vcalendarDateValue.length() == 8) {
1007                     dateParser = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
1008                 } else {
1009                     dateParser = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH);
1010                 }
1011                 if (vcalendarDateValue.endsWith("Z")) {
1012                     // date value is Zulu, ignore provided timezone
1013                     dateParser.setTimeZone(TimeZone.getTimeZone("UTC"));
1014                 } else {
1015                     dateParser.setTimeZone(timeZone);
1016                 }
1017                 dateParser.setTimeZone(timeZone);
1018                 SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
1019                 dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE);
1020                 zuluDateValue = dateFormatter.format(dateParser.parse(vcalendarDateValue));
1021             } catch (ParseException e) {
1022                 throw new IOException("Invalid date " + vcalendarDateValue + " with tzid " + tzid);
1023             }
1024         }
1025         return zuluDateValue;
1026     }
1027 
1028     /**
1029      * Convert date format, keep timezone.
1030      * @param vcalendarDateValue input date in ics format
1031      * @param tzid ics timezone id
1032      * @return converted date
1033      * @throws IOException on error
1034      */
1035     public String convertCalendarDateToGraph(String vcalendarDateValue, String tzid) throws IOException {
1036         String graphDateValue = null;
1037         TimeZone timeZone;
1038         if (tzid == null) {
1039             timeZone = ExchangeSession.GMT_TIMEZONE;
1040         } else {
1041             timeZone = getStandardTimezoneId(tzid);
1042         }
1043         if (vcalendarDateValue != null) {
1044             try {
1045                 SimpleDateFormat dateParser;
1046                 if (vcalendarDateValue.length() == 8) {
1047                     dateParser = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
1048                 } else {
1049                     dateParser = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH);
1050                 }
1051                 dateParser.setTimeZone(timeZone);
1052                 SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
1053                 dateFormatter.setTimeZone(timeZone);
1054                 graphDateValue = dateFormatter.format(dateParser.parse(vcalendarDateValue));
1055             } catch (ParseException e) {
1056                 throw new IOException("Invalid date " + vcalendarDateValue + " with tzid " + tzid);
1057             }
1058         }
1059         return graphDateValue;
1060     }
1061 
1062 }