Example #1
0
def gen_ical(courses):
    cal = Calendar()
    cal["version"] = "2.0"
    cal[
        "prodid"
    ] = "-//Zhejiang University//LIU Dongyuan//ZH"  # *mandatory elements* where the prodid can be changed, see RFC 5445

    for course in courses:
        for lesson in course["lessons"]:
            weeks = lesson["weeks"]
            for recur in weeks:
                event = Event()
                event.add("summary", unify_brackets(course["name"]))
                offset_days = lesson["day"] - 1 + 7 * (int(recur) - 1)
                offset = timedelta(days=offset_days)
                classdate = week_start + offset
                start = lesson_time[lesson["start"]]["start"]
                end = lesson_time[lesson["end"]]["end"]
                event.add("dtstart", datetime.combine(classdate, start))
                event.add("dtend", datetime.combine(classdate, end))
                event.add("location", lesson["location"])
                event.add("description", u"教师:" + course["teacher"])
                event["uid"] = str(uuid1()) + "@ZJU"
                cal.add_component(event)
    return cal.to_ical()
Example #2
0
def scrape_scical():
    data = urllib2.urlopen('http://www.hopkinsmedicine.org/scical/').read()
    soup = BeautifulSoup(data)
    cal = Calendar()
    cal.add('prodid', '-//Hopkins Science Calendar//mattshirley.com/scical//')
    cal.add('version', '2.0')
    rows = soup.find_all('tr')
    events = list()
    for col in rows:
        strongs = col.find_all('strong')
        strongs_list = list()
        for item in strongs:
            strongs_list.append(item.get_text().encode('ascii','ignore').translate(None, '\t\r'))
        breaks = col.find_all('br')
        breaks_list = list()
        for item in breaks:
            breaks_list.extend(filter(len, re.split('\n+', item.get_text().encode('ascii','ignore').translate(None, '\t\r'))))
        events.append(strongs_list + breaks_list[:4])
    for item in events:
        try:
            event = Event()
            event.add('summary', item[1])
            event.add('location', item[5])
            event.add('description', ','.join(item[3:]))
            date_start = datetime.strptime(' '.join([item[0], item[2]]), '%A %b %d, %Y %I:%M %p')
            date_end = date_start + timedelta(hours=1)
            event.add('dtstart', date_start)
            event.add('dtend', date_end)
            event.add('dtstamp', date_start)
            cal.add_component(event)
        except IndexError:
            pass
    return cal.to_ical()
Example #3
0
def build_calendar(issues, ics_path):
    cal = Calendar()
    for i in issues:
        event = Event()
        if "Full" in str(i.status):
            summary = "[COMPLET] " + i.subject
        else:
            summary = i.subject
        event.add('summary', summary)
        event.add('description', i.description)
        event['uid'] = i.id
        for c in i.custom_fields:
            if c.id == 20: # 20 is 'debut'
                start_time = str(c.value).replace(':', '')+"00"
            if c.id == 21: # 21 is 'fin'
                end_time = str(c.value).replace(':', '')+"00"
        event['dtstart'] = i.due_date.replace('/','')+"T"+start_time
        event['dtend'] = i.due_date.replace('/','')+"T"+end_time
        event['dtstamp'] = vDatetime(now).to_ical()
        organizer = vCalAddress('MAILTO:[email protected]')
        organizer.params['cn'] = vText('Les fruits défendus')
        event['organizer'] = organizer
        event['location'] = vText('Montréal, QC')
        cal.add_component(event)

        f = open(ics_path, 'wb')
        f.write(cal.to_ical())
        f.close()
Example #4
0
def generate_ics(request, organization_pk, agent_pk=None, category_pk=None, title=''):
    obj = get_object_or_404(Organization.query(request, readonly=True), pk=organization_pk)
    cal = Calendar()
    cal.add('prodid', '-//AutoPlanner//19pouces.net//')
    cal.add('version', '2.0')
    cal.add('X-PUBLISHED-TTL', 'PT' + settings.REFRESH_DURATION)
    cal.add('X-WR-TIMEZONE', settings.TIME_ZONE)
    cal.add('X-WR-CALNAME', title or obj.name)
    cal.add('X-WR-CALDESC', obj.description)
    query = Task.objects.filter(organization=obj)
    if agent_pk:
        query = query.filter(agent__id=agent_pk)
    if category_pk:
        query = query.filter(categories__id=category_pk)
    agents = {x.pk: x.name for x in Agent.objects.filter(organization=obj)}
    for task in query:
        event = Event()
        if task.agent_id:
            summary = '%s (%s)' % (task.name, agents[task.agent_id])
        else:
            summary = task.name
        event.add('summary', summary)
        event.add('dtstart', task.start_time)
        event.add('dtend', task.end_time)
        event['uid'] = task.start_time.strftime('%Y%m%dT%H%M%S-') + str(task.pk)
        cal.add_component(event)
    return HttpResponse(cal.to_ical(), content_type='text/calendar')
Example #5
0
def ical(request):
    CALENDAR_NAME = u"profsoux"
    CALENDAR_SHORT_NAME = u"profsoux.ru"
    events = ScheduleSection.objects.all()

    cal = Calendar()
    cal.add("prodid", u"-//%s//%s//" % (CALENDAR_NAME, CALENDAR_SHORT_NAME))
    cal.add("version", "2.0")
    cal.add("calscale", "GREGORIAN")
    cal.add("X-ORIGINAL-URL", CALENDAR_SHORT_NAME)
    cal.add("method", "PUBLISH")

    for event in events:
        ical_event = Event()
        ical_event.add("uid", str(event.id) + "@" + CALENDAR_SHORT_NAME)
        title = event.title or u""

        if event.lecture:
            speakers = event.lecture.get_speakers()
            ical_event.add("summary", u"%s%s «%s»" % (title, speakers, event.lecture.title))
        else:
            ical_event.add("summary", title)

        dtstart = datetime.datetime(2005, 4, 4, 8, 0, 0, tzinfo=pytz.utc)
        dtend = datetime.datetime(2005, 4, 4, 10, 0, 0, tzinfo=pytz.utc)
        ical_event.add("dtstart", dtstart)
        ical_event.add("dtend", dtend)
        ical_event.add("dtstamp", dtstart)

        cal.add_component(ical_event)

    response = HttpResponse(cal.to_ical(), mimetype="text/calendar")
    response["Content-Disposition"] = "attachment; filename=%s.ics" % "ical"

    return response
Example #6
0
    def get(self, format):
        events = Event.all().filter('status IN', ['approved', 'canceled']).order('start_time')
        if format == 'ics':
            cal = Calendar()
            for event in events:
                cal.add_component(event.to_ical())
            self.response.headers['content-type'] = 'text/calendar'
            self.response.out.write(cal.as_string())
        elif format == 'json':
            self.response.headers['content-type'] = 'application/json'
            events = map(lambda x: x.to_dict(summarize=True), Event.get_approved_list())
            self.response.out.write(simplejson.dumps(events))
        elif format =='rss':
            url_base = 'http://' + self.request.headers.get('host', 'events.hackerdojo.com')
            rss = PyRSS2Gen.RSS2(
                title = "Hacker Dojo Events Feed",
                link = url_base,
                description = "Upcoming events at the Hacker Dojo in Mountain View, CA",
                lastBuildDate = datetime.now(),
                items = [PyRSS2Gen.RSSItem(
                            title = event.name,
                            link = url_base + event_path(event),
                            description = event.details,
                            guid = url_base + event_path(event),
                            pubDate = event.updated,
                         ) for event in events]
            )

            self.response.headers['content-type'] = 'application/xml'
            self.response.out.write(rss.to_xml())
Example #7
0
def make_anc_ical(request, anc=None):
	# Collect future meetings and sort after collating meetings across ANCs.
	now = datetime.datetime.now()
	meetings = []
	for mtganc, mtgs in meeting_data.items():
		if anc != None and mtganc.lower() != anc: continue
		for mtgdate, mtginfo in sorted(mtgs['meetings'].items()):
			mtgdate = dateutil.parser.parse(mtgdate)
			if mtgdate < now: continue
			meetings.append( (mtgdate, mtganc, mtginfo) )
	meetings.sort()

	# Make ical.
	from icalendar import Calendar, Event
	cal = Calendar()
	for mtgdate, mtganc, mtginfo in meetings:
		if mtginfo.get("status") == "invalid": continue
		event = Event()
		event.add('dtstart', mtgdate)
		event['summary'] = "ANC %s Meeting" % mtganc
		event['description'] = "See ANCFinder.org for details: http://ancfinder.org/%s" % mtganc
		event['location'] = '; '.join(mtginfo[k] for k in ('building', 'address', 'root') if mtginfo.get(k))
		event['link'] = mtginfo.get("link")
		cal.add_component(event)

	return HttpResponse(cal.to_ical(), "text/calendar" if "mime" not in request.GET else "text/plain")
