예제 #1
0
def output(cal_name, cal_data, exam_lst, firstMonday):
    ical = icalendar.Calendar()
    ical["verison"] = "2.0"
    ical["x-wr-calname"] = cal_name

    # parse class
    for day in range(0, 7):
        for time_pnt in range(0, 6):
            for each_class in cal_data[day][time_pnt]:
                try:
                    for week in each_class["weeks"]:
                        target_date = firstMonday + datetime.timedelta(weeks=week-1, days=day)
                        
                        start_datetime = target_date + misc.get_class_start_time(time_pnt)
                        end_datetime = target_date + misc.get_class_end_time(time_pnt)

                        thisClass = icalendar.Event()
                        thisClass["summary"] = each_class["name"]
                        thisClass["location"] = each_class["classroom"]
                        thisClass["dtend;TZID=Asia/Shanghai"] = end_datetime.strftime("%Y%m%dT%H%M%S")
                        thisClass["dtstart;TZID=Asia/Shanghai"] = start_datetime.strftime("%Y%m%dT%H%M%S")
                        thisClass["uid"] = \
                            start_datetime.strftime("%Y%m%dT%H%M%S") +\
                            "w" + str(week) +\
                            "@" + config.CrawlerParams.username

                        ical.add_component(thisClass)
                except:
                    pass

    # parse exam
    for each_exam in exam_lst:
        thisExamAlarm = icalendar.Alarm()
        thisExamAlarm["ACTION"] = "AUDIO"
        thisExamAlarm["TRIGGER"] = "-P1D"  # remind 1 day earlier
        thisExamAlarm["ATTACH;VALUE"] = "URI:Chord"
        thisExamAlarm["UID"] = thisExamAlarm["X-WR-ALARMUID"] = \
            each_exam["start"].strftime("%Y%m%dT%H%M%S") +\
            "wexam_alarm@" + config.CrawlerParams.username

        thisExam = icalendar.Event()
        thisExam["summary"] = "【考试】" + each_exam["examname"]
        thisExam["location"] = each_exam["classroom"]
        thisExam["dtend;TZID=Asia/Shanghai"] = each_exam["end"].strftime("%Y%m%dT%H%M%S")
        thisExam["dtstart;TZID=Asia/Shanghai"] = each_exam["start"].strftime("%Y%m%dT%H%M%S")
        thisExam["UID"] = \
            each_exam["start"].strftime("%Y%m%dT%H%M%S") +\
            "wexam@" + config.CrawlerParams.username
        
        # thisExam.add_component(thisExamAlarm)
        ical.add_component(thisExam)

    if config.OutputTarget.stdout:
        print(ical.to_ical().decode('utf-8').replace('\r\n', '\n'))
    else:
        with open(config.OutputTarget.filePath, "wb") as fp:
            fp.write(ical.to_ical())
예제 #2
0
파일: utils.py 프로젝트: manonthemat/froide
def add_ical_events(foirequest, cal):
    event_timezone = pytz.timezone(settings.TIME_ZONE)

    def tz(x):
        return x.astimezone(event_timezone)

    uid = 'event-%s-{pk}@{domain}'.format(
        pk=foirequest.id, domain=settings.SITE_URL.split('/')[-1])

    title = '{} [#{}]'.format(foirequest.title, foirequest.pk)
    url = settings.SITE_URL + foirequest.get_absolute_url()

    event = icalendar.Event()
    event.add('uid', uid % 'request')
    event.add('dtstamp', tz(timezone.now()))
    event.add('dtstart', tz(foirequest.first_message))
    event.add('url', url)
    event.add('summary', title)
    event.add('description', foirequest.description)
    cal.add_component(event)

    if foirequest.due_date:
        event = icalendar.Event()
        event.add('uid', uid % 'duedate')
        event.add('dtstamp', tz(timezone.now()))
        event.add('dtstart', tz(foirequest.due_date).date())
        event.add('url', url)
        event.add('summary', _('Due date: %s') % title)
        event.add('description', foirequest.description)
        cal.add_component(event)

    if foirequest.status == 'awaiting_response' and (
            foirequest.resolution in ('partially_successful', 'refused')):

        responses = foirequest.response_messages()
        if responses:
            appeal_deadline = foirequest.law.calculate_due_date(
                date=responses[-1].timestamp
            )
            event = icalendar.Event()
            event.add('uid', uid % 'appeal_deadline')
            event.add('dtstamp', tz(timezone.now()))
            event.add('dtstart', tz(appeal_deadline).date())
            event.add('url', url)
            event.add('summary', _('Appeal deadline: %s') % title)
            event.add('description', foirequest.description)
            alarm = icalendar.Alarm()
            alarm.add('trigger', icalendar.prop.vDuration(-timedelta(days=1)))
            alarm.add('action', 'DISPLAY')
            alarm.add('description', _('Appeal deadline: %s') % title)
            event.add_component(alarm)
            cal.add_component(event)
