Example #1
0
    def test_property_params(self):
        cal_address = icalendar.vCalAddress('mailto:[email protected]')
        cal_address.params["CN"] = "Doe, John"
        ical = icalendar.Calendar()
        ical.add('organizer', cal_address)

        ical_str = icalendar.Calendar.to_ical(ical)
        exp_str = """BEGIN:VCALENDAR\r\nORGANIZER;CN="Doe, John":"""\
                  """mailto:[email protected]\r\nEND:VCALENDAR\r\n"""

        self.assertEqual(ical_str, exp_str)

        # other way around: ensure the property parameters can be restored from
        # an icalendar string.
        ical2 = icalendar.Calendar.from_ical(ical_str)
        self.assertEqual(ical2.get('ORGANIZER').params.get('CN'), 'Doe, John')

        # test unicode parameter value
        cal_address = icalendar.vCalAddress('mailto:[email protected]')
        cal_address.params["CN"] = "Джон Доу"
        vevent = icalendar.Event()
        vevent['ORGANIZER'] = cal_address
        self.assertEqual(
            vevent.to_ical(),
            'BEGIN:VEVENT\r\n'
            'ORGANIZER;CN="Джон Доу":mailto:[email protected]\r\n'
            'END:VEVENT\r\n'
        )
        self.assertEqual(vevent['ORGANIZER'].params['CN'], 'Джон Доу')
Example #2
0
    def to_ical(self):
        """Generates an iCal formatted buffer of event's details"""
        vevent = icalendar.Event()
        vevent.add('uid', self.ical_uid)
        if self.status:
            vevent.add('status', self.status)
        vevent.add('created', self.created_at)
        vevent.add('last-modified', self.updated_at)
        vevent.add('summary', self.summary)
        if self.description:
            vevent.add('description', self.description)
        if self.location:
            vevent.add('location', self.location)
        organizer = icalendar.vCalAddress(u'MAILTO:%s' % self.organizer.email)
        organizer.params['CN'] = self.organizer.get_full_name() or ''
        vevent.add('organizer', organizer)
        vevent.add('dtstart', self.start.date_or_dt())
        vevent.add('dtend', self.end.date_or_dt())
        if self.transparency:
            vevent.add('transp', self.transparency)

        # Recurrences
        if self.recurrence:
            for recur in self.recurrence.splitlines():
                if recur.startswith('RRULE:'):
                    vrecur = icalendar.vRecur.from_ical(recur[6:])
                    vevent.add('rrule', vrecur)
                elif recur.startswith('EXRULE:'):
                    vrecur = icalendar.vRecur.from_ical(recur[7:])
                    vevent.add('exrule', vrecur)
                elif recur.startswith('RDATE:'):
                    vdddlist = icalendar.vDDDLists.from_ical(recur[6:])
                    vevent.add('rdate', vdddlist)
                elif recur.startswith('EXDATE:'):
                    vdddlist = icalendar.vDDDLists.from_ical(recur[7:])
                    vevent.add('exdate', vdddlist)

        # Attendees
        if self.attendees:
            for attendee in self.attendees:
                vattendee = icalendar.vCalAddress(u'MAILTO:%s' % attendee.email)
                if attendee.display_name:
                    vattendee.params['CN'] = attendee.display_name
                if attendee.optional:
                    vattendee.params['ROLE'] = 'OPT-PARTICIPANT'
                if attendee.optional is False:
                    vattendee.params['ROLE'] = 'REQ-PARTICIPANT'
                if attendee.optional is None:
                    vattendee.params['ROLE'] = 'NON-PARTICIPANT'
                if attendee.response_status:
                    vattendee.params['PARTSTAT'] = attendee.response_status
                if attendee.vosae_user:
                    vattendee.params['X-VOSAE-USER'] = unicode(attendee.vosae_user.id)
                vevent.add('attendee', vattendee)

        # Vosae specific
        vevent.add('x-vosae-creator', unicode(self.creator.id))
        vevent.add('x-vosae-event', unicode(self.id))
        return vevent.to_ical()
Example #3
0
def booking_ical_feed(request, room_slug):
	rooms = [r for r in Room.objects.all() if r.slug() == room_slug]
	if len(rooms) == 1:
		room = rooms[0]

		all_future_events, timeZone = get_future_events()
		future_events = split_events_on_rooms(all_future_events)
		future_events = calculate_conflicts(future_events)

		# Create a calendar
		cal = Calendar()
		#cal['summary'] = u'☑ %s room' % room.title
		#cal['X-WR-CALNAME'] = u'☑ %s room' % room.title
		cal['summary'] = u'Room: %s' % room.title
		cal['X-WR-CALNAME'] = u'Room: %s' % room.title
		cal['prodid'] = '-//Socialsquare ApS//Aabenthus_com Rooms Booking//EN'
		cal['version'] = '2.0'
		cal['CALSCALE'] = 'GREGORIAN'
		cal['METHOD'] = 'PUBLISH'
		cal['X-WR-TIMEZONE'] = timeZone

		for some_room in future_events:
			if some_room.get('title') == room.title:
				for event in some_room.get('events'):
					if not event.get('conflicts'):
						ical_event = Event()

						ical_event.add('uid', "aabenthus.%s" % event.get('iCalUID'))

						start = get_event_date_or_datetime( event.get('start'), timeZone )
						end = get_event_date_or_datetime( event.get('end'), timeZone )
						ical_event.add('dtstart', start)
						ical_event.add('dtend', end)
							
						ical_organizer = vCalAddress( 'MAILTO:%s' % event.get('organizer').get('email') )
						if event.get('organizer').get('displayName'):
							ical_organizer.params['cn'] = event.get('organizer').get('displayName')
						ical_event.add('organizer', ical_organizer)

						if event.get('visibility') == 'private':
							ical_event.add('summary', 'Booked')
						else:
							ical_event.add('summary', event.get('summary'))
							ical_event.add('location', event.get('location'))
							if event.get('attendees'):
								for attendee in event.get('attendees'):
									ical_attendee = vCalAddress('MAILTO:%s' % attendee.get('email'))
									if attendee.get('displayName'):
										ical_attendee.params['cn'] = attendee.get('displayName')
									ical_event.add('attendee', ical_attendee)

						cal.add_component(ical_event)

		return HttpResponse( cal.to_ical(), content_type="text/calendar" )
	else:
		slugs = ', '.join([room.slug() for room in Room.objects.all()])
		return HttpResponse('Please choose one of the following room slugs: %s' % slugs)
Example #4
0
def test_create_entry(pytestconfig):
    # cook up a datetime for our calendar entry
    (dt_now, dt_mtg_start, dt_mtg_end) = start_two_hours_from_now()
    dt_cal_start = dt_now - timedelta(10)

    # example script to add X-MAINTNOTE to an ical
    cal = Calendar()
    cal.add('prodid', '-//Maint Note//https://github.com/maint-notification//')
    cal.add('version', '2.0')

    event = xmaintnote.XMaintNoteEvent()

    event.add('summary', 'Maint Note Example')
    event.add('uid', '42')
    event.add('sequence', 1)
    event.add('dtstart', dt_mtg_start)
    event.add('dtend', dt_mtg_end)
    event.add('dtstamp', dt_now)

    organizer = vCalAddress('mailto:[email protected]')
    organizer.params['cn'] = vText('Example NOC')
    event['organizer'] = organizer

    # maintnote stuff
    event.add('x-maintnote-provider', 'example.com' )
    event.add('x-maintnote-account', '137.035999173' )
    event.add('x-maintnote-maintenance-id', 'WorkOrder-31415' )
    event.add('x-maintnote-object-id', 'acme-widgets-as-a-service' )
    event.add('x-maintnote-impact', "NO-IMPACT");
    # test the regex
    #event.add('x-maintnote-impact', "GARBAGE");


    if 0:
        organizer = vCalAddress('MAILTO:[email protected]')
        organizer.params['cn'] = vText('Max Rasmussen')
        organizer.params['role'] = vText('CHAIR')
        event['organizer'] = organizer
        event['location'] = vText('Odense, Denmark')
        event['uid'] = '20050115T101010/[email protected]'
        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)
    
        attendee = vCalAddress('MAILTO:[email protected]')
        attendee.params['cn'] = vText('The Dude')
        attendee.params['ROLE'] = vText('REQ-PARTICIPANT')
        event.add('attendee', attendee, encode=0)

    cal.add_component(event)

    expected_output = pytestconfig.rootdir.join('tests/example.ical')
    assert display(cal) == expected_output.read().strip()
Example #5
0
 def item_organizer(self, obj):
     organizer_dic = obj.get('organizer', None)
     if organizer_dic:
         if isinstance(organizer_dic, dict):
             organizer = icalendar.vCalAddress('MAILTO:%s' % organizer_dic['email'])
             for key, val in organizer_dic.iteritems():
                 if key is not 'email':
                     organizer.params[key] = icalendar.vText(val)
         else:
             organizer = icalendar.vCalAddress('MAILTO:%s' % organizer_dic)
         return organizer
Example #6
0
def create_milestone(milestone, author, projectname):
    print("\tAdding Milestone ID {} with title: {}".format(milestone.id, milestone.title))
    event = Event()

    # Parse due date
    dyear, dmonth, dday = milestone.due_date.split('-')

    event['uid'] = '{}/{}@{}'.format(milestone.created_at, author.username, CALENDAR_FQDN)

    event.add('summary', milestone.title)
    description = "{}\n\n---> {} <---\n".format(milestone.description, projectname)
    event.add('description', description)


    event.add('dtstart', date(int(dyear), int(dmonth), int(dday)))
    # event.add('dtend', datetime(2016,7,12,12,0,0,tzinfo=pytz.utc))
    event.add('dtstamp', datetime.utcnow())

    # event['location'] = vText('Koeln, Deutschland')
    event.add('categories', "Milestone")
    event.add('priority', 2)

    organizer = vCalAddress('{}@{}'.format(author.username, CALENDAR_FQDN))
    organizer.params['cn'] = vText(author.name)
    organizer.params['role'] = vText('Author')
    event['organizer'] = organizer
    return event