Example #8
0
def get_course_calendar(user, course_key_string):
    try:
        from icalendar import Calendar, Event
    except ImportError:
        logging.error('Calendar module not installed')
        return

    course_key = CourseKey.from_string(course_key_string)
    checked = ['course', 'vertical', 'sequential']
    items = modulestore().get_items(course_key)
    hour = timedelta(hours=1)

    cal = Calendar()
    for num, item in enumerate(items):
        if not item.category in checked:
            continue
        if not item.graded:
            continue
        if not has_access(user, 'load', item, course_key=item.location.course_key):
            continue
        if not item.due:
            continue
        if item.category != 'course':
            format = item.format or item.get_parent().format
        else:
            format = 'course'
        url = u'http://{}{}'.format(settings.SITE_NAME, _reverse_usage(item))
        event = Event()
        summary = u'Type: {}; Name: {}({})'.format(format, item.display_name, url).encode('utf-8')
        event.add('summary', summary)
        event.add('dtstart', item.due - hour)
        event.add('dtend', item.due)
        cal.add_component(event)
    text = cal.to_ical().decode('utf-8')
    return text
Example #9
0
def main(infiles=None, locfile=None, **kwargs):
    locations = {}
    metadata_file = locfile.read()
    match = PATTERN2.finditer(metadata_file)
    for entry in match:
        locations[entry.group(1)] = demjson.decode(entry.group(2))

    tracks = {}
    match = PATTERN3.finditer(metadata_file)
    for entry in match:
        tracks[entry.group(1)] = demjson.decode(entry.group(2)).get('name')

    events = []
    for infile in infiles:
        data = json.load(infile)
        if data is None:
            continue
        events.extend(data['events'])

    for track_id, track_name in tracks.items():
        cal = Calendar()
        cal['dtstart'] = '20180519T080000'
        cal['summary'] = 'OpenStack Summit Vancouver 2018: ' + track_name
        tz = Timezone(TZID='America/Vancouver')
        tz.add_component(TimezoneStandard(DTSTART="20171105T020000",
                                        TZOFFSETFROM="-0700",
                                        TZOFFSETTO="-0800",
                                        RDATE="20181104T020000",
                                        TZNAME="PST"))
        tz.add_component(TimezoneDaylight(DTSTART="20180311T020000",
                                        TZOFFSETFROM="-0800",
                                        TZOFFSETTO="-0700",
                                        TZNAME="PDT"))
        cal.add_component(tz)

        for session in events:
            if track_id != str(session.get('track_id')):
                continue
            timezone_str = session.get('time_zone_id')
            tzinfos = {"UN": gettz(timezone_str)}
            start_datetime_str = session.get('start_datetime')
            start_datetime = parse(start_datetime_str + " UN", tzinfos=tzinfos)
            start_datetime_utc = start_datetime.astimezone(utc)
            end_datetime_str = session.get('end_datetime')
            end_datetime = parse(end_datetime_str + " UN", tzinfos=tzinfos)
            end_datetime_utc = end_datetime.astimezone(utc)
            desc = PATTERN.sub('', session.get('abstract'))
            for pre, post in REPLACE_MAP.items():
                desc = desc.replace(pre, post)

            event = Event()
            event.add('dtstart', start_datetime_utc)
            event.add('dtend', end_datetime_utc)
            event.add('summary', session.get('title'))
            event.add('location', locations.get(str(session.get('location_id')), {}).get('name_nice', ""))
            event.add('description', desc)
            event.add('uid', "%s@openstacksummitboston2017" % session.get('id'))
            cal.add_component(event)
        with open("%s.ics" % PATTERN4.sub("-", track_name), "w") as f:
            f.write(cal.to_ical())
Example #10
0
    def update_event(self, username, uid, event_name, start_timestamp, quantity):
        """
        Update the info about a specific event on the user calendar.
        :param username: username of the calendar to insert the event.
        :param uid: UID tha identifies the event in the calendar.
        :param event_name: Event name.
        :param start_timestamp: The date where the event are scheduled.
        :param quantity: The quantity reserved.
        :return: Keyword 'OK'
        """
        cal = Calendar()
        cal['version'] = "2.0"
        cal['prodid'] = "//Radicale//NONSGML Radicale Server//EN"

        event = Event()
        event['uid'] = uid
        event['dtstart'] = vDatetime(datetime.fromtimestamp(start_timestamp)).to_ical()
        event['summary'] = event_name
        event['description'] = 'Quantity: ' + str(quantity)
        event['x-radicale-name'] = str(uid) + '.ics'

        cal.add_component(event)

        headers = {'Content-Type': 'text/calendar',
                   'charset': 'utf-8'}
        self.client.put(self.url + username + '/calendar.ics/' + str(uid) + '.ics', cal.to_ical(), headers)
        return 'OK'
Example #11
0
def export_ical(events):
	cal = Calendar()
	
	site = Site.objects.get_current()
	
	cal.add('prodid', '-//%s Events Calendar//%s//' % (site.name, site.domain))
	cal.add('version', '2.0')
	
	site_token = site.domain.split('.')
	site_token.reverse()
	site_token = '.'.join(site_token)
	
	for event in events:
		ical_event = Event()
		ical_event.add('summary', event.title)
		ical_event.add('description', event.body)
		ical_event.add('dtstart', event.start_datetime)
		ical_event.add('dtend', event.end_datetime)
		ical_event.add('dtstamp', event.end_datetime)
		ical_event.add('url', vUri('http://' + site.domain + event.get_absolute_url()))
		ical_event['location'] = vText(event.location)
		ical_event['uid'] = '%d.event.events.%s' % (event.id, site_token)
		cal.add_component(ical_event)
	
	return cal
def convert_to_ics(time_slots, file_name):

	cal = Calendar()
	cal.add('prodid', '-//NTU Schedule')
	cal.add('version', '1.0')

	for time_slot in time_slots:

		if time_slot.status == 'REGISTERED' or show_all_courses:
			# get the time and date info for time slot
			class_event_info = convert_to_datetime(time_slot)

			# create the event
			event = Event()
			event_summary = '{} - {} - {}'.format(time_slot.course, time_slot.class_type, time_slot.course_title)
			print event_summary
			event.add('summary', event_summary)
			event.add('dtstart', class_event_info.datetimes[0])
			event.add('dtend', class_event_info.datetimes[1])
			event.add('dtstamp', datetime.datetime.now())
			event.add('location', time_slot.venue)
			if class_event_info.recurrences > 0:
				event.add('rrule', {'freq' : 'weekly', 'count' : class_event_info.recurrences})

				if class_event_info.is_bi_weekly:
					event['rrule']['interval'] = 2

			cal.add_component(event)

	#  write to ics file
	f = open('{}.ics'.format(file_name), 'wb')
	f.write(cal.to_ical())
	f.close()
Example #13
0
 def export_ics(self):
     events = Event.get_recent_past_and_future()
     url_base = 'http://' + self.request.headers.get('host', 'events.hackerdojo.com')
     cal = Calendar()
     for event in events:
         iev = CalendarEvent()
         iev.add('summary', event.name if event.status == 'approved' else event.name + ' (%s)' % event.status.upper())
         # make verbose description with empty fields where information is missing
         ev_desc = '__Status: %s\n__Member: %s\n__Type: %s\n__Estimated size: %s\n__Info URL: %s\n__Fee: %s\n__Contact: %s, %s\n__Rooms: %s\n\n__Details: %s\n\n__Notes: %s' % (
             event.status,
             event.owner(),
             event.type,
             event.estimated_size,
             event.url,
             event.fee,
             event.contact_name,
             event.contact_phone,
             event.roomlist(),
             event.details,
             event.notes)
         # then delete the empty fields with a regex
         ev_desc = re.sub(re.compile(r'^__.*?:[ ,]*$\n*',re.M),'',ev_desc)
         ev_desc = re.sub(re.compile(r'^__',re.M),'',ev_desc)
         ev_url = url_base + event_path(event)
         iev.add('description', ev_desc + '\n--\n' + ev_url)
         iev.add('url', ev_url)
         if event.start_time:
           iev.add('dtstart', event.start_time.replace(tzinfo=pytz.timezone('US/Pacific')))
         if event.end_time:
           iev.add('dtend', event.end_time.replace(tzinfo=pytz.timezone('US/Pacific')))
         cal.add_component(iev)
     return 'text/calendar', cal.as_string()