예제 #3
0
def examples_for_term(course_year, term):
    examples = list(course_year.examples(term))

    events = []

    for example in examples:
        events.append(
            icalendar.Event(
                summary='P{0.paper_no}: {0.name} - Example paper {0.sheet_no}'.
                format(example),
                dtstart=icalendar.vDatetime(
                    timezone.localize(example.class_start).astimezone(
                        pytz.utc)),
                dtend=icalendar.vDatetime(
                    timezone.localize(example.class_end).astimezone(pytz.utc)),
                dtstamp=icalendar.vDatetime(last_updated),
                location=icalendar.vText(
                    "{} - {}".format(example.class_location, cued_address)
                    if example.class_location else cued_address),
                uid='{0.paper_no}-{0.sheet_no}.{term}.{part}@efw27.user.srcf.net'
                .format(example, term=term, part=course_year.part),
                description=icalendar.vText(
                    'Lecturer: {.class_lecturer}'.format(example))))

    # group and order by issue date, ignoring those issued the previous term
    issue_key = lambda e: e.issue_date
    examples = filter(issue_key, examples)
    examples = sorted(examples, key=issue_key)
    examples = itertools.groupby(examples, issue_key)

    for i, (issue_date, papers) in enumerate(examples):
        # consume the iterable so that we can len() it
        papers = list(papers)
        events.append(
            icalendar.Event(
                summary='Collect {} example paper{}'.format(
                    len(papers), '' if len(papers) == 1 else 's'),
                dtstart=icalendar.vDate(
                    timezone.localize(issue_date).astimezone(pytz.utc)),
                dtend=icalendar.vDate(
                    timezone.localize(issue_date).astimezone(pytz.utc)),
                dtstamp=icalendar.vDatetime(last_updated),
                location=icalendar.vText(cued_address),
                uid='collection-{i}.{term}.{part}@efw27.user.srcf.net'.format(
                    i=i, term=term, part=course_year.part),
                description=icalendar.vText('\n'.join(
                    'P{0.paper_no}: {0.name} - Example paper {0.sheet_no}'.
                    format(p) for p in papers))))

    return events
예제 #4
0
def make_cal(target, num=20):
    '''make a ical file
    :parameters:
    target: the target ical file to write
    num: total numbers of aspects.
    '''
    nx = get_next(num)
    cal = ic.Calendar()
    for k, v in nx.iteritems():
        dt = k.to_datetime()
        summary = "{}: URANvsSATU@24".format(v)

        ev = ic.Event()
        ev.add('dtstart', dt.date())
        ev.add('summary', summary)

        # alarm = ic.Alarm()
        # alarm.add('trigger', timedelta(hours=-12))
        # alarm.add('action', 'DISPLAY')
        # alarm.add('description', summary)

        # ev.add_component(alarm)
        cal.add_component(ev)

    with open(target, 'w') as f:
        f.write(cal.to_ical())
        f.close()
예제 #5
0
    def test_issue_116(self):
        """Issue #116/#117 - How to add 'X-APPLE-STRUCTURED-LOCATION'
        """
        event = icalendar.Event()
        event.add(
            "X-APPLE-STRUCTURED-LOCATION",
            "geo:-33.868900,151.207000",
            parameters={
                "VALUE": "URI",
                "X-ADDRESS": "367 George Street Sydney CBD NSW 2000",
                "X-APPLE-RADIUS": "72",
                "X-TITLE": "367 George Street"
            }
        )
        self.assertEqual(
            event.to_ical(),
            b'BEGIN:VEVENT\r\nX-APPLE-STRUCTURED-LOCATION;VALUE=URI;'
            b'X-ADDRESS="367 George Street Sydney \r\n CBD NSW 2000";'
            b'X-APPLE-RADIUS=72;X-TITLE="367 George Street":'
            b'geo:-33.868900\r\n \\,151.207000\r\nEND:VEVENT\r\n'
        )

        # roundtrip
        self.assertEqual(
            event.to_ical(),
            icalendar.Event.from_ical(event.to_ical()).to_ical()
        )
예제 #6
0
    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['text_unit__document__name'], du['text_unit__pk'],
                              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_pk)

        response = HttpResponse(cal.to_ical(), content_type='text/calendar; charset=utf8')
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
        return response
