Python icalendar.Event() Examples

The following are 16 code examples of icalendar.Event(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module icalendar , or try the search function .
Example #1
Source File: build_event.py    From gyft with MIT License 6 votes vote down vote up
def build_event_duration(summary, description, start, duration, location,
        freq_of_recurrence, until):

    '''
    Return an event that can be added to a calendar

    summary: summary of the event
    description: description of the event
    location: self explanatory
    start, end, stamp: These are datetime.datetime objects
    freq_of_recurrence: frequency of recurrence, string which can take the
    values daily, weekly, monthly, etc.
    until: A datetime.datetime object which signifies when the recurrence will
    end
    '''

    event = Event()
    event.add('summary', summary)
    event.add('description', description)
    event.add('dtstart', start)
    event.add('duration', timedelta(hours=duration))
    event.add('dtstamp', datetime.now())
    event.add('location', location)
    event.add('rrule', { 'FREQ': freq_of_recurrence, 'UNTIL': until})

    return event 
Example #2
Source File: ics_generator.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def _build_event(card_name: str, times: Tuple[datetime, datetime], classroom: str, teacher: str, current_week: int,
                 week_string: str, cid: str) -> Event:
    """
    生成 `Event` 对象

    :param card_name: 课程名
    :param times: 开始和结束时间
    :param classroom: 课程地点
    :param teacher: 任课教师
    :return: `Event` 对象
    """

    event = Event()
    event.add('transp', 'TRANSPARENT')
    summary = card_name
    if classroom != 'None':
        summary = card_name + '@' + classroom
        event.add('location', classroom)

    description = week_string
    if teacher != 'None':
        description += '\n教师:' + teacher
    description += '\n由 EveryClass 每课 (https://everyclass.xyz) 导入'

    event.add('summary', summary)
    event.add('description', description)
    event.add('dtstart', times[0])
    event.add('dtend', times[1])
    event.add('last-modified', datetime.now())

    # 使用"cid-当前周"作为事件的超码
    event_sk = cid + '-' + str(current_week)
    event['uid'] = hashlib.md5(event_sk.encode('utf-8')).hexdigest() + '@everyclass.xyz'
    alarm = Alarm()
    alarm.add('action', 'none')
    alarm.add('trigger', datetime(1980, 1, 1, 3, 5, 0))
    event.add_component(alarm)
    return event 
Example #3
Source File: city_sdk.py    From linkedevents with MIT License 5 votes vote down vote up
def generate_icalendar_element(event):
    icalendar_event = CalendarEvent()
    if event.start_time:
        icalendar_event.add('dtstart', event.start_time)
    if event.end_time:
        icalendar_event.add('dtend', event.end_time)
    if event.name_en:
        icalendar_event.add('summary', event.name_en)

    cal = Calendar()
    cal.add('version', '2.0')
    cal.add('prodid', '-//events.hel.fi//NONSGML Feeder//EN')
    cal.add_component(icalendar_event)

    term = None
    if event.start_time and event.end_time:
        term = "open"
    elif event.start_time:
        term = "open"
    elif event.end_time:
        term = "close"

    if term:
        return {
            "term": "open",
            "value": cal.to_ical().decode('utf8'),
            "type": "text/icalendar"
        }
    else:
        return None 
Example #4
Source File: feedgenerator.py    From django-ical with MIT License 5 votes vote down vote up
def write_items(self, calendar):
        """
        Write all events to the calendar
        """
        for item in self.items:
            event = Event()
            for ifield, efield in ITEM_EVENT_FIELD_MAP:
                val = item.get(ifield)
                if val is not None:
                    if ifield == "attendee":
                        for list_item in val:
                            event.add(efield, list_item)
                    else:
                        event.add(efield, val)
            calendar.add_component(event) 
Example #5
Source File: generate_data.py    From awesome-italy-events with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def write_ical(events, year, dataDir):
    # write iCal
    cal = Calendar()

    for awesomeEvent in events:
        event = Event()

        event.add('summary', awesomeEvent.title)
        event.add('dtstart', date.fromisoformat(awesomeEvent.startDate))
        event.add('dtend', date.fromisoformat(
            awesomeEvent.endDate) + timedelta(days=1))
        event.add('description',
                  f'{awesomeEvent.description} - {awesomeEvent.url}')
        event.add('location', awesomeEvent.location)
        cal.add_component(event)

    with open(f'{dataDir}{year}.ics', 'wb') as ics:
        ics.write(cal.to_ical()) 
Example #6
Source File: curriculum_calendar.py    From hfut with MIT License 5 votes vote down vote up
def schedule2calendar(schedule, name='课表', using_todo=True):
    """
    将上课时间表转换为 icalendar

    :param schedule: 上课时间表
    :param name: 日历名称
    :param using_todo: 使用 ``icalendar.Todo`` 而不是 ``icalendar.Event`` 作为活动类
    :return: icalendar.Calendar()
    """
    # https://zh.wikipedia.org/wiki/ICalendar
    # http://icalendar.readthedocs.io/en/latest
    # https://tools.ietf.org/html/rfc5545
    cal = icalendar.Calendar()
    cal.add('X-WR-TIMEZONE', 'Asia/Shanghai')
    cal.add('X-WR-CALNAME', name)
    cls = icalendar.Todo if using_todo else icalendar.Event
    for week, start, end, data in schedule:
        # "事件"组件更具通用性, Google 日历不支持"待办"组件
        item = cls(
            SUMMARY='第{:02d}周-{}'.format(week, data),
            DTSTART=icalendar.vDatetime(start),
            DTEND=icalendar.vDatetime(end),
            DESCRIPTION='起始于 {}, 结束于 {}'.format(start.strftime('%H:%M'), end.strftime('%H:%M'))
        )
        now = datetime.now()
        # 这个状态"事件"组件是没有的, 对于待办列表类应用有作用
        # https://tools.ietf.org/html/rfc5545#section-3.2.12
        if using_todo:
            if start < now < end:
                item.add('STATUS', 'IN-PROCESS')
            elif now > end:
                item.add('STATUS', 'COMPLETED')
        cal.add_component(item)
    return cal 
Example #7
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        document_id = request.GET.get('document_id')
        if not document_id:
            return JsonResponse({'error': "Document id is not defined."})

        sample_length = 100
        # Create calendar
        cal = icalendar.Calendar()
        cal.add('prodid', 'ContraxSuite (https://contraxsuite.com)')
        cal.add('version', settings.VERSION_NUMBER)

        # Filter to text unit
        for du in self.get_queryset():
            event = icalendar.Event()
            event.add("summary", "Calendar reminder for document {0}, text unit {1}:\n{2}"
                      .format(du.text_unit.document.name, du.text_unit_id,
                              du.text_unit.text[:sample_length]))
            event.add("dtstart", du.date)
            event.add("dtend", du.date)
            event.add("dtstamp", du.date)
            cal.add_component(event)

        filename = "document-{0}.ics".format(document_id)

        response = HttpResponse(cal.to_ical(), content_type='text/calendar; charset=utf8')
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
        return response


# --------------------------------------------------------
# Date Duration Usage Views
# -------------------------------------------------------- 
Example #8
Source File: calendar.py    From uqcsbot with MIT License 5 votes vote down vote up
def get_calendar(assessment):
    """
    Returns a compiled calendar containing the given assessment.
    """
    calendar = Calendar()
    for assessment_item in assessment:
        course, task, due_date, weight = assessment_item
        event = Event()
        event['uid'] = str(uuid())
        event['summary'] = f'{course} ({weight}): {task}'
        try:
            start_datetime, end_datetime = get_parsed_assessment_due_date(assessment_item)
        except DateSyntaxException as e:
            bot.logger.error(e.message)
            # If we can't parse a date, set its due date to today
            # and let the user know through its summary.
            # TODO(mitch): Keep track of these instances to attempt to accurately
            # parse them in future. Will require manual detection + parsing.
            start_datetime = end_datetime = datetime.today()
            event['summary'] = ("WARNING: DATE PARSING FAILED\n"
                                "Please manually set date for event!\n"
                                "The provided due date from UQ was"
                                + f" '{due_date}\'. {event['summary']}")
        event.add('dtstart', start_datetime)
        event.add('dtend', end_datetime)
        calendar.add_component(event)
    return calendar.to_ical() 
Example #9
Source File: planning.py    From PonyConf with Apache License 2.0 5 votes vote down vote up
def _as_ics(self, citymeo=False):
        if not self.initialized:
            self._lazy_init()
        cal = iCalendar()
        cal.add('prodid', '-//PonyConf.io//PonyConf//FR')
        cal.add('version', '2.0')
        cal.add('x-wr-calname', self.conference.name)
        cal.add('x-wr-timezone', settings.TIME_ZONE)
        cal.add('calscale', 'GREGORIAN')
        talks = self.talks
        if citymeo and talks.exists():
            talks = talks.filter(start_date__gte=now()-timedelta(minutes=5))
            if talks.exists():
                limit = talks.first().start_date.replace(hour=23, minute=59, second=59)
                talks = talks.filter(start_date__lte=limit)
        for talk in talks:
            event = iEvent()
            event.add('dtstart', talk.start_date)
            if not talk.end_date:
                continue
            event.add('dtend', talk.end_date)
            event.add('dtstamp', talk.updated)
            event.add('summary', talk.title)
            if talk.room:
                event.add('location', talk.room)
            event.add('status', 'CONFIRMED' if talk.accepted else 'TENTATIVE')
            if not citymeo:
                event.add('description', talk.description)
            event.add('uid', '%s/%s' % (self.site.domain, talk.id))
            cal.add_component(event)
        return cal.to_ical() 
Example #10
Source File: views.py    From coursys with GNU General Public License v3.0 4 votes vote down vote up
def calendar_ical(request, token, userid):
    """
    Return an iCalendar for this user, authenticated by the token in the URL
    """
    local_tz = pytz.timezone(settings.TIME_ZONE)
    utc = pytz.utc
    user = get_object_or_404(Person, userid=userid)
    
    # make sure the token in the URL (32 hex characters) matches the token stored in the DB
    config = _get_calendar_config(user)
    if 'token' not in config or config['token'] != token:
        # no token set or wrong token provided
        return NotFoundResponse(request)
    #else:
        # authenticated

    now = datetime.datetime.now()
    start = local_tz.localize(now - datetime.timedelta(days=180))
    end = local_tz.localize(now + datetime.timedelta(days=365))
    
    cal = Calendar()
    cal.add('version', '2.0')
    cal.add('prodid', '-//SFU CourSys//courses.cs.sfu.ca//')
    cal.add('X-PUBLISHED-TTL', 'PT1D')
    
    for data in _calendar_event_data(user, start, end, local_tz, dt_string=False):
        e = Event()
        e['uid'] = str(data['id'])
        e.add('summary', data['title'])
        e.add('dtstart', _ical_datetime(utc, data['start']))
        e.add('dtend', _ical_datetime(utc, data['end']))
        if data['category'] in ('DUE', 'HOLIDAY'):
            # these shouldn't be "busy" on calendars
            e.add('transp', 'TRANSPARENT')
        else:
            e.add('transp', 'OPAQUE')

        # spec says no TZID on UTC times
        if 'TZID' in e['dtstart'].params:
            del e['dtstart'].params['TZID']
        if 'TZID' in e['dtend'].params:
            del e['dtend'].params['TZID']
        
        e.add('categories', data['category'])
        if 'url' in data:
            e.add('url', data['url'])
        if 'location' in data:
            e.add('location', data['location'])
        cal.add_component(e)

    resp = HttpResponse(cal.to_ical(), content_type="text/calendar")
    return resp 
Example #11
Source File: views.py    From heltour with MIT License 4 votes vote down vote up
def ical_from_pairings_list(self, pairings, calendar_title, uid_component):
        cal = Calendar()
        cal.add('prodid', '-//{}//www.lichess4545.com//'.format(calendar_title))
        cal.add('version', '2.0')

        has_league = hasattr(self, 'league')
        league = self.league if has_league else None

        for pairing in pairings:
            if not has_league:
                round_ = pairing.get_round()
                if not round_:
                    continue
                league = round_.season.league
            time_control_seconds = league.time_control_total()
            if time_control_seconds:
                game_duration = timedelta(seconds=time_control_seconds * 2)
            else:
                game_duration = timedelta(hours=3)

            ical_event = Event()
            ical_event.add('summary', '{} vs {}'.format(
                pairing.white.lichess_username,
                pairing.black.lichess_username,
            ))
            ical_event.add('dtstart', pairing.scheduled_time)
            ical_event.add('dtend', pairing.scheduled_time + game_duration)
            ical_event.add('dtstamp', pairing.scheduled_time + game_duration)
            ical_event['uid'] = 'lichess4545.{}.events.{}'.format(
                uid_component,
                pairing.id,
            )
            cal.add_component(ical_event)

        response = HttpResponse(cal.to_ical(), content_type="text/calendar")
        response['Content-Disposition'] = 'attachment; filename={}.ics'.format(
            slugify(calendar_title)
        )
        return response


# -------------------------------------------------------------------------------
# Actual views 
Example #12
Source File: cal-ics.py    From inky-phat with MIT License 4 votes vote down vote up
def has_event(dt):
    if ics is None:
        return False

    for item in ics.walk():
        if isinstance(item, icalendar.Event):
            dtstart = item['DTSTART'].dt
            dtend = item['DTEND'].dt
            summary = item['SUMMARY']

            if dt >= dtstart and dt < dtend:
                return True

    return False 
Example #13
Source File: views.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 4 votes vote down vote up
def get(self, request, *args, **kwargs):
        document_pk = request.GET.get('document_pk')
        if not document_pk:
            return Http404("Document pk is not defined.")

        sample_length = 100
        # Create calendar
        cal = icalendar.Calendar()
        cal.add('prodid', 'ContraxSuite (https://contraxsuite.com)')
        cal.add('version', '1.0.3')

        # Filter to text unit
        for du in self.get_json_data()['data']:
            event = icalendar.Event()
            event.add("summary", "Calendar reminder for document {0}, text unit {1}:\n{2}"
                      .format(du['document__name'], du['text_unit_id'],
                              du['text_unit__textunittext__text'][:sample_length]))
            event.add("dtstart", du['date'])
            event.add("dtend", du['date'])
            event.add("dtstamp", du['date'])
            cal.add_component(event)

        filename = "document-{0}.ics".format(document_pk)

        response = HttpResponse(cal.to_ical(), content_type='text/calendar; charset=utf8')
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
        return response 
Example #14
Source File: ical.py    From sync-engine with GNU Affero General Public License v3.0 4 votes vote down vote up
def process_invites(db_session, message, account, invites):
    new_uids = [event.uid for event in invites]

    # Get the list of events which share a uid with those we received.
    # Note that we're limiting this query to events in the 'emailed events'
    # calendar, because that's where all the invites go.
    existing_events = db_session.query(Event).filter(
        Event.calendar_id == account.emailed_events_calendar_id,
        Event.namespace_id == account.namespace.id,
        Event.uid.in_(new_uids)).all()

    existing_events_table = {event.uid: event for event in existing_events}

    for event in invites:
        if event.uid not in existing_events_table:
            # This is some SQLAlchemy trickery -- the events returned
            # by events_from_ics aren't bound to a session yet. Because of
            # this, we don't care if they get garbage-collected. This is
            # important because we only want to keep events we haven't seen
            # yet --- updates are merged with the existing events and are
            # dropped immediately afterwards.
            # By associating the event to the message we make sure it
            # will be flushed to the db.
            event.calendar = account.emailed_events_calendar
            event.message = message
        else:
            # This is an event we already have in the db.
            # Let's see if the version we have is older or newer.
            existing_event = existing_events_table[event.uid]

            if existing_event.sequence_number <= event.sequence_number:
                merged_participants = existing_event.\
                    _partial_participants_merge(event)

                existing_event.update(event)
                existing_event.message = message

                # We have to do this mumbo-jumbo because MutableList does
                # not register changes to nested elements.
                # We could probably change MutableList to handle it (see:
                # https://groups.google.com/d/msg/sqlalchemy/i2SIkLwVYRA/mp2WJFaQxnQJ)
                # but this sounds very brittle.
                existing_event.participants = []
                for participant in merged_participants:
                    existing_event.participants.append(participant) 
Example #15
Source File: ical.py    From sync-engine with GNU Affero General Public License v3.0 4 votes vote down vote up
def process_nylas_rsvps(db_session, message, account, rsvps):
    # The invite sending code generates invites with uids of the form
    # `public_id@nylas.com`. We couldn't use Event.uid for this because
    # it wouldn't work with Exchange (Exchange uids are of the form
    # 1:2323 and aren't guaranteed to be unique).
    new_uids = [_cleanup_nylas_uid(event.uid) for event in rsvps
                if '@nylas.com' in event.uid]

    # Drop uids which aren't base36 uids.
    new_uids = [uid for uid in new_uids if valid_base36(uid)]

    # Get the list of events which share a uid with those we received.
    # Note that we're excluding events from "Emailed events" because
    # we don't want to process RSVPs to invites we received.
    existing_events = db_session.query(Event).filter(
        Event.namespace_id == account.namespace.id,
        Event.calendar_id != account.emailed_events_calendar_id,
        Event.public_id.in_(new_uids)).all()

    existing_events_table = {event.public_id: event
                             for event in existing_events}

    for event in rsvps:
        event_uid = _cleanup_nylas_uid(event.uid)
        if event_uid not in existing_events_table:
            # We've received an RSVP to an event we never heard about. Save it,
            # maybe we'll sync the invite later.
            event.message = message
        else:
            # This is an event we already have in the db.
            existing_event = existing_events_table[event_uid]

            # Is the current event an update?
            if existing_event.sequence_number == event.sequence_number:
                merged_participants = existing_event.\
                    _partial_participants_merge(event)

                # We have to do this mumbo-jumbo because MutableList does
                # not register changes to nested elements.
                # We could probably change MutableList to handle it (see:
                # https://groups.google.com/d/msg/sqlalchemy/i2SIkLwVYRA/mp2WJFaQxnQJ)
                # but it seems very brittle.
                existing_event.participants = []
                for participant in merged_participants:
                    existing_event.participants.append(participant)

                # We need to sync back changes to the event manually
                if existing_event.calendar != account.emailed_events_calendar:
                    schedule_action('update_event', existing_event,
                                    existing_event.namespace.id, db_session,
                                    calendar_uid=existing_event.calendar.uid)

                db_session.flush() 
Example #16
Source File: ical.py    From sync-engine with GNU Affero General Public License v3.0 4 votes vote down vote up
def _generate_rsvp(status, account, event):
    # It seems that Google Calendar requires us to copy a number of fields
    # in the RVSP reply. I suppose it's for reconciling the reply with the
    # invite. - karim
    cal = iCalendar()
    cal.add('PRODID', '-//Nylas sync engine//nylas.com//')
    cal.add('METHOD', 'REPLY')
    cal.add('VERSION', '2.0')
    cal.add('CALSCALE', 'GREGORIAN')

    icalevent = icalendar.Event()
    icalevent['uid'] = event.uid

    if event.organizer_email is not None:
        icalevent['organizer'] = event.organizer_email

    icalevent['sequence'] = event.sequence_number
    icalevent['X-MICROSOFT-CDO-APPT-SEQUENCE'] = icalevent['sequence']

    if event.status == 'confirmed':
        icalevent['status'] = 'CONFIRMED'

    icalevent['dtstamp'] = serialize_datetime(datetime.utcnow())

    if event.start is not None:
        icalevent['dtstart'] = serialize_datetime(event.start)

    if event.end is not None:
        icalevent['dtend'] = serialize_datetime(event.end)

    if event.description is not None:
        icalevent['description'] = event.description

    if event.location is not None:
        icalevent['location'] = event.location

    if event.title is not None:
        icalevent['summary'] = event.title

    attendee = icalendar.vCalAddress(u'MAILTO:{}'.format(
        account.email_address))
    attendee.params['cn'] = account.name
    attendee.params['partstat'] = status
    icalevent.add('attendee', attendee, encode=0)
    cal.add_component(icalevent)

    ret = {}
    ret["cal"] = cal

    return ret