Example #14
0
def calendar(code):
	url = "https://www.eventbriteapi.com/v3/users/me/orders/?expand=event,event.venue"
	data = urlopen(Request(url = url, headers= {"Authorization": "Bearer %s"%code})).read()
	data = json.loads(data)
	if "error" in data:
		raise Exception(data["error"])

	cal = Calendar()
	cal.add('prodid', '-//Eventbrite calendar//tevp.net//')
	cal.add('version', '2.0')
	if "orders" in data:
		cal.add('X-WR-CALNAME', 'Eventbrite Calendar for %s'%(data["orders"][0]["email"]))

		for order in data["orders"]:
			event_data = order["event"]
			event = Event()
			event.add('summary', event_data["name"]["text"])
			event.add('description', event_data["description"]["text"])
			event.add('location', event_data["venue"]["address"]["localized_address_display"])
			dformat = "%Y-%m-%dT%H:%M:%SZ"
			utc = pytz.timezone("UTC")
			event.add('dtstart', datetime.strptime(event_data["start"]["utc"], dformat).replace(tzinfo=utc))
			event.add('dtend', datetime.strptime(event_data["end"]["utc"], dformat).replace(tzinfo=utc))
			event.add('dtstamp', datetime.strptime(event_data["changed"], dformat).replace(tzinfo=utc))
			event['uid'] = order["id"]
			cal.add_component(event)
	else:
		cal.add('X-WR-CALNAME', 'Eventbrite Calendar')

	return cal.to_ical()
Example #15
0
def for_user(user):
    """Returns an `icalendar.Calendar` object."""
    signups = ShiftSignup.objects.filter(
        user=user,
    ).order_by('shift__when', 'shift__span').distinct()

    oncalls = OnCallDuty.objects.filter(
        user=user,
    ).order_by('shift__when', 'shift__span').distinct()

    cal = Calendar()
    cal.add('prodid', '-//Baljan//Baljan Schedule//EN')
    cal.add('version', '2.0')
    cal.add('method', 'PUBLISH')

    for signup in signups:
        ev = Event()
        start, end = signup.shift.worker_times()
        ev.add('summary', _(u"work in Baljan"))
        ev.add('dtstart', encode_dt(start), encode=False)
        ev.add('dtend', encode_dt(end), encode=False)
        ev.add('dtstamp', encode_dt(signup.made), encode=False)
        cal.add_component(ev)

    for oncall in oncalls:
        ev = Event()
        start, end = oncall.shift.oncall_times()
        ev.add('summary', _(u"on call in Baljan"))
        ev.add('dtstart', encode_dt(start), encode=False)
        ev.add('dtend', encode_dt(end), encode=False)
        ev.add('dtstamp', encode_dt(oncall.made), encode=False)
        cal.add_component(ev)

    return cal
Example #16
0
def schedule_user_bookmarks(request, user_id, user_hash):
    
    user = get_object_or_404(User, id=user_id)
    auth_hash = hash_for_user(user)
    
    if user_hash != auth_hash:
        raise Http404()
    
    bookmarks = UserBookmark.objects.filter(user=user)
    
    cal = Calendar()
    cal.add("prodid", "-//PyCon 2011 Bookmarks//us.pycon.org//EN")
    cal.add("version", "2.0")
    cal.add("method", "REQUEST")
    cal.add("calscale", "GREGORIAN")
    cal.add("X-WR-CALNAME", "PyCon 2011 Bookmarks - %s" % user.username)
    cal.add("X-WR-TIMEZONE","US/Eastern")
    
    for bookmark in bookmarks:
        p = bookmark.presentation
        if p.slot is not None:
            event = Event()
            event.add("summary", p.title)
            event.add("dtstart", p.slot.start)
            event.add("dtend", p.slot.end)
            event.add("dtstamp", datetime.datetime.utcnow())
            event.add("description", p.speaker.name + "\n\n" + p.description)
            event.add("location", p.slot.track)
            event["uid"] = str(p.pk) + "-2011.us.pycon.org"
            cal.add_component(event)
    
    response = HttpResponse(cal.as_string(), content_type="text/calendar")
    response["Content-Disposition"] = "filename=pycon2011-%s-bookmarks.ics" % user.username.encode("utf-8")
    return response
Example #17
0
def calendar(username):
	access_token = request.args.get("access_token")

	try:
		data = urlopen("https://www.beeminder.com/api/v1/users/%s/goals.json?access_token=%s"%(username, access_token)).read()
		data = json.loads(data.decode(encoding='UTF-8'))
	except HTTPError:
		return error_page()

	cal = Calendar()
	cal.add('prodid', '-//Beeminder calendar//tevp.net//')
	cal.add('version', '2.0')
	cal.add('X-WR-CALNAME', 'Beeminder Calendar for %s'%username)

	for goal in data:
		start = datetime.fromtimestamp(goal["losedate"])
		startdate = start.date()
		if start.hour <=4: # Assume that times before 4am are effectively "yesterday"
			startdate -= timedelta(days = 1)
		enddate = startdate + timedelta(days = 1)
		title = goal["title"]
		event = Event()
		event.add('summary', "%s fail day" % title)
		event.add('dtstart', startdate)
		event.add('dtend', enddate)
		event.add('last-modified', datetime.now())
		event['uid'] = hashlib.md5(title.encode() + str(startdate).encode()).hexdigest()
		cal.add_component(event)

	resp = make_response(cal.to_ical())
	resp.headers["Content-Type"] = "text/Calendar"
	resp.headers["Cache-Control"] = "no-cache, must-revalidate"
	resp.headers["Expires"] = "Sat, 26 Jul 1997 05:00:00 GMT"
	return resp
Example #18
0
def event_detail_ics(request, slug):
    event_obj = get_object_or_404(Event.published, slug__exact=slug)
    calendar = Calendar()
    calendar.add('prodid', '-//US Ignite//us-ignite.org//')
    calendar.add('version', '2.0')
    event = CalEvent()
    event.add('summary', event_obj.name)
    url = '%s%s' % (settings.SITE_URL, event_obj.get_absolute_url())
    description = event_obj.description + '\n\n' + url
    event.add('description', description)
    event.add('url', url)
    event['location'] = vText(event_obj.address)
    # Use timezone aware datetime objects:
    event_tz = pytz.timezone(_swap_timezone(event_obj.timezone))
    event.add('dtstart', event_obj.start_datetime.astimezone(event_tz))
    if event_obj.end_datetime:
        event.add('dtend', event_obj.end_datetime.astimezone(event_tz))
    event.add('dtstamp', timezone.now())
    event['uid'] = 'event-%s/@us-ignite.org' % (event_obj.pk)
    event.add('priority', 5)
    calendar.add_component(event)
    file_name = 'event-%s.ics' % event_obj.slug
    response = HttpResponse(calendar.to_ical(), content_type='text/calendar')
    response['Content-Disposition'] = 'attachment; filename="%s"' % file_name
    return response
Example #19
0
def event_ical(request, abbr, event_id):
    event = db.events.find_one({'_id': event_id})
    if event is None:
        raise Http404

    x_name = "X-BILLY"

    cal = Calendar()
    cal.add('prodid', '-//Sunlight Labs//billy//')
    cal.add('version', billy.__version__)

    cal_event = Event()
    cal_event.add('summary', event['description'])
    cal_event['uid'] = "%s@%s" % (event['_id'], Site.objects.all()[0].domain)
    cal_event.add('priority', 5)
    cal_event.add('dtstart', event['when'])
    cal_event.add('dtend', (event['when'] + dt.timedelta(hours=1)))
    cal_event.add('dtstamp', event['updated_at'])

    if "participants" in event:
        for participant in event['participants']:
            name = participant['participant']
            cal_event.add('attendee', name)
            if "id" in participant and participant['id']:
                cal_event.add("%s-ATTENDEE-ID" % (x_name), participant['id'])

    if "related_bills" in event:
        for bill in event['related_bills']:
            if "bill_id" in bill and bill['bill_id']:
                cal_event.add("%s-RELATED-BILL-ID" % (x_name), bill['bill_id'])

    cal.add_component(cal_event)
    return HttpResponse(cal.to_ical(), content_type="text/calendar")
Example #20
0
def process_xls(filename):
    wb = xlrd.open_workbook(filename)
    sheet = wb.sheet_by_index(0)
    calendar = Calendar()
    calendar.add('x-wr-calname','Schedule for U8 Summer Hockey 2015')
    for irow in range(sheet.nrows):
        row = sheet.row(irow)
        basedate = xlrd.xldate_as_tuple(row[1].value, wb.datemode)
        (hh, mmxx) = row[3].value.split(':')
        hh = int(hh)
        mm = int(mmxx[:2])
        xx = mmxx[2:]
        if xx == 'PM': 
            hh += 12
        basedt = list(basedate[:3]) + [hh, mm]
        tstamp = datetime(*basedt)
        uid = tstamp.strftime('%Y%m%d%H%M')+'@pugswald.com'
        event = Event()
        event.add('uid', uid)
        event.add('dtstart', tstamp)
        event.add('summary', 'AYHL U8 Hockey %s'%row[2].value)
        event.add('dtend', tstamp + timedelta(minutes=60))
        event.add('location', row[5].value)
        alarm = Alarm()
        alarm.add('action', 'DISPLAY')
        alarm.add('description', 'Reminder')
        alarm.add('trigger', timedelta(minutes=-45))
        event.add_component(alarm)
        calendar.add_component(event)
    print calendar.to_ical()
