Beispiel #1
0
def _add_event_component_ics(
        component: cal.Event, calendar_content: List[Dict[str, Any]]) -> None:
    """Appends event data from an *.ics file.

    Args:
        component: An event component.
        calendar_content: A list of event data.
    """
    calendar_content.append({
        "Head": str(component.get('summary')),
        "Content": str(component.get('description')),
        "S_Date": component.get('dtstart').dt.replace(tzinfo=None),
        "E_Date": component.get('dtend').dt.replace(tzinfo=None),
        "Location": str(component.get('location')),
    })
Beispiel #2
0
def _is_valid_data_event_ics(component: cal.Event) -> bool:
    """Whether the ics event data is valid.

    Args:
        component: An event component.

    Returns:
        True if valid, otherwise returns False.
    """
    return not (str(component.get('summary')) is None
                or component.get('dtstart') is None
                or component.get('dtend') is None
                or not _is_date_in_range(component.get('dtstart').dt)
                or not _is_date_in_range(component.get('dtend').dt)
                )
    def test_repr(self):
        """Test correct class representation.
        """
        from icalendar.cal import Component, Calendar, Event

        component = Component()
        component['key1'] = 'value1'

        self.assertTrue(
            re.match(r"Component\({u?'KEY1': 'value1'}\)", str(component)))

        calendar = Calendar()
        calendar['key1'] = 'value1'

        self.assertTrue(
            re.match(r"VCALENDAR\({u?'KEY1': 'value1'}\)", str(calendar)))

        event = Event()
        event['key1'] = 'value1'

        self.assertTrue(re.match(r"VEVENT\({u?'KEY1': 'value1'}\)",
                                 str(event)))

        # Representation of nested Components
        nested = Component(key1='VALUE1')
        nested.add_component(component)
        calendar.add_component(event)
        nested.add_component(calendar)

        self.assertTrue(
            re.match(
                r"Component\({u?'KEY1': 'VALUE1'}, Component\({u?'KEY1': 'value1'}\), VCALENDAR\({u?'KEY1': 'value1'}, VEVENT\({u?'KEY1': 'value1'}\)\)\)",  # nopep8
                str(nested)))
Beispiel #4
0
 def test_missing_dtstart(self):
     ev = Event()
     self.assertRaises(
         MissingProperty,
         apply_time_range_vevent,
         datetime.utcnow(),
         datetime.utcnow(),
         ev,
         self._tzify,
     )
Beispiel #5
0
def generate_calendar(request):
    """http://codespeak.net/icalendar/"""

    cal = Calendar()
    cal.add("prodid", "-//Club Connect//ericleong.me//")
    cal.add("version", "2.0")
    posts = Post.objects.order_by("-created")

    cal["X-WR-CALNAME"] = "Club Connect Events"
    cal["X-PUBLISH-TTL"] = "PT12H"
    cal["CALSCALE"] = "GREGORIAN"
    cal["METHOD"] = "PUBLISH"

    # TODO: separate out private events using a private URL?
    # TODO: switch to using EDT
    for post in posts:
        if post.start_time:
            # Make sure we have a time
            event = Event()
            event.add("summary", vText(post.title))
            event.add("dtstart", post.start_time)
            event.add("dtend", post.end_time if post.end_time else post.start_time)
            # event.add('dtstamp', datetime(2005,4,4,0,10,0,tzinfo=UTC))
            event["uid"] = vText(post.id)
            event["organizer"] = vText(post.author.username)
            event["description"] = vText(post.description)
            event["url"] = vUri(post.get_absolute_url())

            if post.location:
                if post.location.room:
                    event["location"] = vText("%s (%s)" % (post.location.name, post.location.room))
                else:
                    event["location"] = vText(post.location.name)

            for commit in post.committed.all():
                attendee = vCalAddress("MAILTO:" + commit.email)
                name = (
                    ([commit.first_name, commit.last_name])
                    if (commit.first_name and commit.last_name)
                    else commit.username
                )
                attendee.params["cn"] = vText(name)
                event.add("attendee", attendee, encode=0)

            cal.add_component(event)

    return HttpResponse(cal.to_ical().replace("\n", "\r\n"), content_type="text/calendar")
