Exemplo n.º 1
0
def create_timezone(tz, first_date=None, last_date=None):
    """
    create an icalendar vtimezone from a pytz.tzinfo

    :param tz: the timezone
    :type tz: pytz.tzinfo
    :param first_date: the very first datetime that needs to be included in the
    transition times, typically the DTSTART value of the (first recurring)
    event
    :type first_date: datetime.datetime
    :param last_date: the last datetime that needs to included, typically the
    end of the (very last) event (of a recursion set)
    :returns: timezone information
    :rtype: icalendar.Timezone()

    we currently have a problem here:

       pytz.timezones only carry the absolute dates of time zone transitions,
       not their RRULEs. This will a) make for rather bloated VTIMEZONE
       components, especially for long recurring events, b) we'll need to
       specify for which time range this VTIMEZONE should be generated and c)
       will not be valid for recurring events that go into eternity.

    Possible Solutions:

    As this information is not provided by pytz at all, there is no
    easy solution, we'd really need to ship another version of the OLSON DB.

    """

    # TODO last_date = None, recurring to infinity

    first_date = datetime.today() if not first_date else to_naive_utc(
        first_date)
    last_date = datetime.today() if not last_date else to_naive_utc(last_date)
    timezone = icalendar.Timezone()
    timezone.add('TZID', tz)

    dst = {
        one[2]: 'DST' in two.__repr__()
        for one, two in iter(tz._tzinfos.items())
    }
    bst = {
        one[2]: 'BST' in two.__repr__()
        for one, two in iter(tz._tzinfos.items())
    }

    # looking for the first and last transition time we need to include
    first_num, last_num = 0, len(tz._utc_transition_times) - 1
    first_tt = tz._utc_transition_times[0]
    last_tt = tz._utc_transition_times[-1]
    for num, dt in enumerate(tz._utc_transition_times):
        if dt > first_tt and dt < first_date:
            first_num = num
            first_tt = dt
        if dt < last_tt and dt > last_date:
            last_num = num
            last_tt = dt

    timezones = dict()
    for num in range(first_num, last_num + 1):
        name = tz._transition_info[num][2]
        if name in timezones:
            ttime = tz.fromutc(
                tz._utc_transition_times[num]).replace(tzinfo=None)
            if 'RDATE' in timezones[name]:
                timezones[name]['RDATE'].dts.append(
                    icalendar.prop.vDDDTypes(ttime))
            else:
                timezones[name].add('RDATE', ttime)
            continue

        if dst[name] or bst[name]:
            subcomp = icalendar.TimezoneDaylight()
        else:
            subcomp = icalendar.TimezoneStandard()

        subcomp.add('TZNAME', tz._transition_info[num][2])
        subcomp.add(
            'DTSTART',
            tz.fromutc(tz._utc_transition_times[num]).replace(tzinfo=None))
        subcomp.add('TZOFFSETTO', tz._transition_info[num][0])
        subcomp.add('TZOFFSETFROM', tz._transition_info[num - 1][0])
        timezones[name] = subcomp

    for subcomp in timezones.values():
        timezone.add_component(subcomp)

    return timezone
Exemplo n.º 2
0
    event.add('ATTACH', attachval, parameters=paramdict)


cal = Calendar()
cal.add('prodid', '-//testCalPy')
cal.add('version', '2.0')
cal.add('calscale', 'GREGORIAN')

tzd = icalendar.TimezoneDaylight()
tzd.add('rrule', {'freq': 'yearly', 'bymonth': 3, 'byday': '2su'})
tzd.add('dtstart', datetime.datetime(2007, 3, 11, 2, 0, 0))
tzd.add('tzname', 'MDT')
tzd.add('TZOFFSETFROM', datetime.timedelta(hours=-7))
tzd.add('TZOFFSETTO', datetime.timedelta(hours=-6))

tzs = icalendar.TimezoneStandard()
tzs.add('rrule', {'freq': 'yearly', 'bymonth': 11, 'byday': '1su'})
tzs.add('dtstart', datetime.datetime(2007, 11, 4, 2, 0, 0))
tzs.add('tzname', 'MST')
tzs.add('TZOFFSETFROM', datetime.timedelta(hours=-6))
tzs.add('TZOFFSETTO', datetime.timedelta(hours=-7))

tzc = icalendar.Timezone()
tzc.add('tzid', 'America/Denver')
tzc.add_component(tzd)
tzc.add_component(tzs)

cal.add_component(tzc)