Example #21
0
def make_calendar_object(event_id):
    event = get_object_or_404(Events, pk=event_id)

    site = Site.objects.get_current()

    site_token = site.domain.split(".")
    site_token.reverse()
    site_token = ".".join(site_token)

    cal = Calendar()
    cal.add("prodid", "-//%s Events Calendar//%s//" % (site.name, site.domain))
    cal.add("version", "2.0")

    eventObj = Event()
    eventObj.add("summary", event.name)
    eventObj.add("location", event.location)
    eventObj.add("dtstart", event.start_datetime)
    eventObj.add("dtend", event.end_datetime)
    eventObj.add("dtstamp", event.created_datetime)
    eventObj["uid"] = "%dT%d.events.%s" % (event.id, random.randrange(111111111, 999999999), site_token)
    eventObj.add("priority", 5)

    cal.add_component(eventObj)

    output = ""
    for line in cal.content_lines():
        if line:
            output += line + "\n"

    return output
Example #22
0
def format_to_ical(info_sessions):
    cal = Calendar()
    cal.add("X-WR-CALNAME", "Info Sessions")  # Calendar name
    eastern = timezone("Canada/Eastern")  # Embed timezone info into events

    for session in info_sessions:
        # If the session is longer than 4 hours it's probably a holiday entry
        # Also filter out closed/cancelled info sessions
        # This should probably be done in filtering.py
        if (
            ((session.end - session.start).total_seconds() > 14400)
            or ("closed info" in session.employer.lower())
            or ("cancelled" in session.employer.lower())
        ):
            continue
        event = Event()
        event.add("summary", session.employer)  # Event title
        event.add("description", session.description)
        event.add("location", session.location)
        event.add("dtstart", eastern.localize(session.start))
        event.add("dtend", eastern.localize(session.end))
        event.add("url", session.website)
        cal.add_component(event)

    return cal.to_ical()
Example #23
0
def index():
    cfg = load_config('config.json')

    calendar = Calendar()
    calendar['prodid'] = '-//worker-perlence//Worker calendar'
    calendar['version'] = '2.0'
    calendar['x-wr-calname'] = 'Worker calendar'
    for day, shift in workdays(cfg['FORMULA'], cfg['FIRST_DAY']):
        if shift == '0':
            continue
        event = Event()
        event.add('uid', 'WORKER-DAY-' + day.isoformat())
        event.add('dtstamp', datetime.now())
        event.add('dtstart', day)
        event.add('dtend', day + timedelta(days=1))
        event.add('summary', cfg['SUMMARY'][shift])
        event['dtstamp'].to_ical()
        event['dtstart'].to_ical()
        event['dtend'].to_ical()
        calendar.add_component(event)

    data = calendar.to_ical()
    cache_bust = md5(data).hexdigest()[:7]

    response = make_response(data)
    response.headers['Content-Type'] = 'text/calendar;charset=utf-8'
    response.headers['Content-Disposition'] = (
        'inline; filename="worker-day-%s.ics"' % cache_bust)
    return response
Example #24
0
def sk_forum_planning_calendar(request):
    from datetime import datetime, date
    from icalendar import Calendar, Event, UTC, LocalTimezone # timezone
    cal = Calendar()
    cal.add('prodid', '-//SK Forum Calendar//killingar.net//')
    cal.add('version', '2.0')
    
    import MySQLdb
    connection = MySQLdb.connect(user='******', passwd='2oVGx8VwuqUfY', db='forum')
    cursor = connection.cursor()
    from django.utils.encoding import smart_unicode
    cursor.execute(u'SELECT id FROM users where name = "%s"' % (smart_unicode(request.REQUEST['username'])))
    userID = cursor.fetchall()[0]
    cursor.execute("select id, name, time, description from events, eventdata where events.id = eventdata.event and events.visible = 1 and eventdata.user = %s and eventdata.data in (1, 0)" % userID)
    rows = cursor.fetchall()
    for row in rows:
        id, name, time, description = row
        event = Event()
        event.add('summary', smart_unicode(name.decode('latin-1')))
        #event.add('dtstart', 'DATE:'+time.strftime("%Y%m%d"))
        #event.add('dtend', 'DATE:'+time.strftime("%Y%m%d"))
        event.add('dtstart', date(time.year, time.month, time.day))
        event.add('dtend', date(time.year, time.month, time.day))
        if description:
            event.add('description', smart_unicode(description.decode('latin-1')))
        #event.add('X-FUNAMBOL-ALLDAY', '')
        event['uid'] = 'planning/%[email protected]' % id
        event.add('priority', 5) # normal priority
    
        cal.add_component(event)
    connection.close()
    
    return HttpResponse(cal.as_string(), content_type='text/calendar')
Example #25
0
def view_instance_calendar(request, course_url, instance_url):
    """ 
    Renders a iCalendar feed for a CourseInstance. Unlike most other views in this module, this
    view does not require the user to be logged in.
    
    @param request: the Django HttpRequest object
    @param course_url: the url value of a Course object
    @param instance_url: the url value of a CourseInstance object 
    """
    
    course_instance = _get_course_instance(course_url, instance_url)
    
    cal = Calendar()
    
    cal.add('prodid', '-// A+ calendar //')
    cal.add('version', '2.0')
    
    for course_module in course_instance.course_modules.all():
        event = Event()
        event.add('summary', course_module.name)
        
        # FIXME: Currently all times added are the closing time.
        # The event will need to be longer than 0 seconds in order 
        # to be displayed clearly on calendar applications.
        event.add('dtstart', course_module.closing_time)
        event.add('dtend', course_module.closing_time)
        event.add('dtstamp', course_module.closing_time)
        
        event['uid'] = "module/" + str(course_module.id) + "/A+"
        
        cal.add_component(event)
    
    response = HttpResponse(cal.as_string(), content_type="text/calendar; charset=utf-8")
    return response
def ical(request, type='Full'):
	"""
	"""
	cal = Calendar()
	site = Site.objects.get_current()
	
	if type.lower() == 'full':
		gigs = g.objects.all()
	else:
		gigs = g.objects.filter(date__gte=datetime.now())

	cal.add('prodid','-//{0} Events Calendar//{1}//EN'.format(type, site.domain))
	cal.add('version','2.0')

	for gig in gigs:
		performances = p.objects.filter(gig=gig.id)
		for performance in performances:
			start = datetime.strptime('{0} {1}'.format(gig.date, performance.time), "%Y-%m-%d %H:%M:%S")
			end = start + timedelta(hours=2)
			ical_event = Event()
			ical_event.add('summary','{0}, {1}, {2}'.format(gig.venue.name, gig.venue.city, gig.venue.state))
			ical_event.add('dtstart',start)
			ical_event.add('dtend',end)
			url = 'http://{0}{1}'.format(site.domain,gig.get_absolute_url())
			ical_event.add('description',url)
			cal.add_component(ical_event)

	response = HttpResponse(cal.as_string(), mimetype='text/calendar')
	response['Filename'] = 'filename.ics'
	response['Content-Disposition'] = 'attachment; filename=filename.ics'
	return response
Example #27
0
def icalendar(native_languages, foreign_languages):
    calendar = calendar_for_languages(
        native_languages, foreign_languages)
    def full_names(langs):
        str = ", ".join([LANGUAGE_DICT(l) for l in langs[:-1]])
        if len(langs) > 1:
            str = " or ".join(str, langs[-1])
        return str
    cal = Calendar()
    calendar_description = \
        ("Dates where we have at least {0} speakers of "
         "{1} learning {2} scheduled to be online at langolab.com.").format(
        NOTIFICATION_PARTNER_THRESHOLD,
        full_names(foreign_languages), 
        full_names(native_languages))
    cal.add('prodid', '-//Langolab//langolab.com//EN')
    cal.add("version", "2.0")
    cal.add("X-WR-CALNAME", "Langolab Language Pairings")
    cal.add("X-WR-CALDESC", calendar_description)
    cal_ranges = calendar.languagecalendarrange_set.filter(
        end_date__gte=utcnow()).order_by('start_date')
    for cal_range in cal_ranges:
        event = Event()
        event.add('summary', 'Partners online at langolab.com')
        event.add('dtstart', cal_range.start_date)
        event.add('dtend', cal_range.end_date + timedelta(hours=1))
        event.add('dtstamp', utcnow())
        event['uid'] = cal_range.uid
        cal.add_component(event)
    return cal.as_string()