Example #7
0
    def item_organizer(self, item):
        """Get item organizer."""
        organizer = item.leave.user.email
        organizer = vCalAddress(organizer)
        organizer.params["CN"] = str(item.leave.user)

        return organizer
Example #8
0
def adicionar_participante_em_evento(ical_event, usuario):
    """Adiciona um usuario em um evento."""
    # REMOVER OS xx DOS EMAILS
    atnd = vCalAddress("MAILTO:{}".format(usuario.email))
    atnd.params["CN"] = "{0} {1}".format(usuario.first_name, usuario.last_name)
    atnd.params["ROLE"] = "REQ-PARTICIPANT"
    ical_event.add("attendee", atnd, encode=0)
    def save_ical(self):
        '''
        Save events_list as an ical calandar
        input: self
        output: filename.ical

        most of the code of this method is copy/path from icalandar doc.
        The rest is datetime object and timezone crap.

        '''
        cal = Calendar()
        cal.add('prodid', '-//Crappy Calandar Cow/')
        cal.add('version', '2.0')

        for item in self.events_list:
            event = Event()
            event.add('summary', item["summary"])
            event.add('dtstart', item["start"].astimezone(pytz.utc))
            event.add('dtend', item["end"].astimezone(pytz.utc))
            event.add('dtstamp', datetime.utcnow())
            event.add('location', vText(item["location"]))
            event.add('description', vText(item["description"]))
            event.add('class', 'PUBLIC')
            organizer = vCalAddress('MAILTO:[email protected]')
            organizer.params['cn'] = vText(item["organizer"])
            event['organizer'] = organizer
            event['uid'] = item["id"] + '@facebook.com'
            # add the event to calandar
            cal.add_component(event)

        with open(self.dump, 'wb') as filehandle:
            filehandle.write(cal.to_ical())
Example #10
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 #11
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 #12
0
def getIcal(
    talks, series
):  # talks is a list of Talk objects. series is a name for the talk series to be used in the UUID (juvitop, topology-seminar)
    cal = Calendar()
    organizer = vCalAddress("MAILTO:" + config.organizer_email)
    organizer.params['cn'] = vText(config.organizer_first_name + " " +
                                   config.organizer_last_name)
    for talk in talks:
        if talk.invalid:
            continue

        event = Event()
        event['uid'] = talk.date.strftime(
            "%Y%m%d%H%M%S") + "-" + series + "@math.mit.edu"
        event.add('dtstart', localToUTC(talk.date))
        event.add('dtend', localToUTC(talk.enddate))
        event.add('dtstamp', datetime.utcnow())
        event['organizer'] = organizer
        if talk.title:
            event.add('summary', talk.speaker.text + ": " + talk.title_email)
        else:
            event.add('summary', talk.speaker.text)

        if talk.email_abstract_text:
            event.add('description', talk.email_abstract_text)

        event.add('location', 'MIT ' + talk.room)
        cal.add_component(event)
    return (cal.to_ical())
Example #13
0
def ical(request):
    cal = icalendar.Calendar()
    cal.add('prodid', '-//Kiberpipa//NONSGML intranet//EN')
    cal.add('version', '2.0')

    events = Event.objects.order_by('-chg_date')[:20]

    for e in events:
        if e.public:
            classification = u'PUBLIC'
        else:
            continue
        cal_event = icalendar.Event()
        cal_event.add('uid', u'UID:event-%s-%[email protected]' % (e.id, e.slug))
        cal_event.add('summary', u'%s: %s' % (e.project, e.title))
        cal_event.add('url', u'https://www.kiberpipa.org%s' % e.get_absolute_url())
        cal_event.add('location', e.place.name)
        cal_event.add('classification', classification)
        cal_event.add('categories', u','.join([e.project.name, e.category.name]))
        # http://www.kanzaki.com/docs/ical/transp.html
        cal_event.add('transp', 'OPAQUE')
        # dtstamp means when was the last time icalendar feed has changed
        cal_event.add('dtstamp', ljubljana_tz.localize(datetime.datetime.now()))
        cal_event.add('dtstart', ljubljana_tz.localize(e.start_date))
        cal_event.add('dtend', ljubljana_tz.localize(e.end_date))
        cal_event.add('last-modified', ljubljana_tz.localize(e.chg_date))
        organizer = icalendar.vCalAddress(u'MAILTO:[email protected]')
        organizer.params['cn'] = u'Kiberpipa'
        cal_event.add('organizer', organizer)
        cal.add_component(cal_event)

    response = HttpResponse(mimetype='text/calendar; charset=UTF-8')
    response.write(cal.to_ical())
    return response
def CreateReminder(cal, days, text, fromaddress):
  """Creates a calendar entry in days days with title text.

  Args:
    cal: A Calendar.
    days: How many days in the future to create the reminder.
    text: The calendar summary

  Returns:
    A calendar entry.
    """
  event = Event()
  event.add('summary', text)
  eventdate = datetime.datetime.now() + datetime.timedelta(days=int(days))
  event.add('dtstart',eventdate)
  event.add('dtend', eventdate)
  event.add('dtstamp', eventdate)
  event['uid'] = str(uuid.uuid1()) + '@kumari.net'
  event.add('priority', 5)

  organizer = vCalAddress('MAILTO:%s' % fromaddress)
  organizer.params['cn'] = vText('%s' % fromaddress)
  organizer.params['role'] = vText('CHAIR')
  event['organizer'] = organizer
  event['location'] = vText('Online')

  cal.add_component(event)
  return cal
def to_ical_event(ev):
    """
    Convert Eventure Event to ical (CalDAV) string format
    Params: ev: core.models.event
    """
    cal = Calendar()
    cal.add('prodid', '-//Eventure Interactive.//CalDAV Client//EN')
    cal.add('version', '2.0')

    event = iEvent()
    event.add('summary', ev.title)
    event.add('dtstart', ev.start)
    event.add('dtend', ev.end)
    event.add('dtstamp', ev.created)
    event.add('uid', 'EVENTURE-' + str(ev.id))
    event['location'] = vText(ev.location)

    # Add Guests
    for guest in ev.guests.all():
        attendee = vCalAddress('MAILTO:%s' % (guest.email))
        attendee.params['cn'] = vText(guest.name)
        attendee.params['ROLE'] = vText('REQ-PARTICIPANT')
        event.add('attendee', attendee, encode=0)

    cal.add_component(event)

    return cal.to_ical()
Example #16
0
    def generate_icalendar(self, event_count=1):
        calendar = icalendar.Calendar()
        calendar.add("VERSION", "2.0")
        calendar.add("PRODID", "-//hacksw/handcal//NONSGML v1.0//EN")

        start = pytz.utc.localize(
            datetime.datetime(1997, 7, 14, 17, 0, 0))
        end = pytz.utc.localize(
            datetime.datetime(1997, 7, 15, 3, 59, 59))

        for i in xrange(event_count):
            event = icalendar.Event()
            event.add("UID", "uid{}@example.com".format(i + 1))
            event.add("DTSTAMP", start)

            organiser = icalendar.vCalAddress("MAILTO:[email protected]")
            organiser.params["CN"] = "John Doe"
            event.add("ORGANIZER", organiser)

            event.add("DTSTART", start)
            event.add("DTEND", end)

            event.add("SUMMARY", "Bastille Day Party")

            # To generate exactly the iCal text we want we need to remove
            # some auto-generated properties from the dates
            event["DTSTAMP"].params.clear()
            event["DTSTART"].params.clear()
            event["DTEND"].params.clear()

            calendar.add_component(event)

        return calendar.to_ical()
Example #17
0
    def item_attendee(self, item):
        attendee_list = list()
        participants = item.participants.all()
        default_attendee_params = {
            "cutype": icalendar.vText("INDIVIDUAL"),  # 日曆的使用者
            "rsvp": icalendar.vText("TRUE"),  # 參與者回覆
            "role": icalendar.vText("REQ-PARTICIPANT"),  # 參與者角色
        }

        for participant in participants:
            attendee = icalendar.vCalAddress(f"MAILTO:{participant.email}")
            participant_dic = default_attendee_params.copy()
            try:
                response = item.participants.through.objects \
                    .values_list('response', flat=True) \
                    .get(user=participant)
            except Exception as error:
                print(f'Feed item.participants.through.objects.get{error}')

            # 參與者邀請回覆
            if response == 'accept':
                attendee.params['partstat'] = icalendar.vText("ACCEPTED")
            elif response == 'decline':
                attendee.params['partstat'] = icalendar.vText("DECLINED")
            else:
                attendee.params['partstat'] = icalendar.vText("NEEDS-ACTION")

            for key, val in participant_dic.items():
                attendee.params[key] = icalendar.vText(val)
            attendee_list.append(attendee)

        return attendee_list