tz = pytz.timezone('America/Denver')
Exemplo n.º 3
0
def construct_icalendar(context, events):
    """Returns an icalendar.Calendar object.

    :param context: A content object, which is used for calendar details like
                    Title and Description. Usually a container, collection or
                    the event itself.

    :param events: The list of event objects, which are included in this
                   calendar.
    """
    cal = icalendar.Calendar()
    cal.add('prodid', PRODID)
    cal.add('version', VERSION)

    cal_tz = default_timezone(context)
    if cal_tz:
        cal.add('x-wr-timezone', cal_tz)

    tzmap = {}
    if not hasattr(events, '__getslice__'):  # LazyMap doesn't have __iter__
        events = [events]
    for event in events:
        if ICatalogBrain.providedBy(event) or\
                IContentListingObject.providedBy(event):
            event = event.getObject()
        acc = IEventAccessor(event)
        tz = acc.timezone
        # TODO: the standard wants each recurrence to have a valid timezone
        # definition. sounds decent, but not realizable.
        if not acc.whole_day:  # whole day events are exported as dates without
            # timezone information
            if isinstance(tz, tuple):
                tz_start, tz_end = tz
            else:
                tz_start = tz_end = tz
            tzmap = add_to_zones_map(tzmap, tz_start, acc.start)
            tzmap = add_to_zones_map(tzmap, tz_end, acc.end)
        cal.add_component(IICalendarEventComponent(event).to_ical())

    for (tzid, transitions) in tzmap.items():
        cal_tz = icalendar.Timezone()
        cal_tz.add('tzid', tzid)
        cal_tz.add('x-lic-location', tzid)

        for (transition, tzinfo) in transitions.items():

            if tzinfo['dst']:
                cal_tz_sub = icalendar.TimezoneDaylight()
            else:
                cal_tz_sub = icalendar.TimezoneStandard()

            cal_tz_sub.add('tzname', tzinfo['name'])
            cal_tz_sub.add('dtstart', transition)
            cal_tz_sub.add('tzoffsetfrom', tzinfo['tzoffsetfrom'])
            cal_tz_sub.add('tzoffsetto', tzinfo['tzoffsetto'])
            # TODO: add rrule
            # tzi.add('rrule',
            #         {'freq': 'yearly', 'bymonth': 10, 'byday': '-1su'})
            cal_tz.add_component(cal_tz_sub)
        cal.add_component(cal_tz)

    return cal
Exemplo n.º 4
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',
                  tz.localize(datetime.datetime(2012, 2, 13, 10, 00, 00)))
        event.add('dtend',
                  tz.localize(datetime.datetime(2012, 2, 17, 18, 00, 00)))
        event.add('dtstamp',
                  tz.localize(datetime.datetime(2010, 10, 10, 10, 10, 10)))
        event.add('created',
                  tz.localize(datetime.datetime(2010, 10, 10, 10, 10, 10)))
        event.add('uid', u'123456')
        event.add('last-modified',
                  tz.localize(datetime.datetime(2010, 10, 10, 10, 10, 10)))
        event.add('summary', u'artsprint 2012')
        # event.add('rrule', u'FREQ=YEARLY;INTERVAL=1;COUNT=10')
        event.add('description', u'sprinting at the artsprint')
        event.add('location', u'aka bild, wien')
        event.add('categories', u'first subject')
        event.add('categories', u'second subject')
        event.add('attendee', u'häns')
        event.add('attendee', u'franz')
        event.add('attendee', u'sepp')
        event.add('contact', u'Max Mustermann, 1010 Wien')
        event.add('url', u'http://plone.org')
        cal.add_component(event)

        test_out = b'|'.join(cal.to_ical().splitlines())
        test_out = test_out.decode('utf-8')

        vtimezone_lines = "BEGIN:VTIMEZONE|TZID:Europe/Vienna|X-LIC-LOCATION:"
        "Europe/Vienna|BEGIN:STANDARD|DTSTART;VALUE=DATE-TIME:19701025T03"
        "0000|RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10|RRULE:FREQ=YEARLY;B"
        "YDAY=-1SU;BYMONTH=3|TZNAME:CET|TZOFFSETFROM:+0200|TZOFFSETTO:+01"
        "00|END:STANDARD|BEGIN:DAYLIGHT|DTSTART;VALUE=DATE-TIME:19700329T"
        "020000|TZNAME:CEST|TZOFFSETFROM:+0100|TZOFFSETTO:+0200|END:DAYLI"
        "GHT|END:VTIMEZONE"
        self.assertTrue(vtimezone_lines in test_out)

        test_str = "DTSTART;TZID=Europe/Vienna;VALUE=DATE-TIME:20120213T100000"
        self.assertTrue(test_str in test_out)
        self.assertTrue("ATTENDEE:sepp" in test_out)

        # ical standard expects DTSTAMP and CREATED in UTC
        self.assertTrue("DTSTAMP;VALUE=DATE-TIME:20101010T081010Z" in test_out)
        self.assertTrue("CREATED;VALUE=DATE-TIME:20101010T081010Z" in test_out)