Beispiel #6
0
    def test_cal_Component(self):
        from icalendar.cal import Component, Calendar, Event
        from icalendar import prop

        # A component is like a dictionary with extra methods and attributes.
        c = Component()
        c.name = 'VCALENDAR'

        # Every key defines a property.A property can consist of either a
        # single item. This can be set with a single value...
        c['prodid'] = '-//max m//icalendar.mxm.dk/'
        self.assertEqual(c, Calendar({'PRODID':
                                      '-//max m//icalendar.mxm.dk/'}))

        # or with a list
        c['ATTENDEE'] = ['Max M', 'Rasmussen']
        self.assertEqual(
            c,
            Calendar({
                'ATTENDEE': ['Max M', 'Rasmussen'],
                'PRODID': '-//max m//icalendar.mxm.dk/'
            }))

        ### ADD MULTIPLE VALUES TO A PROPERTY

        # if you use the add method you don't have to considder if a value is
        # a list or not.
        c = Component()
        c.name = 'VEVENT'

        # add multiple values at once
        c.add('attendee', ['*****@*****.**', '*****@*****.**'])

        # or add one per line
        c.add('attendee', '*****@*****.**')
        c.add('attendee', '*****@*****.**')

        # add again multiple values at once to very concatenaton of lists
        c.add('attendee', ['*****@*****.**', '*****@*****.**'])

        self.assertEqual(
            c,
            Event({
                'ATTENDEE': [
                    prop.vCalAddress('*****@*****.**'),
                    prop.vCalAddress('*****@*****.**'),
                    prop.vCalAddress('*****@*****.**'),
                    prop.vCalAddress('*****@*****.**'),
                    prop.vCalAddress('*****@*****.**'),
                    prop.vCalAddress('*****@*****.**')
                ]
            }))

        ###

        # You can get the values back directly ...
        c.add('prodid', '-//my product//')
        self.assertEqual(c['prodid'], prop.vText(u'-//my product//'))

        # ... or decoded to a python type
        self.assertEqual(c.decoded('prodid'), b'-//my product//')

        # With default values for non existing properties
        self.assertEqual(c.decoded('version', 'No Version'), 'No Version')

        c.add('rdate', [datetime(2013, 3, 28), datetime(2013, 3, 27)])
        self.assertTrue(isinstance(c.decoded('rdate'), prop.vDDDLists))

        # The component can render itself in the RFC 2445 format.
        c = Component()
        c.name = 'VCALENDAR'
        c.add('attendee', 'Max M')
        self.assertEqual(
            c.to_ical(),
            b'BEGIN:VCALENDAR\r\nATTENDEE:Max M\r\nEND:VCALENDAR\r\n')

        # Components can be nested, so You can add a subcompont. Eg a calendar
        # holds events.
        e = Component(summary='A brief history of time')
        e.name = 'VEVENT'
        e.add('dtend', '20000102T000000', encode=0)
        e.add('dtstart', '20000101T000000', encode=0)
        self.assertEqual(
            e.to_ical(), b'BEGIN:VEVENT\r\nDTEND:20000102T000000\r\n' +
            b'DTSTART:20000101T000000\r\nSUMMARY:A brief history of time\r' +
            b'\nEND:VEVENT\r\n')

        c.add_component(e)
        self.assertEqual(c.subcomponents, [
            Event({
                'DTEND': '20000102T000000',
                'DTSTART': '20000101T000000',
                'SUMMARY': 'A brief history of time'
            })
        ])

        # We can walk over nested componentes with the walk method.
        self.assertEqual([i.name for i in c.walk()], ['VCALENDAR', 'VEVENT'])

        # We can also just walk over specific component types, by filtering
        # them on their name.
        self.assertEqual([i.name for i in c.walk('VEVENT')], ['VEVENT'])

        self.assertEqual([i['dtstart'] for i in c.walk('VEVENT')],
                         ['20000101T000000'])

        # We can enumerate property items recursively with the property_items
        # method.
        self.assertEqual(c.property_items(),
                         [('BEGIN', b'VCALENDAR'),
                          ('ATTENDEE', prop.vCalAddress('Max M')),
                          ('BEGIN', b'VEVENT'), ('DTEND', '20000102T000000'),
                          ('DTSTART', '20000101T000000'),
                          ('SUMMARY', 'A brief history of time'),
                          ('END', b'VEVENT'), ('END', b'VCALENDAR')])

        # We can also enumerate property items just under the component.
        self.assertEqual(c.property_items(recursive=False),
                         [('BEGIN', b'VCALENDAR'),
                          ('ATTENDEE', prop.vCalAddress('Max M')),
                          ('END', b'VCALENDAR')])

        sc = c.subcomponents[0]
        self.assertEqual(sc.property_items(recursive=False),
                         [('BEGIN', b'VEVENT'), ('DTEND', '20000102T000000'),
                          ('DTSTART', '20000101T000000'),
                          ('SUMMARY', 'A brief history of time'),
                          ('END', b'VEVENT')])

        # Text fields which span multiple mulitple lines require proper
        # indenting
        c = Calendar()
        c['description'] = u'Paragraph one\n\nParagraph two'
        self.assertEqual(
            c.to_ical(),
            b'BEGIN:VCALENDAR\r\nDESCRIPTION:Paragraph one\\n\\nParagraph two'
            + b'\r\nEND:VCALENDAR\r\n')

        # INLINE properties have their values on one property line. Note the
        # double quoting of the value with a colon in it.
        c = Calendar()
        c['resources'] = 'Chair, Table, "Room: 42"'
        self.assertEqual(c, Calendar({'RESOURCES':
                                      'Chair, Table, "Room: 42"'}))

        self.assertEqual(
            c.to_ical(),
            b'BEGIN:VCALENDAR\r\nRESOURCES:Chair\\, Table\\, "Room: 42"\r\n' +
            b'END:VCALENDAR\r\n')

        # The inline values must be handled by the get_inline() and
        # set_inline() methods.
        self.assertEqual(c.get_inline('resources', decode=0),
                         [u'Chair', u'Table', u'Room: 42'])

        # These can also be decoded
        self.assertEqual(c.get_inline('resources', decode=1),
                         [b'Chair', b'Table', b'Room: 42'])

        # You can set them directly ...
        c.set_inline('resources', ['A', 'List', 'of', 'some, recources'],
                     encode=1)
        self.assertEqual(c['resources'], 'A,List,of,"some, recources"')

        # ... and back again
        self.assertEqual(c.get_inline('resources', decode=0),
                         ['A', 'List', 'of', 'some, recources'])

        c['freebusy'] = '19970308T160000Z/PT3H,19970308T200000Z/PT1H,'\
                        + '19970308T230000Z/19970309T000000Z'
        self.assertEqual(c.get_inline('freebusy', decode=0), [
            '19970308T160000Z/PT3H', '19970308T200000Z/PT1H',
            '19970308T230000Z/19970309T000000Z'
        ])

        freebusy = c.get_inline('freebusy', decode=1)
        self.assertTrue(isinstance(freebusy[0][0], datetime))
        self.assertTrue(isinstance(freebusy[0][1], timedelta))