Example #18
0
def createICalFile(courses, name="default.ics", path=os.getcwd()):
    cal = Calendar()

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

    for course in courses:
        event = Event()
        summary = course["name"]
        if isinstance(course["prof"], basestring):
            summary += " : " + course["prof"]
        event.add('summary', summary)
        event.add('dtstart', datetime(course["dateStart"].year, course["dateStart"].month, course["dateStart"].day, course["dateStart"].hour-1, 0, 0, tzinfo=pytz.utc))
        event.add('dtend', datetime(course["dateEnd"].year, course["dateEnd"].month, course["dateEnd"].day, course["dateEnd"].hour-1, 0, 0, tzinfo=pytz.utc))
        #event.add('dtstamp', datetime(2014, 2, 22, 0, 10, 0, tzinfo=pytz.utc))

        #A property with parameters. Notice that they are an attribute on the value:
        organizer = vCalAddress('MAILTO:[email protected]')

        #Automatic encoding is not yet implemented for parameter values, so you must use the ‘v*’ types you can import from the icalendar package (they’re defined in icalendar.prop):
        organizer.params['cn'] = vText(course["prof"])
        organizer.params['role'] = vText('CHAIR')
        event['organizer'] = organizer
        event['location'] = vText('EPSI')

        event['uid'] = course["dateStart"].strftime("%Y-%m-%d%H:%M") + '/[email protected]'
        event.add('priority', 5)

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

        attendee = vCalAddress('MAILTO:[email protected]')
        attendee.params['cn'] = vText('The Dude')
        attendee.params['ROLE'] = vText('REQ-PARTICIPANT')
        event.add('attendee', attendee, encode=0)
        #Add the event to the calendar:
        cal.add_component(event)

    #Write to disk:
    if path is None:
        path = os.getcwd()
    f = open(os.path.join(path, name), 'wb')
    f.write(cal.to_ical())
    f.close()
Example #19
0
def ical_from_eb_feed( eb_feed, ignore_draft=True ):
    ''' Converts an EventBrite feed into iCal format. '''
    cal = Calendar()
    cal.add('prodid', '-//eventbrite2ical//reincubate//')
    cal.add('version', '2.0')

    for event in eb_feed['events']:
        if ignore_draft and event['event']['status'] == 'Draft':
            continue

        tzinfo = timezone( event['event']['timezone'] )

        title = event['event']['title']
        description = event['event']['title']
        url = event['event']['url']

        organiser = event['event']['organizer']['name']

        if not 'venue' in event['event']:
            venue = None
        else:
            venue = event['event']['venue']

            addresses = [ venue['name'], venue['address'], venue['address_2'], venue['city'], venue['region'], venue['postal_code'], venue['country'], ]
            filled_addresses = []
            for a in addresses:
                if a: filled_addresses.append( a )

            venue_address = ', '.join( filled_addresses )
            latitude = venue['latitude']
            longitude = venue['longitude']

        start_date = datetime.strptime( event['event']['start_date'], '%Y-%m-%d %H:%M:%S' ).replace(tzinfo=tzinfo)
        end_date = datetime.strptime( event['event']['end_date'], '%Y-%m-%d %H:%M:%S' ).replace(tzinfo=tzinfo)
        created = datetime.strptime( event['event']['created'], '%Y-%m-%d %H:%M:%S' ).replace(tzinfo=tzinfo)
      
        entry = Event()
        entry.add( 'summary', title )

        if url:
            description = '%s\n\n%s' % ( description, url )

        entry.add( 'description', description )
        entry.add( 'dtstart', start_date )
        entry.add( 'dtend',  end_date )
        entry.add( 'dtstamp', created )

        if venue:
            entry.add( 'location', venue_address )
            entry.add( 'geoLat', latitude )
            entry.add( 'geoLong', longitude )

        eorganiser = vCalAddress( url )
        eorganiser.params['cn'] = organiser
        entry['organizer'] = eorganiser

        cal.add_component( entry )

    return cal.to_ical()
Example #20
0
def createEvent(cal, eventData):
    from datetime import datetime
    from icalendar import Event, vCalAddress, vText, Calendar, vDatetime
    import pytz
    correct = "n"
    while correct != 's':
        event = Event()
        tempCal = Calendar()
        if eventData["summary"] == '':
            eventData["summary"] = "Dummy event"
        print("\tGenerando evento <<%s>>...\n" % (eventData["summary"]))
        bdate = [int(i) for i in eventData["BDate"].split('-')]
        bhour = [int(i) for i in eventData["BHour"].split(':')]
        edate = [int(i) for i in eventData["EDate"].split('-')]
        ehour = [int(i) for i in eventData["EHour"].split(':')]
        btz = pytz.timezone(eventData["Btz"])
        etz = pytz.timezone(eventData["Etz"])
        event["summary"] = eventData["summary"]
        event["organizer"] = vCalAddress('MAILTO:' + eventData["organizer"])
        event["dtstart"] = vDatetime(
            datetime(bdate[2],
                     bdate[1],
                     bdate[0],
                     bhour[0],
                     bhour[1],
                     0,
                     tzinfo=btz))
        event["dtend"] = vDatetime(
            datetime(edate[2],
                     edate[1],
                     edate[0],
                     ehour[0],
                     ehour[1],
                     0,
                     tzinfo=etz))
        event["dtstamp"] = vDatetime(
            datetime(bdate[2],
                     bdate[1],
                     bdate[0],
                     bhour[0],
                     bhour[1],
                     0,
                     tzinfo=btz))
        event["location"] = vText(eventData["location"])
        if eventData["description"] == '':
            event["description"] = vText("XoXo.")
        else:
            event["description"] = vText(eventData["description"])
        event['uid'] = "xOxO-" + str(datetime.timestamp(
            datetime.now())) + "-XoXo"
        event['priority'] = 5
        print("La información es correcta?:\n")
        tempCal.add_component(event)
        displayCal(tempCal)
        correct = input("\n Correcto? s/n: ")
        if correct == "s":
            cal.add_component(event)
    return cal
Example #21
0
def events_to_ical(events, identifier):
    connection = db.connect()
    cursor = connection.cursor()

    ical = Calendar()
    ical.add('calscale', 'GREGORIAN')
    ical.add('prodid', '-//Oncall//Oncall calendar feed//EN')
    ical.add('version', '2.0')
    ical.add('x-wr-calname', '%s Oncall Calendar' % identifier)

    users = {}

    for event in events:
        username = event['user']
        if username not in users:
            cursor.execute(
                '''
                SELECT `user`.`full_name`, `contact_mode`.`name`, `user_contact`.`destination`
                FROM `user_contact`
                JOIN `contact_mode` ON `contact_mode`.`id` = `user_contact`.`mode_id`
                JOIN `user` ON `user`.`id` = `user_contact`.`user_id`
                WHERE `user`.`name` = %s
            ''', username)
            info = {'username': username, 'contacts': {}}
            for row in cursor:
                info['full_name'] = row[0]
                info['contacts'][row[1]] = row[2]
            users[username] = info
        user = users[username]

        # Create the event itself
        full_name = user.get('full_name', user['username'])
        cal_event = Event()
        cal_event.add('uid', 'event-%s@oncall' % event['id'])
        cal_event.add('dtstart', dt.fromtimestamp(event['start'], utc))
        cal_event.add('dtend', dt.fromtimestamp(event['end'], utc))
        cal_event.add('dtstamp', dt.utcnow())
        cal_event.add(
            'summary',
            '%s %s shift: %s' % (event['team'], event['role'], full_name))
        cal_event.add(
            'description', '%s\n' % full_name + '\n'.join([
                '%s: %s' % (mode, dest)
                for mode, dest in user['contacts'].items()
            ]))

        # Attach info about the user oncall
        attendee = vCalAddress('MAILTO:%s' % user['contacts'].get('email'))
        attendee.params['cn'] = vText(full_name)
        attendee.params['ROLE'] = vText('REQ-PARTICIPANT')
        cal_event.add('attendee', attendee, encode=0)

        ical.add_component(cal_event)

    cursor.close()
    connection.close()
    return ical.to_ical()
Example #22
0
 def get_attendee(self, activity):
     attendees = []
     for attendee in get_user_model().objects.filter(activityparticipant__activity=activity):
         address = vCalAddress(attendee.email)
         address.params['cn'] = vText(attendee.get_full_name())
         address.params['role'] = vText('REQ-PARTICIPANT')
         address.params['partstat'] = vText('ACCEPTED')
         attendees.append(address)
     return attendees
Example #23
0
    def get_ical_organizer(self):
        contact = self.get_organizer()
        organizer = icalendar.vCalAddress("MAILTO:%s" % contact.email())
        name = contact.name()

        if not name == None and not name == "":
            organizer.params["CN"] = icalendar.vText(name)

        return organizer
Example #24
0
def icalendar(request):
    if not request.user:
        request.response.status = 403
    #	return HTTPFound(location = request.route_url('user_login'))
    cal = Calendar()
    cal.add(
        'prodid',
        '-//MÜSLI - Mathematisches Übungsgruppen- und Scheinlisten-Interface//https://mathi.uni-heidelberg.de/muesli///'
    )
    cal.add('version', '2.0')

    # Lecture information cannot be added, since lecture times are not handled within MÜSLI

    # Get some information about the user
    attendee = vCalAddress('MAILTO:' + request.user.email)
    attendee.params['cn'] = vText(request.user.name)
    attendee.params['ROLE'] = vText('REQ-PARTICIPANT')

    # Begin with tutorials
    for tutorial in request.user.all_tutorials.options(
            joinedload(Tutorial.tutor), joinedload(Tutorial.lecture)):
        event = Event()
        event.add('summary', 'Tutorium: ' + Tutorial.lecture.name)
        # Oh Gosh! We need to parse this horrible time format to create a real date :(
        # Actually not, this will be too error-prone
        year = int(tutorial.lecture.term.value[0:4])
        event.add(
            'dtstart', datetime(2005, 4, 4, 8, 0, 0, tzinfo=pytz.utc)
        )  # For these lines we need a new structure to hold Events in tutorials
        event.add('dtend', datetime(2005, 4, 4, 10, 0, 0, tzinfo=pytz.utc)
                  )  # We also need a UI to enter event-details for the tutors
        event.add('dtstamp', datetime(2005, 4, 4, 0, 10, 0, tzinfo=pytz.utc))
        organizer = vCalAddress('MAILTO:' + tutorial.tutor.email)
        organizer.params['cn'] = vText(tutorial.tutor.name)
        event['location'] = vText(tutorial.tutor.name)
        event['uid'] = '20050115T101010/[email protected]'  # TODO
        #event.add('priority', 5)
        event.add('attendee', attendee, encode=0)  # mark the user as attendee
        cal.add_component(event)