Example #28
0
def convert(content):
    soup = BeautifulSoup(content)
    entries = [cell.span.text for cell in soup.find_all(name="td", attrs={"class": "allocated"})]

    entries = [filter(lambda x: len(x) > 0, map(lambda x: x.strip(), e.split("\n"))) for e in entries]

    d = datetime.datetime(datetime.date.today().year - 1, 1, 1, tzinfo=pytz.timezone("Europe/Ljubljana"))
    d = d - datetime.timedelta(d.weekday())  # find monday

    cal = Calendar()
    cal.add("prodid", "-//FRiCal//SL")
    cal.add("version", "2.0")

    for e in entries:
        dt_tokens = e[0].split(" ")  # u'sreda 08:00 - 11:00'
        weekday = weekday_names.index(dt_tokens[0])
        time_start = int(dt_tokens[1].split(":")[0])
        time_end = int(dt_tokens[3].split(":")[0])
        d_start = d + datetime.timedelta(days=weekday, hours=time_start)
        d_end = d + datetime.timedelta(days=weekday, hours=time_end)
        summary = "%s; %s" % (e[2], e[1])
        description = "%s\n%s" % (e[3], "\n".join(e[4:]))

        event = Event()
        event.add("dtstart", d_start)
        event.add("dtend", d_end)
        event.add("dtstamp", d)
        event.add("rrule", vRecur(freq="daily", interval=7))
        event.add("summary", summary)
        event.add("description", description)
        cal.add_component(event)

    return cal.to_ical()
Example #29
0
def ical_init():
	cal = Calendar()
	cal.add('prodid', '-//CSPay calendar//EN/')
	cal.add('version', '2.0')
	TZ = Timezone()
	TZ.add('tzid','Europe/Bucharest')
	
	TZS = StandardT()
	TZS.add('TZOFFSETFROM',timedelta(hours=3))
	TZS.add('TZOFFSETTO',timedelta(hours=2))
	TZS.add('TZNAME','EET')
	TZS.add('DTSTART',datetime(1997,10,26))
	TZS.add('rrule',vRecur.from_ical('FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU'))
	TZ.add_component(TZS)

	TZS = DaylightT()
	TZS.add('TZOFFSETFROM',timedelta(hours=2))
	TZS.add('TZOFFSETTO',timedelta(hours=3))
	TZS.add('TZNAME','EEST')
	TZS.add('DTSTART',datetime(1997,03,30))
	TZS.add('rrule',vRecur.from_ical('FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU'))
	TZ.add_component(TZS)
	
	cal.add_component(TZ)
	
	return cal
Example #30
0
def get_plan_ical(request, html_week):
    queryset = MealPlan.objects.filter(Q(created_by=request.user) | Q(shared=request.user)).distinct().all()

    y, w = html_week.replace('-W', ' ').split()
    queryset = queryset.filter(date__week=w, date__year=y)

    cal = Calendar()

    for p in queryset:
        event = Event()
        event['uid'] = p.id
        event.add('dtstart', p.date)
        event.add('dtend', p.date)
        event['summary'] = f'{p.meal_type.name}: {p.get_label()}'
        event['description'] = p.note
        cal.add_component(event)

    response = FileResponse(io.BytesIO(cal.to_ical()))
    response["Content-Disposition"] = f'attachment; filename=meal_plan_{html_week}.ics'

    return response
Example #31
0
    def create_ical(self, eventdata):
        #moved this method here from the public file bc we need to generate an ical multiple times
        cal = Calendar()
        event = Event()
        permalink = "http://calendar.olin.build/events/" + str(
            eventdata["_id"])
        if eventdata["all_day"]:
            event["dtstart"] = datetime.strftime(eventdata["dtstart"],
                                                 "%Y%m%d")
            event["dtend"] = datetime.strftime(eventdata["dtend"], "%Y%m%d")
        else:
            event["dtstart"] = datetime.strftime(eventdata["dtstart"],
                                                 "%Y%m%dT%H%M%S")
            event["dtend"] = datetime.strftime(eventdata["dtend"],
                                               "%Y%m%dT%H%M%S")
        event["summary"] = eventdata["title"]
        event["location"] = eventdata["location"]
        event["description"] = eventdata["description"] + "\n \n" + permalink
        cal.add_component(event)

        return cal.to_ical()
Example #32
0
def schedule_ical():
    schedule = _get_scheduled_proposals(request.args)
    title = 'EMF {}'.format(event_start().year)

    cal = Calendar()
    cal.add('summary', title)
    cal.add('X-WR-CALNAME', title)
    cal.add('X-WR-CALDESC', title)
    cal.add('version', '2.0')

    for event in schedule:
        cal_event = Event()
        cal_event.add('uid', event['id'])
        cal_event.add('summary', event['title'])
        cal_event.add('description', event['description'])
        cal_event.add('location', event['venue'])
        cal_event.add('dtstart', event['start_date'])
        cal_event.add('dtend', event['end_date'])
        cal.add_component(cal_event)

    return Response(cal.to_ical(), mimetype='text/calendar')
Example #33
0
def generate_calendar(bond: Bond, coupons: List[CouponScheduleEntry],
                      amorts: List[AmortizationScheduleEntry]) -> Calendar:
    """returns tuple with first element a calendar with events of payments for a bond
    and second element as a textual description"""
    cal = Calendar()
    cal.add("prodid", "-//Coupon notifier")
    cal.add("version", "2.0")

    ccy_char = ccy_to_char(bond.notional_ccy)
    for coupon in coupons:
        event = generate_event(
            f'"{bond.name}" coupon of {coupon.value}{ccy_char} ({bond.isin})',
            coupon.coupon_date)
        cal.add_component(event)

    for amort in amorts:
        event = generate_event(
            f'"{bond.name}" notional repayment of {amort.value}{ccy_char} ({bond.isin})',
            amort.amort_date)
        cal.add_component(event)
    return cal
Example #34
0
def ical_creat(filename):
    courselist = JsonLoadHandle(filename)
    cal = Calendar()
    cal.add('prodid', '-//My CourseTable//')
    cal.add('version', '2.0')
    cal.add('CALSCALE', 'GREGORIAN')
    cal.add('method', 'PUBLISH')
    tz = Timezone()
    tzst = TimezoneStandard()
    tzst.add('tzoffsetfrom', timedelta(hours=8))
    tzst.add('tzoffsetto', timedelta(hours=8))
    tzst.add('tzname', 'CST')
    tzst.add('dtstart', datetime(1970, 1, 1, 0, 0, 0))
    tz.add('tzid', 'Asia/Shanghai')
    tz.add_component(tzst)
    cal.add_component(tz)
    for course in courselist:
        cal.add_component(course.getEvent())
    f = open(os.path.abspath('cache/ics/' + filename + '.ics'), 'wb')
    f.write(cal.to_ical())
    f.close()
Example #35
0
    def handle(self, *args, **options):
        URL = r'http://contests.acmicpc.info/contests.json'
        TZ = timezone('Asia/Shanghai')

        cal = Calendar()
        cal.add('prodid', '-//ACM EVENTS CALENDAR//WHUACM TEAM//')
        cal.add('version', '2.0')
        events = requests.get(URL).json()

        for item in events:
            event = Event()
            fmt = '%Y-%m-%d %H:%M:%S'
            time = datetime.strptime(item['start_time'], fmt).replace(tzinfo=TZ)
            event.add('dtstart', time)
            event.add('summary', item['name'])
            event['location'] = vText(item['oj'])
            event['uid'] = item['id'] + '@whuctf.org'
            cal.add_component(event)
        f = open(os.path.join(settings.MEDIA_ROOT, 'acmevents.ics'), 'wb')
        f.write(cal.to_ical())
        f.close()
Example #36
0
def ical_feed(request):
    cal = Calendar()

    cal.add('prodid', '-//Events Calendar//blanc-basic-events//EN')
    cal.add('version', '2.0')
    cal.add('x-wr-calname', getattr(settings, 'EVENTS_CALENDAR_NAME', 'Events'))
    cal.add('x-wr-caldesc', getattr(settings, 'EVENTS_CALENDAR_DESCRIPTION', 'Events Calendar'))

    domain = get_current_site(request).domain

    # Events
    for i in SpecialEvent.objects.filter(published=True, end_date__gte=datetime.date.today()):
        event = Event(uid='%d@%s' % (i.id, domain), summary=i.title)
        event.add('dtstart', i.start)  # Ensure the datetime gets encoded
        event.add('dtend', i.end)
        cal.add_component(event)

    response = HttpResponse(cal.to_ical(), content_type='text/calendar')
    response['Content-Disposition'] = 'attachment; filename=events.ics'

    return response
Example #37
0
def generate_ics(event_list: list):
    """
    generate ics file
    :param event_list: [birthday, [year, month, day]]
    :return:
    """
    cal = Calendar()
    cal.add('prodid', '-//My calendar product//mxm.dk//')
    cal.add('version', '2.0')
    tz = pytz.timezone('Asia/Shanghai')
    for birthday, date in event_list:
        print(birthday, date)
        event = Event()
        age = date[0] - birthday.year
        event.add("summary", f"{birthday.name}'s {age} years old birthday")
        event.add('dtstart', datetime(*date, 0, 0, 0, tzinfo=tz))
        event.add('dtend', datetime(*date, 23, 59, 59, tzinfo=tz))
        event.add('dtstamp', datetime.now())
        cal.add_component(event)
    with open("birthday.ics", "wb") as f:
        f.write(cal.to_ical())