예제 #7
0
파일: http_api.py 프로젝트: arturodr/indico
def serialize_collaboration(cal, fossil, now):
    event = ical.Event()
    url = str(fossil['url'])
    event.set('uid', '*****@*****.**' % fossil['uniqueId'])
    event.set('dtstamp', now)
    event.set('dtstart', getAdjustedDate(fossil['startDate'], None, "UTC"))
    event.set('dtend', getAdjustedDate(fossil['endDate'], None, "UTC"))
    event.set('url', url)
    event.set('categories', "VideoService - " + fossil['type'])
    event.set('summary', VideoExportUtilities.getCondensedPrefix(fossil['type'],
                                                                 fossil['status']) + fossil['title'].decode('utf-8'))
    loc = fossil.get('location', '')
    if loc:
        loc = loc.decode('utf-8')
    if fossil.get('room',''):
        loc += ': ' + fossil['room'].decode('utf-8')
    event.set('location', loc)
    description = "Event URL: " + url
    audience = fossil.get("audience", None)
    if audience:
        description = "Audience: %s\n"% audience + description
    event.set('description', description)

    # If there is an alarm required, add a subcomponent to the Event
    if fossil.has_key('alarm'):
        event.add_component(serialize_collaboration_alarm(fossil, now))
    cal.add_component(event)
예제 #8
0
def generate_icalendar_event(event_id):
    """Takes an event id and returns the event in iCal format"""
    cal = Calendar()
    event = icalendar.Event()
    matching_event = Event.query.get(event_id)
    if matching_event is None:
        return api_response(status_code=404, error='Event')
    event.add('summary', matching_event.name)
    event.add('geo', (matching_event.latitude, matching_event.longitude))
    event.add('location', matching_event.location_name)
    event.add('color', matching_event.color)
    event.add('dtstart', matching_event.start_time)
    event.add('dtend', matching_event.end_time)
    event.add('logo', matching_event.logo)
    event.add('email', matching_event.email)
    event.add('description', matching_event.description)
    event.add(
        'url',
        url_for('event_detail.display_event_detail_home',
                identifier=matching_event.identifier,
                _external=True))
    cal.add_component(event)

    #Saving ical in file
    filename = "event_calendar/event-calendar-" + str(event_id) + ".ics"
    f = open(os.path.join(os.path.realpath('.') + '/static/', filename), 'wb')
    f.write(cal.to_ical())
    f.close()

    return api_response(data=jsonify(calendar=str(cal.to_ical),
                                     filename=filename),
                        status_code=event_status_code(event_id),
                        error='Event')
예제 #9
0
def generate_basic_component(entity,
                             uid=None,
                             url=None,
                             title=None,
                             description=None):
    """Generate an iCalendar component with basic common properties.

    :param entity: Event/session/contribution where properties come from
    :param uid: UID for the component
    :param url: URL for the component (defaults to `entity.external_url`)
    :param title: A title for the component
    :param description: A text based description for the component

    :return: iCalendar event with basic properties
    """
    component = icalendar.Event()

    component.add('dtstamp', now_utc(False))
    component.add('dtstart', entity.start_dt)
    component.add('dtend', entity.end_dt)
    component.add('summary', title or entity.title)

    if uid:
        component.add('uid', uid)

    if not url and hasattr(entity, 'external_url'):
        url = entity.external_url
    if url:
        component.add('url', url)

    location = (f'{entity.room_name} ({entity.venue_name})'
                if entity.venue_name and entity.room_name else
                (entity.venue_name or entity.room_name))
    if location:
        component.add('location', location)

    speaker_list = getattr(entity, 'person_links', [])
    cal_description = []
    if speaker_list:
        speakers = [
            f'{x.full_name} ({x.affiliation})'
            if x.affiliation else x.full_name for x in speaker_list
        ]
        cal_description.append('Speakers: {}'.format(', '.join(speakers)))
    if description is None:
        description = getattr(entity, 'description', None)
    if description:
        desc_text = str(description) or '<p/>'  # get rid of RichMarkup
        try:
            cal_description.append(
                str(html.fromstring(desc_text).text_content()))
        except ParserError:
            # this happens if desc_text only contains a html comment
            pass
    if url:
        cal_description.append(url)
    if cal_description:
        component.add('description', '\n'.join(cal_description))

    return component