# Now exams
# TODO
    return cal.to_ical()
    def generate_ics(self, user, current_member=None):

        meeting = self.closest_repetition.to_meeting_with_repetition_date()

        # if current_member and current_member.timezone:
        #     tz_info = current_member.timezone
        # elif meeting.creator and meeting.creator.timezone:
        #     tz_info = meeting.creator.timezone
        # else:
        #     tz_info = timezone.get_default_timezone()

        cal = Calendar()
        event = Event()

        event.add('summary', vText(meeting.name))

        start_time = timezone.datetime.strftime(
            timezone.localtime(meeting.start), '%A, %B %d, %Y; %H:%M (%p) %Z')
        description = u"%s\r\n%s" % (start_time, self.description)
        event.add('description', vText(description))

        event.add('dtstart', meeting.start.astimezone(timezone.utc))
        event.add('dtend', meeting.end.astimezone(timezone.utc))
        event.add('dtstamp', datetime.now())
        event['uid'] = "%s%06i@boarddirector" % (
            meeting.start.strftime('%Y%m%d%H%M'), meeting.id)
        event.add('priority', 1)

        organizer = vCalAddress('MAILTO:' + user.email)
        organizer.params['cn'] = vText(user.get_full_name())
        event['organizer'] = organizer

        event['location'] = vText(self.location)

        for member in Membership.objects.filter(committees=self.committee,
                                                account=self.account):
            attendee = vCalAddress('MAILTO:' + member.user.email)
            attendee.params['cn'] = vText(member.user.get_full_name())
            event.add('attendee', attendee, encode=0)

        cal.add_component(event)

        return cal.to_ical()
Example #26
0
    def render(self, request):
        cal = icalendar.Calendar()
        for obj in self.construct():
            if obj.get('_type') != 'event':
                # We can only serialize events
                continue

            event = icalendar.Event()

            if obj.get('all_day', False):
                event.add('dtstart', obj['when'].date())
                event['X-FUNAMBOL-ALLDAY'] = 1
                event['X-MICROSOFT-CDO-ALLDAYEVENT'] = 1
            else:
                event.add('dtstart', obj['when'])

                end = obj.get('end')
                if not end:
                    end = obj['when'] + datetime.timedelta(hours=1)
                event.add('dtend', end)

            if obj['type'] == 'committee:meeting':
                summary = "%s Committee Meeting" % (
                    obj['participants'][0]['participant'])
            elif obj['type'] == 'bill:action':
                summary = obj['description']
            else:
                continue

            event.add('summary', summary)
            event.add('location', obj.get('location', 'Unknown'))
            event['uid'] = obj['_id']

            if 'status' in obj:
                event.add('status', obj['status'].upper())

            if 'notes' in obj:
                event.add('description', obj['notes'])

            for participant in obj['participants']:
                addr = icalendar.vCalAddress('MAILTO:[email protected]')

                cn = participant['participant']

                if participant['type'] == 'committee':
                    cn += ' Committee'

                addr.params['cn'] = icalendar.vText(cn)
                #addr.params['ROLE'] = icalendar.vText('COMMITTEE')
                event.add('attendee', addr, encode=0)
                event['organizer'] = addr

            cal.add_component(event)

        return cal.as_string()
Example #27
0
    def render(self, request):
        cal = icalendar.Calendar()
        for obj in self.construct():
            if obj.get('_type') != 'event':
                # We can only serialize events
                continue

            event = icalendar.Event()

            if obj.get('all_day', False):
                event.add('dtstart', obj['when'].date())
                event['X-FUNAMBOL-ALLDAY'] = 1
                event['X-MICROSOFT-CDO-ALLDAYEVENT'] = 1
            else:
                event.add('dtstart', obj['when'])

                end = obj.get('end')
                if not end:
                    end = obj['when'] + datetime.timedelta(hours=1)
                event.add('dtend', end)

            if obj['type'] == 'committee:meeting':
                summary = "%s Committee Meeting" % (
                    obj['participants'][0]['participant'])
            elif obj['type'] == 'bill:action':
                summary = obj['description']
            else:
                continue

            event.add('summary', summary)
            event.add('location', obj.get('location', 'Unknown'))
            event['uid'] = obj['_id']

            if 'status' in obj:
                event.add('status', obj['status'].upper())

            if 'notes' in obj:
                event.add('description', obj['notes'])

            for participant in obj['participants']:
                addr = icalendar.vCalAddress('MAILTO:[email protected]')

                cn = participant['participant']

                if participant['type'] == 'committee':
                    cn += ' Committee'

                addr.params['cn'] = icalendar.vText(cn)
                #addr.params['ROLE'] = icalendar.vText('COMMITTEE')
                event.add('attendee', addr, encode=0)
                event['organizer'] = addr

            cal.add_component(event)

        return cal.as_string()
Example #28
0
def org_ics(request, org_short_name, org_feed_hash):
    host = request.META['HTTP_HOST']
    current_org, message = Organization.objects.get_current_org(org_short_name)
    if message:
        return HttpResponseRedirect(reverse('org_orgs_list'))

    if not org_feed_hash == current_org.org_feed_hash:
        return HttpResponseRedirect(
            reverse('org_org_view',
                    kwargs={'org_short_name': current_org.org_short_name}))

    events = current_org.event_set.all().order_by('-event_date')
    orgical = Calendar()

    orgical['summary'] = "Calendar for organization %s" % (
        current_org.org_name)
    orgical.add('prodid', '-//Evesch//NONSGML v1.0//EN')
    orgical.add('version', '2.0')

    for event in events:
        cal_event = icalendar.Event()
        cal_event.add('summary', event.event_name)
        cal_event.add('dtstart', event.event_date)
        cal_event.add('description', event.event_desc)
        cal_event.add('categories', event.event_type)
        cal_event.add('duration', timedelta(hours=1))
        cal_event.add(
            'url', "http://%s%s" %
            (host,
             reverse('event_event_view',
                     kwargs={
                         'org_short_name': current_org.org_short_name,
                         'event_hash': event.event_hash,
                     })))
        if event.event_creator_name.email:
            organizer_n = event.event_creator_name.email
        else:
            organizer_n = "%s %s" % (event.event_creator_name.first_name,
                                     event.event_creator_name.last_name)
        organizer = vCalAddress('MAILTO:' + organizer_n)
        organizer.params['cn'] = vText("%s %s" %
                                       (event.event_creator_name.first_name,
                                        event.event_creator_name.last_name))
        organizer.params['role'] = vText('CREATOR')
        cal_event.add('organizer', organizer, encode=0)
        orgical.add_component(cal_event)

    template_name = "core/message.html"
    context = {}

    response = HttpResponse()
    response['Content-Type'] = 'text/calendar'
    response.write(orgical.to_ical())
    #template_name = "error.html"
    return response
Example #29
0
    def test_unicode_param(self):
        cal_address = vCalAddress("mailto:[email protected]")
        cal_address.params["CN"] = "Джон Доу"
        vevent = Event()
        vevent["ORGANIZER"] = cal_address
        self.assertEqual(
            vevent.to_ical().decode("utf-8"),
            u"BEGIN:VEVENT\r\n" u'ORGANIZER;CN="Джон Доу":mailto:[email protected]\r\n' u"END:VEVENT\r\n",
        )

        self.assertEqual(vevent["ORGANIZER"].params["CN"], "Джон Доу")
Example #30
0
    def test_unicode_param(self):
        cal_address = vCalAddress('mailto:[email protected]')
        cal_address.params["CN"] = "Джон Доу"
        vevent = Event()
        vevent['ORGANIZER'] = cal_address
        self.assertEqual(
            vevent.to_ical().decode('utf-8'), u'BEGIN:VEVENT\r\n'
            u'ORGANIZER;CN="Джон Доу":mailto:[email protected]\r\n'
            u'END:VEVENT\r\n')

        self.assertEqual(vevent['ORGANIZER'].params['CN'], 'Джон Доу')
Example #31
0
def createSimpleICalFile():
    cal = Calendar()

    #Some properties are required to be compliant:
    cal.add('prodid', '-//My calendar product//mxm.dk//')
    cal.add('version', '2.0')
    #We need at least one subcomponent for a calendar to be compliant:
    event = Event()
    event.add('summary', 'Python meeting about calendaring')
    event.add('dtstart', datetime(2014, 2, 22, 8, 0, 0, tzinfo=pytz.utc))
    event.add('dtend', datetime(2014, 2, 22, 10, 0, 0, tzinfo=pytz.utc))
    event.add('dtstamp', datetime(2014, 2, 22, 0, 10, 0, tzinfo=pytz.utc))

    #A property with parameters. Notice that they are an attribute on the value:
    organizer = vCalAddress('MAILTO:[email protected]')

    #Automatic encoding is not yet implemented for parameter values, so you must use the ‘v*’ types you can import from the icalendar package (they’re defined in icalendar.prop):
    organizer.params['cn'] = vText('Max Rasmussen')
    organizer.params['role'] = vText('CHAIR')
    event['organizer'] = organizer
    event['location'] = vText('Odense, Denmark')

    event['uid'] = '20050115T101010/[email protected]'
    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)

    attendee = vCalAddress('MAILTO:[email protected]')
    attendee.params['cn'] = vText('The Dude')
    attendee.params['ROLE'] = vText('REQ-PARTICIPANT')
    event.add('attendee', attendee, encode=0)
    #Add the event to the calendar:
    cal.add_component(event)

    #Write to disk:
    f = open(os.path.join(os.getcwd(), 'example.ics'), 'wb')
    f.write(cal.to_ical())
    f.close()
