def test_escaping(self): # verify that escaped non safe chars are decoded correctly NON_SAFE_CHARS = u',\\;:' for char in NON_SAFE_CHARS: cn_escaped = u"Society\\%s 2014" % char cn_decoded = u"Society%s 2014" % char vevent = Event.from_ical( u'BEGIN:VEVENT\r\n' u'ORGANIZER;CN=%s:that\r\n' u'END:VEVENT\r\n' % cn_escaped ) self.assertEqual(vevent['ORGANIZER'].params['CN'], cn_decoded) vevent = Event.from_ical( 'BEGIN:VEVENT\r\n' 'ORGANIZER;CN=that\\, that\\; %th%%at%\\\\ that\\:' ':это\\, то\\; that\\\\ %th%%at%\\:\r\n' 'END:VEVENT\r\n' ) self.assertEqual( vevent['ORGANIZER'].params['CN'], r'that, that; %th%%at%\ that:' ) self.assertEqual( vevent['ORGANIZER'].to_ical().decode('utf-8'), u'это, то; that\\ %th%%at%:' )
def test_timestamp_in_recursive_event_with_exceptions(self): etp = CalendarTimePeriod(Event.from_ical("""BEGIN:VEVENT DTSTART:20151010T100000Z DTEND:20151010T120000Z CREATED:20151010T100000Z RRULE:FREQ=DAILY;COUNT=5 EXDATE:20151011T100000Z,20151012T100000Z EXDATE:20151013T100000Z UID:123456 END:VEVENT""")) assert_that(etp.start(), is_(datetime(2015, 10, 10, 10, tzinfo=pytz.utc))) assert_that(etp.duration(), is_(timedelta(hours=2))) assert_that(datetime(2015, 10, 10, 11, tzinfo=pytz.utc) in etp, is_(True)) assert_that(datetime(2015, 10, 10, 9, tzinfo=pytz.utc) in etp, is_(False)) assert_that(datetime(2015, 10, 10, 13, tzinfo=pytz.utc) in etp, is_(False)) assert_that(datetime(2015, 10, 11, 11, tzinfo=pytz.utc) in etp, is_(False)) assert_that(datetime(2015, 10, 12, 11, tzinfo=pytz.utc) in etp, is_(False)) assert_that(datetime(2015, 10, 13, 11, tzinfo=pytz.utc) in etp, is_(False)) assert_that(datetime(2015, 10, 14, 11, tzinfo=pytz.utc) in etp, is_(True)) assert_that(datetime(2015, 10, 15, 11, tzinfo=pytz.utc) in etp, is_(False))
def read(self): ps = self.db.prepare("""select o.startdate, o.enddate, summary, calendardata from oc_clndr_objects o join oc_clndr_calendars c on o.calendarid=c.id where userid='fabi' and objecttype='VEVENT' order by startdate asc""") self.data = [] for startdate, enddate, summary, data in ps(): if startdate != None and enddate != None and len(summary) > 0: summary = self.myescape(summary) item = { 'type': 'Event', 'label': summary, 'start': str(startdate), 'end': str(enddate) } if enddate - startdate > datetime.timedelta(hours=24): item['isDuration'] = True # parse ical event icalCalendar = Event.from_ical(data) for comp in icalCalendar.subcomponents: if comp.name == 'VEVENT': item['description'] = comp.get('description') item['location'] = comp.get('location') item['categories'] = comp.get('categories') item['id'] = comp.get('uid') self.data.append(item) return self.data
def test_escaping(self): # verify that escaped non safe chars are decoded correctly NON_SAFE_CHARS = u",\\;:" for char in NON_SAFE_CHARS: cn_escaped = u"Society\\%s 2014" % char cn_decoded = u"Society%s 2014" % char vevent = Event.from_ical(u"BEGIN:VEVENT\r\n" u"ORGANIZER;CN=%s:that\r\n" u"END:VEVENT\r\n" % cn_escaped) self.assertEqual(vevent["ORGANIZER"].params["CN"], cn_decoded) vevent = Event.from_ical( "BEGIN:VEVENT\r\n" "ORGANIZER;CN=that\\, that\\; %th%%at%\\\\ that\\:" ":это\\, то\\; that\\\\ %th%%at%\\:\r\n" "END:VEVENT\r\n" ) self.assertEqual(vevent["ORGANIZER"].params["CN"], r"that, that; %th%%at%\ that:") self.assertEqual(vevent["ORGANIZER"].to_ical().decode("utf-8"), u"это, то; that\\ %th%%at%:")
def test_is_date(calendars, attribute, dt_type, event_name, dt_or_content): """Check the type of the attributes""" calendar = calendars[event_name] events = calendar.all() assert len(events) == 1 event = events[0] event = Event.from_ical(event.to_ical()) dt = event[attribute] assert isinstance(dt.dt, dt_type), "content of ical should match"
def test(self): """Test with a vevent containing pbehaviors. """ iCalvevent = 'BEGIN:VEVENT\n{0}:["test"]\nEND:VEVENT'.format( PBehaviorManager.BEHAVIOR_TYPE ) vevent = Event.from_ical(iCalvevent) result = self.manager._get_vevent_properties(vevent=vevent) self.assertEqual(result, {PBehaviorManager.BEHAVIORS: ['test']})
def sync(self): start = datetime.now() - timedelta(days=1) end = datetime.now() + timedelta(days=1) calendars = self.dav.principal().calendars() self.intervals.clear() for calendar in calendars: events = calendar.date_search(start, end) for event in events: self.intervals.add( Event.from_ical(event.data).walk(), start, end)
def test_event(self): # Arrange. ical_str = ('BEGIN:VEVENT\r\n' 'END:VEVENT\r\n') event = Event.from_ical(ical_str) # Act. with self.assertRaises(AssertionError) as ex: event_model = EventModel(event) # Assert. self.assertEqual(ex.exception.args[0], model.REQ_PROP_MISSING.format('uid'))
def on_get(self, _, resp): """A method that corresponds to ``GET`` for the root resource.""" cal = Calendar() cal.add('prodid', '-//Azavea//NONSGML bamboo-blossom//EN') cal.add('version', '2.0') for employee in Company().get_employees(): employee_ical = CACHE.get('employee:{}'.format(employee.id)) if employee_ical is not None: self.logger.debug('HIT: For employee [%s]', employee.id) event = Event.from_ical(employee_ical) else: self.logger.debug('MISS: For employee [%s]', employee.id) event = Event.from_ical(employee.to_ical()) cal.add_component(event) resp.content_type = 'text/calendar' resp.data = cal.to_ical()
def test_timestamp_in_event_without_an_end(self): etp = CalendarTimePeriod(Event.from_ical("""BEGIN:VEVENT DTSTART:20130921T230000Z DTSTAMP:20150925T051339Z SEQUENCE:1 CREATED:20130903T183447Z LAST-MODIFIED:20130916T165029Z END:VEVENT""")) assert_that(etp.start(), is_(datetime(2013, 9, 21, 23, tzinfo=pytz.utc))) assert_that(datetime(2013, 9, 21, 23, tzinfo=pytz.utc) in etp, is_(False))
def _extract_event(self, name: str, text: str) -> iCalendarEvent: """ Return a icalendar.cal.Event construct with given Radicale ICS data. :param name: Event name (ID) like 20160602T083511Z-18100-1001-1-71_Bastien-20160602T083516Z.ics :param text: ICS Event content :return: ICS Event representation """ radicale_items = self._parse(text, (RadicaleEvent,), name) for item_name in radicale_items: item = radicale_items[item_name] if isinstance(item, RadicaleEvent): return iCalendarEvent.from_ical(item.text)
def _extract_event(self, name: str, text: str) -> iCalendarEvent: """ Return a icalendar.cal.Event construct with given Radicale ICS data. :param name: Event name (ID) like 20160602T083511Z-18100-1001-1-71_Bastien-20160602T083516Z.ics :param text: ICS Event content :return: ICS Event representation """ radicale_items = self._parse(text, (RadicaleEvent, ), name) for item_name in radicale_items: item = radicale_items[item_name] if isinstance(item, RadicaleEvent): return iCalendarEvent.from_ical(item.text)
def test_timestamp_in_byday_event(self): etp = CalendarTimePeriod(Event.from_ical("""BEGIN:VEVENT DTSTART;TZID=America/Toronto:20150602T183000 DTEND;TZID=America/Toronto:20150602T193000 DTSTAMP:20150925T035639Z SEQUENCE:0 EXDATE;TZID=America/Toronto:20150827T183000 CREATED:20150519T235325Z LAST-MODIFIED:20150706T153006Z RRULE:FREQ=WEEKLY;UNTIL=20150827T223000Z;BYDAY=TU,TH;WKST=SU END:VEVENT""")) assert_that(etp.start(), is_(datetime(2015, 06, 02, 18, 30, tzinfo=pytz.timezone('Etc/GMT+4'))))
def test_calculates_if_single_event_occurs_on_date(self): self.assertTrue( s.event_occurs_on_day( Event.from_ical(""" BEGIN:VEVENT DTSTART:20200608T130000Z DTEND:20200608T133000Z DTSTAMP:20200609T185535Z UID:[email protected] CREATED:20200603T165951Z LAST-MODIFIED:20200607T144853Z SUMMARY:One time event END:VEVENT """), self.date))
def test_event(self): # Arrange. ical_str = ( 'BEGIN:VEVENT\r\n' 'END:VEVENT\r\n' ) event = Event.from_ical(ical_str) # Act. with self.assertRaises(AssertionError) as ex: event_model = EventModel(event) # Assert. self.assertEqual( ex.exception.args[0], model.REQ_PROP_MISSING.format('uid'))
def test_timestamp_in_yearly_event(self): etp = CalendarTimePeriod(Event.from_ical("""BEGIN:VEVENT DTSTART;VALUE=DATE:20120702 DTEND;VALUE=DATE:20120703 DTSTAMP:20150925T043431Z SEQUENCE:2 CREATED:20110922T001534Z LAST-MODIFIED:20150706T153006Z RRULE:FREQ=YEARLY END:VEVENT""")) assert_that(etp.start(), is_(date(2012, 07, 02))) assert_that(etp.duration(), is_(timedelta(days=1))) assert_that(datetime(2012, 07, 02, 12) in etp, is_(True))
def test_timestamp_in_simple_event(self): etp = CalendarTimePeriod(Event.from_ical("""BEGIN:VEVENT DTSTART:20151010T100000Z DTEND:20151010T120000Z CREATED:20151010T100000Z UID:123456 END:VEVENT""")) assert_that(etp.start(), is_(datetime(2015, 10, 10, 10, tzinfo=pytz.utc))) assert_that(etp.duration(), is_(timedelta(hours=2))) assert_that(datetime(2015, 10, 10, 11, tzinfo=pytz.utc) in etp, is_(True)) assert_that(datetime(2015, 10, 10, 9, tzinfo=pytz.utc) in etp, is_(False)) assert_that(datetime(2015, 10, 10, 13, tzinfo=pytz.utc) in etp, is_(False))
def test_timestamp_in_timeless_event(self): etp = CalendarTimePeriod(Event.from_ical("""BEGIN:VEVENT DTSTART;VALUE=DATE:20151113 DTEND;VALUE=DATE:20151114 DTSTAMP:20150925T034508Z UID:9E783D57-BF34-47B0-86D8-FE6FD83B05A2 SEQUENCE:0 CREATED:20150922T191411Z LAST-MODIFIED:20150922T191823Z END:VEVENT""")) assert_that(etp.start(), is_(date(2015, 11, 13))) assert_that(etp.duration(), is_(timedelta(days=1))) assert_that(datetime(2015, 11, 12, 12, tzinfo=pytz.utc) in etp, is_(False)) assert_that(datetime(2015, 11, 13, 12, tzinfo=pytz.utc) in etp, is_(True)) assert_that(datetime(2015, 11, 14, 9, tzinfo=pytz.utc) in etp, is_(False))
def test_calculates_if_weekly_event_occurs_on_date(self): self.assertTrue( s.event_occurs_on_day( Event.from_ical(""" BEGIN:VEVENT DTSTART;TZID=America/Toronto:20200604T100000 DTEND;TZID=America/Toronto:20200604T130000 RRULE:FREQ=WEEKLY;WKST=SU;BYDAY=FR,MO,TH,TU,WE,SU,SA DTSTAMP:20200605T204051Z UID:[email protected] CREATED:20200605T013629Z DESCRIPTION: LAST-MODIFIED:20200605T204040Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Class TRANSP:OPAQUE END:VEVENT """), self.date))
def caldav2events(caldav_events): """ Takes calendar.events() or calendar.date_search() results and generates events in a user friendlier form.""" for event in caldav_events: for ev in iEvent.from_ical(event.data).subcomponents: if ev.name == "VEVENT": yield ev
def put(self, vevents, source=None, cache=False): """Add vevents (and optionally data) related to input source. :param str source: vevent source if not None. :param list vevents: vevents (document, str or ical vevent). :param dict info: vevent info. :param bool cache: if True (default False), use storage cache. :return: new documents. :rtype: list """ result = [] for vevent in vevents: document = None if not isinstance(vevent, Event): # Event inherit from dict... document = vevent # get uid uid = document.get(VEventManager.UID) if not uid: uid = str(uuid()) document[VEventManager.UID] = uid # get source source = document.get(VEventManager.SOURCE, source) # get dtstart dtstart = document[VEventManager.DTSTART] # get dtend dtend = document[VEventManager.DTEND] # get duration duration = document[VEventManager.DURATION] # get rrule rrule = document[VEventManager.RRULE] # if document has to be generated ... else: # ensure vevent is an ical format if isinstance(vevent, basestring): vevent = Event.from_ical(vevent) # prepare the document with specific properties document = self._get_vevent_properties(vevent=vevent) # get dtstart dtstart = vevent.get(VEventManager.DTSTART, 0).dt if isinstance(dtstart, datetime): dtstart = int(time.mktime(dtstart.timetuple())) # get dtend dtend = vevent.get(VEventManager.DTEND, 0).dt if isinstance(dtend, datetime): dtend = int(time.mktime(dtend.timetuple())) # get rrule rrule = vevent.get(VEventManager.RRULE) if rrule is not None: _rrule = "" for rrule_key in rrule: rrule_value = rrule[rrule_key] _rrule += "{0}={1};".format(rrule_key, rrule_value) rrule = _rrule # get duration duration = vevent.get(VEventManager.DURATION) if duration: duration = duration.dt.total_seconds() # get uid uid = vevent.get(VEventManager.UID) if not uid: uid = str(uuid()) # get source if not source: source = vevent.get(VEventManager.SOURCE_TYPE) # prepare the document document.update({ VEventManager.UID: uid, VEventManager.SOURCE: source, VEventManager.DTSTART: dtstart, VEventManager.DTEND: dtend, VEventManager.DURATION: duration, VEventManager.RRULE: rrule }) self.storage.put_element( _id=uid, element=document ) document['_id'] = uid result.append(document) return result
from icalendar import Calendar, Event filename = "/Users/nordmenss/Library/Calendars/FEF22724-F6A1-4EB3-B568-62D339C98CD8.calendar/Events/2AFB30D3-E760-4A91-A323-6E2D50C5489B.ics" e = Event.from_ical(open(filename, 'rb').read()) for component in e.walk(): print component.name if component.name == "VEVENT": print component.get('summary') print component.get('dtstart') print component.get('dtend') print component.get('dtstamp')