예제 #10
0
def serialize_category_ical(category, user, event_filter):
    """Export the events in a category to iCal

    :param category: The category to export
    :param user: The user who needs to be able to access the events
    :param event_filter: A SQLalchemy criterion to restrict which
                         events will be returned.  Usually something
                         involving the start/end date of the event.
    """
    own_room_strategy = joinedload('own_room')
    own_room_strategy.load_only('building', 'floor', 'number', 'name')
    own_room_strategy.lazyload('owner')
    own_venue_strategy = joinedload('own_venue').load_only('name')
    query = (Event.query
             .filter(Event.category_chain.contains([int(category.getId())]),
                     ~Event.is_deleted,
                     event_filter)
             .options(load_only('id', 'start_dt', 'end_dt', 'title', 'description', 'own_venue_name',
                                'own_room_name', 'protection_mode'),
                      subqueryload('acl_entries'),
                      joinedload('person_links'),
                      own_room_strategy,
                      own_venue_strategy)
             .order_by(Event.start_dt))
    events = [e for e in query if e.can_access(user)]
    cal = ical.Calendar()
    cal.add('version', '2.0')
    cal.add('prodid', '-//CERN//INDICO//EN')

    now = now_utc(False)
    for event in events:
        url = url_for('event.conferenceDisplay', confId=event.id, _external=True)
        location = ('{} ({})'.format(event.room_name, event.venue_name)
                    if event.venue_name and event.room_name
                    else (event.venue_name or event.room_name))
        cal_event = ical.Event()
        cal_event.add('uid', u'indico-event-{}@cern.ch'.format(event.id))
        cal_event.add('dtstamp', now)
        cal_event.add('dtstart', event.start_dt)
        cal_event.add('dtend', event.end_dt)
        cal_event.add('url', url)
        cal_event.add('summary', event.title)
        cal_event.add('location', location)
        description = []
        if event.person_links:
            speakers = [u'{} ({})'.format(x.full_name, x.affiliation) if x.affiliation else x.full_name
                        for x in event.person_links]
            description.append(u'Speakers: {}'.format(u', '.join(speakers)))

        if event.description:
            desc_text = unicode(event.description) or u'<p/>'  # get rid of RichMarkup
            try:
                description.append(unicode(html.fromstring(desc_text).text_content()))
            except ParserError:
                # this happens e.g. if desc_text contains only a html comment
                pass
        description.append(url)
        cal_event.add('description', u'\n'.join(description))
        cal.add_component(cal_event)
    return BytesIO(cal.to_ical())
예제 #11
0
파일: ics.py 프로젝트: itkpi/events-admin
def generate_ics(events, config):
    """
    Return an ics file for a given event.
    """

    # Create the Calendar
    calendar = icalendar.Calendar()
    calendar.add('prodid', config.calendar_prodid)
    calendar.add('version', '2.0')
    calendar.add('method', 'publish')

    for event_data in events:
        # Create the event
        event = icalendar.Event()

        # Populate the event
        event.add('summary', event_data['title'])
        event.add('description', get_description(event_data))
        event.add('uid', event_data['id'])
        event.add('location', event_data['place'])
        event.add('dtstart', get_datetime(event_data, 'when_start'))
        if event_data['when_end']:
            event.add('dtend', get_datetime(event_data, 'when_end'))
        event.add('dtstamp', datetime.datetime.now())

        # Add the event to the calendar
        calendar.add_component(event)

    return calendar.to_ical()
예제 #12
0
파일: ics.py 프로젝트: tannewt/us
def generate(dates, output_filename, *, name=None, description=None, uid=None):
    c = ical.Calendar()
    c.add("prodid", "-//electioncal.us generator//circuitpython.org//")
    c.add("version", "2.0")
    path_parts = output_filename.split("/")
    c.add(
        "url",
        ical.vUri("https://electioncal.us/" + "/".join(path_parts[1:-1]) +
                  "/"))
    c.add("source",
          ical.vUri("https://electioncal.us/" + "/".join(path_parts[1:])))
    # c.add('REFRESH-INTERVAL'VALUE=DURATION:P1W, value)
    if name:
        c.add("name", name)
    if description:
        c.add("description", description)
    if uid:
        c.add("uid", uid)

    last_modified = None
    for date in dates:
        event = ical.Event()
        event.add("summary", date["name"])
        event.add("dtstart", ical.vDate(date["date"]))
        c.add_component(event)

    if description:
        c.add("last-modified", ical.vDate(date["date"]))

    with open(output_filename, "wb") as f:
        f.write(c.to_ical())
예제 #13
0
    def test_create_to_ical(self):
        cal = icalendar.Calendar()

        cal.add('prodid', u"-//Plone.org//NONSGML plone.app.event//EN")
        cal.add('version', u"2.0")
        cal.add('x-wr-calname', u"test create calendar")
        cal.add('x-wr-caldesc', u"icalendar tests")
        cal.add('x-wr-relcalid', u"12345")
        cal.add('x-wr-timezone', u"Europe/Vienna")

        tzc = icalendar.Timezone()
        tzc.add('tzid', 'Europe/Vienna')
        tzc.add('x-lic-location', 'Europe/Vienna')

        tzs = icalendar.TimezoneStandard()
        tzs.add('tzname', 'CET')
        tzs.add('dtstart', datetime.datetime(1970, 10, 25, 3, 0, 0))
        tzs.add('rrule', {'freq': 'yearly', 'bymonth': 10, 'byday': '-1su'})
        tzs.add('TZOFFSETFROM', datetime.timedelta(hours=2))
        tzs.add('TZOFFSETTO', datetime.timedelta(hours=1))

        tzd = icalendar.TimezoneDaylight()
        tzd.add('tzname', 'CEST')
        tzd.add('dtstart', datetime.datetime(1970, 3, 29, 2, 0, 0))
        tzs.add('rrule', {'freq': 'yearly', 'bymonth': 3, 'byday': '-1su'})
        tzd.add('TZOFFSETFROM', datetime.timedelta(hours=1))
        tzd.add('TZOFFSETTO', datetime.timedelta(hours=2))

        tzc.add_component(tzs)
        tzc.add_component(tzd)
        cal.add_component(tzc)

        event = icalendar.Event()
        tz = pytz.timezone("Europe/Vienna")
        event.add('dtstart', datetime.datetime(2012, 02, 13, 10, 00, 00, tzinfo=tz))
