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()
423 int add
= (count
-1) * cal
.Interval
;
424 tempdate
.tm_year
+= (tempdate
.tm_mon
+add
)/12;
425 tempdate
.tm_mon
= (tempdate
.tm_mon
+add
)%12;
426 if(tempdate
.tm_mday
>28 && tempdate
.tm_mon
==1) {
427 // force it to 1st Mar
428 // TODO Potential bug on leap years
432 if(tempdate
.tm_mday
==31 && (tempdate
.tm_mon
==8 ||
433 tempdate
.tm_mon
==3 ||
434 tempdate
.tm_mon
==5 ||
435 tempdate
.tm_mon
==10)) {
439 // Just in case we're crossing DST boundaries,
440 // add an hour, to make sure we reach the ending
441 // month, in the case of intervals
443 cal
.RecurringEndTime
.Time
= mktime(&tempdate
);
445 } else if(args
["FREQ"]=="YEARLY") {
446 bool need_assumption
= true;
447 if(args
.find(string("BYMONTH"))!=args
.end()) {
448 cal
.MonthOfYear
=atoi(args
["BYMONTH"].c_str());
449 if(args
.find(string("BYMONTHDAY"))!=args
.end()) {
450 cal
.RecurringType
=Calendar::YearByDate
;
451 cal
.DayOfMonth
=atoi(args
["BYMONTHDAY"].c_str());
452 need_assumption
= false;
454 if(args
.find(string("BYDAY"))!=args
.end()) {
455 cal
.RecurringType
=Calendar::YearByDay
;
456 cal
.WeekOfMonth
=GetMonthWeekNumFromBYDAY(args
["BYDAY"]);
457 cal
.DayOfWeek
=GetWeekDayIndexFromBYDAY(args
["BYDAY"]);
458 need_assumption
= false;
460 // fall through to assumption below...
465 if( need_assumption
) {
466 // otherwise use the start date and translate
468 // cal.StartTime has already been processed
469 // when we get here we need month of year,
471 cal
.RecurringType
=Calendar::YearByDate
;
472 cal
.MonthOfYear
=datestruct
.tm_mon
;
473 cal
.DayOfMonth
=datestruct
.tm_mday
;
474 barrylog("Warning: YEARLY VEVENT without a day type specified (no BYMONTHDAY nor BYDAY). Assuming BYMONTHDAY, using day and month of start time.");
475 barryverbose("Record data so far:\n" << cal
);
478 // convert to struct tm, then simply add to the year.
480 // Note: intervals do work in the device firmware,
481 // but not all of the devices allow you to edit it
482 // with their GUI... hmmm... oh well, allow it
483 // anyway, and do the multiplication below.
484 struct tm tempdate
= datestruct
;
485 tempdate
.tm_year
+= (count
-1) * cal
.Interval
;
486 cal
.RecurringEndTime
.Time
= mktime(&tempdate
);
490 // unsigned char WeekDays; // bitmask, bit 0 = sunday
492 // #define CAL_WD_SUN 0x01
493 // #define CAL_WD_MON 0x02
494 // #define CAL_WD_TUE 0x04
495 // #define CAL_WD_WED 0x08
496 // #define CAL_WD_THU 0x10
497 // #define CAL_WD_FRI 0x20
498 // #define CAL_WD_SAT 0x40
501 // Main conversion routine for converting from Barry::Calendar to
502 // a vCalendar string of data.
503 const std::string
& vCalendar::ToVCal(const Barry::Calendar
&cal
)
505 // Trace trace("vCalendar::ToVCal");
506 std::ostringstream oss
;
508 // trace.logf("ToVCal, initial Barry record: %s", oss.str().c_str());
512 SetFormat( b_vformat_new() );
514 throw ConvertError("resource error allocating vformat");
516 // store the Barry object we're working with
519 // RFC section 4.8.7.2 requires DTSTAMP in all VEVENT, VTODO,
520 // VJOURNAL, and VFREEBUSY calendar components, and it must be
521 // in UTC. DTSTAMP holds the timestamp of when the iCal object itself
522 // was created, not when the object was created in the device or app.
523 // So, find out what time it is "now".
524 time_t now
= time(NULL
);
526 // begin building vCalendar data
527 AddAttr(NewAttr("PRODID", "-//OpenSync//NONSGML Barry Calendar Record//EN"));
528 AddAttr(NewAttr("BEGIN", "VEVENT"));
529 AddAttr(NewAttr("DTSTAMP", m_vtc
.unix2vtime(&now
).c_str())); // see note above
530 AddAttr(NewAttr("SEQUENCE", "0"));
531 AddAttr(NewAttr("SUMMARY", cal
.Subject
.c_str()));
532 AddAttr(NewAttr("DESCRIPTION", cal
.Notes
.c_str()));
533 AddAttr(NewAttr("LOCATION", cal
.Location
.c_str()));
535 string
start(m_vtc
.unix2vtime(&cal
.StartTime
.Time
));
536 string
end(m_vtc
.unix2vtime(&cal
.EndTime
.Time
));
537 string
notify(m_vtc
.unix2vtime(&cal
.NotificationTime
.Time
));
539 // if an all day event, only print the date parts of the string
540 if( cal
.AllDayEvent
&& start
.find('T') != string::npos
) {
541 // truncate start date
542 start
= start
.substr(0, start
.find('T'));
544 // create end date 1 day in future
545 time_t end_t
= cal
.StartTime
.Time
+ 24 * 60 * 60;
546 end
= m_vtc
.unix2vtime(&end_t
);
547 end
= end
.substr(0, end
.find('T'));
550 AddAttr(NewAttr("DTSTART", start
.c_str()));
551 AddAttr(NewAttr("DTEND", end
.c_str()));
552 // FIXME - add a truly globally unique "UID" string?
555 AddAttr(NewAttr("BEGIN", "VALARM"));
556 AddAttr(NewAttr("ACTION", "AUDIO"));
558 // notify must be UTC, when specified in DATE-TIME
559 vAttrPtr trigger
= NewAttr("TRIGGER", notify
.c_str());
560 AddParam(trigger
, "VALUE", "DATE-TIME");
563 AddAttr(NewAttr("END", "VALARM"));
566 if( cal
.Recurring
) {
570 AddAttr(NewAttr("END", "VEVENT"));
572 // generate the raw VCALENDAR data
573 m_gCalData
= b_vformat_to_string(Format(), VFORMAT_EVENT_20
);
574 m_vCalData
= m_gCalData
;
576 // trace.logf("ToVCal, resulting vcal data: %s", m_vCalData.c_str());
580 // Main conversion routine for converting from vCalendar data string
581 // to a Barry::Calendar object.
582 const Barry::Calendar
& vCalendar::ToBarry(const char *vcal
, uint32_t RecordId
)
586 // Trace trace("vCalendar::ToBarry");
587 // trace.logf("ToBarry, working on vcal data: %s", vcal);
589 // we only handle vCalendar data with one vevent block
590 if( HasMultipleVEvents() )
591 throw ConvertError("vCalendar data contains more than one VEVENT block, unsupported");
596 // store the vCalendar raw data
599 // create format parser structures
600 SetFormat( b_vformat_new_from_string(vcal
) );
602 throw ConvertError("resource error allocating vformat");
604 string start
= GetAttr("DTSTART", "/vevent");
605 // trace.logf("DTSTART attr retrieved: %s", start.c_str());
606 string end
= GetAttr("DTEND", "/vevent");
607 // trace.logf("DTEND attr retrieved: %s", end.c_str());
608 string subject
= GetAttr("SUMMARY", "/vevent");
609 // trace.logf("SUMMARY attr retrieved: %s", subject.c_str());
610 if( subject
.size() == 0 ) {
611 subject
= "<blank subject>";
612 // trace.logf("ERROR: bad data, blank SUMMARY: %s", vcal);
614 vAttr trigger_obj
= GetAttrObj("TRIGGER", 0, "/valarm");
616 string location
= GetAttr("LOCATION", "/vevent");
617 // trace.logf("LOCATION attr retrieved: %s", location.c_str());
619 string notes
= GetAttr("DESCRIPTION", "/vevent");
620 // trace.logf("DESCRIPTION attr retrieved: %s", notes.c_str());
622 vAttr rrule
= GetAttrObj("RRULE",0,"/vevent");
626 // Now, run checks and convert into Barry object
630 // FIXME - we are assuming that any non-UTC timestamps
631 // in the vcalendar record will be in the current timezone...
632 // This is wrong! fix this later.
634 // Also, we currently ignore any time zone
635 // parameters that might be in the vcalendar format... this
638 Barry::Calendar
&rec
= m_BarryCal
;
639 rec
.SetIds(Barry::Calendar::GetDefaultRecType(), RecordId
);
642 throw ConvertError("Blank DTSTART");
643 rec
.StartTime
.Time
= m_vtc
.vtime2unix(start
.c_str());
646 // DTEND is actually optional! According to the
647 // RFC, a DTSTART with no DTEND should be treated
648 // like a "special day" like an anniversary, which occupies
651 // Since the Blackberry doesn't really map well to this
652 // case, we'll set the end time to 1 day past start.
654 rec
.EndTime
.Time
= rec
.StartTime
.Time
+ 24 * 60 * 60;
657 rec
.EndTime
.Time
= m_vtc
.vtime2unix(end
.c_str());
660 // check for "all day event" which is specified by a DTSTART
661 // and a DTEND with no times, and one day apart
662 if( start
.find('T') == string::npos
&& end
.size() &&
663 end
.find('T') == string::npos
&&
664 (rec
.EndTime
.Time
- rec
.StartTime
.Time
) == 24 * 60 * 60 )
666 rec
.AllDayEvent
= true;
669 rec
.Subject
= subject
;
670 rec
.Location
= location
;
674 RecurToBarryCal(rrule
, rec
.StartTime
.Time
);
677 // convert trigger time into notification time
678 // assume no notification, by default
679 rec
.NotificationTime
.Time
= 0;
680 if( trigger_obj
.Get() ) {
681 string trigger_type
= trigger_obj
.GetParam("VALUE");
682 string trigger
= trigger_obj
.GetValue();
684 if( trigger
.size() == 0 ) {
685 // trace.logf("ERROR: no TRIGGER found in calendar entry, assuming notification time as 15 minutes before start.");
687 else if( trigger_type
== "DATE-TIME" ) {
688 rec
.NotificationTime
.Time
= m_vtc
.vtime2unix(trigger
.c_str());
690 else if( trigger_type
== "DURATION" || trigger_type
.size() == 0 ) {
691 // default is DURATION (RFC 4.8.6.3)
692 string related
= trigger_obj
.GetParam("RELATED");
694 // default to relative to start time
695 time_t *relative
= &rec
.StartTime
.Time
;
696 if( related
== "END" )
697 relative
= &rec
.EndTime
.Time
;
699 rec
.NotificationTime
.Time
= *relative
+ m_vtc
.alarmduration2sec(trigger
.c_str());
702 throw ConvertError("Unknown TRIGGER VALUE");
706 // trace.logf("ERROR: no TRIGGER found in calendar entry, assuming notification time as 15 minutes before start.");
709 std::ostringstream oss
;
710 m_BarryCal
.Dump(oss
);
711 // trace.logf("ToBarry, resulting Barry record: %s", oss.str().c_str());
715 // Transfers ownership of m_gCalData to the caller.
716 char* vCalendar::ExtractVCal()
718 char *ret
= m_gCalData
;
723 void vCalendar::Clear()
735 }} // namespace Barry::Sync