Example #1
0
def talk_ics(slug):
    cal = Calendar()
    cal.add('prodid', '-//PyCon Canada 2016//2016.pycon.ca')
    cal.add('version', '2.0')

    if slug == 'schedule':
        schedule = get_data_file('schedule.json')

        # TODO: This should be refactored.
        for day in schedule.get('days'):
            for slot in day.get('entries'):
                if slot.get('talks'):
                    for room, talk in slot.get('talks').iteritems():
                        if talk:
                            cal.add_component(event_ics(talk))
    else:
        cal.add_component(event_ics(slug))

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

    return Response(response=cal.to_ical(),
                    status=200,
                    mimetype='text/calendar',
                    headers=headers)
Example #2
0
def writeIcal(sleeps, f, fmt='Sleeping...zzZzz'):
    from icalendar import Calendar, Event
    import md5

    cal = Calendar()
    cal.add('prodid', '-//SleepBot Calendar//LUDO6431//FR')
    cal.add('version', '2.0')

    for sleep in sleeps:
        event = Event()
        try:
            dts = sleep2dates(sleep)
            event.add('summary', fmt.format(**sleep))
        except KeyError:
            sleep = new2oldref(sleep)
            dts = sleep2dates(sleep)
            event.add('summary', fmt.format(**sleep))
        event.add('dtstart', dts[0])
        event.add('dtend', dts[1])
        event['uid'] = md5.new(str(dts[0]) + 'SleepBot' +
                               str(dts[1])).hexdigest() + '@mysleepbot.com'

        cal.add_component(event)

    f.write(cal.to_ical())
Example #3
0
def make_meeting_ics(meeting):
    study_group = meeting.study_group
    cal = Calendar()
    cal.add('prodid', '-//learningcircles.p2pu.org//LearningCircles')
    cal.add('version', '2.0')
    event = Event()
    event.add('summary', str(meeting))
    event.add('dtstart', meeting.meeting_datetime())
    event.add('dtend', meeting.meeting_datetime_end())

    organizer = vCalAddress('MAILTO:{}'.format(study_group.facilitator.email))
    organizer.params['cn'] = vText(study_group.facilitator.first_name)
    organizer.params['role'] = vText('Facilitator')
    event['organizer'] = organizer
    event['location'] = vText('{}, {}, {}, {}'.format(study_group.venue_name,
                                                      study_group.city,
                                                      study_group.region,
                                                      study_group.country))

    event['uid'] = '{}-{}@p2pu'.format(study_group.uuid, meeting.pk)
    event.add('priority', 5)

    #attendee = vCalAddress('MAILTO:[email protected]')
    #attendee.params['cn'] = vText('Max Rasmussen')
    #attendee.params['ROLE'] = vText('REQ-PARTICIPANT')
    #event.add('attendee', attendee, encode=0)

    cal.add_component(event)
    return cal.to_ical().decode()
Example #4
0
def export(request, agenda_id):
    event = get_object_or_404(CustomAgendaItems, id = agenda_id)

    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)

    ical_event = Event()
    ical_event.add('location', event.location)
    ical_event.add('summary', event.title)
    # ical_event.add('description', event.session_description)
    start = datetime.combine(event.start_date, event.start_time)
    ical_event.add('dtstart', start)
    end = datetime.combine(event.start_date, event.end_time)
    ical_event.add('dtend', end and end or start)
    ical_event.add('dtstamp', end and end or start)
    ical_event['uid'] = '%d.event.events.%s' % (event.id, site_token)
    cal.add_component(ical_event)

    response = HttpResponse(cal.to_ical(), content_type="text/calendar")
    response['Content-Disposition'] = 'attachment; filename=%s.ics' % event.slug
    return response
Example #5
0
def export(request):
    event_list = Event.objects.filter()

    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 event_list:
        ical_event = CalEvent()
        if event.madeByAdmin:
            ical_event.add('name', event.name)
        else:
            ical_event.add(
                'name', event.name + ' (' + event.member.get_full_name() + ')')
        ical_event.add('summary', event.name)
        ical_event.add('dtstart', event.date)
        ical_event.add('location', event.place)
        ical_event.add('description', event.description)
        # ical_event.add('dtstamp', event.end and event.end or event.start)
        ical_event['uid'] = '%d.event.events.%s' % (event.id, site_token)
        cal.add_component(ical_event)
        calString = unicode(cal.to_ical(), "utf-8")
    response = HttpResponse(calString,
                            content_type="text/calendar; charset=UTF-8")
    response['Content-Disposition'] = 'attachment; filename=%s.ics' % 'ics'
    return response