예제 #14
0
def build_ical(session, filename):
    calendar = icalendar.Calendar()
    calendar.add('prodid', "toggl2ical")
    calendar.add('version', '2.0')
    calendar.add('CALSCALE', 'GREGORIAN')
    calendar.add('X-WR-CALNAME', 'Toggl events')
    calendar.add('method', 'publish')

    for entry in session.query(TimeEntry).order_by(TimeEntry.start):
        entry: TimeEntry
        event = icalendar.Event()
        event.add('summary', entry.description)
        event.add('uid', entry.id)
        event.add('dtstart', entry.start)
        if entry.end:
            adjusted_end = entry.end - timedelta(minutes=5)

            event.add('dtend', adjusted_end)
        else:
            event.add('dtend', datetime.now())
        event.add('dtstamp', datetime.now())
        calendar.add_component(event)

    ical = calendar.to_ical()

    with open(filename, "wb") as file:
        file.write(ical)
예제 #15
0
def ical(db: sqlite3.Connection, emojis: Optional[Emojis]) -> bytes:
    cal = icalendar.Calendar()
    cal.add('prodid', "foursquare-swarm-ical")
    cal.add('version', "2.0")

    for checkin in db.execute("SELECT data FROM checkins ORDER BY createdAt"):
        checkin = json.loads(checkin['data'])

        prefix = emojis.get_emoji_for_venue(
            checkin['venue']) if emojis else "@"

        location = checkin['venue']['location']
        address = ', '.join(location.get('formattedAddress', []))
        if not address:
            address = str(location['lat']) + "," + str(location['lng'])

        ev = icalendar.Event()
        ev.add('uid', checkin['id'] + "@foursquare.com")
        ev.add('url', "https://www.swarmapp.com/self/checkin/" + checkin['id'])
        ev.add('summary', prefix + " " + checkin['venue']['name'])
        ev.add('location', address)
        ev.add('dtstart', datetime.fromtimestamp(checkin['createdAt'],
                                                 pytz.utc))
        ev.add('dtend', datetime.fromtimestamp(checkin['createdAt'], pytz.utc))
        ev.add('geo', (location['lat'], location['lng']))
        cal.add_component(ev)

    return cal.to_ical()
예제 #16
0
def makeEvent(term_start, term_end, section, meeting_time, uid):
    event = icalendar.Event()
    event.add('uid', uid)
    event.add('summary',
              '%s %s' % (section['course_code'], section['section']))
    first_day = firstOccurrence(term_start, meeting_time['days'])
    event.add('dtstart', replaceTime(first_day, meeting_time['start']))
    event.add('dtend', replaceTime(first_day, meeting_time['end']))
    event.add('dtstamp', section['user_updated'])
    event.add('categories', 'CLASS')
    rrule = icalendar.vRecur(
        freq='weekly',
        byday=icalDaysOfWeek(meeting_time['days']),
        until=term_end,
    )
    event.add('rrule', rrule)
    descr = io.StringIO()
    descr.write(section['course_name'])
    if 'type' in meeting_time:
        descr.write('\n' + meeting_time['type'])
    if section['instructors']:
        descr.write('\n\nInstructor')
        if len(section['instructors']) > 1:
            descr.write('s')
        descr.write(': ')
        descr.write(', '.join(
            util.name(instr) for instr in section['instructors']))
    event.add('description', descr.getvalue())
    if meeting_time.get('building') or meeting_time.get('room'):
        loc = '%s %s' % (meeting_time.get('building',
                                          ''), meeting_time.get('room', ''))
        event.add('location', loc.strip())
    return event
예제 #17
0
    def test_create_to_ical(self):
        cal = icalendar.Calendar()

        cal.add('prodid', u"-//Plönë.org//NONSGML plone.app.event//EN")
        cal.add('version', u"2.0")
        cal.add('x-wr-calname', u"äöü ÄÖÜ €")
        cal.add('x-wr-caldesc', u"test non ascii: äöü ÄÖÜ €")
        cal.add('x-wr-relcalid', u"12345")

        event = icalendar.Event()
        event.add('dtstart',
                  pytz.utc.localize(datetime.datetime(2010, 10, 10, 10, 0, 0)))
        event.add('dtend',
                  pytz.utc.localize(datetime.datetime(2010, 10, 10, 12, 0, 0)))
        event.add('created',
                  pytz.utc.localize(datetime.datetime(2010, 10, 10, 0, 0, 0)))
        event.add('uid', u'123456')
        event.add('summary', u'Non-ASCII Test: ÄÖÜ äöü €')
        event.add('description',
                  u'icalendar should be able to de/serialize non-ascii.')
        event.add('location', u'Tribstrül')
        cal.add_component(event)

        ical_lines = cal.to_ical().splitlines()
        cmp = b'PRODID:-//Pl\xc3\xb6n\xc3\xab.org//NONSGML plone.app.event//EN'
        self.assertTrue(cmp in ical_lines)
