Exemplo n.º 1
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
Exemplo n.º 2
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")
Exemplo n.º 3
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)
Exemplo n.º 4
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')
Exemplo n.º 5
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)