Beispiel #7
0
def generate_ics(showings, location):
    calendar = Calendar()
    caplocation = location.capitalize()
    calendar.add('prodid', '-//BFiCal %s Calendar//bfical.com//' % caplocation)
    calendar.add('version', '2.0')

    for showing in showings:
        if showing.master_location == location:
            calevent = CalEvent()
            if showing.ident:
                calevent.add('uid', '*****@*****.**' % showing.ident)
            else:
                calevent.add('uid', '*****@*****.**' % int(time.time()))
            calevent.add('summary', showing.parent().name)
            calevent.add('description', showing.parent().precis)
            calevent.add('location', '%s, BFI %s, London' % (showing.location, caplocation))
            calevent.add('dtstart', showing.start.replace(tzinfo=GB_TZ).astimezone(pytz.utc))
            calevent.add('dtend', showing.end.replace(tzinfo=GB_TZ).astimezone(pytz.utc))
            calevent.add('url', showing.parent().src_url)
            calevent.add('sequence', int(time.time())) # TODO - fix
            #calevent.add('dtstamp', datetime.datetime.now())

            calendar.add_component(calevent)

    return calendar
Beispiel #8
0
def icsout(inp):
    from icalendar.cal import Calendar, Event
    from hashlib import sha1
    inp = os.path.expanduser(inp)
    cal = Calendar()
    cal.add('prodid', '-//ccal.py 0.5//niij.org//')
    cal.add('version', '2.0')

    entries = Entries(every=True, comm=True)
    for entry in entries:
        event = Event()
        event.add('summary', entry.desc)
        event.add('dtstart', entry.dt)
        event.add('dtend', entry.dt + dt.timedelta(days=1))
        event.add('dtstamp', dt.datetime.now())
        uid = "%s%s%s %s" % (entry.dt.year, entry.dt.month, entry.dt.day,
                             entry.desc)
        event.add('uid', sha1(uid.encode('utf-8')).hexdigest())
        if (entry.comm):
            event.add('description', entry.comm.strip())
        cal.add_component(event)
    print(cal.to_ical().decode('utf-8'))
    sys.exit(0)
