def make_ical(self): for row in self.csv_data: event = Event() event.add('summary', row[self.NAME]) event.add('dtstart', row[self.START_DATE]) event.add('dtend', row[self.END_DATE]) event.add('description', row[self.DESCRIPTION]) event.add('location', row[self.LOCATION]) self.cal.add_component(event) return self.cal
def put2Calendar(): dfh = sortEvents() for i in range(0, len(dfh)): evt = Event() evt.add('summary', dfh.iloc[i]['SUMMARY']) evt.add('location', dfh.iloc[i]['LOCATION']) evt.add('description', dfh.iloc[i]['DESCRIPTION']) evt.add('dtstart', dfh.iloc[i]['DTSTART']) evt.add('dtend', dfh.iloc[i]['DTEND']) daftarCuti.add_component(evt)
def CB4(ical, session): #get ical, read it as Calendar context = ssl._create_unverified_context() user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7' hdr = { 'User-Agent': user_agent, } req = urllib.request.Request(ical, None, hdr) response = urllib.request.urlopen(req, context=context).read() cal = Calendar.from_ical(response) events_dict = {} #iterrate through events in cal with new events from each 'vevent' #search for time,date, title and detaisls and add to events_dict for i, event in enumerate(cal.walk('vevent')): date = event.get('dtstart') try: time = date.dt.hour if (date.dt.hour > 12): time = time - 12 time = str(time) + ":" + str(date.dt.minute).zfill(2) + " PM" else: time = str(time) + ":" + str(date.dt.minute).zfill(2) + " AM" except: continue location = event.get('location') topic = event.get('summary') description = event.get('DESCRIPTION') events_dict[i] = { 'date': str(date.dt.month) + "/" + str(date.dt.day), 'time': time, 'topic': str(topic).strip(), 'location': str(location), 'description': str(description).replace('\n', ' ').replace('\xa0', ' ').strip() } districtNumber = 104 #remove previous entries session.query(Event).filter(Event.district == districtNumber).delete() session.commit() #add items from events_dict to database for event in events_dict.values(): row = Event( title=event['topic'], date=event['date'], details=f'Location: {event["location"]}\n{event["description"]}', time=event['time'], district=districtNumber) session.add(row) session.commit()
def calendar_ical(request, token, userid): """ Return an iCalendar for this user, authenticated by the token in the URL """ local_tz = pytz.timezone(settings.TIME_ZONE) utc = pytz.utc user = get_object_or_404(Person, userid=userid) # make sure the token in the URL (32 hex characters) matches the token stored in the DB config = _get_calendar_config(user) if 'token' not in config or config['token'] != token: # no token set or wrong token provided return NotFoundResponse(request) #else: # authenticated now = datetime.datetime.now() start = local_tz.localize(now - datetime.timedelta(days=180)) end = local_tz.localize(now + datetime.timedelta(days=365)) cal = Calendar() cal.add('version', '2.0') cal.add('prodid', '-//SFU CourSys//courses.cs.sfu.ca//') cal.add('X-PUBLISHED-TTL', 'PT1D') for data in _calendar_event_data(user, start, end, local_tz, dt_string=False): e = Event() e['uid'] = str(data['id']) e.add('summary', data['title']) e.add('dtstart', _ical_datetime(utc, data['start'])) e.add('dtend', _ical_datetime(utc, data['end'])) if data['category'] in ('DUE', 'HOLIDAY'): # these shouldn't be "busy" on calendars e.add('transp', 'TRANSPARENT') else: e.add('transp', 'OPAQUE') # spec says no TZID on UTC times if 'TZID' in e['dtstart'].params: del e['dtstart'].params['TZID'] if 'TZID' in e['dtend'].params: del e['dtend'].params['TZID'] e.add('categories', data['category']) if 'url' in data: e.add('url', data['url']) if 'location' in data: e.add('location', data['location']) cal.add_component(e) return HttpResponse(cal.to_ical(), content_type="text/calendar")
def create_ics(lessons, semester_start_date): cal = Calendar() cal.add('prodid', '-//miaotony//NUAA_ClassSchedule//CN') cal.add('version', VERSION) cal.add('X-WR-TIMEZONE', 'Asia/Shanghai') for lesson in lessons: for week in lesson.vaildWeeks: event = Event() event.add('summary', lesson.courseName) # Lesson start time # 隐含bug:未匹配天目湖校区 lesson_start_hour = { '1': 8, '3': 10, '5': 14, '7': 16, '9': 18, '11': 20, }.get(lesson.course_unit[0]) lesson_start_minute = { '1': 0, '3': 15, '5': 0, '7': 15, '9': 45, '11': 35, }.get(lesson.course_unit[0]) lesson_start_time = semester_start_date + \ timedelta(weeks=week - 1, days=int(lesson.day_of_week) - 1, hours=lesson_start_hour - semester_start_date.hour, minutes=lesson_start_minute - semester_start_date.minute, seconds=-semester_start_date.second, milliseconds=-semester_start_date.microsecond) lesson_end_time = lesson_start_time + timedelta( minutes=50 * len(lesson.course_unit) + 5 * (len(lesson.course_unit) - 1)) # fix隐含bug:课程时间仅一节或超过两节(非连续两节课)的情况 event.add('dtstart', lesson_start_time) event.add('dtend', lesson_end_time) # event.add('dtstamp', datetime.now(tz=timezone('Asia/Shanghai'))) event.add('location', lesson.roomName) try: event.add('description', lesson.output_description(week=week)) except UnicodeDecodeError: print("ERROR!") exit(6) # 放弃python2.x了 cal.add_component(event) return cal
def get(self, request, *args, **kwargs): event_obj = get_object_or_404( self.event_class, id=kwargs[self.event_kwarg] ) cal = Calendar() cal['prodid'] = '-//We All Code//weallcode.org//' cal['version'] = '2.0' cal['calscale'] = 'GREGORIAN' event = Event() event['uid'] = f"{self.event_type.upper()}{event_obj.id:04}@weallcode.org" event['summary'] = self.get_summary(request, event_obj) event['dtstart'] = self.get_dtstart(request, event_obj) event['dtend'] = self.get_dtend(request, event_obj) event['dtstamp'] = event['dtstart'][:-1] if event_obj.location.address: location = ( f"{event_obj.location.name}, {event_obj.location.address}, " f"{event_obj.location.city}, {event_obj.location.state}, {event_obj.location.zip}" ) else: location = f"{event_obj.location.name}" event['location'] = vText(location) event['url'] = f"{settings.SITE_URL}{event_obj.get_absolute_url()}" event['description'] = self.get_description(event_obj) # A value of 5 is the normal or "MEDIUM" priority. # see: https://tools.ietf.org/html/rfc5545#section-3.8.1.9 event['priority'] = 5 cal.add_component(event) event_slug = "weallcode-{event_type}_{date}".format( event_type=self.event_type.lower(), date=arrow.get( event_obj.start_date ).to('local').format('MM-DD-YYYY_HH-mma') ) # Return the ICS formatted calendar response = HttpResponse( cal.to_ical(), content_type='text/calendar', charset='utf-8' ) response['Content-Disposition'] = f"attachment;filename={event_slug}.ics" return response
def create_event(self, uid, title, message, location=None, start=None, stop=None): ical = Calendar.from_ical(self.__ical_data) create = uid is None or '' == uid if start is None: start = datetime.now() if stop is None: stop = start if create: uid = str(datetime.now()).replace( ' ', '@') + '/' + str(start) + '/' + str(uid) event = Event() event.add('uid', uid) event.add('summary', title) event.add('description', message) if location is not None: event.add('location', location) event.add('dtstart', start) event.add('dtend', stop) event.add('dtstamp', datetime.now()) ical.add_component(event) else: for subcomponent in ical.subcomponents: if subcomponent.get('uid') == uid: update_data = { 'summary': subcomponent._encode('summary', title), 'description': subcomponent._encode('description', message), 'dtstart': subcomponent._encode('dtstart', start), 'dtend': subcomponent._encode('dtend', stop) } if location is not None: update_data['location'] = subcomponent._encode( 'location', location) subcomponent.update(update_data) with open(terrariumCalendar.ICS_FILE, 'wb') as fp: fp.write(ical.to_ical()) self.__ical_data = ical.to_ical()
def events_to_ical(events, user=None): """Serialize multiple events into an ical. :param events: A list of events to serialize :param user: The user who needs to be able to access the events """ calendar = Calendar() calendar.add('version', '2.0') calendar.add('prodid', '-//CERN//INDICO//EN') for event in events: cal_event = Event() location = (f'{event.room_name} ({event.venue_name})' if event.venue_name and event.room_name else (event.venue_name or event.room_name)) cal_event.add('uid', 'indico-event-{}@{}'.format(event.id, url_parse(config.BASE_URL).host)) cal_event.add('dtstamp', now_utc(False)) cal_event.add('dtstart', event.start_dt) cal_event.add('dtend', event.end_dt) cal_event.add('url', event.external_url) cal_event.add('summary', event.title) cal_event.add('location', location) description = [] if event.person_links: speakers = [f'{x.full_name} ({x.affiliation})' if x.affiliation else x.full_name for x in event.person_links] description.append('Speakers: {}'.format(', '.join(speakers))) if event.description: desc_text = str(event.description) or '<p/>' # get rid of RichMarkup try: description.append(str(html.fromstring(desc_text).text_content())) except ParserError: # this happens if desc_text only contains a html comment pass description.append(event.external_url) data = {'description': '\n'.join(description)} for update in values_from_signal( signals.event.metadata_postprocess.send('ical-export', event=event, data=data, user=user), as_list=True ): data.update(update) cal_event.add('description', data['description']) calendar.add_component(cal_event) return calendar.to_ical()
def calendar_add(caldav_conn, args): cal = Calendar() cal.add( 'prodid', '-//{author_short}//{product}//{language}'.format( author_short=__author_short__, product=__product__, language=args.language)) cal.add('version', '2.0') event = Event() ## TODO: timezone ## read timestamps from arguments event_spec = args.event_time.split('+') if len(event_spec) > 3: raise ValueError( 'Invalid event time "%s" - can max contain 2 plus-signs' % event_time) elif len(event_spec) == 3: event_time = '%s+%s' % tuple(event_spec[0:2]) event_duration = event_spec[2] elif len(event_spec) == 2 and not event_spec[1][-1:] in time_units: event_time = '%s+%s' % tuple(event_spec[0:2]) event_duration = '1h' elif len(event_spec) == 2: event_time = '%s' % event_spec[0] event_duration = event_spec[1] else: event_time = event_spec[0] event_duration = '1h' ## TODO: error handling event_duration_secs = int( event_duration[:-1]) * time_units[event_duration[-1:]] dtstart = dateutil.parser.parse(event_spec[0]) if args.whole_day: if event_spec[1][-1:] != 'd': raise ValueError( 'Duration of whole-day event must be multiple of 1d') duration = int(event_spec[1][:-1]) dtstart = dateutil.parser.parse(event_spec[0]) dtend = dtstart + timedelta(days=duration) event.add('dtstart', dtstart.date()) event.add('dtend', dtend.date()) else: event.add('dtstart', dtstart) ## TODO: handle duration and end-time as options. default 3600s by now. event.add('dtend', dtstart + timedelta(0, event_duration_secs)) ## TODO: what does the cryptic comment here really mean, and why was the dtstamp commented out? dtstamp is required according to the RFC. ## not really correct, and it breaks i.e. with google calendar event.add('dtstamp', datetime.now()) ## maybe we should generate some uid? uid = uuid.uuid1() event.add('uid', str(uid)) event.add('summary', ' '.join(args.summary)) cal.add_component(event) _calendar_addics(caldav_conn, cal.to_ical(), uid, args) print("Added event with uid=%s" % uid)
def TDecode(url): """Creates a list of event objects based on a ical url""" if url is None: return None # Nob hasnt given us their timetable yet rawCal = urllib.request.urlopen( url) # Try and download the timetable's ical cal = Calendar.from_ical(rawCal.read()) # Parse the ical events = [] # create a list of events for component in cal.walk(): # for "thing" in the cal if component.name == "VEVENT": # if its an event description = component.get('description').split( "\n") # get all its information location = component.get( 'location' ) # unused location data because description has it more reliably startdt = component.get('dtstart').dt # start date/time enddt = component.get('dtend').dt # end date/time module = "Undefined" room = "Undefined" type = "Undefined" for item in description: item = str(item) if "MODULE TITLE:" in item: # get the modules name module = item.replace("MODULE TITLE: ", "") if "ROOM(S):" in item: # get the room name room = item.replace("ROOM(S): ", "") if "EVENT TYPE:" in item: # is it a lecture? workshop? seminar? type = item.replace("EVENT TYPE: ", "") date = "{:02d}/{:02d}".format(startdt.day, startdt.month) timeFormatted = "{Date}-{hour:02d}:{minute:02d}".format( Date=date, hour=startdt.hour + 1, minute=startdt.minute) endFormatted = "{hour:02d}:{minute:02d}".format( hour=enddt.hour + 1, minute=enddt.minute) event = Event() # create an event object event.module = module event.Ftime = timeFormatted event.date = startdt event.end = endFormatted event.type = type event.room = room if len( events ) != 0: # put the event, in order, in the list of events for i in range(len(events)): if event.date < events[i].date: events.insert(i, event) break if i == len(events) - 1: events.append(event) else: events.append(event) return events
def create_schedule_calendar(query, name): logger = logging.getLogger(__name__) calendar = Calendar() calendar.add("prodid", "gimvicurnik") calendar.add("version", "2.0") calendar.add("X-WR-TIMEZONE", "Europe/Ljubljana") calendar.add("X-WR-CALNAME", name) calendar.add("X-WR-CALDESC", name) calendar.add("NAME", name) calendar.add("X-PUBLISHED-TTL", vDuration(timedelta(hours=1))) calendar.add("REFRESH-INTERVAL", vDuration(timedelta(hours=1))) for model in query: with start_span(op="event") as span: span.set_tag("event.type", "lunch-schedule") span.set_tag("event.date", model.date) span.set_tag("event.time", model.time) span.set_data("event.source", model) logger.info("Preparing iCalendar event", extra={ "type": "lunch-schedule", "source": model }) event = Event() event.add("dtstamp", datetime.now()) event.add("CATEGORIES", vText("LUNCH")) event.add("COLOR", vText("darkblue")) event.add( "UID", sha256((str(model.date) + str(model.time) + str(model.class_.name) + str(model.location)).encode()).hexdigest(), ) event.add("summary", "Kosilo") event.add("description", model.notes or "") event.add("location", vText(model.location)) event.add("dtstart", datetime.combine(model.date, model.time)) event.add( "dtend", datetime.combine(model.date, model.time) + timedelta(minutes=15)) calendar.add_component(event) response = make_response(calendar.to_ical().decode("utf-8").replace( "\\", "")) response.headers[ "Content-Disposition"] = "attachment; filename=calendar.ics" response.headers["Content-Type"] = "text/calendar; charset=utf-8" return response
def test_unicode_param(self): cal_address = vCalAddress('mailto:[email protected]') cal_address.params["CN"] = "Джон Доу" vevent = Event() vevent['ORGANIZER'] = cal_address self.assertEqual( vevent.to_ical().decode('utf-8'), u'BEGIN:VEVENT\r\n' u'ORGANIZER;CN="Джон Доу":mailto:[email protected]\r\n' u'END:VEVENT\r\n') self.assertEqual(vevent['ORGANIZER'].params['CN'], 'Джон Доу')
def make_ics(work,i): event = Event() event.add('summary', work[0]) event.add('dtstart', datetime(work[1].year,work[1].month,work[1].day,work[2].hour-2,work[2].minute,0,tzinfo=UTC)) event.add('dtend', datetime(work[3].year,work[3].month,work[3].day,work[4].hour-2,work[4].minute,0,tzinfo=UTC)) event.add('dtstamp', datetime.now()) event.add('location', work[7]) event['uid'] = str(i)+'@mxm.dk' event.add('priority', 5) cal.add_component(event)
def _event_to_ical(event): ical_event = Event() ical_event.add("summary", event.name) ical_event.add("uid", event.id) ical_event.add("dtstart", event.starts_at) ical_event.add("dtend", event.ends_at) ical_event.add("dtstamp", datetime.now()) # ical_event.add("url", event.url) return ical_event
def generate_ical(info: List[DueModel]): cal = Calendar() cal['summary'] = "WebCMS3 Due date calendar" cal['X-WR-CALNAME'] = "WebCMS3" event = Event() event.add('summary', "NEW") event.add('dtstart', datetime.now()) event.add('description', "Calendar was updated on " + str(datetime.now())) for i in info: due = Event() due.add('dtstart', i.due_date - timedelta(minutes=10)) # 10 mins before due.add('dtend', i.due_date) due.add('summary', i.name) due.add('description', i.course_code + " " + i.url) cal.add_component(due) return cal.to_ical()
def parse_html_table(html, location): def get_utc_datetime(string): local = pytz.timezone('Europe/Paris') naive = datetime.strptime(string, "%d/%m/%Y") local_dt = local.localize(naive, is_dst=None) return local_dt.astimezone(pytz.utc) def parse_event_id(string): re1 = 'javascript:ev\((\\d+)' rg = re.compile(re1, re.IGNORECASE | re.DOTALL) m = rg.search(string) if m: return m.group(1) else: return str(uuid.uuid4()) def duration_to_date(date, string): if string.endswith('h'): string = u"%s00" % string else: string = string.replace('min', '') hours, minutes = 0, 0 items = list(int(i) for i in string.split('h')) if len(items) == 1: minutes = items[0] elif len(items) == 2: hours, minutes = items[0], items[1] return date + timedelta(seconds=((hours) * 3600 + minutes * 60)) soup = BeautifulSoup(html) table = soup.find('table') rows = list(table.findAll('tr')) if len(rows) > 2: for tr in rows[2:]: cols = [(td.find(text=True) or '') for td in tr.findAll('td')] date = get_utc_datetime(cols[0]) start_date = duration_to_date(date, cols[2]) stop_date = duration_to_date(start_date, cols[3]) summary = cols[1] if cols[6]: classroom = cols[6] else: classroom = "Salle inconnue" location_title = "%s - %s" % (location, classroom) if cols[4]: summary = "%s - %s - %s" % (summary, cols[4], location_title) event = Event() event.add('summary', summary) event.add('dtstart', start_date) event.add('dtend', stop_date) event.add('dtstamp', date) event.add('location', location_title) event['uid'] = parse_event_id(str(tr)) yield event
def to_ics(self): self.logger.warning('拆分后的课程总数:' + str(len(self.schedule))) cal = Calendar() cal['version'] = '2.0' cal['prodid'] = '-//CQUT//Syllabus//CN' # *mandatory elements* where the prodid can be changed, see RFC 5445 self.date_start = date(2018, 2, 26) # 开学第一周星期一的时间 self.logger.info('开学第一周星期一的时间为:' + str(self.date_start)) # datetime.now() # TODO: 从 http://cale.dc.cqut.edu.cn/Index.aspx?term=201x-201x 抓取开学时间 dict_week = {'一': 0, '二': 1, '三': 2, '四': 3, '五': 4, '六': 5, '日': 6} # dict_time = {1: relativedelta(hours=8, minutes=20), 3: relativedelta(hours=10, minutes=20), # 5: relativedelta(hours=14, minutes=0), 7: relativedelta(hours=16, minutes=0), # 9: relativedelta(hours=19, minutes=0)} dict_time = { 1: time(8, 20), 3: time(10, 20), 5: time(14, 0), 7: time(16, 0), 9: time(19, 0) } self.logger.info('正在导出日程文件......') for i in self.schedule: # print(i) event = Event() ev_start_date = self.date_start + relativedelta( weeks=int(i['起始周']) - 1, weekday=dict_week[i['星期几']]) ev_start_datetime = datetime.combine(ev_start_date, dict_time[int( i['第几节'])]) # 上课时间 # 我们的课持续一小时四十分钟(中间有十分钟课间时间) ev_last_relative_delta = relativedelta(hours=1, minutes=40) \ if int(i['第几节']) != 9 else relativedelta(hours=1, minutes=35) # 我们晚上的课要少五分钟课间时间 ev_end_datetime = ev_start_datetime + ev_last_relative_delta # 下课时间 ev_interval = 1 if not i['单周?'] | i[ '双周?'] else 2 # 如果有单双周的课 那么这些课隔一周上一次 ev_count = int(i['结课周']) - int(i['起始周']) + 1 \ if not i['单周?'] | i['双周?'] else (int(i['结课周']) - int(i['起始周'])) // 2 + 1 # 添加事件 event.add('uid', str(uuid1()) + '@CQUT') event.add('summary', i['课程名']) event.add('dtstamp', datetime.now()) event.add('dtstart', ev_start_datetime) event.add('dtend', ev_end_datetime) event.add('location', i['教师名'] + '@' + i['教室']) event.add('rrule', { 'freq': 'weekly', 'interval': ev_interval, 'count': ev_count }) cal.add_component(event) with open('output.ics', 'w+', encoding='utf-8') as file: file.write(cal.to_ical().decode('utf-8'.replace('\r\n', '\n').strip())) self.logger.info('导出成功!')
def crearEvento(fe, nom, desc): evento = Event() time.sleep( 0.10 ) # Genero un retardo para que aquellos cumpleaños con misma fecha puedan almacenarse correctamente evento.add('summary', 'Cumpleaños de ' + nom) evento.add('dtstart', fe) evento.add('dtend', fe) evento.add('rrule', vRecur(freq='yearly')) evento.add('description', desc) return evento
def generate_event(the_class): event = Event() event.add('summary', the_class.name) event.add('rrule', {'freq': 'weekly', 'byday': weekdays[the_class.day]}) if the_class.place is not None: event.add('location', the_class.place) stime, etime = generate_time(the_class.day, the_class.time) event.add('dtstart', stime) event.add('dtend', etime) event.add('attendee', the_class.teacher) return event
def get_event(title, description, f, hour, minute=00, duration=2): event = Event() event.add('summary', title) event.add('dtstart', f.replace(hour=hour, minute=minute)) event.add('dtend', f.replace(hour=hour + duration, minute=minute)) event.add('location', 'Av. de Carabanchel Alto, 64, 28044 Madrid, España') if description: event.add('DESCRIPTION', description) event.add('uid', f.strftime("%Y-%m-%d") + "_" + title.replace(" ", "_").lower()) return event
def vevent(request, talk_id): t = get_object_or_404(Talk, pk=talk_id) event = Event() event.add('description', t.title) ical = event.to_ical response = HttpResponse(ical, mimetype='text/calendar') response['Filename'] = 'filename.ics' # IE needs this response[ 'Content-Disposition'] = 'attachment; filename=talk-%s.ics' % t.start.strftime( '%Y%m') return response
def to_ics(self): if not os.path.exists(self.storagedir): os.makedirs(self.storagedir) cal = Calendar() cal.add('version', '2.0') cal.add( 'prodid', '-//A.P.U Timetable Synchronizer by MavJS// http://goog.gl/9FRHL //' ) final_html = self.scrape() for row in final_html.findAll('tr')[1:]: event = Event() col = row.findAll('td') date = col[0].font.string time = col[1].font.string classroom = col[2].font.string location = col[3].font.string subject = col[4].font.string lecturer = col[5].font.string record = (date, time, classroom, location, subject, lecturer) line = "|".join(record) #this is lot of unesswary work i know but i like it this way feel free to edit parts = line.split('|') #trying to find the time times = parts[1].split(' - ') title = parts[4] where = parts[2] + "\t" + parts[3] content = parts[5] begin_str = "%s %s:00" % (parts[0][4:].strip(""), times[0]) end_str = "%s %s:00" % (parts[0][4:].strip(""), times[1]) now = datetime.now() now_time = now.strftime('%Y%m%dT%H%M%SZ') begin_time = datetime.strptime( begin_str, '%d-%b-%y %H:%M:%S').strftime('%Y%m%dT%H%M%SZ') end_time = datetime.strptime( end_str, '%d-%b-%y %H:%M:%S').strftime('%Y%m%dT%H%M%SZ') #start gathering info for VEVENT summary = title + " by " + content + " at " + where desc = title start = begin_time end = end_time stamp = now_time event.add('dtstart', start, encode=0) event.add('dtend', end, encode=0) event.add('transp', 'TRANSPARENT') event.add('summary', summary) event.add('description', desc) event['uid'] = hashlib.md5(desc).hexdigest() event.add('dtstamp', stamp, encode=0) cal.add_component(event) f = file(self.saveics, 'wb') f.write(cal.as_string()) f.close() return self.saveics
def task2ical(self, task): event = Event() event['uid'] = '{}-{}'.format(task.index, task.slug) event['summary'] = task.name event['dtstart'] = task.dStart.strftime(self._datetime_format) event['dtend'] = task.dFinish.strftime(self._datetime_format) event['dtstamp'] = self._now.strftime(self._datetime_format) event['transp'] = 'TRANSPARENT' # invisible to free/busy searches event['description'] = task.note return event
def write_items(self, calendar): """ Write all events to the calendar """ for item in self.items: event = Event() for ifield, efield in ITEM_EVENT_FIELD_MAP: val = item.get(ifield) if val is not None: event.add(efield, val) calendar.add_component(event)
def gen_event(self): event = Event() event.add('DTSTART', self.dt_start) event.add('DTEND', self.dt_end) event.add('DTSTAMP', self.dt_stamp) event.add('X-CO-RECURRINGID', self.recurring_i) event['UID'] = self.uid event.add("DESCRIPTION", self.description) event.add('SUMMARY', self.summary) event.add('LOCATION', self.location) return event
def build_ical(tickets): cal = Calendar() cal.add('summary', 'Student Agency') for ticket in tickets: event = Event() for key, value in ticket.items(): event.add(key, value) cal.add_component(event) return cal.to_ical()
def as_event_ical(self): """Get the vEvent component """ event = Event() event.add('summary', self.event.name) event.add('dtstart', self.event.start_time) event.add('dtend', self.event.end_time) event.add('description', self.event.description) event.add('location', self.event.location) event['uid'] = self.event.signature return event
def export_to_icalendar(schedule): """Export schedule model to iCalendar format. :param schedule: """ cal = Calendar() for index, day in enumerate(schedule.day_set.all()): for slot in day.slot_set.all().select_related(): if slot.kind.plenary: event = Event() event['uid'] = slot.pk event['dtstart'] = "{}T{}".format( day.date.strftime("%Y%m%d"), slot.start.strftime("%H%M%S"), ) event['dtend'] = "{}T{}".format( day.date.strftime("%Y%m%d"), slot.end.strftime("%H%M%S"), ) if slot.default_room: event.add('location', slot.default_room.name) event.add('summary', slot.content_override.raw) cal.add_component(event) if slot.content is not None: event = Event() event['uid'] = slot.pk event['dtstart'] = "{}T{}".format( day.date.strftime("%Y%m%d"), slot.start.strftime("%H%M%S"), ) event['dtend'] = "{}T{}".format( day.date.strftime("%Y%m%d"), slot.end.strftime("%H%M%S"), ) if slot.default_room: event.add('location', slot.default_room.name) event.add('summary', slot.content.get_title()) description = slot.content.get_description() event.add('description', (description.raw if hasattr( description, "raw") else description).replace("\r\n", "")) cal.add_component(event) return cal.to_ical()
def event(self, user): event = Event() #FIXME: code to remove hrefs from speaker name is a temporary hack to be # removed once we support multiple speakers if "href=" in self.speaker: tokens = re.split(r'>([a-zA-Z ]*)', self.speaker) speaker = ', '.join([ tokens[i] for i in range(1, len(tokens), 2) if tokens[i].strip() ]) else: speaker = self.speaker event.add("summary", speaker) event.add("dtstart", adapt_datetime(self.start_time, pytz.UTC)) event.add("dtend", adapt_datetime(self.end_time, pytz.UTC)) desc = "" # Title if self.title: desc += "Title: %s\n" % (self.title) # Speaker and seminar desc += "by %s" % (speaker) if self.speaker_affiliation: desc += " (%s)" % (self.speaker_affiliation) if self.seminar.name: desc += " as part of %s" % (self.seminar.name) desc += "\n\n" if self.live_link: link = self.show_live_link(user=user, raw=True) if link.startswith("http"): desc += "Interactive livestream: %s\n" % link if self.access_control == 2 and self.access_hint: desc += "Password hint: %s\n" % self.access_hint event.add("url", link) if self.stream_link: link = self.show_stream_link(user=user, raw=True) if link.startswith("http"): desc += "View-only livestream: %s\n" % link event.add("url", link) if self.room: desc += "Lecture held in %s.\n" % self.room if self.abstract: desc += "\nAbstract\n%s\n" % self.abstract else: desc += "Abstract: TBA\n" if self.comments: desc += "\n%s\n" % self.comments event.add("description", desc) if self.room: event.add("location", "Lecture held in {}".format(self.room)) event.add("DTSTAMP", datetime.now(tz=pytz.UTC)) event.add("UID", "%s/%s" % (self.seminar_id, self.seminar_ctr)) return event
def make_event(title, date, location, link, speaker): """Make an iCal `Event` object from the colloquium details.""" event = Event() event.add('summary', title) event.add('dtstart', date) event.add('dtend', date + timedelta(minutes=COLLOQ_LENGTH)) event['location'] = vText(location) event['uid'] = link event['description'] = vText(speaker or 'Colloquium') event['URL'] = vUri(link) return event