Example #6
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 #7
0
def export_event_to_ical(event):
    from icalendar import Event, Calendar
    import pytz

    cal = Calendar()
    cal.add("prodid", "-//janun.de//")
    cal.add("version", "2.0")
    ical_event = Event()
    ical_event.add("uid", event.slug + "@" + "janun.de")
    ical_event.add("summary", event.title)
    if event.all_day:
        ical_event.add("dtstart", event.start_datetime.astimezone(pytz.utc).date())
    else:
        ical_event.add("dtstart", event.start_datetime.astimezone(pytz.utc))
    if event.end_datetime:
        if event.all_day:
            ical_event.add("dtend", event.end_datetime.astimezone(pytz.utc).date())
        else:
            ical_event.add("dtend", event.end_datetime.astimezone(pytz.utc))
    ical_event.add("dtstamp", event.latest_revision_created_at.astimezone(pytz.utc))
    if event.content:
        ical_event.add("description", event.get_description())
    if event.location:
        ical_event.add("location", event.location)
    # TODO: different url if external event
    ical_event.add("url", event.full_url)
    cal.add_component(ical_event)
    return cal.to_ical()
Example #8
0
def export_event_to_ical(event):
    cal = Calendar()
    cal.add("prodid", "-//janun.de//")
    cal.add("version", "2.0")
    ical_event = Event()
    ical_event.add("uid", event.slug + "@" + "janun.de")
    ical_event.add("summary", event.title)
    if event.all_day:
        ical_event.add("dtstart",
                       event.start_datetime.astimezone(pytz.utc).date())
    else:
        ical_event.add("dtstart", event.start_datetime.astimezone(pytz.utc))
    if event.end_datetime:
        if event.all_day:
            ical_event.add("dtend",
                           event.end_datetime.astimezone(pytz.utc).date())
        else:
            ical_event.add("dtend", event.end_datetime.astimezone(pytz.utc))
    ical_event.add("dtstamp",
                   event.latest_revision_created_at.astimezone(pytz.utc))
    if event.content:
        ical_event.add("description", event.get_description())
    if event.location:
        ical_event.add("location", event.location)
    ical_event.add("url", event.full_url)
    cal.add_component(ical_event)
    return cal.to_ical()
Example #9
0
def createIcs(user, password):
    course_list = getCourse(user, password)
    cal = Calendar()
    cal.add('prodid', '-//Sirius//Tongji Calendar 70.9054//CN')
    cal.add('version', '2.0')
    cal.add('calscale', 'GREGORIAN')
    cal.add('method', 'PUBLISH')
    cal.add('x-wr-calname', '课程表')
    for index, course in enumerate(course_list):
        title = re.split("[\||\r\n]", course.get("title"))
        title.pop(2)
        title[0] = title[0][:-1]
        title[1] = title[1][1:]
        title[2] = title[2][3:-1]
        title[3] = title[3][4:]
        event = Event()
        event.add(
            'dtstart',
            datetime.datetime.strptime(course.get('start'),
                                       '%Y-%m-%d %H:%M:%S'))
        event.add(
            'dtend',
            datetime.datetime.strptime(course.get('end'), '%Y-%m-%d %H:%M:%S'))
        event.add('dtstamp', datetime.datetime(2020, 3, 10, 13, 30, 0))
        event.add('uid', index)
        event.add('location', '教师:' + title[1])
        event.add('description', '会议号:' + title[2] + '|密码:' + title[3])
        event.add('status', 'CONFIRMED')
        event.add('summary', title[0])
        cal.add_component(event)
    f = open(os.path.join('./static/ics', user + '.ics'), 'wb')
    f.write(cal.to_ical())
    f.close()
Example #10
0
def callback4():

    make_ical_file.config(state="disabled")
    cal = Calendar()
    cal.add('prodid', '-//My calendar product//mxm.dk//')
    cal.add('version', '2.0')
    event = Event()
    last_day_date_selected_begin = last_day_date_selected + "/16/30"
    last_day_date_selected_end = last_day_date_selected + "/17/00"
    event.add('summary', last_day_selected + ": " + case_var.get())
    event.add(
        'dtstart',
        datetime.datetime.strptime(last_day_date_selected_begin,
                                   '%m/%d/%Y/%H/%M'))
    event.add(
        'dtend',
        datetime.datetime.strptime(last_day_date_selected_end,
                                   '%m/%d/%Y/%H/%M'))
    alarm = Alarm()
    alarm.add("action", "DISPLAY")
    alarm.add("description", "Reminder")
    alarm.add("TRIGGER;RELATED=START", "-PT{0}H".format(24))
    event.add_component(alarm)
    cal.add_component(event)
    m = os.path.join(os.path.expanduser('~'), 'Desktop', "Last Day.ics")
    with open(m, 'wb') as f:
        f.write(cal.to_ical())
        f.close()
    quit_button = tk.Button(root, text="Quit", command=quit_widget)
    quit_button.grid(row=21, column=1)
Example #11
0
def calendar(data):
    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(
    )
    itercolors = iter(COLORS)
    colormap = defaultdict(lambda: next(itercolors))

    for startdt, enddt, bandname, stagename in 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 #12
0
def get_ics_of_events(request):
    cal = Calendar()
    cal.add('prodid', 'Hacker Agenda')
    cal.add('version', '2.0')

    for event in filter_events(
            request=request,
            queryset=Event.objects.filter(agenda=settings.AGENDA)):
        ics_event = ICSEvent()
        ics_event.add('summary', '%s [%s]' % (event.title, event.source))
        if event.start.hour == 0 and event.start.minute == 0:
            ics_event.add('dtstart', event.start.date())
        else:
            ics_event.add('dtstart', event.start)
            if event.end:
                ics_event.add('dtend', event.end)
            else:
                ics_event.add('dtend', event.start + timedelta(hours=3))
        ics_event.add('dtstamp', event.start)
        ics_event['uid'] = event.url
        ics_event['categories'] = event.source

        cal.add_component(ics_event)

    return HttpResponse(cal.to_ical(), content_type="text/calendar")