예제 #18
0
def build_calendar(time_entries):
    # Create the Calendar
    calendar = icalendar.Calendar()
    calendar.add('prodid', "toggl2ical")
    calendar.add('version', '2.0')
    calendar.add('CALSCALE', 'GREGORIAN')
    calendar.add('X-WR-CALNAME', 'Toggl events')
    calendar.add('method', 'publish')

    for entry in time_entries:
        event = icalendar.Event()
        if all(field in entry for field in ["start", "description", "id"]):
            event.add('summary', entry["description"])
            if "tags" in entry:
                event.add('description', ", ".join(entry["tags"]))
            event.add('uid', entry["id"])
            event.add('dtstart', parse(entry["start"]))
            if "stop" in entry:
                event.add('dtend', parse(entry["stop"]))
            else:
                event.add('dtend', datetime.now())
            event.add('dtstamp', datetime.now())
            # event.add('STATUS', 'CANCELLED')
            calendar.add_component(event)

    ical = str(calendar.to_ical()).replace("\\r\\n",
                                           "\n").strip("b'").strip("'")
    return ical
예제 #19
0
    def get(self, *args, **kwargs):
        instance = self.get_object()
        calendar = icalendar.Calendar()

        event = icalendar.Event()
        event.add('summary', instance.title)
        event.add('description', instance.details)
        event.add('url', instance.get_absolute_url())
        event.add('dtstart', instance.start.astimezone(utc))
        event.add('dtend', instance.end.astimezone(utc))
        event['uid'] = instance.uid

        organizer = icalendar.vCalAddress('MAILTO:{}'.format(
            instance.owner.email))
        organizer.params['cn'] = icalendar.vText(instance.owner.full_name)

        event['organizer'] = organizer
        if instance.location:
            event['location'] = icalendar.vText(
                instance.location.formatted_address)

        calendar.add_component(event)

        response = HttpResponse(calendar.to_ical(),
                                content_type='text/calendar')
        response['Content-Disposition'] = 'attachment; filename="%s.ics"' % (
            instance.slug)

        return response
예제 #20
0
    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
예제 #21
0
def serialize_event(cal, fossil, now, id_prefix="indico-event"):
    event = ical.Event()
    event.add('uid', '{}-{}@{}'.format(id_prefix, fossil['id'], url_parse(config.BASE_URL).host))
    event.add('dtstamp', now)
    event.add('dtstart', _deserialize_date(fossil['startDate']))
    event.add('dtend', _deserialize_date(fossil['endDate']))
    event.add('url', fossil['url'])
    event.add('summary', to_unicode(fossil['title']))
    loc = fossil['location'] or ''
    if loc:
        loc = to_unicode(loc)
    if fossil['roomFullname']:
        loc += ' ' + to_unicode(fossil['roomFullname'])
    event.add('location', loc)
    description = ''
    if fossil.get('speakers'):
        speakers = ('{} ({})'.format(speaker['fullName'].encode('utf-8'),
                                     speaker['affiliation'].encode('utf-8')) for speaker in fossil['speakers'])
        description += 'Speakers: {}\n'.format(', '.join(speakers))

    if fossil['description']:
        desc_text = fossil['description'].strip()
        if not desc_text:
            desc_text = '<p/>'
        try:
            description += '{}\n\n{}'.format(to_unicode(html.fromstring(to_unicode(desc_text))
                                                        .text_content()).encode('utf-8'),
                                             fossil['url'].encode('utf-8'))
        except ParserError:
            # this happens e.g. if desc_text contains only a html comment
            description += fossil['url'].encode('utf-8')
    else:
        description += fossil['url']
    event.add('description', description)
    cal.add_component(event)
예제 #22
0
 def get_ics_event(self):
     ievent = icalendar.Event()
     ievent['summary'] = self.event.title
     ievent['dtstart'] = icalendar.vDatetime(self.when.lower).to_ical()
     ievent['dtend'] = icalendar.vDatetime(self.when.upper).to_ical()
     ievent['location'] = icalendar.vText(self.location.name)
     return ievent