Exemplo n.º 5
0
def siakng_ics():
    if request.method == 'GET':
        return render_template('index.html')

    try:
        raw = request.form.get('tabel-jadwal')
        raw = raw[raw.index(prefix):raw.index(suffix) + len(suffix)]
        raw = raw.replace('<br>', delimiter)
        rows = pandas.read_html(raw)[0].to_dict('records')

        cal = icalendar.Calendar()
        cal.add('prodid', 'PRODID:-//faisalhanif.id//NONSGML SIAKNG.ics//ID')
        cal.add('version', '2.0')

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

        tzs = icalendar.TimezoneStandard()
        tzs.add('tzname', 'WIB')
        tzs.add('dtstart', datetime.datetime(1970, 1, 1, 0, 0, 0))
        tzs.add('TZOFFSETFROM', datetime.timedelta(hours=7))
        tzs.add('TZOFFSETTO', datetime.timedelta(hours=7))

        tzc.add_component(tzs)
        cal.add_component(tzc)
        tz = pytz.timezone('Asia/Jakarta')

        for row in rows:
            row = list(row.values())
            periode_raw = row[4]
            kelas_raw = row[2]
            jadwal_raw = row[5]
            ruangan_raw = row[6]

            periodes = periode_raw.split(delimiter)
            kelas = kelas_raw[:kelas_raw.index(delimiter)]
            jadwals = jadwal_raw.split(delimiter)
            ruangans = ruangan_raw.split(delimiter)

            assert len(periodes) == len(jadwals) == len(ruangans)

            for periode, jadwal, ruangan in zip(periodes, jadwals, ruangans):
                event = icalendar.Event()

                jadwal_by, jadwal = jadwal.split(', ')
                periode_op, periode_ed = periode.split(' - ')

                op, ed = [
                    datetime.datetime.strptime(periode_op + ' ' + jam,
                                               '%d/%m/%Y %H.%M')
                    for jam in jadwal.split('-')
                ]
                op = onDay(op, days_i[jadwal_by])
                ed = onDay(ed, days_i[jadwal_by])
                true_ed = datetime.datetime.strptime(
                    periode_ed + ' ' + '23.59.59', '%d/%m/%Y %H.%M.%S')

                event.add('dtstart', tz.localize(op))
                event.add('dtend', tz.localize(ed))
                event.add('dtstamp', tz.localize(datetime.datetime.today()))
                event.add('rrule', {'freq': 'weekly', 'until': true_ed})
                event.add('summary', kelas)
                event.add('location', ruangan)

                status = request.form.get('status')
                event.add('status', status_s[status])

                event_hash = hashlib.sha1(
                    (kelas + str(op)).encode()).hexdigest()
                event.add('uid', uuid.uuid5(uuid.NAMESPACE_URL, event_hash))

                cal.add_component(event)

        return Response(
            cal.to_ical(),
            mimetype='text/calendar',
            headers={'Content-disposition': 'attachment; filename=SIAKNG.ics'})

    except:
        return Response(
            'ERROR',
            mimetype='text/plain',
            headers={'Content-disposition': 'attachment; filename=ERROR'})
Exemplo n.º 6
0
Arquivo: O2.py Projeto: ghyun8/O2
    def create_ical(self, name, summary, description, location, count, st_hr,
                    st_mn, et_hr, et_mn, day, start_date):
        """ Create iCal file with given values """
        cal = ical.Calendar()
        """ Add Timezone """
        timezone = ical.Timezone()
        timezone.add('TZID', pytz.timezone('US/Eastern'))

        timezone_standard = ical.TimezoneStandard()
        timezone_standard.add('DTSTART', dt.datetime(1601, 11, 4, 2, 0, 0))
        timezone_standard.add('RRULE', {
            'FREQ': 'YEARLY',
            'BYDAY': '1SU',
            'BYMONTH': '11'
        })
        timezone_standard.add('TZOFFSETFROM', dt.timedelta(hours=-4))
        timezone_standard.add('TZOFFSETTO', dt.timedelta(hours=-5))

        timezone_daylight = ical.TimezoneDaylight()
        timezone_daylight.add('DTSTART', dt.datetime(1601, 3, 11, 2, 0, 0))
        timezone_daylight.add('RRULE', {
            'FREQ': 'YEARLY',
            'BYDAY': '2SU',
            'BYMONTH': '3'
        })
        timezone_daylight.add('TZOFFSETFROM', dt.timedelta(hours=-5))
        timezone_daylight.add('TZOFFSETTO', dt.timedelta(hours=-4))

        timezone.add_component(timezone_standard)
        timezone.add_component(timezone_daylight)

        cal.add_component(timezone)
        """ Add Event"""
        event = ical.Event()
        event.add(
            'DTSTART',
            dt.datetime(2015,
                        9,
                        start_date,
                        st_hr,
                        st_mn,
                        0,
                        tzinfo=pytz.timezone('US/Eastern')))
        event.add(
            'DTEND',
            dt.datetime(2015,
                        9,
                        start_date,
                        et_hr,
                        et_mn,
                        0,
                        tzinfo=pytz.timezone('US/Eastern')))
        event.add('SUMMARY', summary)
        event.add('DESCRIPTION', description)
        event.add('LOCATION', location)
        event.add('RRULE', {'FREQ': 'weekly', 'COUNT': count, 'BYDAY': day})
        cal.add_component(event)

        f = open(name, "wb")
        f.write(cal.to_ical())
        f.close()