Example #13
0
def create_ical_file(list_of_events, strasse, hausnummer):
    """ Creates an iCal file from a list of Events
    Inspired by tutorial from https://icalendar.readthedocs.io/en/latest/usage.html

    Args:
        list_of_events (list): List of Calender Events to be converted into iCal Format
        strasse (str): Street name
        hausnummer (str): Street number

    Returns:
        str: path to created iCal file
    """
    cal = Calendar()

    # Some properties are required to be compliant:
    cal.add('prodid', '-//My calendar product//mxm.dk//')
    cal.add('version', '2.0')

    global total_number_of_events
    total_number_of_events = len(list_of_events)

    all_ical_events = create_cal_events(list_of_events, strasse, hausnummer)
    for evnt in all_ical_events:
        # Add the event to the calendar:
        cal.add_component(evnt)

    cal_as_ical = cal.to_ical()
    create_folder_if_not_exists()
    # Write iCal file to disk
    return save_ical_file(cal_as_ical, get_filename(strasse, hausnummer))
Example #14
0
def export(request, slug):
    event = Trip.objects.get(slug=slug)

    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)

    ical_event = Event()
    ical_event.add('summary', event.trail)
    ical_event.add('dtstart', event.start_date)
    ical_event.add('dtend', event.end_date + timedelta(days=1))
    ical_event['uid'] = '%d.event.events.%s' % (event.id, site_token)
    cal.add_component(ical_event)

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

    return response
Example #15
0
def create_ics(name, begin, end, description, location, participants,
               creator_name, creator_email):
    cal = Calendar()
    cal.add('prodid', '-//My calendar product//mxm.dk//')
    cal.add('version', '2.0')
    event = Event()
    event.add('summary', name)
    event.add('description', description)
    event.add('dtstart', parser.parse(begin))
    event.add('dtend', parser.parse(end))
    organizer = vCalAddress('MAILTO:{}'.format(creator_email))
    organizer.params['cn'] = vText(creator_name)
    event['organizer'] = organizer
    event['location'] = vText(location)

    event['uid'] = '9999/[email protected]'
    event.add('priority', 5)

    for p_email, p_name in participants.items():
        attendee = vCalAddress('MAILTO:{}'.format(p_email))
        attendee.params['cn'] = vText(p_name)
        attendee.params['ROLE'] = vText('REQ-PARTICIPANT')
        event.add('attendee', attendee, encode=0)

    cal.add_component(event)

    f = open('invite.ics', 'wb')
    f.write(cal.to_ical())
    f.close()
    def __init__(self):
        if not os.path.isfile(terrariumCalendar.ICS_FILE):
            ical = Calendar()
            ical.add('prodid',
                     '-//TerrariumPI calendar//terrarium.theyosh.nl//')
            ical.add('version', '2.0')

            event = Event()
            event.add('uid', '1')
            event.add('summary', 'TerrariumPI initial github commit')
            event.add(
                'location',
                'https://github.com/theyosh/TerrariumPI/commit/526d39a9ceac57768c6fffe6ffe19afd71782952'
            )
            event.add('dtstart', date(2016, 1, 14))
            event.add('dtend', date(2016, 1, 14))
            event.add('dtstamp', datetime.now())

            ical.add_component(event)

            with open(terrariumCalendar.ICS_FILE, 'wb') as fp:
                fp.write(ical.to_ical())

        self.__ical_data = None
        with open(terrariumCalendar.ICS_FILE, 'rb') as fp:
            self.__ical_data = fp.read()