예제 #23
0
def weeklyEvent(Course, CalDir):
    event = ical.Event()
    event.add('summary', Course.name)
    #pretty this up with the Course Class
    event.add('dtstart', Course.startDay())
    event.add('dtend', Course.endDay())
    event.add('dtstamp', Course.startDay())

    #for some reason, the ical python module
    #does not like it when i specify >1 days
    #in the same line for 'byday'
    for day in Course.listDays():
        freq = {'freq': 'weekly', 'until': Course.lastDay(), 'byday': day}
        event.add('rrule', freq)

    #adding in exception days / holidays
    #exdate has to have exact time as starttime, and same format (TZID)
    #maybe I should try use exrule (opposite of rrule)
    for day in Course.holiDays():
        event.add('exdate', day)
    event.add('location', Course.locate())
    cal.add_component(event)

    f = open(os.path.join(CalDir, 'Room.ics'), 'wb')
    f.write(cal.to_ical())
    f.close()
예제 #24
0
파일: ical.py 프로젝트: arturodr/indico
def serialize_event(cal, fossil, now, id_prefix="indico-event"):
    event = ical.Event()
    event.set('uid', '*****@*****.**' % (id_prefix, fossil['id']))
    event.set('dtstamp', now)
    event.set('dtstart', getAdjustedDate(fossil['startDate'], None, "UTC"))
    event.set('dtend', getAdjustedDate(fossil['endDate'], None, "UTC"))
    event.set('url', fossil['url'])
    event.set('summary', fossil['title'].decode('utf-8'))
    loc = fossil['location'] or ''
    if loc:
        loc = loc.decode('utf-8')
    if fossil['room']:
        loc += ' ' + fossil['room'].decode('utf-8')
    event.set('location', loc)
    description = ""
    if fossil.has_key("speakers"):
        speakerList = []
        for speaker in fossil["speakers"]:
            speakerList.append("%s (%s)"%(speaker["fullName"], speaker["affiliation"]))
        description += "Speakers: "+ (", ").join(speakerList) + "\n"

    if fossil['description']:
        desc_text = fossil.get('description', '').strip()
        if not desc_text:
            desc_text = '<p/>'
        description += "Description: " + html.fromstring(desc_text.decode('utf-8')).text_content() \
                    + '\nURL: ' + fossil['url']
    else:
        description += "URL: " + fossil['url']
    event.set('description', description)
    cal.add_component(event)
예제 #25
0
def as_ical_event(year, event):
    """
    Convert an event dict into an ical event
    """
    md5 = hashlib.md5()
    md5.update(event['event'].encode('utf-8'))
    md5.update(event['day'].encode('utf-8'))
    md5.update(str(year).encode('utf-8'))
    if 'time' in event:
        md5.update(event['time'].encode('utf-8'))

    guid = uuid.UUID(bytes=md5.digest())

    ics_event = icalendar.Event()
    ics_event.add('summary', event['event'])
    ics_event.add('uid', str(guid) + '@ralismark.github.io')
    ics_event.add('sequence', str(SEQ_NUM))

    date = datetime.datetime.strptime(event['day'],
                                      '%b %d').replace(year=year,
                                                       tzinfo=LOCALTZ)
    if 'time' in event:  # specific time
        dtstart, dtend = parse_duration(event['time'])
        duration = dtend - dtstart
        when = datetime.datetime.combine(date, dtstart.time(),
                                         pytz.timezone(TZID))
        ics_event.add('dtstart', when)
        ics_event.add('duration', duration)
    else:  # all day
        ics_event.add('dtstart', date)
        ics_event.add('dtend', date)

    return ics_event
예제 #26
0
파일: utils.py 프로젝트: mkobel/khal
def new_event(locale, dtstart=None, dtend=None, summary=None, timezone=None,
              allday=False, description=None, location=None, categories=None,
              repeat=None, until=None, alarms=None):
    """create a new event

    :param dtstart: starttime of that event
    :type dtstart: datetime
    :param dtend: end time of that event, if this is a *date*, this value is
        interpreted as being the last date the event is scheduled on, i.e.
        the VEVENT DTEND will be *one day later*
    :type dtend: datetime
    :param summary: description of the event, used in the SUMMARY property
    :type summary: unicode
    :param timezone: timezone of the event (start and end)
    :type timezone: pytz.timezone
    :param allday: if set to True, we will not transform dtstart and dtend to
        datetime
    :type allday: bool
    :returns: event
    :rtype: icalendar.Event
    """

    if dtstart is None:
        raise ValueError("no start given")
    if dtend is None:
        raise ValueError("no end given")
    if summary is None:
        raise ValueError("no summary given")

    if not allday and timezone is not None:
        dtstart = timezone.localize(dtstart)
        dtend = timezone.localize(dtend)

    event = icalendar.Event()
    event.add('dtstart', dtstart)
    event.add('dtend', dtend)
    event.add('dtstamp', datetime.now())
    event.add('summary', summary)
    event.add('uid', generate_random_uid())
    # event.add('sequence', 0)

    if description:
        event.add('description', description)
    if location:
        event.add('location', location)
    if categories:
        event.add('categories', categories)
    if repeat and repeat != "none":
        rrule = rrulefstr(repeat, until, locale)
        event.add('rrule', rrule)
    if alarms:
        for alarm in alarms.split(","):
            alarm = alarm.strip()
            alarm_trig = -1 * guesstimedeltafstr(alarm)
            new_alarm = icalendar.Alarm()
            new_alarm.add('ACTION', 'DISPLAY')
            new_alarm.add('TRIGGER', alarm_trig)
            new_alarm.add('DESCRIPTION', description)
            event.add_component(new_alarm)
    return event