Example #32
0
def createSimpleICalFile():
    cal = Calendar()

    #Some properties are required to be compliant:
    cal.add('prodid', '-//My calendar product//mxm.dk//')
    cal.add('version', '2.0')
    #We need at least one subcomponent for a calendar to be compliant:
    event = Event()
    event.add('summary', 'Python meeting about calendaring')
    event.add('dtstart', datetime(2014,2,22,8,0,0,tzinfo=pytz.utc))
    event.add('dtend', datetime(2014,2,22,10,0,0,tzinfo=pytz.utc))
    event.add('dtstamp', datetime(2014,2,22,0,10,0,tzinfo=pytz.utc))

    #A property with parameters. Notice that they are an attribute on the value:
    organizer = vCalAddress('MAILTO:[email protected]')

    #Automatic encoding is not yet implemented for parameter values, so you must use the ‘v*’ types you can import from the icalendar package (they’re defined in icalendar.prop):
    organizer.params['cn'] = vText('Max Rasmussen')
    organizer.params['role'] = vText('CHAIR')
    event['organizer'] = organizer
    event['location'] = vText('Odense, Denmark')

    event['uid'] = '20050115T101010/[email protected]'
    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)

    attendee = vCalAddress('MAILTO:[email protected]')
    attendee.params['cn'] = vText('The Dude')
    attendee.params['ROLE'] = vText('REQ-PARTICIPANT')
    event.add('attendee', attendee, encode=0)
    #Add the event to the calendar:
    cal.add_component(event)

    #Write to disk:
    f = open(os.path.join(os.getcwd(), 'example.ics'), 'wb')
    f.write(cal.to_ical())
    f.close()
Example #33
0
def add_attendee(email, organizer=False):
    """Adds an attendee to the event."""

    attendee = vCalAddress(f'MAILTO:{email}')
    if organizer:
        attendee.params['partstat'] = vText('ACCEPTED')
        attendee.params['role'] = vText('CHAIR')
    else:
        attendee.params['partstat'] = vText('NEEDS-ACTION')
        attendee.params['role'] = vText('PARTICIPANT')

    return attendee
Example #34
0
    def test_property_params(self):
        cal_address = icalendar.vCalAddress('mailto:[email protected]')
        cal_address.params["CN"] = "Doe, John"
        ical = icalendar.Calendar()
        ical.add('organizer', cal_address)

        ical_str = icalendar.Calendar.to_ical(ical)
        exp_str = """BEGIN:VCALENDAR\r\nORGANIZER;CN="Doe, John":mailto:[email protected]\r\nEND:VCALENDAR\r\n"""

        self.assertEqual(ical_str, exp_str)

        raise Exception
Example #35
0
 def _test_quoting(self, cn_param, cn_quoted):
     """
     @param cn_param: CN parameter value to test for quoting
     @param cn_quoted: expected quoted parameter in icalendar format
     """
     vevent = Event()
     attendee = vCalAddress('*****@*****.**')
     attendee.params['CN'] = cn_param
     vevent.add('ATTENDEE', attendee)
     self.assertEqual(
         vevent.to_ical(), b'BEGIN:VEVENT\r\nATTENDEE;CN=' +
         cn_quoted.encode('utf-8') + b':[email protected]\r\nEND:VEVENT\r\n')
Example #36
0
def _generate_rsvp(status, account, event):
    # It seems that Google Calendar requires us to copy a number of fields
    # in the RVSP reply. I suppose it's for reconciling the reply with the
    # invite. - karim
    cal = iCalendar()
    cal.add('PRODID', '-//Nylas sync engine//nylas.com//')
    cal.add('METHOD', 'REPLY')
    cal.add('VERSION', '2.0')
    cal.add('CALSCALE', 'GREGORIAN')

    icalevent = icalendar.Event()
    icalevent['uid'] = event.uid

    # For ahem, 'historic reasons', we're saving the owner field
    # as "Organizer <*****@*****.**>".
    organizer_name, organizer_email = event.owner.split('<')
    organizer_email = organizer_email[:-1]

    icalevent['sequence'] = event.sequence_number
    icalevent['X-MICROSOFT-CDO-APPT-SEQUENCE'] = icalevent['sequence']

    if event.status == 'confirmed':
        icalevent['status'] = 'CONFIRMED'

    icalevent['dtstamp'] = serialize_datetime(datetime.utcnow())

    if event.start is not None:
        icalevent['dtstart'] = serialize_datetime(event.start)

    if event.end is not None:
        icalevent['dtend'] = serialize_datetime(event.end)

    if event.description is not None:
        icalevent['description'] = event.description

    if event.location is not None:
        icalevent['location'] = event.location

    if event.title is not None:
        icalevent['summary'] = event.title

    attendee = icalendar.vCalAddress(u'MAILTO:{}'.format(
        account.email_address))
    attendee.params['cn'] = account.name
    attendee.params['partstat'] = status
    icalevent.add('attendee', attendee, encode=0)
    cal.add_component(icalevent)

    ret = {}
    ret["cal"] = cal
    ret["organizer_email"] = organizer_email

    return ret
Example #37
0
def _generate_rsvp(status, account, event):
    # It seems that Google Calendar requires us to copy a number of fields
    # in the RVSP reply. I suppose it's for reconciling the reply with the
    # invite. - karim
    cal = iCalendar()
    cal.add('PRODID', '-//Nylas sync engine//nylas.com//')
    cal.add('METHOD', 'REPLY')
    cal.add('VERSION', '2.0')
    cal.add('CALSCALE', 'GREGORIAN')

    icalevent = icalendar.Event()
    icalevent['uid'] = event.uid

    # For ahem, 'historic reasons', we're saving the owner field
    # as "Organizer <*****@*****.**>".
    organizer_name, organizer_email = event.owner.split('<')
    organizer_email = organizer_email[:-1]

    icalevent['sequence'] = event.sequence_number
    icalevent['X-MICROSOFT-CDO-APPT-SEQUENCE'] = icalevent['sequence']

    if event.status == 'confirmed':
        icalevent['status'] = 'CONFIRMED'

    icalevent['dtstamp'] = serialize_datetime(datetime.utcnow())

    if event.start is not None:
        icalevent['dtstart'] = serialize_datetime(event.start)

    if event.end is not None:
        icalevent['dtend'] = serialize_datetime(event.end)

    if event.description is not None:
        icalevent['description'] = event.description

    if event.location is not None:
        icalevent['location'] = event.location

    if event.title is not None:
        icalevent['summary'] = event.title

    attendee = icalendar.vCalAddress(u'MAILTO:{}'.format(
        account.email_address))
    attendee.params['cn'] = account.name
    attendee.params['partstat'] = status
    icalevent.add('attendee', attendee, encode=0)
    cal.add_component(icalevent)

    ret = {}
    ret["cal"] = cal
    ret["organizer_email"] = organizer_email

    return ret
    def export(event_id):
        """Takes an event id and returns the event in iCal format"""

        event = EventModel.query.get(event_id)

        cal = Calendar()
        cal.add('prodid', '-//fossasia//open-event//EN')
        cal.add('version', '2.0')
        cal.add('x-wr-calname', event.name)
        cal.add('x-wr-caldesc', "Schedule for sessions at " + event.name)

        tz = event.timezone or 'UTC'
        tz = pytz.timezone(tz)

        sessions = Session.query \
            .filter_by(event_id=event_id) \
            .filter_by(state='accepted') \
            .filter(Session.in_trash is not True) \
            .order_by(asc(Session.start_time)).all()

        for session in sessions:

            if session and session.start_time and session.end_time:
                event_component = icalendar.Event()
                event_component.add('summary', session.title)
                event_component.add('uid',
                                    str(session.id) + "-" + event.identifier)
                event_component.add('geo', (event.latitude, event.longitude))
                event_component.add(
                    'location', session.microlocation.name
                    or '' + " " + event.location_name)
                event_component.add('dtstart', tz.localize(session.start_time))
                event_component.add('dtend', tz.localize(session.end_time))
                event_component.add('email', event.email)
                event_component.add('description', session.short_abstract)
                event_component.add(
                    'url',
                    url_for('event_detail.display_event_detail_home',
                            identifier=event.identifier,
                            _external=True))

                for speaker in session.speakers:
                    # Ref: http://icalendar.readthedocs.io/en/latest/usage.html#file-structure
                    # can use speaker.email below but privacy reasons
                    attendee = vCalAddress(
                        'MAILTO:' +
                        event.email if event.email else '*****@*****.**')
                    attendee.params['cn'] = vText(speaker.name)
                    event_component.add('attendee', attendee)

                cal.add_component(event_component)

        return cal.to_ical()