Example #38
0
    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 get(self, request, *args, **kwargs):
        postcode = kwargs["postcode"]
        polling_station = self.get_polling_station_info(postcode)

        cal = Calendar()
        cal["summary"] = "Elections in {}".format(postcode)
        cal["X-WR-CALNAME"] = "Elections in {}".format(postcode)
        cal["X-WR-TIMEZONE"] = "Europe/London"

        cal.add("version", "2.0")
        cal.add("prodid", "-//Elections in {}//mxm.dk//".format(postcode))

        for post_election in self.postcode_to_ballots(postcode):
            event = Event()
            event["uid"] = "{}-{}".format(post_election.post.ynr_id,
                                          post_election.election.slug)
            event["summary"] = "{} - {}".format(post_election.election.name,
                                                post_election.post.label)

            event.add("dtstart", post_election.election.start_time)
            event.add("dtend", post_election.election.end_time)
            event.add(
                "DESCRIPTION",
                "Find out more at {}/elections/{}/".format(
                    settings.CANONICAL_URL, postcode.replace(" ", "")),
            )
            if polling_station.get("polling_station_known"):
                geometry = polling_station["polling_station"]["geometry"]
                if geometry:
                    event["geo"] = "{};{}".format(geometry["coordinates"][0],
                                                  geometry["coordinates"][1])
                properties = polling_station["polling_station"]["properties"]
                event["location"] = vText("{}, {}".format(
                    properties["address"].replace("\n", ", "),
                    properties["postcode"],
                ))

            cal.add_component(event)

        return HttpResponse(cal.to_ical(), content_type="text/calendar")
    def get(self, request, *args, **kwargs):
        postcode = kwargs['postcode']
        polling_station = self.get_polling_station_info(postcode)

        cal = Calendar()
        cal['summary'] = 'Elections in {}'.format(postcode)
        cal['X-WR-CALNAME'] = 'Elections in {}'.format(postcode)
        cal['X-WR-TIMEZONE'] = 'Europe/London'

        cal.add('version', '2.0')
        cal.add('prodid', '-//Elections in {}//mxm.dk//'.format(postcode))

        for post_election in self.postcode_to_posts(postcode):
            event = Event()
            event['uid'] = "{}-{}".format(post_election.post.ynr_id,
                                          post_election.election.slug)
            event['summary'] = "{} - {}".format(post_election.election.name,
                                                post_election.post.label)

            event.add('dtstart', post_election.election.start_time)
            event.add('dtend', post_election.election.end_time)
            event.add(
                'DESCRIPTION', "Find out more at {}/elections/{}/".format(
                    settings.CANONICAL_URL, postcode))

            if polling_station['polling_station_known']:
                geometry = polling_station['polling_station']['geometry']
                event['geo'] = "{};{}".format(
                    geometry['coordinates'][0],
                    geometry['coordinates'][1],
                )
                properties = polling_station['polling_station']['properties']
                event['location'] = vText("{}, {}".format(
                    properties['address'].replace('\n', ', '),
                    properties['postcode'],
                ))

            cal.add_component(event)

        return HttpResponse(cal.to_ical(), content_type="text/calendar")
Example #41
0
def build_calender(class_table: List[List[CourseInfo]],
                   start_date: Union[tuple, list]) -> Tuple[Calendar, str]:
    """生成日历
    :param class_table:
    :param start_date: (年,月,日)
    :return:
    """
    calender = Calendar()
    # 版本,用于支持一些新特性,比如换行什么的
    calender.add('version', '2.0')
    # 日历开始时间
    calender.add('dtstart', datetime.now())
    # 日历名称
    calender.add('summary', f'{current_term(start_date)} syllabus')
    # 遍历日历事件
    for courses in class_table:
        for course in courses:
            # TODO 如果有更多的范围该怎么办呢?
            week_range_len = len(course.week_range)
            if week_range_len == 1:  # 只在某一周上课
                calender.add_component(
                    get_cal_event(course, start_date, end_week=0))
            else:
                calender.add_component(get_cal_event(course,
                                                     start_date))  # 一个周次范围
                if week_range_len == 4:  # 第二个周次范围
                    calender.add_component(
                        get_cal_event(course,
                                      start_date,
                                      start_week=2,
                                      end_week=3))

    return calender, current_term(start_date)
Example #42
0
class Schedule:
    def __init__(self, f):
        schedule = yaml.load(f)
        self.ical = Calendar()

        # fill out info
        self.fill_meta(schedule)
        self.fill_term(schedule, 'first')
        self.fill_term(schedule, 'second')

    def fill_meta(self, schedule):
        self.ical.add('version', '2.0')
        self.ical.add('prodid', '-//kamilab calendar//yaml2ical.py//')
        self.ical.add('attendee', 'MAILTO:' + schedule['mailto'])

    def fill_term(self, schedule, term):
        parser = PeriodParser(schedule['year'], term)

        for evt in schedule[term]:
            vevt = Event()
            dtstart, dtend = parser.parse(evt)
            vevt.add('dtstart', dtstart)
            vevt.add('dtend', dtend)

            # set info
            vevt.add('summary', evt['summary'])
            vevt.add('description', evt['description'])

            # set RRULE
            rec = vRecur()
            rec['FREQ'] = 'WEEKLY'
            rec['BYDAY'] = evt['weekday']
            rec['UNTIL'] = parser.eot
            vevt.add('RRULE', rec)

            self.ical.add_component(vevt)

    def to_ical(self, out):
        out.write(self.ical.to_ical())
        out.close()
Example #43
0
    def get(self):
        type_ = self.get_argument('type', 0)

        cal = Calendar()
        cal.add('prodid', '-//BGmi Followed Bangumi Calendar//bangumi.ricterz.me//')
        cal.add('version', '2.0')

        data = Followed.get_all_followed(order='followed.updated_time', desc=True)
        data.extend(self.patch_list)

        if type_ == 0:

            bangumi = defaultdict(list)
            [bangumi[Bangumi.week.index(i['update_time']) + 1].append(i['bangumi_name']) for i in data]

            weekday = datetime.datetime.now().weekday()
            for i, k in enumerate(range(weekday, weekday + 7)):
                if k % 7 in bangumi:
                    for v in bangumi[k % 7]:
                        event = Event()
                        event.add('summary', v)
                        event.add('dtstart', datetime.datetime.now().date() + datetime.timedelta(i - 1))
                        event.add('dtend', datetime.datetime.now().date() + datetime.timedelta(i - 1))
                        cal.add_component(event)
        else:
            data = [bangumi for bangumi in data if bangumi['status'] == 2]
            for bangumi in data:
                event = Event()
                event.add('summary', 'Updated: {}'.format(bangumi['bangumi_name']))
                event.add('dtstart', datetime.datetime.now().date())
                event.add('dtend', datetime.datetime.now().date())
                cal.add_component(event)

        cal.add('name', 'Bangumi Calendar')
        cal.add('X-WR-CALNAM', 'Bangumi Calendar')
        cal.add('description', 'Followed Bangumi Calendar')
        cal.add('X-WR-CALDESC', 'Followed Bangumi Calendar')

        self.write(cal.to_ical())
        self.finish()
Example #44
0
    def createAnIcs(self, title, starttime, endtime, place):
        '''
			title:日历的标题
			start:日历的开始时间
			endtime:日历持续的时间
			place:地点

		'''
        cal = Calendar()
        cal['version'] = '2.0'
        cal['prodid'] = '-//Apple Inc.//Mac OS X 10.13.6//EN'
        event = Event()
        alarm = Alarm()
        #ev_start_date = startdate
        #ev_start_datetime = datetime.combine(ev_start_date,starttime)
        ev_start_datetime = starttime
        #ev_last_relative_delta = relativedelta(lasttime[0],lasttime[1])
        #ev_end_datetime = ev_start_date + ev_last_relative_delta
        ev_end_datetime = endtime

        event.add('uid', str(uuid1()) + '@COUT')
        event.add('summary', title)
        event.add('dtstamp', datetime.now())
        event.add('dtstart', ev_start_datetime)
        event.add('dtend', ev_end_datetime)
        event.add('location', place)
        alarm.add('TRIGGER', ev_start_datetime)
        alarm.add('action', 'DISPLAY')
        event.add_component(alarm)
        '''
		BEGIN:VALARM
		TRIGGER:-PT15M
		ACTION:DISPLAY
		END:VALARM
		'''
        cal.add_component(event)
        with open("记忆事件.ics", "w+") as file:
            file.write(cal.to_ical().decode('utf-8'.replace('\r\n',
                                                            '\n').strip()))
            file.close()