def ical(request, pk):
    user = get_object_or_404(User, pk=pk)
    days = CheckDay.objects.filter(checker=user).all()
    sbz_location = pytz.timezone('Europe/Amsterdam')

    cal = icalendar.Calendar()

    for day in days:
        event = icalendar.Event()
        event['uid'] = day.pk
        event.add(
            'dtstart',
            sbz_location.localize(
                datetime.datetime.combine(day.date, datetime.time(
                    8, 30))).astimezone(pytz.UTC))
        event.add(
            'dtend',
            sbz_location.localize(
                datetime.datetime.combine(day.date, datetime.time(
                    9, 0))).astimezone(pytz.UTC))
        event.add('summary', 'Check Drink Rooms')
        # event.add('description', reverse_lazy('hygiene:check_day', day.pk))
        cal.add_component(event)

    return HttpResponse(cal.to_ical(), content_type='text/calendar')
예제 #28
0
    def render(self):
        cal = icalendar.Calendar()
        cal.add('prodid', '-//asm.cms//Assembly Organizing//')
        stamp = datetime.datetime.now()

        for event in self.context.events:
            ievent = icalendar.Event()
            ievent.add('summary', event.title)
            ievent.add('location', event.location)
            ievent.add('categories', event.class_)
            ievent.add('dtstart', event.start)
            url = event.url
            # A hack to make imported URL data to have the site address
            # correct.
            if re.match("/[^/]", url):
                url = "http://www.assembly.org%s" % url

            ievent.add('url', url)
            ievent.add('dtend', event.end)
            ievent.add('dtstamp', stamp)
            cal.add_component(ievent)

        self.request.response.setHeader('Content-Type',
                                        self.context.content_type)

        return cal.as_string()
예제 #29
0
def output(cal_name, cal_data):
    ical = icalendar.Calendar()
    ical["verison"] = "2.0"
    ical["x-wr-calname"] = cal_name

    for day in range(0, 7):
        for time_pnt in range(0, 6):
         for each_class in cal_data[day][time_pnt]:
            try:
                for week in each_class["weeks"]:
                    config.start_date = config.DateTime.startDate
                    target_date = config.DateTime.startDate + datetime.timedelta(weeks=week-1, days=day)
                    
                    start_datetime = target_date + misc.get_class_start_time(time_pnt)
                    end_datetime = target_date + misc.get_class_end_time(time_pnt)

                    thisClass = icalendar.Event()
                    thisClass["summary"] = each_class["name"]
                    thisClass["location"] = each_class["classroom"]
                    thisClass["dtend;TZID=Asia/Shanghai"] = end_datetime.strftime("%Y%m%dT%H%M%S")
                    thisClass["dtstart;TZID=Asia/Shanghai"] = start_datetime.strftime("%Y%m%dT%H%M%S")
                    thisClass["uid"] = \
                        start_datetime.strftime("%Y%m%dT%H%M%S") +\
                        "w" + str(week) +\
                        "@" + "课表"

                    ical.add_component(thisClass)
            except:
                pass
    
    if config.OutputTarget.stdout:
        print(ical.to_ical().decode('utf-8').replace('\r\n', '\n'))
    else:
        with open(config.OutputTarget.filePath, "wb") as fp:
            fp.write(ical.to_ical())
예제 #30
0
    def buildEvent(self, startDate, endDate, details):
        #print details
        print details['Event Type'], details['Event Name'], startDate, endDate
        event = icalendar.Event()
        event.add('dtstart', startDate)
        event.add('dtend', endDate)
        event.add('summary', details['Event Name'])
        event.add('status', details['Event Status'])
        event.add('location', details['Event Location'])
        event.add('url', details['Registration Website'])

        description = "TXBRA Event: " + details['TXBRA Event'] + os.linesep
        description += "Registration Website: " + details[
            'Registration Website'] + os.linesep
        description += 'Event Type: ' + details['Event Type'] + os.linesep
        description += 'Event Status: ' + details['Event Status'] + os.linesep
        description += 'Event Flyer: ' + details['Event Flyer'] + os.linesep
        description += 'Contact Name: ' + details['Contact Name'] + os.linesep
        description += 'Email Address: ' + details['Email Address'] + os.linesep
        description += 'Event Website: ' + details['Event Website'] + os.linesep
        description += 'Texas Cup Tier: ' + details[
            'Texas Cup Tier'] + os.linesep
        description += 'Texas Cup Event: ' + details[
            'Texas Cup Event'] + os.linesep
        event.add('description', description)
        return event