def generate_calendar(classes):
    cal = icalendar.Calendar()
    cal.add('prodid', '-//WPI Calender Generator//adamgoldsmith.name//')
    cal.add('version', '2.0')

    tz = create_eastern_vtimezone()
    cal.add_component(tz)

    for index, c in enumerate(classes):
        event = icalendar.Event()
        if c['times'] == ['TBA']:
            continue
        # push the start and end dates back one day, then exclude the start date
        # this fixes a problem where the first day of the term would have all of the classes
        start_date = format_dates(c['dates'][0], c['times'][0]) - timedelta(days=1) # start of the first class
        end_date = format_dates(c['dates'][0], c['times'][1]) - timedelta(days=1) # end of the first class
        final_end_date = format_dates(c["dates"][1]) # end of the term
        event.add('summary', c['course'] + " " + c['type'])
        event.add('dtstart', start_date)
        event.add('location', c['location'])
        description = "{} {}\n{} {}".format(c['title'],
                                              c['section'],
                                              c['instructor'],
                                              c['instructor_email'])
        if c['Status'].split(' ')[0] == 'Waitlist':
            description += "\nWaitlist:" + c['waitlist_position']
        event.add('description', description)
        event.add('dtend', end_date)
        event.add('rrule', {'freq': "weekly",
                            'until': final_end_date,
                            'byday': format_days(c['days'])})
        event.add('exdate', start_date)
        event.add('uid',
                  "WPICal_{}{}{}{}{}@adamgoldsmith.name".format(c['term'],
                                                                c['course'],
                                                                c['section'],
                                                                c['type'],
                                                                c['days']).replace(' ', ''))
        event.add('dtstamp', datetime.now())

        if c['instructor_email'] is not None:
            organizer = icalendar.vCalAddress(c['instructor_email'])
            organizer.params['cn'] = c['instructor']
            event['organizer'] = organizer

        alarm = icalendar.Alarm()
        alarm.add('trigger', icalendar.vDuration(timedelta(minutes=-10)))
        alarm.add('action', "display")
        event.add_component(alarm)

        cal.add_component(event)
    return cal
Example #40
0
def generate_calendar(classes):
    cal = icalendar.Calendar()
    cal.add('prodid', '-//WPI Calender Generator//adamgoldsmith.name//')
    cal.add('version', '2.0')

    tz = create_eastern_vtimezone()
    cal.add_component(tz)

    for index, c in enumerate(classes):
        event = icalendar.Event()
        if c['times'] == ['TBA']:
            continue
        # push the start and end dates back one day, then exclude the start date
        # this fixes a problem where the first day of the term would have all of the classes
        start_date = format_dates(c['dates'][0], c['times'][0]) - timedelta(days=1) # start of the first class
        end_date = format_dates(c['dates'][0], c['times'][1]) - timedelta(days=1) # end of the first class
        final_end_date = format_dates(c["dates"][1]) # end of the term
        event.add('summary', c['course'] + " " + c['type'])
        event.add('dtstart', start_date)
        event.add('location', c['location'])
        description = "{} {}\n{} {}".format(c['title'],
                                              c['section'],
                                              c['instructor'],
                                              c['instructor_email'])
        if c['Status'].split(' ')[0] == 'Waitlist':
            description += "\nWaitlist:" + c['waitlist_position']
        event.add('description', description)
        event.add('dtend', end_date)
        event.add('rrule', {'freq': "weekly",
                            'until': final_end_date,
                            'byday': format_days(c['days'])})
        event.add('exdate', start_date)
        event.add('uid',
                  "WPICal_{}{}{}{}{}@adamgoldsmith.name".format(c['term'],
                                                                c['course'],
                                                                c['section'],
                                                                c['type'],
                                                                c['days']).replace(' ', ''))
        event.add('dtstamp', datetime.now())

        if c['instructor_email'] is not None:
            organizer = icalendar.vCalAddress(c['instructor_email'])
            organizer.params['cn'] = c['instructor']
            event['organizer'] = organizer

        alarm = icalendar.Alarm()
        alarm.add('trigger', icalendar.vDuration(timedelta(minutes=-10)))
        alarm.add('action', "display")
        event.add_component(alarm)

        cal.add_component(event)
    return cal
Example #41
0
 def _test_quoting(self, cn_param, cn_quoted):
     """
     @param cn_param: CN parameter value to test for quoting
     @param cn_quoted: expected quoted parameter in icalendar format
     """
     vevent = Event()
     attendee = vCalAddress("*****@*****.**")
     attendee.params["CN"] = cn_param
     vevent.add("ATTENDEE", attendee)
     self.assertEqual(
         vevent.to_ical(),
         b"BEGIN:VEVENT\r\nATTENDEE;CN=" + cn_quoted.encode("utf-8") + b":[email protected]\r\nEND:VEVENT\r\n",
     )
Example #42
0
def action_to_ical_event(action):
    from icalendar import Event, vText, vCalAddress, vDatetime
    from pytz import timezone

    evt = Event()
    evt["uid"] = f"{action.id}@{base_url()}"
    evt.add("summary", action.html_title)
    evt["url"] = action.full_url

    outreach_circle = get_circle("outreach")
    if outreach_circle:
        organizer = vCalAddress(f"MAILTO:{outreach_circle.public_email}")
        organizer.params["cn"] = "Extinction Rebellion Boston"
        evt["organizer"] = organizer

    start = action.when
    # TODO: event listings don't have a duration so making one up.
    end = action.when + timedelta(hours=2)

    evt.add("dtstart", vDatetime(start))
    evt.add("dtend", vDatetime(end))
    evt.add("dtstamp", vDatetime(now()))

    # Attempt to put video conferencing information into the ics.
    # TODO: this doesn't work entirely but it doesn't hurt. Revisit
    # when we have more time and patience to work on it.
    if action.virtual:
        dlines = [
            f"Join online: <a href=\"{action.location}\">{action.location}</a>\n",
            f"Event details: <a href=\"{action.full_url}\">{action.full_url}</a>\n",
            f"{action.description}\n",
            ICS_VIDEO_CONFERENCE_SEP,
            "Do not edit this section of the description.\n",
            "This event has a video call.",
            f"Join: {action.location}\n",
            f"View your event at {action.full_url}",
            ICS_VIDEO_CONFERENCE_SEP,
        ]
        evt["location"] = "Online event"
    else:
        dlines = [
            f"Event details: {action.full_url}\n",
            f"{action.description}",
        ]
        evt["location"] = action.location

    description = "\n".join(dlines)
    evt.add("description", description)
    evt["last-modified"] = vDatetime(action.modified)
    evt["created"] = vDatetime(now())
    return evt
Example #43
0
    def export(event_id):
        """Takes an event id and returns the event in iCal format"""

        event = EventModel.query.get(event_id)

        cal = Calendar()
        cal.add('prodid', '-//fossasia//open-event//EN')
        cal.add('version', '2.0')
        cal.add('x-wr-calname', event.name)
        cal.add('x-wr-caldesc', "Schedule for sessions at " + event.name)

        sessions = Session.query \
            .filter_by(event_id=event_id) \
            .filter_by(state='accepted') \
            .filter(Session.deleted_at.is_(None)) \
            .order_by(asc(Session.starts_at)).all()

        for session in sessions:

            if not (session and session.starts_at and session.ends_at):
                continue

            event_component = icalendar.Event()
            event_component.add('summary', session.title)
            event_component.add('uid',
                                str(session.id) + "-" + event.identifier)
            event_component.add('geo', (event.latitude, event.longitude))
            event_component.add(
                'location',
                session.microlocation and session.microlocation.name
                or '' + " " + event.location_name)
            event_component.add('dtstart', session.starts_at)
            event_component.add('dtend', session.ends_at)
            event_component.add('description', session.short_abstract)
            event_component.add(
                'url',
                url_for('v1.event_list',
                        identifier=event.identifier,
                        _external=True))

            for speaker in session.speakers:
                # Ref: http://icalendar.readthedocs.io/en/latest/usage.html#file-structure
                attendee = vCalAddress(
                    'MAILTO:' +
                    speaker.email if speaker.email else '*****@*****.**')
                attendee.params['cn'] = vText(speaker.name)
                event_component.add('attendee', attendee)

            cal.add_component(event_component)

        return cal.to_ical()
def toiCalendar(List_Event):
    # Entry value has the following structure: it is a LIST!!!
    # [      event = {'name': '',
    #               'dstart': ''
    #               'dtend': ''
    #               'category': "All day event",
    #               'infoLink': "",
    #               'ticketsLink': "",
    #               'image': ""}
    # ]
    cal = Calendar()
    cal.add('prodid', '-//O2 Arena calendar')
    cal.add('version', '2.0')
    organizer = vCalAddress('MAILTO:[email protected]')

    location = vText('O2 Arena at Ceskomoravska')
    dtstamp = datetime(2017, 10, 24, 0, 0, 0, tzinfo=pytz.utc)

    for i in (range(len(List_Event))):
        event = Event()
        description = ""
        print("Elem %i and name %s and datestart %s" %
              (i, List_Event[i]['name'], List_Event[i]['dtstart']))
        #        print(List_Event[i])
        event.add('dtstart', List_Event[i]['dtstart'])
        event.add('dtend', List_Event[i]['dtend'])
        event.add('summary', List_Event[i]['name'])
        event.add('location', location)
        event.add('organizer', organizer)
        event.add('url', List_Event[i]['infoLink'])
        event.add('geo', '50.104788;14.493774')
        event.add('dtstamp', dtstamp)
        event['uid'] = ("%s/%[email protected]" %
                        (dtstamp.now().strftime("%Y%m%d%H%M%S"), i))
        print(event['uid'])
        # if there are NOT tickets left.
        if (List_Event[i]['TicketsLeft'] == 0):
            alarm = Alarm()
            alarm.add("action", "DISPLAY")
            alarm.add("description", "Reminder")
            alarm.add("TRIGGER;RELATED=START", "-PT{0}H".format(1))
            description = "This event is FULL! "
            event.add_component(alarm)
        #  print(event)
        event.add('description', description + List_Event[i]['description'])
        cal.add_component(event)
        #  print(event)
        cal_content = cal.to_ical()

    with open("O2ArenaCalendar.ics", 'wb') as f:
        f.write(cal_content)