Beispiel #9
0
    def _create_event(self, match):
        """
        Creates a calendar event for the given match

        :paran match: A Match object holding the match data
        """
        #    print(self.team_data)
        #    print(team_data)

        event = Event()
        event["uid"] = match.id()
        event["location"] = match.location
        event.add("priority", 5)

        event.add("summary", match.summary())
        event.add("description", str(match))
        event.add("dtstart", match.match_start)
        event.add("dtend", match.match_end)
        event.add("dtstamp", datetime.utcnow())

        alarm = Alarm()
        alarm.add("action", "DISPLAY")
        alarm.add("description", "Reminder")
        alarm.add("trigger", timedelta(hours=-1))
        event.add_component(alarm)

        return event
Beispiel #10
0
def main():
    semester_selector = "WS20/21"
    # semester_selector = "SS20"

    group_selector = "EuiDE-9-NT1"

    assert (semester_selector[0:2] == "WS" and len(semester_selector)
            == 7) or (semester_selector[0:2] == "SS"
                      and len(semester_selector) == 4)

    timetable_url = timetable_base_url.replace("%semester%",
                                               semester_selector).replace(
                                                   "%group%", group_selector)
    academic_year_url = academic_year_base_url.replace(
        "%year%",
        f"20{int(semester_selector[2:4]) - 1}-{int(semester_selector[2:4])}"
        if semester_selector[0:2] == "SS" else
        f"20{semester_selector[2:7].replace('/', '-')}")

    fp = urllib.request.urlopen(timetable_url)
    mybytes = fp.read()
    html_doc = mybytes.decode("utf-8").replace("<BR>", seperator)
    fp.close()

    fp = urllib.request.urlopen(academic_year_url)
    mybytes = fp.read()
    html_doc2 = mybytes.decode("utf8")
    fp.close()

    academic_year = Calendar.from_ical(html_doc2)

    semester_date_spans = []
    recess_date_spans = []

    for component in academic_year.walk():
        if component.name == 'VEVENT':
            if component['summary'].startswith(
                    expand_semester(semester_selector)):
                semester_date_spans.append(
                    (component['DTSTART'].dt, component['DTEND'].dt))

            if any(r.lower() in component['summary'].lower() for r in recess):
                recess_date_spans.append(
                    (component['DTSTART'].dt, component['DTEND'].dt))

    weekdates_semester = []

    for start_date, end_date in semester_date_spans:
        delta = end_date - start_date
        for i in range(delta.days + 1):
            day = start_date + timedelta(days=i)
            if not day.weekday() == SATURDAY and not day.weekday() == SUNDAY:
                weekdates_semester.append(day)

    recess_dates_semester = []

    for start_date, end_date in recess_date_spans:
        delta = end_date - start_date
        for i in range(delta.days + 1):
            day = start_date + timedelta(days=i)
            if not day.weekday() == SATURDAY and not day.weekday() == SUNDAY:
                recess_dates_semester.append(day)

    dfs = pd.read_html(html_doc)
    dfs = [
        df.applymap(lambda x: x.replace(u"\xa0", u" ")
                    if isinstance(x, str) else x) for df in dfs
    ]

    timetable = dfs[1].values.tolist()

    cal = Calendar()

    index = 2

    class_list = []
    for i, row in enumerate(timetable):
        if i == 0:
            continue
        for j, cell in enumerate(row):
            if j == 0 or isinstance(cell, float):
                continue
            classes = dfs[index].values.tolist()

            for c in classes:
                print(c[0])
                lecturer, name, room, *_ = c[0].split(seperator)
                if not name in class_list:
                    class_list.append(name)
            index += 1

    print("[")
    for c in class_list:
        print(f"    \"{c}\",")
    print("]")

    index = 2

    for i, row in enumerate(timetable):
        if i == 0:
            continue
        for j, cell in enumerate(row):
            if j == 0 or isinstance(cell, float):
                continue

            time_info = timetable[i][0]
            weekday_tt = timetable[0][j]

            classes = dfs[index].values.tolist()

            for c in classes:
                lecturer, name, room, *_ = c[0].split(seperator)
                odd_even, time_start, time_end = time_info.split(seperator)

                time_start_hour, time_start_minutes = [
                    int(x) for x in time_start.split(COLON)
                ]
                time_end_hour, time_end_minutes = [
                    int(x) for x in time_end.split(COLON)
                ]

                if odd_even == "1.WO":
                    week_mod = 1
                elif odd_even == "2.WO":
                    week_mod = 0
                else:
                    print(f"Error. Invalid odd_even identifier {odd_even}")
                    exit()

                for day in weekdates_semester:
                    _, weeknumber, weekday = day.isocalendar()

                    if not weekday - 1 == WEEKDAYS[weekday_tt.lower()]:
                        continue
                    if not weeknumber % 2 == week_mod:
                        continue
                    if any([
                            d.day == day.day and d.month == day.day
                            and d.year == day.year
                            for d in recess_dates_semester
                    ]):
                        continue

                    e = Event()
                    e.add('summary', name)
                    e.add(
                        'dtstart',
                        datetime(day.year,
                                 day.month,
                                 day.day,
                                 time_start_hour,
                                 time_start_minutes,
                                 0,
                                 tzinfo=pytz.timezone("Europe/Berlin")))
                    e.add(
                        'dtstart',
                        datetime(day.year,
                                 day.month,
                                 day.day,
                                 time_end_hour,
                                 time_end_minutes,
                                 0,
                                 tzinfo=pytz.timezone("Europe/Berlin")))
                    e.add('location', room)
                    e.add('description', f"Dozent: {flip_name(lecturer)}")

                    cal.add_component(e)

            index += 1

    print(cal.to_ical().decode('utf-8'))

    with open('my.ics', 'w', encoding='utf-8') as f:
        f.write(cal.to_ical().decode('utf-8'))
