Python icalendar.Calendar() Examples

The following are 15 code examples of icalendar.Calendar(). 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: feedgenerator.py    From django-ical with MIT License 6 votes vote down vote up
def write(self, outfile, encoding):
        """
        Writes the feed to the specified file in the
        specified encoding.
        """
        cal = Calendar()
        cal.add("version", "2.0")
        cal.add("calscale", "GREGORIAN")

        for ifield, efield in FEED_FIELD_MAP:
            val = self.feed.get(ifield)
            if val is not None:
                cal.add(efield, val)

        self.write_items(cal)

        to_ical = getattr(cal, "as_string", None)
        if not to_ical:
            to_ical = cal.to_ical
        outfile.write(to_ical()) 
Example #2
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def calendar(request):
    """
    Calendar display: all the hard work is JS/AJAX.
    """
    #user = get_object_or_404(Person, userid=request.user.username)
    context = {}
    return render(request, "dashboard/calendar.html", context) 
Example #3
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def create_calendar_url(request):
    user = get_object_or_404(Person, userid=request.user.username)
    config = _get_calendar_config(user)
    if request.method == 'POST':
        form = FeedSetupForm(request.POST)
        if form.is_valid():
            token = new_feed_token()
            config['token'] = token
            uc = UserConfig.objects.filter(user=user, key="calendar-config")
            if uc:
                uc = uc[0]
                uc.value = config
            else:
                uc = UserConfig(user=user, key="calendar-config", value=config)
            uc.save()
            messages.add_message(request, messages.SUCCESS, 'Calendar URL configured.')
            return HttpResponseRedirect(reverse('config:config'))
    else:
        if 'token' in config:
            # pre-check if we're changing the token
            form = FeedSetupForm({'agree': True})
        else:
            form = FeedSetupForm()

    context = {'form': form}
    return render(request, "dashboard/calendar_url.html", context) 
Example #4
Source File: ics.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_ical(self, encoding='utf-8', **kwargs):
		"""
		Convert the calendar object to a string in the iCalendar format.

		:return: The string representation of the data.
		:rtype: str
		"""
		return super(Calendar, self).to_ical(**kwargs).decode('utf-8') 
Example #5
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 #6
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 #7
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 #8
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 #9
Source File: ical.py    From autosuspend with GNU General Public License v2.0 5 votes vote down vote up
def _collect_recurrence_changes(calendar: icalendar.Calendar) -> ChangeMapping:
    ConcreteChangeMapping = Dict[str, List[icalendar.cal.Event]]  # noqa
    recurring_changes = {}  # type: ConcreteChangeMapping
    for component in calendar.walk():
        if component.name != "VEVENT":
            continue
        if component.get("recurrence-id"):
            if component.get("uid") not in recurring_changes:
                recurring_changes[component.get("uid")] = []
            recurring_changes[component.get("uid")].append(component)
    return recurring_changes 
Example #10
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 #11
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 #12
Source File: ics_generator.py    From everyclass-server with Mozilla Public License 2.0 4 votes vote down vote up
def generate(name: str, cards: Dict[Tuple[int, int], List[Dict]], semester: Semester, filename: str) -> None:
    """
    生成 ics 文件并保存到目录

    :param name: 姓名
    :param cards: 参与的课程
    :param semester: 当前导出的学期
    :param filename: 输出的文件名称,带后缀
    :return: None
    """
    from everyclass.server import statsd

    with tracer.trace("calendar_init"):
        semester_string = semester.to_str(simplify=True)
        semester = semester.to_tuple()

        # 创建 calender 对象
        cal = Calendar()
        cal.add('prodid', '-//Admirable//EveryClass//EN')
        cal.add('version', '2.0')
        cal.add('calscale', 'GREGORIAN')
        cal.add('method', 'PUBLISH')
        cal.add('X-WR-CALNAME', name + '的' + semester_string + '课表')
        cal.add('X-WR-TIMEZONE', 'Asia/Shanghai')

        # 时区
        tzc.add_component(tzs)
        cal.add_component(tzc)

    with tracer.trace("add_events"):
        # 创建 events
        for time in range(1, 7):
            for day in range(1, 8):
                if (day, time) in cards:
                    for card in cards[(day, time)]:
                        for week in card['week']:
                            dtstart = _get_datetime(week, day, get_time(time)[0], semester)
                            dtend = _get_datetime(week, day, get_time(time)[1], semester)

                            if dtstart.year == 1984:
                                continue

                            cal.add_component(_build_event(card_name=card['name'],
                                                           times=(dtstart, dtend),
                                                           classroom=card['classroom'],
                                                           teacher=card['teacher'],
                                                           week_string=card['week_string'],
                                                           current_week=week,
                                                           cid=card['cid']))

    with tracer.trace("write_file"):
        with open(os.path.join(calendar_dir(), filename), 'wb') as f:
            data = cal.to_ical()
            statsd.histogram('calendar.ics.generate.size', len(data))
            f.write(data) 
Example #13
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 #14
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 #15
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