Example #17
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"], get_domain())
    cal_event.add("priority", 5)
    cal_event.add("dtstart", event["when"])
    cal_event.add("dtend", (event["when"] + datetime.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 #18
0
def ConvertCalendar(course_dict):
    calendar = Calendar()
    calendar.add('prodid', '-//My calendar product//mxm.dk//')
    calendar.add('version', '2.0')
    semester = int(course_dict['xsxx']['XQMMC'])
    # year = int(course_dict['xsxx']['XNM'])
    yearname = course_dict['xsxx']['XNMC'].split('-')
    if semester == 2:
        year = int(yearname[1])
    else:
        year = int(yearname[0])
    for num in course_dict['kbList']:
        a = num
        week_string_list = a['zcd'].split(',')
        for week_string in week_string_list:
            course_weeks_start, course_weeks_end = GetCourseTakeWeeks(
                week_string)
            calendar = CreateEvent(calendar, course_weeks_start,
                                   course_weeks_end, year, semester, a)

    output_file_name = '{}:{}-{}.ics'.format(course_dict['xsxx']['XH'],
                                             course_dict['xsxx']['XNMC'],
                                             course_dict['xsxx']['XQMMC'])
    output_file = open(output_file_name, 'wb')
    output_file.write(calendar.to_ical())
    output_file.close()
    print('Successfully write your calendar to', output_file_name)
class TTParser:
    _cal = Calendar()
    _tz_london = timezone('Europe/London')
    # the start date has to be the first Monday of the teaching period
    _start_date = date(2015, 9, 14)
    _range = 51 * 7

    def __init__(self):
        self._cal = Calendar()
        self._cal.add('prodid', '-//University of Lincoln//TimeTable//')
        self._cal.add('version', '2.0')
        self._baseUrl = "http://stafftimetables.lincoln.ac.uk/V2/UL/Reports/"

    def ical(self, lecturer):
        for x in range(0, self._range):
        #for x in range(49, 70):
            try:
                self.query(self._start_date + timedelta(x), lecturer)
            except Exception as ex:
                logging.getLogger(__name__).warning(
                    'failed to add_day for '
                    + str(self._start_date + timedelta(x))
                    + ': ' + str(type(ex)) + ': ' + ex.message)
        return self._cal.to_ical()

    def create_event(self, name, room, the_day, dBegin, dEnd):
        event = Event()
        event.add('summary', name)
        event.add('dtstart', dBegin)
        event.add('dtend', dEnd)
        event['location'] = vText(room)
        return event
Example #20
0
def main():
    cal = Calendar()

    # must have this apparently
    cal.add("prodid", "-//Acme Corp//Olof Sjödin//SV")
    cal.add("version", "2.0")

    event = Event()

    utc = arrow.utcnow()
    local = utc.to("local")

    event_start = arrow.get("2017-03-08 21:00", "YYYY-MM-DD HH:mm").datetime
    event_stop = arrow.get("2017-03-08 23:59", "YYYY-MM-DD HH:mm").datetime
    time_now = local.datetime

    event.add("summary", "Terraria")
    event.add("dtstart", event_start)
    event.add("dtend", event_stop)
    event.add("dtstamp", time_now)

    cal.add_component(event)

    with open("example.ics", "w") as fh:
        fh.write(cal.to_ical().decode("utf-8"))
Example #21
0
class ICalFile(FormatFile):
    _cal=None
    
    def __init__(self,name):
        filename=name+'.ics'
        super(ICalFile,self).__init__(filename)
        self._cal=Calendar()
        self._cal.add('prodid', '-//KPlato Export//athabascau.ca//')
        self._cal.add('version', '2.0')
    
    def add_appointment(self,uid,dtstart,dtend,dtstamp,summary,description):
        event=Event()
        event.add('summary',summary)
        event.add('description',description)
        event['uid']=uid

        # event.add('dtstart',dtstart)
        event['dtstart']=vDatetime(dtstart).ical()
        # event.add('dtend',dtend)
        event['dtend']=vDatetime(dtend).ical()
        # event.add('dtstamp',dtstamp)
        event['dtstamp']=vDatetime(dtstamp).ical()
        self._cal.add_component(event)
    
    def save(self):
        f=open(self.filename,'w')
        f.write(self._cal.as_string())
        f.close()
Example #22
0
def generate_icalendar_element(event):
    icalendar_event = CalendarEvent()
    if event.start_time:
        icalendar_event.add('dtstart', event.start_time)
    if event.end_time:
        icalendar_event.add('dtend', event.end_time)
    if event.name_en:
        icalendar_event.add('summary', event.name_en)

    cal = Calendar()
    cal.add('version', '2.0')
    cal.add('prodid', '-//events.hel.fi//NONSGML Feeder//EN')
    cal.add_component(icalendar_event)

    term = None
    if event.start_time and event.end_time:
        term = "open"
    elif event.start_time:
        term = "open"
    elif event.end_time:
        term = "close"

    if term:
        return {
            "term": "open",
            "value": cal.to_ical().decode('utf8'),
            "type": "text/icalendar"
        }
    else:
        return None
Example #23
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
Example #24
0
def write_calendar(calendardict, title, filename):
    cal = Calendar()
    cal.add("prodid", title)
    cal.add("version", "2.0")

    for (date, calendarentries) in calendardict.items():
        for calendarentry in calendarentries["elements"]:
            cal_entry = str(calendarentry["html"])
            cal_entry = cal_entry.replace("<br/>", "\n")
            cal_summary = re.search("([A-z]+)<", cal_entry)
            if cal_summary is not None:
                cal_summary = cal_summary.group(1)
            else:
                cal_summary = "Unknown title"

            event = Event()
            event.add("summary", cal_summary)
            startdate_str = "{0} {1}".format(date, calendarentry["starttime"])
            enddate_str = "{0} {1}".format(date, calendarentry["endtime"])

            event.add("dtstart", datetime.strptime(startdate_str, "%d.%m.%Y %H:%M"))
            event.add("dtend", datetime.strptime(enddate_str, "%d.%m.%Y %H:%M"))
            event.add("description", cal_entry)
            cal.add_component(event)

    with open(filename, "wb") as f:
        f.write(cal.to_ical())
    return cal
Example #25
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
class iCalendar:
	def __init__(self, file):
		self.file = file
		self.cal = Calendar()

		self.cal.add('version', '2.0')
		self.cal.add('prodid', '-//Leeroy Brun - HEIG-VD//Timetable Parser//')

	def add(self, dateStart, dateEnd, summary, location='', description='', categories=''):
		event = Event()

		event.add('summary', summary)
		event.add('location', location)
		event.add('categories', categories, encode=0)
		event.add('description', description)
		event.add('dtstart', dateStart)
		event.add('dtend', dateEnd)
		event.add('dtstamp', datetime.datetime.now())
		event['uid'] = uuid.uuid4()
		event.add('priority', 5)

		self.cal.add_component(event)

	def save(self):
		f = open(self.file, 'wb')
		f.write(self.cal.to_ical())
		f.close()
Example #27
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 Adv Winter Hockey 2015')
    for irow in range(sheet.nrows):
        row = sheet.row(irow)
        evt_desc = None
        if row[0].value == "U8 Advanced":
            evt_desc = row[0].value
        if row[1].value == "Group 1" or row[1].value == "Group 2":
            evt_desc = row[1].value
        if evt_desc is None:
            continue
        basedate = xlrd.xldate_as_tuple(row[3].value, wb.datemode)
        basedt = list(basedate[:3]) + get_hhmm(row[4].value)
        tstamp = datetime(*basedt)
        basedt_end = list(basedate[:3]) + get_hhmm(row[5].value)
        tstamp_end = datetime(*basedt_end)
        uid = tstamp.strftime('%Y%m%d%H%M') + '@pugswald.com'
        event = Event()
        event.add('uid', uid)
        event.add('dtstart', tstamp)
        event.add('summary', 'AYHL Hockey - %s' % evt_desc)
        event.add('dtend', tstamp_end)
        event.add('location', row[6].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 #28
0
    def get(self, request):
        """Create a iCal file from the schedule"""
        # Heavily inspired by https://djangosnippets.org/snippets/2223/ and
        # the icalendar documentation
        calendar = Calendar()
        site = get_current_site(request)
        calendar.add('prodid', '-//%s Schedule//%s//' % (site.name, site.domain))
        calendar.add('version', '2.0')

        # Since we don't need to format anything here, we can just use a list
        # of schedule items
        for item in ScheduleItem.objects.all():
            sched_event = Event()
            sched_event.add('dtstamp', item.last_updated)
            sched_event.add('summary', item.get_title())
            sched_event.add('location', item.venue.name)
            sched_event.add('dtstart', item.get_start_datetime())
            sched_event.add('duration', datetime.timedelta(minutes=item.get_duration_minutes()))
            sched_event.add('class', 'PUBLIC')
            sched_event.add('uid', '%s@%s' % (item.pk, site.domain))
            sched_event.add('url', item.get_url())
            calendar.add_component(sched_event)
        response = HttpResponse(calendar.to_ical(), content_type="text/calendar")
        response['Content-Disposition'] = 'attachment; filename=schedule.ics'
        return response
Example #29
0
	def create_icalendar_workout(self, descName = "workout"):
		print "Generating iCalendar"
		cal = Calendar()
		cal.add('prodid', '-//My workout calendar//mxm.dk//')
		cal.add('version', '2.0')
		
		for p in self.workoutprogram_workouts:
			event = Event()
			event.add('summary', p.workout_name)
			event.add('dtstart', p.workout_dt + timedelta(hours=-11))
			event.add('dtend',   p.workout_dt + timedelta(hours=-9))
			descriptionText = "%.0f%% of max targeting %.f kg volume\n\n" % (100.0 * p.workout_percentOfMax, self.workoutprogram_volume_max)
			
			for x in p.workout_exercises:
				descriptionText += '  %s\n' % x.exercise_name
				for s in x.exercise_sets:
					if (s.units == "kg"):
						descriptionText += "    %d reps x %.0f kg [%.0f lbs]\n" % (s.repititions, s.weight, s.weight * 2.204)
					if (s.units == "reps"):
						descriptionText += "    %d reps\n" % s.repititions
					if (s.units == "sec"):
						descriptionText += "    %d seconds\n" % s.weight
					if (s.units == "yos"):
						climbing = climbing_convert_range_to_grade(s.weight)
						info += "    %s (%s) [%s]\n" % (climbing['yos'], climbing['v'], climbing['spot'])		
					
			event['DESCRIPTION'] = descriptionText
			cal.add_component(event)
				
		# Write the calendar file
		ifilename = "%s-%s.ics" % (descName, self.workoutprogram_username)
		f = open(ifilename, 'wb')
		f.write(cal.to_ical())
		f.close()
Example #30
0
    def get(self, request, *args, **kwargs):
        postcode = kwargs["postcode"]
        try:
            ballots = self.postcode_to_ballots(postcode=postcode)
        except InvalidPostcodeError:
            return HttpResponseRedirect(
                f"/?invalid_postcode=1&postcode={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 ballots:
            if post_election.cancelled:
                continue
            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("dtstamp", timezone.now())
            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)

            # add hustings events if there are any in the future
            for husting in post_election.husting_set.future():
                event = Event()
                event["uid"] = husting.uuid
                event["summary"] = husting.title
                event.add("dtstamp", timezone.now())
                event.add("dtstart", husting.starts)
                if husting.ends:
                    event.add("dtend", husting.ends)
                event.add("DESCRIPTION", f"Find out more at {husting.url}")
                cal.add_component(event)

        return HttpResponse(cal.to_ical(), content_type="text/calendar")
Example #31
0
class TTParser:
    _cal = Calendar()
    _tz_london = timezone('Europe/London')
    # the start date has to be the first Monday of the teaching period
    _start_date = date(2014, 9, 15)
    _range = 51 * 7

    def __init__(self):
        self._cal = Calendar()
        self._cal.add('prodid', '-//University of Lincoln//TimeTable//')
        self._cal.add('version', '2.0')
        self._baseUrl = "http://stafftimetables.lincoln.ac.uk/V2/UL/Reports/"

    def ical(self):
        for x in range(0, self._range):
        #for x in range(49, 70):
            try:
                self.query(self._start_date + timedelta(x))
            except Exception as ex:
                logging.getLogger(__name__).warning(
                    'failed to add_day for '
                    + str(self._start_date + timedelta(x))
                    + ': ' + str(type(ex)) + ': ' + ex.message)
        return self._cal.to_ical()

    def create_event(self, name, room, the_day, dBegin, dEnd):
        event = Event()
        event.add('summary', name)
        event.add('dtstart', dBegin)
        event.add('dtend', dEnd)
        event['location'] = vText(room)
        return event
Example #32
0
def make_ical(html: str, 学期开始日期: datetime, 作息: dict) -> bytes:
    cal = Calendar()
    cal.add("prodid", "-//Zombie110year//CQU Class Table//")
    cal.add("version", "2.0")
    for 课程 in parse_课程(BeautifulSoup(html, 'lxml'), 作息):
        cal.add_component(build_event(课程, 学期开始日期))
    return cal.to_ical()
    def emit( self, serialization ):
        try:
            from icalendar import Calendar, Event
            from icalendar import vText
        except ImportError:
            raise SerializationError( "iCalendar module could not be loaded." )

        cal = Calendar()
        cal.add( 'prodid', '-//European Southern Observatory//Djangoplicity//EN' )
        cal.add( 'version', '2.0' )

        for e in serialization.data:
            event = Event()
            event.add( 'summary', smart_unicode( e['summary'] ) )
            event.add( 'description', smart_unicode( e['description'] ) )
            event.add( 'dtstart', e['dtstart'] )
            event.add( 'dtend', e['dtend'] )
            event.add( 'dtstamp', e['dtstamp'] )

            if 'location' in e:
                event['location'] = vText( smart_unicode( e['location'] ) )

            cal.add_component( event )

        return cal.as_string()
Example #34
0
def sts2ics(sts_string, year=None):
    if not year:
        now = datetime.now()
        year = now.year

    m = re.search("^Time: ([^,]+), Visible: (\d+) min, (.*)$", sts_string)
    if not m:
        sys.exit("Failed to parse input '%s'" % sts_string)

    starttime = m.group(1) + " " + str(year)
    minutes = int(m.group(2))
    description = m.group(3)

    start = datetime.strptime(starttime, "%a %b %d %I:%M %p %Y")
    end = start + timedelta(minutes=minutes)

    vStart = vDatetime(start)
    vEnd = vDatetime(end)

    event = Event()
    event.add('summary', "ISS viewing")
    event.add('description', description)
    event.add('dtstart', vStart)
    event.add('dtend', vEnd)

    cal = Calendar()
    cal.add('prodid', '-//aaronferrucci//sts2ics//')
    cal.add('version', '1.0')

    cal.add_component(event)

    return cal
Example #35
0
def generate_icalendar_element(event):
    icalendar_event = CalendarEvent()
    if event.start_time:
        icalendar_event.add('dtstart', event.start_time)
    if event.end_time:
        icalendar_event.add('dtend', event.end_time)
    if event.name_en:
        icalendar_event.add('summary', event.name_en)

    cal = Calendar()
    cal.add('version', '2.0')
    cal.add('prodid', '-//events.hel.fi//NONSGML Feeder//EN')
    cal.add_component(icalendar_event)

    term = None
    if event.start_time and event.end_time:
        term = "open"
    elif event.start_time:
        term = "open"
    elif event.end_time:
        term = "close"

    if term:
        return {
            "term": "open",
            "value": cal.to_ical(),
            "type": "text/icalendar"
        }
    else:
        return None
Example #36
0
def write_calendar(options, filename):
    #Create and write ics file"
    print('Writing ics...')
    cal = Calendar()
    timezones_cache = []
    global eventcounter
    for key, value in options.items():
        cal.add(key, value)
    for source_id, thiscal in cals.items():
        for timezone in thiscal.walk('VTIMEZONE'):
            if timezone['tzid'] not in timezones_cache:
                timezones_cache.append(timezone['tzid'])
                cal.add_component(timezone)
        for event in thiscal.walk('VEVENT'):
            event_copy = Event(event)
            # Erase categoryies with the one defined in the source file
            # To add a new cateogyr, should be: event_copy.add('category', categories[source_id])
            event_copy['categories'] = categories[source_id]

            # Check if address exists, if not add baseaddress, then try to check if Postal Code present
            if 'LOCATION' not in event_copy:
                event_copy['LOCATION'] = baseaddress[source_id]
            else:
                if countNumbersInString(event_copy['LOCATION']) < 3:
                    event_copy['LOCATION'] = event_copy[
                        'LOCATION'] + ', ' + baseaddress[source_id]
            cal.add_component(event_copy)
            eventcounter = eventcounter + 1
    with open(filename, 'wb') as f:
        f.write(cal.to_ical())
Example #37
0
def _make_ics(event, etime):

    cal = Calendar()
    cal.add('prodid', 'N1-send-availability-package')
    cal.add('version', '1.0')

    evt = Event()
    evt.add('summary', event.title)
    evt.add('location', event.location)
    evt.add('description', event.description)
    evt.add('dtstart', etime.start)
    evt.add('dtend', etime.end)
    evt.add('dtstamp', datetime.now())

    evt['uid'] = '{timestamp}/{email}'.format(
        timestamp=time.mktime(datetime.now().timetuple()),
        email=event.organizer.email
    )
    evt.add('priority', 5)

    organizer = vCalAddress('MAILTO:{}'.format(event.organizer.email))
    organizer.params['cn'] = vText(event.organizer.name)
    organizer.params['role'] = vText('CHAIR')
    evt['organizer'] = organizer

    for attendee in event.attendees:
        atnd = vCalAddress('MAILTO:{}'.format(attendee.email))
        atnd.params['cn'] = vText(attendee.name)
        atnd.params['ROLE'] = vText('REQ-PARTICIPANT')
        evt.add('attendee', atnd, encode=0)

    cal.add_component(evt)

    return cal.to_ical()
Example #38
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
Example #39
0
def mk_ical(lvinfos, endtimes):
	cal = Calendar()
	cal.add('prodid', '-//swt-ps//python-icalendar//DE')
	cal.add('version', '2.0')
	for uri in lvinfos:
		title,start,end,day,location = lvinfos[uri]
		event = Event()
		event.add('uid', uri)
		start_day = time_conversion.first_day(lvinfos[uri][3][:2])
		shour, sminute = start.split(':')
		ehour, eminute = end.split(':')
		sttime = datetime.datetime(start_day.year, start_day.month,\
					start_day.day, hour = int(shour), minute = int(sminute))
		endtime = datetime.datetime(start_day.year, start_day.month,\
					start_day.day, hour = int(ehour), minute = int(eminute))
		event.add('dtstamp', datetime.datetime.today())
		event.add('summary', title)
		recur = vRecur(byday=biweekly[day][0], freq='weekly',\
					   until=endtimes[uri])
		if biweekly[day][1] == "A":
			if start_day.isocalendar()[1] % 2 == 0:
				sttime = sttime + datetime.timedelta(weeks=1)
				endzeit = endzeit + datetime.timedelta(weeks=1)
			recur['interval'] = 2
		elif biweekly[day][1] == "B":
			if start_day.isocalendar()[1] % 2 == 1:
				sttime = sttime + datetime.timedelta(weeks=1)
				endtime = endtime + datetime.timedelta(weeks=1)
			recur['interval'] = 2
		event.add('dtstart', sttime)
		event.add('dtend', endtime)
		event.add('rrule', recur)
		cal.add_component(event)
	return cal
Example #40
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'], get_domain())
    cal_event.add('priority', 5)
    cal_event.add('dtstart', event['when'])
    cal_event.add('dtend', (event['when'] + datetime.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")
def generate_ical(assignments, output_path, SITEURL):
    from icalendar import Calendar, Event
    import datetime
    import pytz
 
    cal = Calendar()

    cal.add('prodid', '-//My calendar product//mxm.dk//')
    cal.add('version', '2.0')

    for (count, a) in enumerate(assignments):
        event = Event()
	summary = strip_tags(a.summary).strip()
        event.add('summary', summary)
        date = datetime.datetime.strptime(a.duedate, '%Y-%m-%d')
	date += datetime.timedelta(hours=25)
	description = 'More Info: ' + SITEURL + '/' + a.url + ' DUE: ' + a.duedate
	event.add('dtstart', date)
	event.add('uid', str(count) + '*****@*****.**')
	event.add('description', description) 
        cal.add_component(event)

    import os
    f = open(os.path.join(output_path, 'assignments.ics'), 'wb')
    f.write(cal.to_ical())
    f.close()
Example #42
0
def create_icalendar(events, event_type):
    calendar = Calendar()
    calendar.add('prodid', '-//TeamLiquid.net//Events Calendar//')
    calendar.add('version', '2.0')

    for item in events:
        if event_type == item['type']:
            event = Event()
            event.add('summary', '{} ({})'.format(item['title'], item['type']))
            event.add(
                'description',
                '{}\nLiquipedia: {}'.format(item['description'], item['url']))
            event.add('uid', item['id'])
            event.add(
                'dtstart',
                datetime(
                    item['year'],
                    item['month'],
                    item['day'],
                    item['hour'],
                    item['minute'],
                    0,  # Seconds.
                    tzinfo=pytz.timezone(TIMEZONE)))

            calendar.add_component(event)

    return calendar
Example #43
0
def ics(request, team_id=None, team_name=None):

    if team_id:
        this_team = Team.objects.get(id=team_id)
    elif team_name:
        this_team = Team.objects.get(name=team_name)

    home_games = Game.objects.filter(home_team=this_team)
    away_games = Game.objects.filter(away_team=this_team)

    games = home_games | away_games
    games = games.order_by("time", "field")

    cal = Calendar()
    cal.add('prodid', '-//Breakway Schedules//Soccer Calendars//EN')
    cal.add('version', '2.0')
    cal.add('X-WR-CALNAME', this_team.name)
    cal.add('X-WR-TIMEZONE', 'CST6CDT')
    cal.add('X-WR-CALDESC', 'Breakaway Team Schedule')

    now_dt = datetime.now()
    now_string = "%04d%02d%02dT%02d%02d%02d" % (
        now_dt.year,
        now_dt.month,
        now_dt.day,
        now_dt.hour,
        now_dt.minute,
        now_dt.second
    )

    for game in games:
        event = Event()
        try:
            summary = '%s vs. %s' % (game.home_team, game.away_team)
        except Exception:
            summary = 'Breakaway game'

        if game.color_conflict:
            desc = 'Color conflict! (%s vs. %s)' % (game.away_team.color, game.home_team.color)
            summary += ' (color conflict)'
            event.add('description', desc)

        event.add('summary', summary)

        event.add('dtstart', game.time)
        event.add('dtend', game.time + timedelta(hours=1))
        event.add('dtstamp', datetime.now())
        event.add('location', "BreakAway Field %s" % game.field)
        event['uid'] = '%s/%[email protected]' % (now_string, shortuuid.uuid())
        event.add('priority', 5)

        alarm = Alarm()
        alarm.add("TRIGGER;RELATED=START", "-PT{0}M".format('45'))
        alarm.add('action', 'display')
        alarm.add('description', 'Breakaway game')

        event.add_component(alarm)
        cal.add_component(event)

    return HttpResponse(cal.to_ical(), content_type='text/calendar')
Example #44
0
def parse_file(fname):    # {{{
    """ Takes markdown with schedule and outputs ical

    :fname: TODO
    :returns: TODO

    """

    bsname = os.path.splitext(os.path.basename(fname))[0]
    # print(bsname)
    calname = bsname + '.ics'

    global cal
    cal = Calendar()
    # The following two lines are required
    cal.add('prodid', '*****@*****.**')
    cal.add('version', '2.0')
    global day
    day = 0

    with open(fname) as f:
        for line in f.readlines():
            parse_line(line)

    with open(os.path.join(directory, calname), 'wb') as fe:
        # print(fe)
        fe.write(cal.to_ical())
Example #45
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 #46
0
def get_calendar(secret):
    # check access
    enabled = frappe.db.get_value("iCal Feed Settings", "iCal Feed Settings",
                                  "enabled")
    if float(enabled) == 0:
        return
    erp_secret = frappe.db.get_value("iCal Feed Settings",
                                     "iCal Feed Settings", "secret")
    if not secret == erp_secret:
        return

    # initialise calendar
    cal = Calendar()

    # set properties
    cal.add('prodid', '-//iCalFeed module//libracore//')
    cal.add('version', '2.0')

    # get data
    sql_query = """SELECT * FROM `tabEvent` WHERE `event_type` = 'Public'"""
    events = frappe.db.sql(sql_query, as_dict=True)
    # add events
    for erp_event in events:
        event = Event()
        event.add('summary', erp_event['subject'])
        event.add('dtstart', erp_event['starts_on'])
        if erp_event['ends_on']:
            event.add('dtend', erp_event['ends_on'])
        event.add('dtstamp', erp_event['modified'])
        event.add('description', erp_event['description'])
        # add to calendar
        cal.add_component(event)

    return cal
Example #47
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 #48
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
def poster_ics(poster, session):
    session = int(session)
    start = by_uid["papers"][poster]["sessions"][session]["time"]
    start = start.replace(tzinfo=pytz.utc)

    cal = Calendar()
    cal.add("prodid", "-//ACL//acl2020.org//")
    cal.add("version", "2.0")
    cal["X-WR-TIMEZONE"] = "GMT"
    cal["X-WR-CALNAME"] = "ACL: " + by_uid["papers"][poster]["title"]

    event = Event()
    link = (
        '<a href="'
        + site_data["config"]["site_url"]
        + '/poster_%s.html">Poster Page</a>' % (poster)
    )
    event.add("summary", by_uid["papers"][poster]["title"])
    event.add("description", link)
    event.add("uid", "-".join(["ACL2020", poster, str(session)]))
    event.add("dtstart", start)
    event.add("dtend", start + timedelta(hours=qa_session_length_hr))
    event.add("dtstamp", start)
    cal.add_component(event)

    response = make_response(cal.to_ical())
    response.mimetype = "text/calendar"
    response.headers["Content-Disposition"] = (
        "attachment; filename=poster_" + poster + "." + str(session) + ".ics"
    )
    return response
Example #50
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 #51
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 #52
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')
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
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 #55
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
Example #56
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 #57
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 #58
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 #59
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 #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