Beispiel #11
0
def create_cal_from_classes(dfs_list, class_list: List[str],
                            semester_selector: str):
    assert (semester_selector[0:2] == "WS" and len(semester_selector)
            == 7) or (semester_selector[0:2] == "SS"
                      and len(semester_selector) == 4)

    academic_year_url = academic_year_base_url.replace(
        "%year%",
        f"20{int(semester_selector[2:4]) - 1}-{int(semester_selector[2:4])}"
        if semester_selector[0:2] == "SS" else
        f"20{semester_selector[2:7].replace('/', '-')}")

    fp = urllib.request.urlopen(academic_year_url)
    mybytes = fp.read()
    html_doc2 = mybytes.decode("utf8")
    fp.close()

    academic_year = Calendar.from_ical(html_doc2)

    semester_date_spans = []
    recess_date_spans = []

    for component in academic_year.walk():
        if component.name == 'VEVENT':
            if component['summary'].startswith(
                    expand_semester(semester_selector)):
                semester_date_spans.append(
                    (component['DTSTART'].dt, component['DTEND'].dt))

            if any(r.lower() in component['summary'].lower() for r in recess):
                recess_date_spans.append(
                    (component['DTSTART'].dt, component['DTEND'].dt))

    weekdates_semester = []

    for start_date, end_date in semester_date_spans:
        delta = end_date - start_date
        for i in range(delta.days + 1):
            day = start_date + timedelta(days=i)
            if not day.weekday() == SATURDAY and not day.weekday() == SUNDAY:
                weekdates_semester.append(day)

    recess_dates_semester = []

    for start_date, end_date in recess_date_spans:
        delta = end_date - start_date
        for i in range(delta.days + 1):
            day = start_date + timedelta(days=i)
            if not day.weekday() == SATURDAY and not day.weekday() == SUNDAY:
                recess_dates_semester.append(day)

    cal = Calendar()
    cal.add("version", 2.0)
    cal.add("prodid", "-//flmann.de//timetable//DE")
    cal.add('x-wr-calname', "Stundenplan")
    cal.add('x-wr-caldesc', "Stundenplan TU Dresden ET")
    cal.add('x-wr-timezone', "Europe/Berlin")

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

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

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

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

    dates_added = set()

    for dfs in dfs_list:
        timetable = dfs[1].values.tolist()
        index = 2

        for i, row in enumerate(timetable):
            if i == 0:
                continue
            for j, cell in enumerate(row):
                if j == 0 or isinstance(cell, float):
                    continue

                time_info = timetable[i][0]
                weekday_tt = timetable[0][j]

                classes = dfs[index].values.tolist()

                for c in classes:
                    lecturer, name, room, *_ = c[0].split(seperator)
                    odd_even, time_start, time_end = time_info.split(seperator)

                    print(f"{name=} {name in class_list}")

                    if not name in class_list:
                        continue

                    time_start_hour, time_start_minutes = [
                        int(x) for x in time_start.split(COLON)
                    ]
                    time_end_hour, time_end_minutes = [
                        int(x) for x in time_end.split(COLON)
                    ]

                    if odd_even == "1.WO":
                        week_mod = 1
                    elif odd_even == "2.WO":
                        week_mod = 0
                    else:
                        print(f"Error. Invalid odd_even identifier {odd_even}")
                        exit()

                    id = f"{c[0]}{time_info}"
                    if id in dates_added:
                        continue
                    dates_added.add(id)

                    for day in weekdates_semester:
                        _, weeknumber, weekday = day.isocalendar()
                        if not weekday - 1 == WEEKDAYS[weekday_tt.lower()]:
                            continue
                        if not weeknumber % 2 == week_mod:
                            continue
                        if any([
                                d.day == day.day and d.month == day.day
                                and d.year == day.year
                                for d in recess_dates_semester
                        ]):
                            continue

                        e = Event()
                        e.add('summary', name)
                        e.add(
                            'dtstart',
                            datetime(day.year,
                                     day.month,
                                     day.day,
                                     time_start_hour,
                                     time_start_minutes,
                                     0,
                                     tzinfo=pytz.timezone("Europe/Berlin")))
                        e.add(
                            'dtend',
                            datetime(day.year,
                                     day.month,
                                     day.day,
                                     time_end_hour,
                                     time_end_minutes,
                                     0,
                                     tzinfo=pytz.timezone("Europe/Berlin")))
                        e.add('dtstamp', datetime.now())
                        e.add('uid', uuid.uuid4())
                        e.add('location', room)
                        e.add('description', f"Dozent: {flip_name(lecturer)}")

                        cal.add_component(e)

                index += 1

    return cal.to_ical().decode('utf-8').replace('\n\n',
                                                 '\n').replace('\r\n', '\n')
