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
251 struct tm
GetConstLocalTime(const time_t &t
)
253 struct tm datestruct
;
254 localtime_r(&t
, &datestruct
);
259 void vCalendar::RecurToBarryCal(vAttr
& rrule
, time_t starttime
)
261 using namespace Barry
;
263 Barry::Calendar
&cal
= m_BarryCal
;
264 // Trace trace("vCalendar::RecurToBarryCal");
265 std::map
<std::string
,unsigned char> pmap
;
266 pmap
["SU"] = CAL_WD_SUN
;
267 pmap
["MO"] = CAL_WD_MON
;
268 pmap
["TU"] = CAL_WD_TUE
;
269 pmap
["WE"] = CAL_WD_WED
;
270 pmap
["TH"] = CAL_WD_THU
;
271 pmap
["FR"] = CAL_WD_FRI
;
272 pmap
["SA"] = CAL_WD_SAT
;
274 const struct tm datestruct
= GetConstLocalTime(starttime
);
277 unsigned int count
=0;
281 val
=rrule
.GetValue(i
++);
282 if(val
.length()==0) {
285 string n
=val
.substr(0,val
.find("="));
286 string v
=val
.substr(val
.find("=")+1);
288 // trace.logf("RecurToBarryCal: |%s|%s|",n.c_str(),v.c_str());
291 // now process the interval.
294 if(args
.find(string("INTERVAL"))!=args
.end()) {
295 int interval
= atoi(args
["INTERVAL"].c_str());
297 // force to at least 1, for math below
300 cal
.Interval
= interval
;
303 // default to 1, for the math below.
304 // RecurBase::Clear() does this for us as well, but
308 if(args
.find(string("UNTIL"))!=args
.end()) {
309 cal
.Perpetual
= FALSE
;
310 cal
.RecurringEndTime
.Time
= m_vtc
.vtime2unix(args
["UNTIL"].c_str());
311 if( cal
.RecurringEndTime
.Time
== (time_t)-1 ) {
312 // trace.logf("osync_time_vtime2unix() failed: UNTIL = %s, zoneoffset = %d", args["UNTIL"].c_str(), zoneoffset);
315 // if we do not also have COUNT, then we must be forerver
316 if(args
.find(string("COUNT"))==args
.end()) {
319 // we do have COUNT. This means we won't have UNTIL.
320 // So we need to process the RecurringEndTime from
321 // the current start date. Set the count level to
322 // something other than zero to indicate we need
323 // to process it as the exact end date will
324 // depend upon the frequency.
325 count
=atoi(args
["COUNT"].c_str());
327 throw std::runtime_error("Invalid COUNT in recurring rule: " + args
["COUNT"]);
332 // we need these if COUNT is true, or if we are a yearly job.
334 // TO-DO: we must process COUNT in terms of an end date if we have it.
336 // warn the user about unsupported arguments
337 CheckUnsupportedArg(args
, "BYSETPOS");// FIXME - theorectically supportable
338 CheckUnsupportedArg(args
, "BYYEARDAY");
339 CheckUnsupportedArg(args
, "BYWEEKNO");
340 CheckUnsupportedArg(args
, "WKST");
341 CheckUnsupportedArg(args
, "BYSECOND");
342 CheckUnsupportedArg(args
, "BYMINUTE");
343 CheckUnsupportedArg(args
, "BYHOUR");
345 // Now deal with the freq
347 if(args
.find(string("FREQ"))==args
.end()) {
348 // trace.logf("RecurToBarryCal: No frequency specified!");
352 if(args
["FREQ"]==string("DAILY")) {
353 cal
.RecurringType
=Calendar::Day
;
356 // add count-1*interval days to find the end time:
357 // i.e. if starting on 2012/01/01 and going
358 // for 3 days, then the last day will be
361 // For intervals, the count is every interval days,
362 // so interval of 2 means 2012/01/01, 2012/01/03, etc.
363 // and the calculation still works.
364 cal
.RecurringEndTime
.Time
=
365 starttime
+ (count
-1) * cal
.Interval
* 24*60*60;
367 } else if(args
["FREQ"]==string("WEEKLY")) {
368 cal
.RecurringType
=Calendar::Week
;
369 // we must have a dayofweek entry
370 if(args
.find(string("BYDAY"))!=args
.end()) {
371 std::vector
<std::string
> v
=Tokenize(args
["BYDAY"]);
372 // iterate along our vector and convert
373 for(unsigned int idx
=0;idx
<v
.size();idx
++) {
374 cal
.WeekDays
|=pmap
[v
[idx
]];
377 // we must have at least one day selected, and if no
378 // BYDAY is selected, use the start time's day
379 cal
.WeekDays
= pmap
[WeekDays
[datestruct
.tm_wday
]];
381 barrylog("Warning: WEEKLY VEVENT without a day selected. Assuming day of start time.");
382 barryverbose("Record data so far:\n" << cal
);
386 // need to process end date. This is easy
387 // for weeks, as a number of weeks can be
388 // reduced to seconds simply.
389 cal
.RecurringEndTime
.Time
=
390 starttime
+ (count
-1) * cal
.Interval
* 60*60*24*7;
392 } else if(args
["FREQ"]=="MONTHLY") {
393 if(args
.find(string("BYMONTHDAY"))!=args
.end()) {
394 cal
.RecurringType
=Calendar::MonthByDate
;
395 cal
.DayOfMonth
=atoi(args
["BYMONTHDAY"].c_str());
397 if(args
.find(string("BYDAY"))!=args
.end()) {
398 cal
.RecurringType
=Calendar::MonthByDay
;
399 cal
.WeekOfMonth
=GetMonthWeekNumFromBYDAY(args
["BYDAY"]);
400 cal
.DayOfWeek
=GetWeekDayIndexFromBYDAY(args
["BYDAY"]);
402 // must have a recurring type, so assume
403 // that monthly means every day on the day
404 // of month specified by starttime
405 cal
.RecurringType
= Calendar::MonthByDate
;
406 cal
.DayOfMonth
= datestruct
.tm_mday
;
407 barrylog("Warning: MONTHLY VEVENT without a day type specified (no BYMONTHDAY nor BYDAY). Assuming BYMONTHDAY, using day of start time.");
408 barryverbose("Record data so far:\n" << cal
);
412 // Nasty. We need to convert to struct tm,
413 // do some modulo-12 addition then back
415 struct tm tempdate
= datestruct
;
417 // now do some modulo-12 on the month and year
418 // We could end up with an illegal date if
419 // the day of month is >28 and the resulting
420 // month falls on a February. We don't need
421 // to worry about day of week as mktime()
424 // We let mktime() normalize any out of range values.
425 int add
= (count
-1) * cal
.Interval
;
426 tempdate
.tm_year
+= (tempdate
.tm_mon
+add
)/12;
427 tempdate
.tm_mon
= (tempdate
.tm_mon
+add
)%12;
429 // Just in case we're crossing DST boundaries,
430 // add an hour, to make sure we reach the ending
431 // month, in the case of intervals
433 cal
.RecurringEndTime
.Time
= mktime(&tempdate
);
435 } else if(args
["FREQ"]=="YEARLY") {
436 bool need_assumption
= true;
437 if(args
.find(string("BYMONTH"))!=args
.end()) {
438 cal
.MonthOfYear
=atoi(args
["BYMONTH"].c_str());
439 if(args
.find(string("BYMONTHDAY"))!=args
.end()) {
440 cal
.RecurringType
=Calendar::YearByDate
;
441 cal
.DayOfMonth
=atoi(args
["BYMONTHDAY"].c_str());
442 need_assumption
= false;
444 if(args
.find(string("BYDAY"))!=args
.end()) {
445 cal
.RecurringType
=Calendar::YearByDay
;
446 cal
.WeekOfMonth
=GetMonthWeekNumFromBYDAY(args
["BYDAY"]);
447 cal
.DayOfWeek
=GetWeekDayIndexFromBYDAY(args
["BYDAY"]);
448 need_assumption
= false;
450 // fall through to assumption below...
455 if( need_assumption
) {
456 // otherwise use the start date and translate
458 // cal.StartTime has already been processed
459 // when we get here we need month of year,
461 cal
.RecurringType
=Calendar::YearByDate
;
462 cal
.MonthOfYear
=datestruct
.tm_mon
;
463 cal
.DayOfMonth
=datestruct
.tm_mday
;
464 barrylog("Warning: YEARLY VEVENT without a day type specified (no BYMONTHDAY nor BYDAY). Assuming BYMONTHDAY, using day and month of start time.");
465 barryverbose("Record data so far:\n" << cal
);
468 // convert to struct tm, then simply add to the year.
470 // Note: intervals do work in the device firmware,
471 // but not all of the devices allow you to edit it
472 // with their GUI... hmmm... oh well, allow it
473 // anyway, and do the multiplication below.
474 struct tm tempdate
= datestruct
;
475 tempdate
.tm_year
+= (count
-1) * cal
.Interval
;
476 cal
.RecurringEndTime
.Time
= mktime(&tempdate
);
480 // unsigned char WeekDays; // bitmask, bit 0 = sunday
482 // #define CAL_WD_SUN 0x01
483 // #define CAL_WD_MON 0x02
484 // #define CAL_WD_TUE 0x04
485 // #define CAL_WD_WED 0x08
486 // #define CAL_WD_THU 0x10
487 // #define CAL_WD_FRI 0x20
488 // #define CAL_WD_SAT 0x40
491 // Main conversion routine for converting from Barry::Calendar to
492 // a vCalendar string of data.
493 const std::string
& vCalendar::ToVCal(const Barry::Calendar
&cal
)
495 // Trace trace("vCalendar::ToVCal");
496 std::ostringstream oss
;
498 // trace.logf("ToVCal, initial Barry record: %s", oss.str().c_str());
502 SetFormat( b_vformat_new() );
504 throw ConvertError("resource error allocating vformat");
506 // store the Barry object we're working with
509 // RFC section 4.8.7.2 requires DTSTAMP in all VEVENT, VTODO,
510 // VJOURNAL, and VFREEBUSY calendar components, and it must be
511 // in UTC. DTSTAMP holds the timestamp of when the iCal object itself
512 // was created, not when the object was created in the device or app.
513 // So, find out what time it is "now".
514 time_t now
= time(NULL
);
516 // begin building vCalendar data
517 AddAttr(NewAttr("PRODID", "-//OpenSync//NONSGML Barry Calendar Record//EN"));
518 AddAttr(NewAttr("BEGIN", "VEVENT"));
519 AddAttr(NewAttr("DTSTAMP", m_vtc
.unix2vtime(&now
).c_str())); // see note above
520 AddAttr(NewAttr("SEQUENCE", "0"));
521 AddAttr(NewAttr("SUMMARY", cal
.Subject
.c_str()));
522 AddAttr(NewAttr("DESCRIPTION", cal
.Notes
.c_str()));
523 AddAttr(NewAttr("LOCATION", cal
.Location
.c_str()));
525 string
start(m_vtc
.unix2vtime(&cal
.StartTime
.Time
));
526 string
end(m_vtc
.unix2vtime(&cal
.EndTime
.Time
));
527 string
notify(m_vtc
.unix2vtime(&cal
.NotificationTime
.Time
));
529 // if an all day event, only print the date parts of the string
530 if( cal
.AllDayEvent
&& start
.find('T') != string::npos
) {
531 // truncate start date
532 start
= start
.substr(0, start
.find('T'));
534 // create end date 1 day in future
535 time_t end_t
= cal
.StartTime
.Time
+ 24 * 60 * 60;
536 end
= m_vtc
.unix2vtime(&end_t
);
537 end
= end
.substr(0, end
.find('T'));
540 AddAttr(NewAttr("DTSTART", start
.c_str()));
541 AddAttr(NewAttr("DTEND", end
.c_str()));
542 // FIXME - add a truly globally unique "UID" string?
545 AddAttr(NewAttr("BEGIN", "VALARM"));
546 AddAttr(NewAttr("ACTION", "AUDIO"));
548 // notify must be UTC, when specified in DATE-TIME
549 vAttrPtr trigger
= NewAttr("TRIGGER", notify
.c_str());
550 AddParam(trigger
, "VALUE", "DATE-TIME");
553 AddAttr(NewAttr("END", "VALARM"));
556 if( cal
.Recurring
) {
560 AddAttr(NewAttr("END", "VEVENT"));
562 // generate the raw VCALENDAR data
563 m_gCalData
= b_vformat_to_string(Format(), VFORMAT_EVENT_20
);
564 m_vCalData
= m_gCalData
;
566 // trace.logf("ToVCal, resulting vcal data: %s", m_vCalData.c_str());
570 // Main conversion routine for converting from vCalendar data string
571 // to a Barry::Calendar object.
572 const Barry::Calendar
& vCalendar::ToBarry(const char *vcal
, uint32_t RecordId
)
576 // Trace trace("vCalendar::ToBarry");
577 // trace.logf("ToBarry, working on vcal data: %s", vcal);
579 // we only handle vCalendar data with one vevent block
580 if( HasMultipleVEvents() )
581 throw ConvertError("vCalendar data contains more than one VEVENT block, unsupported");
586 // store the vCalendar raw data
589 // create format parser structures
590 SetFormat( b_vformat_new_from_string(vcal
) );
592 throw ConvertError("resource error allocating vformat");
594 string start
= GetAttr("DTSTART", "/vevent");
595 // trace.logf("DTSTART attr retrieved: %s", start.c_str());
596 string end
= GetAttr("DTEND", "/vevent");
597 // trace.logf("DTEND attr retrieved: %s", end.c_str());
598 string subject
= GetAttr("SUMMARY", "/vevent");
599 // trace.logf("SUMMARY attr retrieved: %s", subject.c_str());
600 if( subject
.size() == 0 ) {
601 subject
= "<blank subject>";
602 // trace.logf("ERROR: bad data, blank SUMMARY: %s", vcal);
604 vAttr trigger_obj
= GetAttrObj("TRIGGER", 0, "/valarm");
606 string location
= GetAttr("LOCATION", "/vevent");
607 // trace.logf("LOCATION attr retrieved: %s", location.c_str());
609 string notes
= GetAttr("DESCRIPTION", "/vevent");
610 // trace.logf("DESCRIPTION attr retrieved: %s", notes.c_str());
612 vAttr rrule
= GetAttrObj("RRULE",0,"/vevent");
616 // Now, run checks and convert into Barry object
620 // FIXME - we are assuming that any non-UTC timestamps
621 // in the vcalendar record will be in the current timezone...
622 // This is wrong! fix this later.
624 // Also, we currently ignore any time zone
625 // parameters that might be in the vcalendar format... this
628 Barry::Calendar
&rec
= m_BarryCal
;
629 rec
.SetIds(Barry::Calendar::GetDefaultRecType(), RecordId
);
632 throw ConvertError("Blank DTSTART");
633 rec
.StartTime
.Time
= m_vtc
.vtime2unix(start
.c_str());
636 // DTEND is actually optional! According to the
637 // RFC, a DTSTART with no DTEND should be treated
638 // like a "special day" like an anniversary, which occupies
641 // Since the Blackberry doesn't really map well to this
642 // case, we'll set the end time to 1 day past start.
644 rec
.EndTime
.Time
= rec
.StartTime
.Time
+ 24 * 60 * 60;
647 rec
.EndTime
.Time
= m_vtc
.vtime2unix(end
.c_str());
650 // check for "all day event" which is specified by a DTSTART
651 // and a DTEND with no times, and one day apart
652 if( start
.find('T') == string::npos
&& end
.size() &&
653 end
.find('T') == string::npos
&&
654 (rec
.EndTime
.Time
- rec
.StartTime
.Time
) == 24 * 60 * 60 )
656 rec
.AllDayEvent
= true;
659 rec
.Subject
= subject
;
660 rec
.Location
= location
;
664 RecurToBarryCal(rrule
, rec
.StartTime
.Time
);
667 // convert trigger time into notification time
668 // assume no notification, by default
669 rec
.NotificationTime
.Time
= 0;
670 if( trigger_obj
.Get() ) {
671 string trigger_type
= trigger_obj
.GetParam("VALUE");
672 string trigger
= trigger_obj
.GetValue();
674 if( trigger
.size() == 0 ) {
675 // trace.logf("ERROR: no TRIGGER found in calendar entry, assuming notification time as 15 minutes before start.");
677 else if( trigger_type
== "DATE-TIME" ) {
678 rec
.NotificationTime
.Time
= m_vtc
.vtime2unix(trigger
.c_str());
680 else if( trigger_type
== "DURATION" || trigger_type
.size() == 0 ) {
681 // default is DURATION (RFC 4.8.6.3)
682 string related
= trigger_obj
.GetParam("RELATED");
684 // default to relative to start time
685 time_t *relative
= &rec
.StartTime
.Time
;
686 if( related
== "END" )
687 relative
= &rec
.EndTime
.Time
;
689 rec
.NotificationTime
.Time
= *relative
+ m_vtc
.alarmduration2sec(trigger
.c_str());
692 throw ConvertError("Unknown TRIGGER VALUE");
696 // trace.logf("ERROR: no TRIGGER found in calendar entry, assuming notification time as 15 minutes before start.");
699 std::ostringstream oss
;
700 m_BarryCal
.Dump(oss
);
701 // trace.logf("ToBarry, resulting Barry record: %s", oss.str().c_str());
705 // Transfers ownership of m_gCalData to the caller.
706 char* vCalendar::ExtractVCal()
708 char *ret
= m_gCalData
;
713 void vCalendar::Clear()
725 }} // namespace Barry::Sync