Example #45
0
    def get(self, request, *args, **kwargs):

        # code copied from http://icalendar.readthedocs.io/en/latest/usage.html#example

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

        event = Event()
        event.add('summary', 'Python meeting about calendaring')
        event.add('dtstart', datetime(2005, 4, 4, 8, 0, 0, tzinfo=pytz.utc))
        event.add('dtend', datetime(2005, 4, 4, 10, 0, 0, tzinfo=pytz.utc))
        event.add('dtstamp', datetime(2005, 4, 4, 0, 10, 0, tzinfo=pytz.utc))
        organizer = vCalAddress('MAILTO:[email protected]')

        organizer.params['cn'] = vText('Max Rasmussen')
        organizer.params['role'] = vText('CHAIR')
        event['organizer'] = organizer
        event['location'] = vText('Odense, Denmark')

        event['uid'] = '20050115T101010/[email protected]'
        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)

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

        cal.add_component(event)

        html = cal.to_ical()

        return HttpResponse(html)
Example #46
0
File: views.py Project: khchine5/xl
    def get(self, request, *args, **kwargs):
        
        # code copied from http://icalendar.readthedocs.io/en/latest/usage.html#example
        
        cal = Calendar()
        cal.add('prodid', '-//My calendar product//mxm.dk//')
        cal.add('version', '2.0')

        event = Event()
        event.add('summary', 'Python meeting about calendaring')
        event.add('dtstart', datetime(2005,4,4,8,0,0,tzinfo=pytz.utc))
        event.add('dtend', datetime(2005,4,4,10,0,0,tzinfo=pytz.utc))
        event.add('dtstamp', datetime(2005,4,4,0,10,0,tzinfo=pytz.utc))
        organizer = vCalAddress('MAILTO:[email protected]')

        organizer.params['cn'] = vText('Max Rasmussen')
        organizer.params['role'] = vText('CHAIR')
        event['organizer'] = organizer
        event['location'] = vText('Odense, Denmark')

        event['uid'] = '20050115T101010/[email protected]'
        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)

        attendee = vCalAddress('MAILTO:[email protected]')
        attendee.params['cn'] = vText('The Dude')
        attendee.params['ROLE'] = vText('REQ-PARTICIPANT')
        event.add('attendee', attendee, encode=0)
        
        cal.add_component(event)
        
        html = cal.to_ical()
        
        return HttpResponse(html)
Example #47
0
def _generate_rsvp(status, account, event):
    # It seems that Google Calendar requires us to copy a number of fields
    # in the RVSP reply. I suppose it's for reconciling the reply with the
    # invite. - karim
    cal = iCalendar()
    cal.add("PRODID", "-//Nylas sync engine//nylas.com//")
    cal.add("METHOD", "REPLY")
    cal.add("VERSION", "2.0")
    cal.add("CALSCALE", "GREGORIAN")

    icalevent = icalendar.Event()
    icalevent["uid"] = event.uid

    if event.organizer_email is not None:
        icalevent["organizer"] = event.organizer_email

    icalevent["sequence"] = event.sequence_number
    icalevent["X-MICROSOFT-CDO-APPT-SEQUENCE"] = icalevent["sequence"]

    if event.status == "confirmed":
        icalevent["status"] = "CONFIRMED"

    icalevent["dtstamp"] = serialize_datetime(datetime.utcnow())

    if event.start is not None:
        icalevent["dtstart"] = serialize_datetime(event.start)

    if event.end is not None:
        icalevent["dtend"] = serialize_datetime(event.end)

    if event.description is not None:
        icalevent["description"] = event.description

    if event.location is not None:
        icalevent["location"] = event.location

    if event.title is not None:
        icalevent["summary"] = event.title

    attendee = icalendar.vCalAddress(u"MAILTO:{}".format(
        account.email_address))
    attendee.params["cn"] = account.name
    attendee.params["partstat"] = status
    icalevent.add("attendee", attendee, encode=0)
    cal.add_component(icalevent)

    ret = {}
    ret["cal"] = cal

    return ret
 def _test_quoting(self, cn_param, cn_quoted):
     """
     @param cn_param: CN parameter value to test for quoting
     @param cn_quoted: expected quoted parameter in icalendar format
     """
     vevent = Event()
     attendee = vCalAddress('*****@*****.**')
     attendee.params['CN'] = cn_param
     vevent.add('ATTENDEE', attendee)
     self.assertEqual(
         vevent.to_ical(),
         b'BEGIN:VEVENT\r\nATTENDEE;CN=' + cn_quoted.encode('utf-8') +
         b':[email protected]\r\nEND:VEVENT\r\n'
     )
    def test_unicode_param(self):
        cal_address = vCalAddress('mailto:[email protected]')
        cal_address.params["CN"] = "Джон Доу"
        vevent = Event()
        vevent['ORGANIZER'] = cal_address
        self.assertEqual(
            vevent.to_ical().decode('utf-8'),
            u'BEGIN:VEVENT\r\n'
            u'ORGANIZER;CN="Джон Доу":mailto:[email protected]\r\n'
            u'END:VEVENT\r\n'
        )

        self.assertEqual(vevent['ORGANIZER'].params['CN'],
                         'Джон Доу')
Example #50
0
    def add_organizer(self, element):
        value = self._get_element_text(element, 'organizer')

        parsed = EmailParser().parse(value)
        if not parsed:
            return

        name = parsed[0].strip().strip('"')

        organizer = vCalAddress('MAILTO:%s' % parsed[1])
        organizer.params['cn'] = vText(name)
        organizer.params['ROLE'] = vText('CHAIR')

        self.add('organizer', organizer, encode=0)
Example #51
0
def makeiCal2(subj, description):
    cal = Calendar()
    cal.add('prodid', '-//My calendar product//mxm.dk//')
    cal.add('version', '2.0')

    event = Event()
    event.add('summary', 'Python meeting about calendaring')
    try:
        event.add('dtstart', dt.datetime(2017,7,7,8,0,0,tzinfo=pytz.utc))
        event.add('dtend', dt.datetime(2017,7,7,10,0,0,tzinfo=pytz.utc))
        event.add('dtstamp', dt.datetime(2017,7,7,0,10,0,tzinfo=pytz.utc))
    except Exception as e:
        pass
    
    from icalendar import vCalAddress, vText
    organizer = vCalAddress('MAILTO:[email protected]')

    organizer.params['cn'] = vText('Dan Piao')
    organizer.params['role'] = vText('CHAIR')
    event['organizer'] = organizer
    event['location'] = vText('Online')

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

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

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

    cal.add_component(event)
    return cal.to_ical()
def evento_list_ical(
    request
):  #U: idem evento_list pero en formato icalendar para importar eg en google, outlook
    from icalendar import Calendar, Event, vCalAddress, vText
    import pytz

    when_generated = timezone.now()

    cal = Calendar()
    cal.add('prodid', '-//PodemosAprender//mxm.dk//')
    cal.add('version', '2.0')

    organizer = vCalAddress('MAILTO:[email protected]')
    organizer.params['cn'] = vText('PodemosAprender')
    organizer.params['role'] = vText('APP')

    schedule, charla_a_eventos = charlas_calendario(31)

    for (when, charla) in schedule:
        print(when, charla)
        for evento in charla_a_eventos[f'#{charla}']:
            event = Event()
            event['organizer'] = organizer
            event['uid'] = f'texto/{evento["id"]}/{when.strftime("%Y%m%d")}'
            #event['location'] = vText('Odense, Denmark')

            txt = re.sub(r'#casual\S+', '', evento['texto'])
            if when.strftime('%H%M') == '0000':  #A: no tiene horario
                hour = 9  #DFLT
                minute = 0  #DFLT
                m = re.search('(\d+)(:(\d+))?hs', txt)
                if not m is None:
                    hour = int(m.group(1))
                    minute = int(m.group(3)) if not m.group(3) is None else 0
                when = dt.datetime(when.year, when.month, when.day, hour,
                                   minute)

            #FALLA CON GOOGLE #when= pytz.utc.localize( when + dt.timedelta(hours=3) ) #A: pasamos de Arg=GMT-3 a UTC
            when = when + dt.timedelta(hours=3)  #A: pasamos de Arg=GMT-3 a UTC

            event.add('summary', txt)
            event.add('dtstart', when)
            event.add('dtend', when + dt.timedelta(hours=1))
            event.add('dtstamp', when_generated)
            event.add('priority', 5)

            cal.add_component(event)

    return HttpResponse(cal.to_ical(), content_type='text/calendar')