Exemplo n.º 7
0
def create_timezone(tz, first_date=None, last_date=None):
    """
    create an icalendar vtimezone from a pytz.tzinfo object

    :param tz: the timezone
    :type tz: pytz.tzinfo
    :param first_date: the very first datetime that needs to be included in the
    transition times, typically the DTSTART value of the (first recurring)
    event
    :type first_date: datetime.datetime
    :param last_date: the last datetime that needs to included, typically the
    end of the (very last) event (of a recursion set)
    :returns: timezone information
    :rtype: icalendar.Timezone()

    we currently have a problem here:

       pytz.timezones only carry the absolute dates of time zone transitions,
       not their RRULEs. This will a) make for rather bloated VTIMEZONE
       components, especially for long recurring events, b) we'll need to
       specify for which time range this VTIMEZONE should be generated and c)
       will not be valid for recurring events that go into eternity.

    Possible Solutions:

    As this information is not provided by pytz at all, there is no
    easy solution, we'd really need to ship another version of the OLSON DB.

    """
    if isinstance(tz, pytz.tzinfo.StaticTzInfo):
        return _create_timezone_static(tz)

    # TODO last_date = None, recurring to infinity

    first_date = dt.datetime.today() if not first_date else to_naive_utc(
        first_date)
    last_date = dt.datetime.today() if not last_date else to_naive_utc(
        last_date)
    timezone = icalendar.Timezone()
    timezone.add('TZID', tz)

    # This is not a reliable way of determining if a transition is for
    # daylight savings.
    # From 1927 to 1941 New Zealand had GMT+11:30 (NZ Mean Time) as standard
    # and GMT+12:00 (NZ Summer Time) as daylight savings time.
    # From 1941 GMT+12:00 (NZ Standard Time) became standard time.
    # So NZST (NZ Summer/Standard Time) can refer to standard or daylight
    # savings time.  And this code depends on the random order the _tzinfos
    # are returned.
    # dst = {
    #     one[2]: 'DST' in two.__repr__()
    #     for one, two in iter(tz._tzinfos.items())
    # }
    # bst = {
    #     one[2]: 'BST' in two.__repr__()
    #     for one, two in iter(tz._tzinfos.items())
    # }
    # ...
    #   if dst[name] or bst[name]:

    # looking for the first and last transition time we need to include
    first_num, last_num = 0, len(tz._utc_transition_times) - 1
    first_tt = tz._utc_transition_times[0]
    last_tt = tz._utc_transition_times[-1]
    for num, transtime in enumerate(tz._utc_transition_times):
        if transtime > first_tt and transtime < first_date:
            first_num = num
            first_tt = transtime
        if transtime < last_tt and transtime > last_date:
            last_num = num
            last_tt = transtime

    timezones = dict()
    for num in range(first_num, last_num + 1):
        name = tz._transition_info[num][2]
        if name in timezones:
            ttime = tz.fromutc(
                tz._utc_transition_times[num]).replace(tzinfo=None)
            if 'RDATE' in timezones[name]:
                timezones[name]['RDATE'].dts.append(
                    icalendar.prop.vDDDTypes(ttime))
            else:
                timezones[name].add('RDATE', ttime)
            continue

        if tz._transition_info[num][1]:
            subcomp = icalendar.TimezoneDaylight()
        else:
            subcomp = icalendar.TimezoneStandard()

        subcomp.add('TZNAME', tz._transition_info[num][2])
        subcomp.add(
            'DTSTART',
            tz.fromutc(tz._utc_transition_times[num]).replace(tzinfo=None))
        subcomp.add('TZOFFSETTO', tz._transition_info[num][0])
        subcomp.add('TZOFFSETFROM', tz._transition_info[num - 1][0])
        timezones[name] = subcomp

    for subcomp in timezones.values():
        timezone.add_component(subcomp)

    return timezone