Example #45
0
def talk_ics(slug):
    description, content = get_markdown_file('talks/{}'.format(slug), 'en')

    tz = pytz.timezone('Canada/Eastern')

    start_time = datetime.strptime(
        '{0} {1}'.format(content['date'][0], content['start_time'][0]),
        '%Y-%m-%d %H:%M:%S')

    end_time = datetime.strptime(
        '{0} {1}'.format(content['date'][0], content['end_time'][0]),
        '%Y-%m-%d %H:%M:%S')

    cal = Calendar()
    cal.add('prodid', '-//PyCon Canada 2016//2016.pycon.ca')
    cal.add('version', '2.0')

    event = Event()
    event.add(
        'summary', u"{0} with {1}".format(content['title'][0],
                                          content['speakers'][0]))
    event.add('dtstart', tz.localize(start_time))
    event.add('dtend', tz.localize(end_time))
    event.add('dtstamp', tz.localize(start_time))

    event.add('uid', slug)

    tpl_url = 'https://2016.pycon.ca{0}'
    event.add('url', tpl_url.format(url_for('schedule.talk', slug=slug)))

    cal.add_component(event)

    headers = {
        'Content-Disposition': 'attachment;filename={0}.ics'.format(slug)
    }

    return Response(response=cal.to_ical(),
                    status=200,
                    mimetype='text/x-calendar',
                    headers=headers)
Example #46
0
def sortidaiCal( request):

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
    cal = Calendar()
    cal.add('method','PUBLISH' ) # IE/Outlook needs this

    for instance in Sortida.objects.filter( calendari_desde__isnull = False ).exclude(estat__in = ['E', 'P', ]).all():
        event = Event()
        
#         d=instance.data_inici
#         t=instance.franja_inici.hora_inici
#         dtstart = datetime( d.year, d.month, d.day, t.hour, t.minute  )
#         d=instance.data_fi
#         t=instance.franja_fi.hora_fi
#         dtend = datetime( d.year, d.month, d.day, t.hour, t.minute  )
        
        
        summary = u"{ambit}: {titol}".format(ambit=instance.ambit ,
                                                   titol= instance.titol_de_la_sortida)
        
        event.add('dtstart',localtime(instance.calendari_desde) )
        event.add('dtend' ,localtime(instance.calendari_finsa) )
        event.add('summary',summary)
        organitzador = u"\nOrganitza: "
        organitzador += u"{0}".format( u"Departament" + instance.departament_que_organitza.nom if instance.departament_que_organitza_id else u"" )
        organitzador += " " + instance.comentari_organitza
        event.add('organizer',  vText( u"{0} {1}".format( u"Departament " + instance.departament_que_organitza.nom  if instance.departament_que_organitza_id else u"" , instance.comentari_organitza )))
        event.add('description',instance.programa_de_la_sortida + organitzador)
        event.add('uid', 'djau-ical-{0}'.format( instance.id ) )
        event['location'] = vText( instance.ciutat )

        
        cal.add_component(event)

#     response = HttpResponse( cal.to_ical() , content_type='text/calendar')
#     response['Filename'] = 'shifts.ics'  # IE needs this
#     response['Content-Disposition'] = 'attachment; filename=shifts.ics'
#     return response

    return HttpResponse( cal.to_ical() )
def writeCal(workschedule, path):
    cal = Calendar()

    for workshift in workschedule:
        event = Event()

        date = workshift.date.split('-')
        stime = workshift.starttime.split(':')
        etime = workshift.endtime.split(':')

        dtstart = datetime(int(date[0]), int(date[1]), int(date[2]),
                           int(stime[0]), int(stime[1]))
        dtend = datetime(int(date[0]), int(date[1]), int(date[2]),
                         int(etime[0]), int(etime[1]))

        event.add('summary', workshift.info)
        event.add('dtstart', dtstart)
        event.add('dtend', dtend)
        cal.add_component(event)

    path = path.split('/')
    output = ''
    for i in range(len(path) - 1):
        output += path[i] + '/'
    output += 'GLT Arbetsschema.ics'

    i = 0
    while os.path.isfile(output):
        if i == 0:
            output = output[:-4] + ' (1).ics'
        else:
            parenthesis = output.find('(')
            output = output[:parenthesis + 1] + str(i) + ').ics'
        i += 1

    f = open(output, 'wb')
    f.write(cal.to_ical())
    f.close()

    return cal
Example #48
0
def generate_event_ical_files(events):
    for event in events:

        cal = Calendar()
        cal.add('prodid', '-//foss.events//foss.events//')
        cal.add('version', '1.3.3.7')

        cal_event = Event()
        cal_event.add('summary', event['label'])
        cal_event.add('dtstart', vDate(event['start_date']))

        cal_end_date = event['end_date'] + timedelta(days=1)
        cal_event.add('dtend', vDate(cal_end_date))

        cal_event.add('location', event['readable_location'])
        cal_event.add('url', vUri(event['abs_details_url']))

        description = event['description'] or ''
        description += '\n\n'

        if event['has_details']:
            description += 'Read everything about ' + event[
                'label'] + ' in a nutshell on // foss.events: ' + event[
                    'abs_details_url'] + '\n\n'

        description += 'Official Homepage: ' + event['homepage'] + '\n\n'

        if event['osm_link']:
            description += 'Find your way: ' + event['osm_link'] + '\n'

        cal_event['description'] = remove_tags(description)

        cal.add_component(cal_event)

        if event['lat'] and event['lon']:
            cal_event['geo'] = vGeo([event['lat'], event['lon']])

        filepath = generate_event_ical_path(event)
        with open('build/' + filepath, 'wb') as f:
            f.write(cal.to_ical())
Example #49
0
 def get(self):
     from icalendar import Calendar, Event, vCalAddress, vText
     cal = Calendar()
     cal.add('prodid', '-//Strings Oxford Calendaring//strings.ox.ac.uk//')
     cal.add('version', '2.0')
     cal.add('X-WR-CALNAME', 'Strings Oxford')
     for ev in self.get_events():
         event = Event()
         event['uid'] = vText(ev.uid)
         event['location'] = vText(ev.location)
         event['summary'] = ev.title
         event['dtstart'] = self._ical_time(ev.start_date)
         event['dtend'] = self._ical_time(ev.end_date)
         desc = u'Speaker: {}\n'.format(ev.speaker)
         desc += u'Location: {}\n'.format(ev.location)
         desc += u'Series: {}\n'.format(ev.series)
         desc += ev.description
         event['description'] = vText(desc)
         cal.add_component(event)
     #self.response.headers['Content-Type'] = 'text/plain'
     self.response.headers['Content-Type'] = 'text/calendar'
     self.response.write(cal.to_ical())
Example #50
0
def get_meeting_ical(request, meeting, desc):
    cal = Calendar()
    cal.add('prodid', '-//commuxi Corporation//bbbforum release//')
    cal.add('version', '2.0')
    event = Event()
    event.add('summary', meeting.name)
    #event.add('dtstart', meeting.start_time)
    event.add(
        'dtstart',
        tz_convert(meeting.start_time, 'UTC',
                   request.user.get_profile().tz))
    if meeting.duration == 0:
        event.add('duration', timedelta(days=1))  #unlimit is 1 day by default
    else:
        event.add('duration', timedelta(minutes=int(meeting.duration)))
    #event.add('dtend', '')
    event.add('location', 'http://www.commux.com')
    event.add('description', desc)
    event['uid'] = "%s@%s" % (meeting.id, request.META['HTTP_HOST'])
    cal.add_component(event)
    #print cal.to_ical()
    return cal.to_ical()
Example #51
0
def ical(request):
    t = loader.get_template(calendar_description_template)

    token = get_token(request)
    if not token:
        return HttpResponseForbidden("Missing authentication token")
    try:
        key = Key.objects.select_related("user").get(token=token)
    except Key.DoesNotExist:
        return HttpResponseForbidden("Invalid authentication token")
    if not key.has_scopes(["export_ical"]):
        return HttpResponseForbidden("Unauthorized operation for the token")
    key.update_used_on()

    cal = Calendar()
    cal.add("prodid", f"-//small-eod//letters//{key.user}//")
    cal.add("version", "2.0")
    for name in refresh_props:
        cal.add(name, "PT1H")
    for obj in Letter.objects.exclude(event__isnull=True).select_related(
            "case", "case__audited_institution"):
        letter = IEvent()
        url = request.build_absolute_uri(
            reverse("admin:cases_letter_change",
                    kwargs={"object_id": str(obj.pk)}))
        description = t.render({"obj": obj}, request).strip()
        categories = [obj.case]
        if obj.case and obj.case.audited_institution:
            categories.append(obj.case.audited_institution)
        letter.add("uid", get_uuid(obj, description))
        letter.add("dtstart", obj.event)
        letter.add("dtstamp", obj.event)
        letter.add("summary", obj.name)
        letter.add("url", url)
        if description:
            letter.add("description", description)
        letter.add("categories", categories)
        cal.add_component(letter)
    return HttpResponse(content=cal.to_ical(), content_type="text/calendar")
