3 /// Conversion routines for vevents (VCALENDAR, etc)
7 Copyright (C) 2006-2012, Net Direct Inc. (http://www.netdirect.ca/)
8 Copyright (C) 2010, Nicolas VIVIEN
9 Copyright (C) 2009, Dr J A Gow <J.A.Gow@wellfrazzled.com>
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 2 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20 See the GNU General Public License in the COPYING file at the
21 root directory of this project for more details.
36 namespace Barry
{ namespace Sync
{
38 //////////////////////////////////////////////////////////////////////////////
41 vCalendar::vCalendar(vTimeConverter
&vtc
)
47 vCalendar::~vCalendar()
54 const char *vCalendar::WeekDays
[] = { "SU", "MO", "TU", "WE", "TH", "FR", "SA" };
56 uint16_t vCalendar::GetWeekDayIndex(const char *dayname
)
58 for( int i
= 0; i
< 7; i
++ ) {
59 if( strcasecmp(dayname
, WeekDays
[i
]) == 0 )
65 void vCalendar::CheckUnsupportedArg(const ArgMapType
&args
,
66 const std::string
&name
)
68 if( args
.find(name
) != args
.end() ) {
69 barrylog("ERROR: recurrence rule contains " << name
<< ", unsupported by Barry. MIME conversion will be incorrect.");
70 barryverbose("Record data so far:\n" << m_BarryCal
);
74 uint16_t vCalendar::GetMonthWeekNumFromBYDAY(const std::string
& ByDay
)
76 return atoi(ByDay
.substr(0,ByDay
.length()-2).c_str());
79 uint16_t vCalendar::GetWeekDayIndexFromBYDAY(const std::string
& ByDay
)
81 return GetWeekDayIndex(ByDay
.substr(ByDay
.length()-2).c_str());
85 bool vCalendar::HasMultipleVEvents() const
88 b_VFormat
*format
= const_cast<b_VFormat
*>(Format());
89 GList
*attrs
= format
? b_vformat_get_attributes(format
) : 0;
90 for( ; attrs
; attrs
= attrs
->next
) {
91 b_VFormatAttribute
*attr
= (b_VFormatAttribute
*) attrs
->data
;
92 if( strcasecmp(b_vformat_attribute_get_name(attr
), "BEGIN") == 0 &&
93 strcasecmp(b_vformat_attribute_get_nth_value(attr
, 0), "VEVENT") == 0 )
101 void vCalendar::RecurToVCal()
103 using namespace Barry
;
105 Barry::Calendar
&cal
= m_BarryCal
;
110 vAttrPtr attr
= NewAttr("RRULE");
112 switch( cal
.RecurringType
)
114 case Calendar::Day
: // eg. every day
115 AddValue(attr
,"FREQ=DAILY");
118 case Calendar::MonthByDate
: // eg. every month on the 12th
120 AddValue(attr
,"FREQ=MONTHLY");
123 oss
<< "BYMONTHDAY=" << cal
.DayOfMonth
;
124 AddValue(attr
, oss
.str().c_str());
128 case Calendar::MonthByDay
: // eg. every month on 3rd Wed
129 // see: DayOfWeek and WeekOfMonth
130 AddValue(attr
, "FREQ=MONTHLY");
131 if( cal
.DayOfWeek
<= 6 ) { // DayOfWeek is unsigned
133 oss
<< "BYDAY=" << cal
.WeekOfMonth
<< WeekDays
[cal
.DayOfWeek
];
134 AddValue(attr
, oss
.str().c_str());
138 case Calendar::YearByDate
: // eg. every year on March 5
139 // see: DayOfMonth and MonthOfYear
140 AddValue(attr
, "FREQ=YEARLY");
143 oss
<< "BYMONTH=" << cal
.MonthOfYear
;
144 AddValue(attr
, oss
.str().c_str());
148 oss
<< "BYMONTHDAY=" << cal
.DayOfMonth
;
149 AddValue(attr
, oss
.str().c_str());
153 case Calendar::YearByDay
: // eg. every year on 3rd Wed of Jan
154 // see: DayOfWeek, WeekOfMonth, and
156 AddValue(attr
, "FREQ=YEARLY");
157 if( cal
.DayOfWeek
<= 6 ) { // DayOfWeek is unsigned
159 oss
<< "BYDAY=" << cal
.WeekOfMonth
<< WeekDays
[cal
.DayOfWeek
];
160 AddValue(attr
, oss
.str().c_str());
163 oss
<< "BYMONTH=" << cal
.MonthOfYear
;
164 AddValue(attr
, oss
.str().c_str());
168 case Calendar::Week
: // eg. every week on Mon and Fri
170 AddValue(attr
, "FREQ=WEEKLY");
174 for( int i
= 0, bm
= 1, cnt
= 0; i
< 7; i
++, bm
<<= 1 ) {
175 if( cal
.WeekDays
& bm
) {
182 AddValue(attr
, oss
.str().c_str());
187 throw ConvertError("Unknown RecurringType in Barry Calendar object");
190 // add some common parameters
191 if( cal
.Interval
> 1 ) {
193 oss
<< "INTERVAL=" << cal
.Interval
;
194 AddValue(attr
, oss
.str().c_str());
196 if( !cal
.Perpetual
) {
198 oss
<< "UNTIL=" << m_vtc
.unix2vtime(&cal
.RecurringEndTime
.Time
);
199 AddValue(attr
, oss
.str().c_str());
210 /// Note: interval can be used on all of these recurring types to
211 /// make it happen "every other time" or more, etc.
215 RecurringCodeType RecurringType;
216 uint16_t Interval; // must be >= 1
217 time_t RecurringEndTime; // only pertains if Recurring is true
218 // sets the date and time when
219 // recurrence of this appointment
220 // should no longer occur
221 // If a perpetual appointment, this
222 // is 0xFFFFFFFF in the low level data
223 // Instead, set the following flag.
224 bool Perpetual; // if true, this will always recur
225 uint16_t TimeZoneCode; // the time zone originally used
226 // for the recurrence data...
227 // seems to have little use, but
228 // set to your current time zone
231 uint16_t // recurring details, depending on type
236 unsigned char WeekDays; // bitmask, bit 0 = sunday
238 #define CAL_WD_SUN 0x01
239 #define CAL_WD_MON 0x02
240 #define CAL_WD_TUE 0x04
241 #define CAL_WD_WED 0x08
242 #define CAL_WD_THU 0x10
243 #define CAL_WD_FRI 0x20
244 #define CAL_WD_SAT 0x40
250 void vCalendar::RecurToBarryCal(vAttr
& rrule
, time_t starttime
)
252 using namespace Barry
;
254 Barry::Calendar
&cal
= m_BarryCal
;
255 // Trace trace("vCalendar::RecurToBarryCal");
256 std::map
<std::string
,unsigned char> pmap
;
257 pmap
["SU"] = CAL_WD_SUN
;
258 pmap
["MO"] = CAL_WD_MON
;
259 pmap
["TU"] = CAL_WD_TUE
;
260 pmap
["WE"] = CAL_WD_WED
;
261 pmap
["TH"] = CAL_WD_THU
;
262 pmap
["FR"] = CAL_WD_FRI
;
263 pmap
["SA"] = CAL_WD_SAT
;
267 unsigned int count
=0;
271 val
=rrule
.GetValue(i
++);
272 if(val
.length()==0) {
275 string n
=val
.substr(0,val
.find("="));
276 string v
=val
.substr(val
.find("=")+1);
278 // trace.logf("RecurToBarryCal: |%s|%s|",n.c_str(),v.c_str());
281 // now process the interval.
284 if(args
.find(string("INTERVAL"))!=args
.end()) {
285 int interval
= atoi(args
["INTERVAL"].c_str());
287 // force to at least 1, for math below
290 cal
.Interval
= interval
;
293 // default to 1, for the math below.
294 // RecurBase::Clear() does this for us as well, but
298 if(args
.find(string("UNTIL"))!=args
.end()) {
299 cal
.Perpetual
= FALSE
;
300 cal
.RecurringEndTime
.Time
= m_vtc
.vtime2unix(args
["UNTIL"].c_str());
301 if( cal
.RecurringEndTime
.Time
== (time_t)-1 ) {
302 // trace.logf("osync_time_vtime2unix() failed: UNTIL = %s, zoneoffset = %d", args["UNTIL"].c_str(), zoneoffset);
305 // if we do not also have COUNT, then we must be forerver
306 if(args
.find(string("COUNT"))==args
.end()) {
309 // we do have COUNT. This means we won't have UNTIL.
310 // So we need to process the RecurringEndTime from
311 // the current start date. Set the count level to
312 // something other than zero to indicate we need
313 // to process it as the exact end date will
314 // depend upon the frequency.
315 count
=atoi(args
["COUNT"].c_str());
317 throw std::runtime_error("Invalid COUNT in recurring rule: " + args
["COUNT"]);
322 // we need these if COUNT is true, or if we are a yearly job.
324 // TO-DO: we must process COUNT in terms of an end date if we have it.
326 // warn the user about unsupported arguments
327 CheckUnsupportedArg(args
, "BYSETPOS");// FIXME - theorectically supportable
328 CheckUnsupportedArg(args
, "BYYEARDAY");
329 CheckUnsupportedArg(args
, "BYWEEKNO");
330 CheckUnsupportedArg(args
, "WKST");
331 CheckUnsupportedArg(args
, "BYSECOND");
332 CheckUnsupportedArg(args
, "BYMINUTE");
333 CheckUnsupportedArg(args
, "BYHOUR");
335 // Now deal with the freq
337 if(args
.find(string("FREQ"))==args
.end()) {
338 // trace.logf("RecurToBarryCal: No frequency specified!");
342 if(args
["FREQ"]==string("DAILY")) {
343 cal
.RecurringType
=Calendar::Day
;
346 // add count-1*interval days to find the end time:
347 // i.e. if starting on 2012/01/01 and going
348 // for 3 days, then the last day will be
351 // For intervals, the count is every interval days,
352 // so interval of 2 means 2012/01/01, 2012/01/03, etc.
353 // and the calculation still works.
354 cal
.RecurringEndTime
.Time
=
355 starttime
+ (count
-1) * cal
.Interval
* 24*60*60;
357 } else if(args
["FREQ"]==string("WEEKLY")) {
358 cal
.RecurringType
=Calendar::Week
;
359 // we must have a dayofweek entry
360 if(args
.find(string("BYDAY"))!=args
.end()) {
361 std::vector
<std::string
> v
=Tokenize(args
["BYDAY"]);
362 // iterate along our vector and convert
363 for(unsigned int idx
=0;idx
<v
.size();idx
++) {
364 cal
.WeekDays
|=pmap
[v
[idx
]];
367 // we must have at least one day selected, and if no
368 // BYDAY is selected, use the start time's day
369 struct tm datestruct
;
370 localtime_r(&starttime
,&datestruct
);
371 cal
.WeekDays
= pmap
[WeekDays
[datestruct
.tm_wday
]];
373 barryverbose("Warning: WEEKLY VEVENT without a day selected. Assuming day of start time.\nRecord data so far:\n" << cal
);
377 // need to process end date. This is easy
378 // for weeks, as a number of weeks can be
379 // reduced to seconds simply.
380 cal
.RecurringEndTime
.Time
=
381 starttime
+ (count
-1) * cal
.Interval
* 60*60*24*7;
383 } else if(args
["FREQ"]=="MONTHLY") {
384 if(args
.find(string("BYMONTHDAY"))!=args
.end()) {
385 cal
.RecurringType
=Calendar::MonthByDate
;
386 cal
.DayOfMonth
=atoi(args
["BYMONTHDAY"].c_str());
388 if(args
.find(string("BYDAY"))!=args
.end()) {
389 cal
.RecurringType
=Calendar::MonthByDay
;
390 cal
.WeekOfMonth
=GetMonthWeekNumFromBYDAY(args
["BYDAY"]);
391 cal
.DayOfWeek
=GetWeekDayIndexFromBYDAY(args
["BYDAY"]);
393 // must have a recurring type, so assume
394 // that monthly means every day on the day
395 // of month specified by starttime
396 struct tm datestruct
;
397 localtime_r(&starttime
,&datestruct
);
399 cal
.RecurringType
= Calendar::MonthByDate
;
400 cal
.DayOfMonth
= datestruct
.tm_mday
;
401 barryverbose("Warning: MONTHLY VEVENT without a day type specified (no BYMONTHDAY nor BYDAY). Assuming BYMONTHDAY, using day of start time.\nRecord data so far:\n" << cal
);
405 // Nasty. We need to convert to struct tm,
406 // do some modulo-12 addition then back
408 struct tm datestruct
;
409 localtime_r(&starttime
,&datestruct
);
410 // now do some modulo-12 on the month and year
411 // We could end up with an illegal date if
412 // the day of month is >28 and the resulting
413 // month falls on a February. We don't need
414 // to worry about day of week as mktime()
416 int add
= (count
-1) * cal
.Interval
;
417 datestruct
.tm_year
+= (datestruct
.tm_mon
+add
)/12;
418 datestruct
.tm_mon
= (datestruct
.tm_mon
+add
)%12;
419 if(datestruct
.tm_mday
>28 && datestruct
.tm_mon
==1) {
420 // force it to 1st Mar
421 // TODO Potential bug on leap years
423 datestruct
.tm_mday
=1;
425 if(datestruct
.tm_mday
==31 && (datestruct
.tm_mon
==8 ||
426 datestruct
.tm_mon
==3 ||
427 datestruct
.tm_mon
==5 ||
428 datestruct
.tm_mon
==10)) {
429 datestruct
.tm_mon
+=1;
430 datestruct
.tm_mday
=1;
432 // Just in case we're crossing DST boundaries,
433 // add an hour, to make sure we reach the ending
434 // month, in the case of intervals
435 datestruct
.tm_hour
++;
436 cal
.RecurringEndTime
.Time
= mktime(&datestruct
);
438 } else if(args
["FREQ"]=="YEARLY") {
439 bool need_assumption
= true;
440 if(args
.find(string("BYMONTH"))!=args
.end()) {
441 cal
.MonthOfYear
=atoi(args
["BYMONTH"].c_str());
442 if(args
.find(string("BYMONTHDAY"))!=args
.end()) {
443 cal
.RecurringType
=Calendar::YearByDate
;
444 cal
.DayOfMonth
=atoi(args
["BYMONTHDAY"].c_str());
445 need_assumption
= false;
447 if(args
.find(string("BYDAY"))!=args
.end()) {
448 cal
.RecurringType
=Calendar::YearByDay
;
449 cal
.WeekOfMonth
=GetMonthWeekNumFromBYDAY(args
["BYDAY"]);
450 cal
.DayOfWeek
=GetWeekDayIndexFromBYDAY(args
["BYDAY"]);
451 need_assumption
= false;
453 // needs assumption below...
458 if( need_assumption
) {
459 // otherwise use the start date and translate
461 // cal.StartTime has already been processed
462 // when we get here we need month of year,
464 struct tm datestruct
;
465 localtime_r(&starttime
,&datestruct
);
466 cal
.RecurringType
=Calendar::YearByDate
;
467 cal
.MonthOfYear
=datestruct
.tm_mon
;
468 cal
.DayOfMonth
=datestruct
.tm_mday
;
469 barryverbose("Warning: YEARLY VEVENT without a day type specified (no BYMONTHDAY nor BYDAY). Assuming BYMONTHDAY, using day and month of start time.\nRecord data so far:\n" << cal
);
472 // convert to struct tm, then simply add to the year.
474 // Note: intervals do work in the device firmware,
475 // but not all of the devices allow you to edit it
476 // with their GUI... hmmm... oh well, allow it
477 // anyway, and do the multiplication below.
478 struct tm datestruct
;
479 localtime_r(&starttime
,&datestruct
);
480 datestruct
.tm_year
+= (count
-1) * cal
.Interval
;
481 cal
.RecurringEndTime
.Time
= mktime(&datestruct
);
485 // unsigned char WeekDays; // bitmask, bit 0 = sunday
487 // #define CAL_WD_SUN 0x01
488 // #define CAL_WD_MON 0x02
489 // #define CAL_WD_TUE 0x04
490 // #define CAL_WD_WED 0x08
491 // #define CAL_WD_THU 0x10
492 // #define CAL_WD_FRI 0x20
493 // #define CAL_WD_SAT 0x40
496 // Main conversion routine for converting from Barry::Calendar to
497 // a vCalendar string of data.
498 const std::string
& vCalendar::ToVCal(const Barry::Calendar
&cal
)
500 // Trace trace("vCalendar::ToVCal");
501 std::ostringstream oss
;
503 // trace.logf("ToVCal, initial Barry record: %s", oss.str().c_str());
507 SetFormat( b_vformat_new() );
509 throw ConvertError("resource error allocating vformat");
511 // store the Barry object we're working with
514 // RFC section 4.8.7.2 requires DTSTAMP in all VEVENT, VTODO,
515 // VJOURNAL, and VFREEBUSY calendar components, and it must be
516 // in UTC. DTSTAMP holds the timestamp of when the iCal object itself
517 // was created, not when the object was created in the device or app.
518 // So, find out what time it is "now".
519 time_t now
= time(NULL
);
521 // begin building vCalendar data
522 AddAttr(NewAttr("PRODID", "-//OpenSync//NONSGML Barry Calendar Record//EN"));
523 AddAttr(NewAttr("BEGIN", "VEVENT"));
524 AddAttr(NewAttr("DTSTAMP", m_vtc
.unix2vtime(&now
).c_str())); // see note above
525 AddAttr(NewAttr("SEQUENCE", "0"));
526 AddAttr(NewAttr("SUMMARY", cal
.Subject
.c_str()));
527 AddAttr(NewAttr("DESCRIPTION", cal
.Notes
.c_str()));
528 AddAttr(NewAttr("LOCATION", cal
.Location
.c_str()));
530 string
start(m_vtc
.unix2vtime(&cal
.StartTime
.Time
));
531 string
end(m_vtc
.unix2vtime(&cal
.EndTime
.Time
));
532 string
notify(m_vtc
.unix2vtime(&cal
.NotificationTime
.Time
));
534 // if an all day event, only print the date parts of the string
535 if( cal
.AllDayEvent
&& start
.find('T') != string::npos
) {
536 // truncate start date
537 start
= start
.substr(0, start
.find('T'));
539 // create end date 1 day in future
540 time_t end_t
= cal
.StartTime
.Time
+ 24 * 60 * 60;
541 end
= m_vtc
.unix2vtime(&end_t
);
542 end
= end
.substr(0, end
.find('T'));
545 AddAttr(NewAttr("DTSTART", start
.c_str()));
546 AddAttr(NewAttr("DTEND", end
.c_str()));
547 // FIXME - add a truly globally unique "UID" string?
550 AddAttr(NewAttr("BEGIN", "VALARM"));
551 AddAttr(NewAttr("ACTION", "AUDIO"));
553 // notify must be UTC, when specified in DATE-TIME
554 vAttrPtr trigger
= NewAttr("TRIGGER", notify
.c_str());
555 AddParam(trigger
, "VALUE", "DATE-TIME");
558 AddAttr(NewAttr("END", "VALARM"));
561 if( cal
.Recurring
) {
565 AddAttr(NewAttr("END", "VEVENT"));
567 // generate the raw VCALENDAR data
568 m_gCalData
= b_vformat_to_string(Format(), VFORMAT_EVENT_20
);
569 m_vCalData
= m_gCalData
;
571 // trace.logf("ToVCal, resulting vcal data: %s", m_vCalData.c_str());
575 // Main conversion routine for converting from vCalendar data string
576 // to a Barry::Calendar object.
577 const Barry::Calendar
& vCalendar::ToBarry(const char *vcal
, uint32_t RecordId
)
581 // Trace trace("vCalendar::ToBarry");
582 // trace.logf("ToBarry, working on vcal data: %s", vcal);
584 // we only handle vCalendar data with one vevent block
585 if( HasMultipleVEvents() )
586 throw ConvertError("vCalendar data contains more than one VEVENT block, unsupported");
591 // store the vCalendar raw data
594 // create format parser structures
595 SetFormat( b_vformat_new_from_string(vcal
) );
597 throw ConvertError("resource error allocating vformat");
599 string start
= GetAttr("DTSTART", "/vevent");
600 // trace.logf("DTSTART attr retrieved: %s", start.c_str());
601 string end
= GetAttr("DTEND", "/vevent");
602 // trace.logf("DTEND attr retrieved: %s", end.c_str());
603 string subject
= GetAttr("SUMMARY", "/vevent");
604 // trace.logf("SUMMARY attr retrieved: %s", subject.c_str());
605 if( subject
.size() == 0 ) {
606 subject
= "<blank subject>";
607 // trace.logf("ERROR: bad data, blank SUMMARY: %s", vcal);
609 vAttr trigger_obj
= GetAttrObj("TRIGGER", 0, "/valarm");
611 string location
= GetAttr("LOCATION", "/vevent");
612 // trace.logf("LOCATION attr retrieved: %s", location.c_str());
614 string notes
= GetAttr("DESCRIPTION", "/vevent");
615 // trace.logf("DESCRIPTION attr retrieved: %s", notes.c_str());
617 vAttr rrule
= GetAttrObj("RRULE",0,"/vevent");
621 // Now, run checks and convert into Barry object
625 // FIXME - we are assuming that any non-UTC timestamps
626 // in the vcalendar record will be in the current timezone...
627 // This is wrong! fix this later.
629 // Also, we currently ignore any time zone
630 // parameters that might be in the vcalendar format... this
633 Barry::Calendar
&rec
= m_BarryCal
;
634 rec
.SetIds(Barry::Calendar::GetDefaultRecType(), RecordId
);
637 throw ConvertError("Blank DTSTART");
638 rec
.StartTime
.Time
= m_vtc
.vtime2unix(start
.c_str());
641 // DTEND is actually optional! According to the
642 // RFC, a DTSTART with no DTEND should be treated
643 // like a "special day" like an anniversary, which occupies
646 // Since the Blackberry doesn't really map well to this
647 // case, we'll set the end time to 1 day past start.
649 rec
.EndTime
.Time
= rec
.StartTime
.Time
+ 24 * 60 * 60;
652 rec
.EndTime
.Time
= m_vtc
.vtime2unix(end
.c_str());
655 // check for "all day event" which is specified by a DTSTART
656 // and a DTEND with no times, and one day apart
657 if( start
.find('T') == string::npos
&& end
.size() &&
658 end
.find('T') == string::npos
&&
659 (rec
.EndTime
.Time
- rec
.StartTime
.Time
) == 24 * 60 * 60 )
661 rec
.AllDayEvent
= true;
664 rec
.Subject
= subject
;
665 rec
.Location
= location
;
669 RecurToBarryCal(rrule
, rec
.StartTime
.Time
);
672 // convert trigger time into notification time
673 // assume no notification, by default
674 rec
.NotificationTime
.Time
= 0;
675 if( trigger_obj
.Get() ) {
676 string trigger_type
= trigger_obj
.GetParam("VALUE");
677 string trigger
= trigger_obj
.GetValue();
679 if( trigger
.size() == 0 ) {
680 // trace.logf("ERROR: no TRIGGER found in calendar entry, assuming notification time as 15 minutes before start.");
682 else if( trigger_type
== "DATE-TIME" ) {
683 rec
.NotificationTime
.Time
= m_vtc
.vtime2unix(trigger
.c_str());
685 else if( trigger_type
== "DURATION" || trigger_type
.size() == 0 ) {
686 // default is DURATION (RFC 4.8.6.3)
687 string related
= trigger_obj
.GetParam("RELATED");
689 // default to relative to start time
690 time_t *relative
= &rec
.StartTime
.Time
;
691 if( related
== "END" )
692 relative
= &rec
.EndTime
.Time
;
694 rec
.NotificationTime
.Time
= *relative
+ m_vtc
.alarmduration2sec(trigger
.c_str());
697 throw ConvertError("Unknown TRIGGER VALUE");
701 // trace.logf("ERROR: no TRIGGER found in calendar entry, assuming notification time as 15 minutes before start.");
704 std::ostringstream oss
;
705 m_BarryCal
.Dump(oss
);
706 // trace.logf("ToBarry, resulting Barry record: %s", oss.str().c_str());
710 // Transfers ownership of m_gCalData to the caller.
711 char* vCalendar::ExtractVCal()
713 char *ret
= m_gCalData
;
718 void vCalendar::Clear()
730 }} // namespace Barry::Sync