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")
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
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)
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
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'))
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')
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)