Example #52
0
    def generate_calendar(self):
        # so we make a calendar to which we add all the events
        cal = Calendar()
        cal['summary'] = self.name

        # adds a new event to the calendar for each date in the list
        for event_name, event_date in self.get_schedule_dates().items():
            event = Event()
            event.add('summary', event_name)
            event.add('dtstart', event_date)
            cal.add_component(event)

        # makes a temporary file to export the calendar to
        directory = tempfile.mkdtemp()
        f = open(os.path.join(directory, 'milestones.ics'), 'wb')
        f.write(cal.to_ical())
        f.close()

        # prints the location of the ics file
        print("Generated new calendar for " + self.name +
              " in this directory:")
        print(directory)
def main():
    """
    Perform iCalendar to hCalendar rendering.
    """
    html_dir = len(sys.argv) > 1 and sys.argv[1] or 'hcal'
    ics_fout = len(sys.argv) > 2 and open(sys.argv[2], 'w') or sys.stdout

    # Parse a directory of HTML files for hCalendar events.
    hp = HCalendarParser()
    events = []
    for dirpath, dirnames, filenames in os.walk(html_dir):
        for fn in filenames:
            if fn.endswith(".html") or fn.endswith(".htm"):
                fp = os.path.join(dirpath, fn)
                data = open(fp, 'r').read()
                events.extend(hp.parse(data))

    # Build a calendar from the parsed events and print the data
    cal = Calendar()
    for e in events:
        cal.add_component(e)
    print cal.as_string()
Example #54
0
def download_calendar_view(request, secret):
    username = base64.urlsafe_b64decode(secret.encode('utf-8'))
    user = User.objects.get(username=username)
    dues = Due.objects.filter(mail__in=Mail.my_mails(user))
    cal = Calendar()
    cal.add('prodid', '-//rmd.io Events Calendar//%s//EN' % settings.SITE_URL)
    cal.add('version', '2.0')

    for due in dues:
        event = Event()
        event.add(
            'summary',
            '%s [rmd.io]' % tools.calendar_clean_subject(due.mail.subject))
        event.add('description', '%s/mails/' % settings.SITE_URL)
        event.add('dtstart', due.due)
        event.add('dtend', due.due)
        cal.add_component(event)

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

    return response
Example #55
0
def get_calendar(schedules, cal, cal_name):
    # calendar metadata
    if cal is None:
        cal = Calendar()
        cal.add('prodid', '-//Uni Hannover//Room ICal Calendar//DE')
        cal.add('X-WR-CALNAME', vText(schedules[0].room_name) + cal_name)
        cal.add('X-WR-TIMEZONE', 'Europe/Berlin')
        cal.add('version', '2.0')
        cal.add('method', 'PUBLISH')

        #=======================================================================
        # cal.add('BEGIN','VTIMEZONE')
        # cal.add('TZID','Europe/Berlin')
        # cal.add('BEGIN','DAYLIGHT')
        # cal.add('TZOFFSETFROM','+0100')
        # cal.add('DTSTART','19810329T020000')
        # cal.add('RRULE','FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU')
        # cal.add('TZNAME','MESZ')
        # cal.add('END','DAYLIGHT')
        # cal.add('BEGIN','STANDARD')
        # cal.add('TZOFFSETFROM','+0200')
        # cal.add('DTSTART','19961027T030000')
        # cal.add('RRULE','FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU')
        # cal.add('TZNAME','MEZ')
        # cal.add('END','STANDARD')
        # cal.add('END','VTIMEZONE')
        #=======================================================================

    for schedule in schedules:
        for reservation in schedule.reservations:
            event = Event()
            event.add('summary', reservation["title"])
            event.add('dtstart', reservation["start"])
            event.add('dtend', reservation["end"])
            event.add('url', reservation["href"])
            event['location'] = vText(schedule.room_name)
            cal.add_component(event)

    return cal
Example #56
0
def write_calendar(options, sources, filename, prepend_calendername):
    """Create and write ics file"""
    cal = Calendar()
    timezones_cache = []
    for key, value in options.items():
        cal.add(key, value)
    for source_id, category in sources.items():
        for timezone in in_cals[source_id].walk('VTIMEZONE'):
            if timezone['tzid'] not in timezones_cache:
                timezones_cache.append(timezone['tzid'])
                cal.add_component(timezone)
        for event in in_cals[source_id].walk('VEVENT'):
            event_copy = Event(event)
            event_copy.add('categories', category)

            if prepend_calendername:
                event_copy[
                    'summary'] = category + " | " + event_copy['summary']

            cal.add_component(event_copy)
    with open(filename, 'wb') as f:
        f.write(cal.to_ical())
Example #57
0
def calendar(data, filtered_bands):
    cal = Calendar()

    cal.add('prodid', '-//Wacken Calendar//mkcal//EN')
    cal.add('version', '1.0.0')

    now = arrow.get().datetime

    COLORS = 'yellow green red blue aqua lime olive navy white maroon fuchsia teal silver gray'.split(
    )  # noqa
    itercolors = itertools.cycle(COLORS)
    colormap = defaultdict(lambda: next(itercolors))

    if filtered_bands is None:
        filtered_data = data
    else:
        filtered_data = ((startdt, enddt, bandname, stagename)
                         for startdt, enddt, bandname, stagename in data
                         if bandname.strip() in filtered_bands)

    for startdt, enddt, bandname, stagename in filtered_data:
        event = Event()

        event.add('uid', '{}/{}@wacken'.format(uuid.uuid1(), '0'))
        event.add('summary', '{} / {}'.format(bandname, stagename))
        event.add('description', '')
        event.add('dtstart', startdt.datetime)
        event.add('dtend', enddt.datetime)
        event.add('dtstamp', now)
        event.add('created', now)
        event.add('last-modified', now)
        event.add('location', 'Wacken, Germany')
        event.add('class', 'PUBLIC')
        event.add('color', colormap[stagename])
        event.add('categories', colormap[stagename])

        cal.add_component(event)

    return cal
Example #58
0
class ReleaseCalendar():
    def __init__(self, zone):
        self.zone = zone
        self.cal = Calendar()

    def add_release(self, game):
        if game.release_date[self.zone]:
            event = Event()
            event.add('summary', game.title)
            event.add('dtstart', game.release_date[self.zone])
            self.cal.add_component(event)

    def populate(self, games):
        for game in games:
            self.add_release(game)

    def write(self, path):
        filename = "%s/%s.ics" % (path, self.zone)
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        file = open(filename, 'wb')
        file.write(self.cal.to_ical())
        file.close()
Example #59
0
def ical(request):
    cal = Calendar()
    cal.add('prodid', '-//%s Events Calendar//%s//' % ("URNIK", "DELAJOZATE"))
    cal.add('version', '2.0')

    site_token = "DELAJOZATE"
    startdate = datetime.date.today() - datetime.timedelta(1)
    events = Event.objects.filter(
        start__gte=startdate).order_by('start')[:NUM_EVENTS]
    for e in events:
        ical_event = IEvent()
        ical_event.add('summary', e.title)
        ical_event.add('dtstart', e.start)
        ical_event.add('dtend', e.end)
        ical_event.add('location', e.location)
        ical_event.add('description', e.category + " " + str(e.url))
        ical_event['uid'] = '%d.event.events.%s' % (e.id, site_token)
        cal.add_component(ical_event)

    response = HttpResponse(cal.to_ical(), mimetype="text/calendar")
    response['Content-Disposition'] = 'attachment; filename=%s.ics' % "urnik"
    return response
Example #60
-1
def cal_events(request, *args, **kwargs):
    cal = Calendar()

    cal.add("prodid", "-//AkCalendar//altekamereren.org")
    cal.add("version",  "2.0")

    cal.add("X-WR-CALDESC", "Alte Kamererens eventkalender")
    cal.add("X-WR-CALNAME", "AKcal")
    cal.add("X-WR-TIMEZONE", "Europe/Stockholm")

    items = app.models.event.Event.objects.filter(
        date__gte=datetime.date.today() - datetime.timedelta(days=30)
    ).select_subclasses()

    for item in items:
        event = Event()
        event.add("uid", item_uid(item))
        event.add("summary", item.name)
        event.add("dtstart", item_start(item))
        event.add("duration", datetime.timedelta(hours=2))
        event.add('created', item.created)
        event.add('last-modified', item.last_modified)
        event.add('description', item_description(item))
        event.add('X-ALT-DESC;FMTTYPE=text/html', item_html_description(item))
        event.add('location', item.location)
        cal.add_component(event)

    response = HttpResponse(cal.to_ical(), mimetype='text/calendar; charset=utf-8')
    filename = "events.ics"
    # following added for IE
    response['Filename'] = filename
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    response["Cache-Control"] = "no-cache, must-revalidate"
    response["Expires"] = "Sat, 26 Jul 1997 05:00:00 GMT"
    return response