Beispiel #12
0
    duration = datetime.timedelta(1)


props = {
    'categories': opts.categories.split(','),
    'dtstart': vDate(dtstart.date()),
    'created': vDatetime(datetime.datetime.now()),
    'class': 'PUBLIC',
    }
if status is not None:
    props['status'] = status
if location is not None:
    props['location'] = vText(location)
if opts.event_url:
    props['url'] = vUri(opts.event_url)
if description is not None:
    props['summary'] = vText(description)
if dtend is not None:
    props['dtend'] = vDate(dtend.date())
if duration is not None:
    props['duration'] = vDuration(duration)

uid = str(uuid.uuid1())
props['UID'] = uid
ev = Event(**props)

c = Calendar()
c.add_component(ev)

utils.add_member(opts.url, 'text/calendar', c.to_ical())
Beispiel #13
0
def add(request):
    def submit_form(form):
        return render_to_response('add.html', {'form': form},
                                  context_instance=RequestContext(request))

    if request.method == 'GET':
        if not request.user.is_authenticated():
            pass  # Ask the user if the want to sign on

        data = {}
        if 'url' in request.GET:
            data.update({'url': request.GET['url']})

        day = datetime.today()
        if 'day' in request.GET:
            if request.GET['day'] != "":
                day = request.GET[
                    'day']  # Javascript hands you Tue May 20 1990
                data.update({'date': day})
            else:
                data.update({'date': day.strftime('%a %b %d %Y')})
        else:
            data.update({'date': day.strftime('%a %b %d %Y')})

        start_time = datetime.today()
        start_time = start_time.strftime('%H:%M')
        if 'start_time' in request.GET:
            if request.GET['start_time'] != '':
                start_time = request.GET['start_time']

        data.update({'start_time': start_time})

        if 'end_time' in request.GET:
            end_time = request.GET['end_time']
            if end_time != 'null':
                data.update({'end_time': end_time})

        data.update({'mail': 'outlook'})

        form = EventForm(data)
        return submit_form(form)

    # Form was returned with data
    if request.method == 'POST':
        form = EventForm(request.POST)
        if not form.is_valid():
            return submit_form(form)

        title = form.cleaned_data['title']
        date = form.cleaned_data['date']
        start_time = form.cleaned_data['start_time']
        end_time = form.cleaned_data['end_time']
        url = form.cleaned_data['url']
        describe = form.cleaned_data['describe']
        address = form.cleaned_data['address']
        mail = form.cleaned_data['mail']

        latitude = None
        longitude = None

        if address != u'':
            local = geocode(address)
            if local != None:
                if 'address' in local:
                    address = local['address']

                if 'latitude' in local and 'longitude' in local:
                    latitude = local['latitude']
                    longitude = local['longitude']

        # If they move the pointer to be more specific override address
        """
        if form.data['lati'] and form.data['lngi']:
            latitude = form.data['lati']
            longitude = form.data['lngi']
        """
        event = EventModel(title=title,
                           date=date,
                           start_time=start_time,
                           end_time=end_time,
                           address=address,
                           longitude=longitude,
                           latitude=latitude,
                           description=describe,
                           url=url)
        # Save this event
        event.save()

        # Make sure you save the event before connecting it to a user
        if request.user.is_authenticated():
            event.connect(request.user)

        # Ical or Outlook iCal file
        if mail == 'outlook' or mail == 'ical':
            # Create the iCal file
            cal = Calendar()
            cal.add('version', '2.0')
            cal.add('prodid',
                    '-//Microsoft Corporation//Windows Calendar 1.0//EN')
            cal.add('method', 'PUBLISH')

            event = Event()
            event.add('summary', describe)
            if start_time != None:
                dt = datetime.combine(date, start_time)
            else:
                dt = date
            event.add('dtstart', dt)
            event.add('dtstamp', dt)

            if end_time != None:
                de = datetime.combine(date, end_time)
                event.add('dtend', de)

            g = (latitude, latitude)
            event.add('geo', g)
            event.add('location', address)

            uid = date.isoformat() + '@wenzit.net'
            event.add('UID', uid)
            event.add('url', url)
            cal.add_component(event)

            f = open('schedule.ics', 'wb')
            f.write(cal.as_string())
            f.close()

            response = HttpResponse(cal.as_string(), mimetype='text/calendar')
            response[
                'Content-Disposition'] = 'attachment; filename=schedule.ics'

            return response

        # Send the event to google
        elif mail == 'google':
            response = "http://www.google.com/calendar/event?action=TEMPLATE"
            response += "&text=" + urllib.quote_plus(title)

            if start_time != None:
                ds = datetime.combine(date, start_time)
            else:
                ds = date

            if end_time != None:
                de = datetime.combine(date, end_time)
                response += "&dates=" + vDatetime(ds).ical()+ \
                            '/'+vDatetime(de).ical()
            else:
                response += "&dates=" + vDatetime(ds).ical()

            response += "&details=" + urllib.quote_plus(title)
            response += "&location=" + urllib.quote_plus(address)
            response += "&sprop=" + urllib.quote_plus(url)
            return HttpResponseRedirect(response)

        # Send the event to Yahoo
        if mail == 'yahoo':
            response = 'http://calendar.yahoo.com/?v=60'
            response += '&TITLE=' + urllib.quote_plus(title)

            ds = datetime.combine(date, start_time)
            if end_time:
                de = datetime.combine(date, end_time)
                dur = de - ds
                hrs, left = divmod(dur.seconds, 3600)
                mins, secs = divmod(left, 60)
                dur = '%02d%02d' % (hrs, mins)
            else:
                dur = ''

            response += '&ST=' + vDatetime(ds).ical()
            response += '&DUR=' + dur

            response += '&in_loc=' + urllib.quote_plus(address)
            response += '&DESC=' + urllib.quote_plus(title)
            response += '&URL=' + urllib.quote_plus(url)
            return HttpResponseRedirect(response)
Beispiel #14
0
def icsout(inp):
    from icalendar.cal import Calendar, Event
    from hashlib import sha1
    inp = os.path.expanduser(inp)
    cal = Calendar()
    cal.add('prodid', '-//ccal.py 0.5//niij.org//')
    cal.add('version', '2.0')

    entries = Entries(every=True, comm=True)
    for entry in entries:
        event = Event()
        event.add('summary', entry.desc)
        event.add('dtstart', entry.dt)
        event.add('dtend', entry.dt+dt.timedelta(days=1))
        event.add('dtstamp', dt.datetime.now())
        uid = "%s%s%s %s" % (entry.dt.year, entry.dt.month, entry.dt.day, entry.desc)
        event.add('uid', sha1(uid.encode('utf-8')).hexdigest())
        if (entry.comm):
            event.add('description', entry.comm.strip())
        cal.add_component(event)
    print(cal.to_ical().decode('utf-8'))
    sys.exit(0)