Example #53
0
def ics_file():
    cal = Calendar()
    cal.add('prodid', '-//GitHub Milestone ICS Feed//herokuapp.com//')
    cal.add('version', '2.0')

    for milestone in Client(github).milestones():
        if milestone.get('due_on'):
            creator = milestone.get('creator')
            dtstart = datetime.strptime(milestone['due_on'],
                                        '%Y-%m-%dT%H:%M:%SZ')
            created = datetime.strptime(milestone['created_at'],
                                        '%Y-%m-%dT%H:%M:%SZ')
            updated = datetime.strptime(milestone['updated_at'],
                                        '%Y-%m-%dT%H:%M:%SZ')

            name, repo, m = re_url_info.findall(milestone.get('html_url'))[0]

            event = Event()
            event.add('summary', "%s/%s - %s" % (name, repo,
                                                 milestone.get('title')))
            event.add('description', milestone.get('description'))

            event.add('dtstart', dtstart.date())
            event.add('dtend', dtstart.date())
            event.add('dtstamp', dtstart.date())
            event.add('created', created.replace(tzinfo=pytz.utc))
            event.add('last-modified', updated.replace(tzinfo=pytz.utc))

            event.add('uid', milestone.get('id'))

            event.add('url', milestone.get('html_url'))

            organizer = vCalAddress('MAILTO:%[email protected]' %
                                    creator.get('login'))
            organizer.params['cn'] = vText(creator.get('login'))

            event['organizer'] = organizer

            cal.add_component(event)

    mimetype = 'text/x-calendar'
    headers = {
        'Content-Disposition': 'attachment;filename=github-calendar.ics'
    }

    return Response(response=cal.to_ical(),
                    status=200,
                    mimetype=mimetype,
                    headers=headers)
Example #54
0
def icalendar(request):
	if not request.user:
		request.response.status=403
	#	return HTTPFound(location = request.route_url('user_login'))
	cal = Calendar()
	cal.add('prodid', '-//MÜSLI - Mathematisches Übungsgruppen- und Scheinlisten-Interface//https://mathi.uni-heidelberg.de/muesli///')
	cal.add('version', '2.0')

        # Lecture information cannot be added, since lecture times are not handled within MÜSLI

        # Get some information about the user
	attendee = vCalAddress('MAILTO:' + request.user.email)
	attendee.params['cn'] = vText(request.user.name)
	attendee.params['ROLE'] = vText('REQ-PARTICIPANT')

        # Begin with tutorials
        for tutorial in request.user.all_tutorials.options(joinedload(Tutorial.tutor), joinedload(Tutorial.lecture)):
	        event = Event()
	        event.add('summary', 'Tutorium: ' + Tutorial.lecture.name)
                # Oh Gosh! We need to parse this horrible time format to create a real date :(
                # Actually not, this will be too error-prone
                year = int(tutorial.lecture.term.value[0:4])
	        event.add('dtstart', datetime(2005,4,4,8,0,0,tzinfo=pytz.utc)) # For these lines we need a new structure to hold Events in tutorials
	        event.add('dtend', datetime(2005,4,4,10,0,0,tzinfo=pytz.utc)) # We also need a UI to enter event-details for the tutors
	        event.add('dtstamp', datetime(2005,4,4,0,10,0,tzinfo=pytz.utc))
	        organizer = vCalAddress('MAILTO:' + tutorial.tutor.email)
	        organizer.params['cn'] = vText(tutorial.tutor.name)
	        event['location'] = vText(tutorial.tutor.name)
	        event['uid'] = '20050115T101010/[email protected]' # TODO
	        #event.add('priority', 5)
	        event.add('attendee', attendee, encode=0) # mark the user as attendee
	        cal.add_component(event)

        # Now exams
        # TODO
	return cal.to_ical()
Example #55
0
def create_meetingrequest(basedate, user, organiser):
    event = Event()
    event.add('summary', 'Simple Meeting Request invite')
    event.add(
        'description',
        'This is a simple meeting request generated by an awesome script')
    event.add('uid', "meetingrequest-event-1")
    event.add('location', "Hamburg")

    start = basedate.replace(hour=10, minute=0)
    end = start + timedelta(hours=1)

    event.add('dtstart', start)
    event.add('dtend', end)
    event.add('dtstamp', basedate)
    event.add('priority', 5)
    event.add('status', 'CONFIRMED')
    event.add('transp', 'OPAQUE')
    event.add('sequence', 1)

    # Organiser
    vcalorg = vCalAddress('MAILTO:{}'.format(organiser.email))
    vcalorg.params['cn'] = vText(organiser.fullname)
    vcalorg.params['role'] = vText('CHAIR')

    event['organizer'] = vcalorg

    # Attendee
    attendee = vCalAddress('MAILTO:{}'.format(user.email))
    attendee.params['cn'] = vText(user.fullname)
    attendee.params['ROLE'] = vText('REQ-PARTICIPANT')
    attendee.params['PARTSTAT'] = vText('NEEDS-ACTION')
    attendee.params['RSVP'] = vText('TRUE')
    event.add('attendee', attendee, encode=0)

    return event
Example #56
0
    def generate_ics(self, event_slug):
        # Get the event json from our source
        source_status = self.get_event_json(event_slug)
        if source_status != 200:
            return HttpResponse('', status=source_status)

        # Create the Calendar
        calendar = icalendar.Calendar()
        calendar.add('prodid', self.event_calendar_prodid)
        calendar.add('version', '2.0')
        calendar.add('method', 'publish')

        # Create the event
        event = icalendar.Event()

        # Populate the event
        event.add('summary', self.get_field_value('event_summary'))
        event.add('uid', self.get_field_value('event_uid'))
        event.add('location', self.get_field_value('event_location'))
        dtstart = self.make_date_tz_aware(
            self.get_field_value('event_dtstart'), 'starting_tzidnfo')
        dtend = self.make_date_tz_aware(self.get_field_value('event_dtend'),
                                        'ending_tzidnfo')
        event.add('dtstart', dtstart)
        event.add('dtend', dtend)
        event.add('dtstamp', parse(self.get_field_value('event_dtstamp')))
        event.add('status', self.get_field_value('event_status'))

        # Create any persons associated with the event
        if self.get_field_value('event_organizer_addr') and \
                self.get_field_value('event_organizer'):
            organizer = icalendar.vCalAddress(
                'MAILTO:' + self.get_field_value('event_organizer_addr'))
            organizer.params['cn'] = icalendar.vText(
                self.get_field_value('event_organizer'))
            event.add('organizer', organizer)

        # Add the event to the calendar
        calendar.add_component(event)

        # Return the ICS formatted calendar
        response = HttpResponse(calendar.to_ical(),
                                content_type='text/calendar',
                                status=source_status,
                                charset='utf-8')
        response['Content-Disposition'] = 'attachment;filename={}.ics'.format(
            event_slug)
        return response
Example #57
0
    def generate_ics(self, event_slug):
        # Get the event json from our source
        source_status = self.get_event_json(event_slug)
        if source_status != 200:
            return HttpResponse('', status=source_status)

        # Create the Calendar
        calendar = icalendar.Calendar()
        calendar.add('prodid', self.event_calendar_prodid)
        calendar.add('version', '2.0')
        calendar.add('method', 'publish')

        # Create the event
        event = icalendar.Event()

         # Populate the event
        event.add('summary', self.get_field_value('event_summary'))
        event.add('uid', self.get_field_value('event_uid'))
        event.add('location', self.get_field_value('event_location'))
        dtstart = self.make_date_tz_aware(self.get_field_value('event_dtstart'),
                                          'starting_tzidnfo')
        dtend = self.make_date_tz_aware(self.get_field_value('event_dtend'),
                                        'ending_tzidnfo')
        event.add('dtstart', dtstart)
        event.add('dtend', dtend)
        event.add('dtstamp', parse(self.get_field_value('event_dtstamp')))
        event.add('status', self.get_field_value('event_status'))

        # Create any persons associated with the event
        if self.get_field_value('event_organizer_addr') and \
                self.get_field_value('event_organizer'):
            organizer = icalendar.vCalAddress(
                'MAILTO:' + self.get_field_value('event_organizer_addr'))
            organizer.params['cn'] = icalendar.vText(
                self.get_field_value('event_organizer'))
            event.add('organizer', organizer)

        # Add the event to the calendar
        calendar.add_component(event)

        # Return the ICS formatted calendar
        response = HttpResponse(calendar.to_ical(),
                                content_type='text/calendar',
                                status=source_status,
                                charset='utf-8')
        response['Content-Disposition'] = 'attachment;filename={}.ics'.format(
            event_slug)
        return response
Example #58
0
	def add_attendee(self, email, cn=None, rsvp=True):
		"""
		Add an attendee to the event. If the event is being sent via an email,
		the recipient should be added as an attendee.

		:param str email: The attendee's email address.
		:param str cn: The attendee's common name.
		:param bool rsvp: Whether or not to request an RSVP response from the
			attendee.
		"""
		attendee = icalendar.vCalAddress('MAILTO:' + email)
		attendee.params['ROLE'] = icalendar.vText('REQ-PARTICIPANT')
		attendee.params['PARTSTAT'] = icalendar.vText('NEEDS-ACTION')
		attendee.params['RSVP'] = icalendar.vText(str(bool(rsvp)).upper())
		attendee.params['CN'] = icalendar.vText(cn or email)
		self._event.add('attendee', attendee)
    def test_property_params(self):
        cal_address = icalendar.vCalAddress('mailto:[email protected]')
        cal_address.params["CN"] = "Doe, John"
        ical = icalendar.Calendar()
        ical.add('organizer', cal_address)

        ical_str = icalendar.Calendar.to_ical(ical)
        exp_str = """BEGIN:VCALENDAR\r\nORGANIZER;CN="Doe, John":"""\
                  """mailto:[email protected]\r\nEND:VCALENDAR\r\n"""

        self.assertEqual(ical_str, exp_str)

        # other way around: ensure the property parameters can be restored from
        # an icalendar string.
        ical2 = icalendar.Calendar.from_ical(ical_str)
        self.assertEqual(ical2.get('ORGANIZER').params.get('CN'), 'Doe, John')