Пример #1
0
def ical_view(request):
    from icalendar import Calendar, Event, Alarm
    start = date.today().replace(day=1)
    end = start + timedelta(days=365)
    cal = Calendar()
    cal.add('prodid', '-//TogetherCal//%s//HE' % request.META['HTTP_HOST'])
    cal.add('version', '1.0')
    cal['dtstart'] = start
    cal['dtend'] = end
    for occurrence in Occurrence.objects.filter(date__range=(start, end)).iterator():
        e = occurrence.get_event_as_subclass()
        if not isinstance(e, WeeklyActivity):
            event = Event()
            event.add('uid', '%d@%s' % (occurrence.pk, request.META['HTTP_HOST']))
            event.add('summary', e.title)
            event.add('dtstamp', occurrence.date)
            event.add('class', 'PRIVATE')
            event.add('categories', occurrence.event_class_name())
            alarm = Alarm()
            alarm.add('action', 'DISPLAY')
            alarm.add('description', e.title)
            alarm.add('trigger', timedelta(hours=-1))
            event.add_component(alarm)
            cal.add_component(event)
    response = HttpResponse(cal.to_ical(), content_type='text/calendar')
    response['Content-Disposition'] = 'filename="family.ics"'
    return response
Пример #2
0
def __add_event(name, times, location, teacher, student_id):
    event = Event()
    event.add('transp', 'TRANSPARENT')
    summary = name
    if location != 'None':
        summary = name + '@' + location
        event.add('location', location)
    description = times[4] + times[5]
    if teacher != 'None':
        description += '\n教师:' + teacher + '\n'
    description += '由 EveryClass (http://every.admirable.one) 导入'
    event.add('summary', summary)
    event.add('description', description)
    event.add('dtstart', times[0])
    event.add('dtend', times[1])
    event.add('last-modified', datetime.now())
    event['uid'] = 'ec-CSU' + student_id + 't' + datetime.now().strftime(
        '%y%m%d%H%M%S%f') + '@admirable.one'
    event.add('rrule', {
        'freq': 'weekly',
        'interval': times[2],
        'until': times[3]
    })
    alarm = Alarm()
    alarm.add('action', 'none')
    alarm.add('trigger', datetime(1980, 1, 1, 3, 5, 0))
    event.add_component(alarm)
    return event
Пример #3
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()
Пример #4
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')
Пример #5
0
def write_calendar(summary: str, start: datetime, end: datetime,
                   description: str, location: str, oponent_info: str):
    calname = "ltc-herren1-" + datetime.strftime(start, "%Y%m%d") + ".ics"
    t_cal = Calendar()
    t_cal.add('prodid',
              '-//LTC Herren 1 Kalender//ltc-scraper.py by Bartosz Swiatek//')
    t_cal.add('version', '2.0')
    t_cal.add('method', 'request')
    event = Event()
    event.add('uid', uuid.uuid4().hex)
    event.add('summary', summary)
    event.add('dtstart', start)
    event.add('dtend', end)
    event.add('description', description)
    event.add('last-modified', datetime.now())
    event.add('dtstamp', datetime.now())
    event.add('location', location)
    event.add('comment', oponent_info)
    alarm = Alarm()
    alarm.add('action', 'DISPLAY')
    alarm.add('TRIGGER;RELATED=START', '-P1D')
    alarm.add('description', 'Erinnerung zum Punktspiel')
    event.add_component(alarm)
    t_cal.add_component(event)
    cal.add_component(event)
    cwd = os.getcwd()
    f = open(os.path.join(cwd, calname), 'wb')
    f.write(t_cal.to_ical())
    f.close()
    del alarm
    del event
    del t_cal
Пример #6
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)
Пример #7
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()
Пример #8
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()
Пример #9
0
def writeICS(format_time_list, row):
    f_year = int(format_time_list[0])
    f_month = int(format_time_list[1])
    f_day = int(format_time_list[2])

    # Event Docs:
    # https://www.kanzaki.com/docs/ical/
    event = Event()
    alarm = Alarm()
    alarm.add("description", "This is an event reminder")
    alarm.add("action", "DISPLAY")
    alarm.add("trigger", timedelta(minutes=-10))

    event.add("rrule", {"freq": "yearly"})
    event.add("summary", row["Name"])
    event.add("dtstart",
              datetime(f_year, f_month, f_day, alert_begin, 0, 0, tzinfo=UTC))
    event.add("dtend",
              datetime(f_year, f_month, f_day, alert_end, 0, 0, tzinfo=UTC))
    event.add("dtstamp", datetime.now())
    # unique ID
    event["uid"] = str(
        datetime(f_year, f_month, f_day, alert_begin, 0, 0,
                 tzinfo=UTC)) + row["Name"]
    event.add("priority", 5)
    event.add_component(alarm)
    cal.add_component(event)

    f = open(ics_export_file, "wb")
    f.write(cal.to_ical())
    f.close()
Пример #10
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()
Пример #11
0
def computeIcsCalendar(P, ics_file_name):
    P.ics_calendar = Calendar()
    for d in range(1, MAX_SZ - 1):
        [y, m, dt, t] = swe.revjul(P.jd_start + d - 1)

        if len(P.festivals[d]) > 0:
            # Eliminate repeat festivals on the same day, and keep the list arbitrarily sorted
            P.festivals[d] = sorted(list(set(P.festivals[d])))

            summary_text = P.festivals[d]
            # this will work whether we have one or more events on the same day
            for stext in summary_text:
                if not stext.find('>>') == -1:
                    # It's an event, with a start and end time
                    event = Event()
                    [stext, t1, arrow, t2] = stext.split('|')
                    event.add('summary',
                              stext.split('|')[-1].replace('-', ' ').strip())
                    h1, m1 = t1.split(':')
                    h2, m2 = t2.split(':')
                    event.add(
                        'dtstart',
                        datetime(y,
                                 m,
                                 dt,
                                 int(h1),
                                 int(m1),
                                 tzinfo=tz(P.city.timezone)))
                    event.add(
                        'dtend',
                        datetime(y,
                                 m,
                                 dt,
                                 int(h2),
                                 int(m2),
                                 tzinfo=tz(P.city.timezone)))
                    P.ics_calendar.add_component(event)
                else:
                    event = Event()
                    # summary = re.sub('{(.*)}','\\1', )  # strip braces around numbers
                    event.add('summary', stext.replace('-', ' '))
                    event.add('dtstart', date(y, m, dt))
                    event.add('dtend',
                              (datetime(y, m, dt) + timedelta(1)).date())
                    alarm = Alarm()
                    alarm.add('action', 'DISPLAY')
                    alarm.add('trigger', timedelta(hours=-4))
                    event.add_component(alarm)
                    event['X-MICROSOFT-CDO-ALLDAYEVENT'] = 'TRUE'
                    event['TRANSP'] = 'TRANSPARENT'
                    event['X-MICROSOFT-CDO-BUSYSTATUS'] = 'FREE'

                    P.ics_calendar.add_component(event)

        if m == 12 and dt == 31:
            break

    with open(ics_file_name, 'wb') as ics_calendar_file:
        ics_calendar_file.write(P.ics_calendar.to_ical())
Пример #12
0
def icsfilemaker(data):
	cal=Calendar()
	cal.add('version','2.0')
	cal.add('prodid','-//cal test//studybuddy.com//')
	daterule=dt.datetime.now()#this is needed just to initialize the vevent
	pattern=re.compile(r'(\S+)([AP]M)')#pattern to find the first time in the textblock from the user(the times are gotten in the following format ('11:30','AM'))
	pattern1=re.compile(r'(\d+)')#pattern to get the first two digits in a timeslot(i.e. the 11 from 11:30 )
	daysrc=['MO','TU','WE','TH','FR','SA','SU']#lists of days for BYDAY
	pattern2=re.compile(r'(\S+)\s+(\S+)\s+([AP]M)')#pattern to get the time in the following format 11 00 AM
	for i in xrange(1,len(data)):#iterating over the data list
		for j in xrange(1,len(data[0])):
			if data[i][j]!='' and not(data[i][j].isspace()) and  data[i][j]!='place':#only interact with textblocks i.e.non-empty elements of the list

				if re.findall(pattern,data[i][j]):#if search is successful assign the timeslot


					timeslot=re.findall(pattern,data[i][j])#gets the time from the textblock

				elif re.findall(pattern2,data[i][j]):#if search is successful assign the timeslot and reformat each element of the timeslot list to (11:30,AM) just as above
					timeslot=re.findall(pattern2,data[i][j])
					count=0
					for a in timeslot:
						timeslot[count]=('%d:%s'%(int(a[0]),a[1]),a[2])
						count=count+1




				if len(timeslot)==2:#if it has the start and end times proceed forward

					minutes=int(re.findall(pattern1,timeslot[0][0])[1])#get the min 30 from 11:30
					nlsplit=data[i][j].split('\n')#split the text at \n since x\nx\nx\nx for each textblock


					dur=dt.datetime.strptime('%s%s'%(timeslot[1][0],timeslot[1][1]), "%I:%M%p")-dt.datetime.strptime('%s%s'%(timeslot[0][0],timeslot[0][1]), "%I:%M%p")#get the duration of each event in 24 hours time
					hour=dt.datetime.strptime('%s%s'%(timeslot[0][0],timeslot[0][1]), "%I:%M%p").hour# get the hour of the start time in 24 hours eg 11 from 11:30
					event=Event()#creating an event instance
					alarm=Alarm()#creating an alarm instance
					event.add('dtstart',daterule)#adding the start date
					event.add('exdate',daterule)#excluding the start date
					event.add('rrule',{'FREQ':'WEEKLY','BYDAY':daysrc[j-1],'BYHOUR':hour,'BYMINUTE':minutes,'BYSECOND':0,'UNTIL':datetime(2015,12,30,23,59,59)})#generate weekly events for each text block until 30 of December
					event.add('summary','%s\r\n%s'%(nlsplit[0],nlsplit[1]))#adds a title for each text block
					alarm['trigger']='-PT30M'#triggers 30 mins before 3 times at 10 min intervals and displays the message in the description
					alarm['repeat']=3
					alarm['duration']='PT10M'
					alarm['action']='DISPLAY'
					alarm['Description']='Time for %s %s'%(nlsplit[0],nlsplit[1])#Time for SWFR 3MX3 Lecture
					event.add_component(alarm)#adds the alarm to the event
					if 'AM' not in nlsplit[len(nlsplit)-1] and 'PM' not in nlsplit[len(nlsplit)-1] and ':'  not in nlsplit[len(nlsplit)-1]:#adds the location which should be the last sentence, if it is not the last sentence it is not added
						event.add('location',nlsplit[len(nlsplit)-1])

					event['duration']='PT%dH%dM'%(int(dur.total_seconds()//3600),int((dur.total_seconds()//60)%60))#calculates the duration from the dur variable which is a timedelta object, using total seconds between the start and end times for a textblock and simple math the hours and minuts are derived

					cal.add_component(event)

	file=open(os.path.expanduser("~/Desktop/cal.ics"),'w+')#creates the ics file
	file.write(cal.to_ical())
	file.close()
Пример #13
0
def genIcal(event):
  from icalendar import Calendar, Event, Alarm

  #get details from event instance
  title         = event.title
  desc          = event.title
  duration    = 3
  start         = datetime.combine(event.when, event.time)
  end           = datetime.combine(event.when, event.time) + timedelta(hours=duration)
  location      = event.location

  # Timezone to use for our dates - change as needed
  reminderHours = 3

  cal = Calendar()
  cal.add('prodid', '-//APERTA calendar application//aperta.lu//')
  cal.add('version', '2.0')
  cal.add('method', "REQUEST")

  vevent = Event()
#  event.add('attendee', self.getEmail())
  vevent.add('organizer', settings.EMAILS['sender']['default'])
  vevent.add('status', "confirmed")
  vevent.add('category', "Event")
  vevent.add('summary', title)
  vevent.add('description', desc)
  vevent.add('location', location)
  vevent.add('dtstart', start)
  vevent.add('dtend', end)
  from attendance.functions import gen_hash
  vevent['uid'] = gen_hash(event,settings.EMAILS['sender']['default'])[:10] # Generate some unique ID
  vevent.add('priority', 5)
  vevent.add('sequence', 1)
  vevent.add('created', timezone.now())

  alarm = Alarm()
  alarm.add("action", "DISPLAY")
  alarm.add('description', "Reminder")
  alarm.add("trigger", timedelta(hours=-reminderHours))
  # The only way to convince Outlook to do it correctly
  alarm.add("TRIGGER;RELATED=START", "-PT{0}H".format(reminderHours))
  vevent.add_component(alarm)
  cal.add_component(vevent)

  #gen file to be attached to an email
  from email import MIMEBase, Encoders

  filename = "invite.ics"
  invite = MIMEBase.MIMEBase('text', "calendar", method="REQUEST", name=filename)
  invite.set_payload( cal.to_ical() )
  Encoders.encode_base64(invite)
  invite.add_header('Content-Description', desc)
  invite.add_header("Content-class", "urn:content-classes:calendarmessage")
  invite.add_header("Filename", filename)
  invite.add_header("Path", filename)

  return invite
Пример #14
0
 def get_ical_event(self):
     event = Event()
     event.add('summary', self.summary)
     event.add('dtstart', self.date_start)
     event.add('dtend', self.date_end)
     event['location'] = self.location
     event.add('status', 'TENTATIVE')
     event.add_component(self.ALARM)
     return event
Пример #15
0
def session_ical(session):
    event = Event()
    event.add('summary', session.title)
    event.add(
        'uid', "/".join([session.proposal_space.name, session.url_name]) +
        '@' + request.host)
    event.add(
        'dtstart',
        utc.localize(session.start).astimezone(
            timezone(session.proposal_space.timezone)))
    event.add(
        'dtend',
        utc.localize(session.end).astimezone(
            timezone(session.proposal_space.timezone)))
    event.add(
        'dtstamp',
        utc.localize(datetime.now()).astimezone(
            timezone(session.proposal_space.timezone)))
    event.add(
        'created',
        utc.localize(session.created_at).astimezone(
            timezone(session.proposal_space.timezone)))
    event.add(
        'last-modified',
        utc.localize(session.updated_at).astimezone(
            timezone(session.proposal_space.timezone)))
    if session.venue_room:
        location = [
            session.venue_room.title + " - " + session.venue_room.venue.title
        ]
        if session.venue_room.venue.city:
            location.append(session.venue_room.venue.city)
        if session.venue_room.venue.country:
            location[len(location) -
                     1] += ", " + session.venue_room.venue.country
        else:
            location.append(session.venue_room.venue.country)
        event.add('location', "\n".join(location))
        if session.venue_room.venue.latitude and session.venue_room.venue.longitude:
            event.add('geo', (session.venue_room.venue.latitude,
                              session.venue_room.venue.longitude))
    if session.description_text:
        event.add('description', session.description_text)
    if session.proposal:
        event.add('url', session.url_for(_external=True))
        if session.proposal.section:
            event.add('categories', [session.proposal.section.title])
    alarm = Alarm()
    alarm.add('trigger', timedelta(minutes=-5))
    alarm.add('action', 'display')
    desc = session.title
    if session.venue_room:
        desc += " in " + session.venue_room.title
    desc += " in 5 minutes"
    alarm.add('description', desc)
    event.add_component(alarm)
    return event
Пример #16
0
    def generate_ical():
        """generate ics file"""
        cal = Calendar()
        cal['version'] = '2.0'
        cal['prodid'] = '-//Simon Fraser University//Svenja Cao//EN'

        for class_item in classes:
            for lesson in class_item['lessons']:
                start_date = data.datelize(lesson['start_date'])
                start_time = data.timelize(lesson['start_time'])
                end_time = data.timelize(lesson['end_time'])
                start = data.time_zone(datetime.combine(start_date, start_time))  # class start datetime
                end = data.time_zone(datetime.combine(start_date, end_time))  # class end datetime
                end_date = data.datelize(lesson['end_date'])
                until = datetime.combine(end_date, end_time)  # recurrence end datetime
                for day in lesson['days']:
                    event = Event()
                    if lesson['start_date'] == lesson['end_date']:
                        # the lesson with same start and end date is the Exam
                        event.add('summary', class_item['name'] + ' Exam')
                    else:
                        event.add('summary', class_item['name'] + ' ' + class_item['component'])
                    event.add('dtstart', start)
                    event.add('dtend', end)
                    event.add('rrule', {'freq': 'weekly', 'byday': day, 'until': until, 'wkst': 'SU'})
                    # byday doesn't support list for now
                    event.add('location', lesson['location'])
                    description = 'Description: ' + class_item['description'] + '\nSection: ' + class_item['section']
                    if 'instructor' in lesson:  # the Final has no instructor
                        description = 'Instructor: ' + lesson['instructor'] + '\n' + description
                    event.add('description', description)

                    if start_date.weekday() == data.weekdays[day]:
                        # if a course has class on first day, the first day won't be ignored
                        # see weekdays{}
                        exdates = []
                    else:
                        exdates = [start]
                    for holiday in data.holidays[year]:
                        exdates.append(datetime.combine(holiday, start_time))
                    event.add('exdate', exdates)

                    if alert and unicode(alert).isnumeric():
                        alarm = Alarm()
                        alarm.add('action', 'DISPLAY')

                        alert_time = timedelta(minutes=-int(alert))
                        alarm.add('trigger', alert_time)
                        event.add_component(alarm)

                    event['uid'] = str(uuid1()) + '@SFU'
                    cal.add_component(event)
        return cal.to_ical()
Пример #17
0
    def save(self, *args, **kwargs):
        if not self.pk and self.user.receive_emails:
            ical = Calendar()
            subject = "You have been selected for cleaning"
            ical["method"] = "REQUEST"
            ical["PRODID"] = "Microsoft Exchange Server 2010"
            ical["VERSION"] = "2.0"
            evt = Event()
            evt["summary"] = "Coffee Machine Cleaning"
            evt["description"] = subject
            evt["dtstart"] = format(self.date)
            evt["dstend"] = format(self.date + datetime.timedelta(days=1))
            evt["dtstamp"] = format(datetime.datetime.now())
            evt["class"] = "PUBLIC"
            evt["organizer"] = "MAILTO:%s" % server.settings.MAIL_SENDER
            evt["location"] = "BPM Lighthouse"
            evt["priority"] = "5"
            evt["status"] = "CONFIRMED"
            evt["transp"] = "OPAQUE"
            evt["sequence"] = "0"
            evt["uid"] = int(random.random()*10**17)
            evt["X-MICROSOFT-CDO-APPT-SEQUENCE"] = "0"
            evt["X-MICROSOFT-CDO-OWNERAPPTID"] = "2113312661"
            evt["X-MICROSOFT-CDO-BUSYSTATUS"] = "TENTATIVE"
            evt["X-MICROSOFT-CDO-INTENDEDSTATUS"] = "BUSY"
            evt["X-MICROSOFT-CDO-ALLDAYEVENT"] = "TRUE"
            evt["X-MICROSOFT-CDO-IMPORTANCE"] = "1"
            evt["X-MICROSOFT-CDO-INSTTYPE"] = "0"
            evt["X-MICROSOFT-DISALLOW-COUNTER"] = "FALSE"
            alarm = Alarm()
            alarm["action"] = "DISPLAY"
            alarm["description"] = "REMINDER"
            alarm["TRIGGER;RELATED=START"] = "-PT15M"
            evt.add_component(alarm)
            ical.add_component(evt)

            content = render_to_string("mail-schedule.txt", {
                           "firstname": self.user.first_name,
                           "lastname": self.user.last_name,
                           "date": self.date,
                           "type": dict(ScheduleEntryTypes).get(self.type, "cleaning"),
                           "mail": self.user.email,
                           "subject": subject,
                           "ical": base64.b64encode(ical.to_ical()),
                           "id": int(random.random()*10**17),
                           "sender_mail": MAIL_SENDER
                       })
            send_email_plain(MAIL_SENDER,
                       [self.user.email],
                       content
            )

        super(ScheduleEntry, self).save(*args, **kwargs)
Пример #18
0
def json2ical(sdata):
    """
    Convert epresence conferences
    sdata: conference list in json format (returned from fetch_conf_list)
    returns a string, the iCal, to be written to a file e.g.

    """

    import json
    from icalendar import Calendar, Event, Alarm
    from datetime import datetime
    import pytz
    data = json.loads(sdata)

    if data:

        cal = Calendar()
        cal.add('prodid', '-//Gamisterous epresence ical generator//lala.la//')
        cal.add('version', '3.0')
        cal.add('X-WR-CALNAME', 'Τηλεδιασκέψεις')
        local = pytz.timezone("Europe/Athens")

        for dato in data:

            confid = dato["cellID"]
            desc = dato["cellDesc"]
            start = datetime.strptime(
                dato["cellStartDate"] + "-" + dato["cellStartTime"],
                "%d-%m-%Y-%H:%M")
            end = datetime.strptime(
                dato["cellStartDate"] + "-" + dato["cellEndTime"],
                "%d-%m-%Y-%H:%M")
            now = datetime.now()

            event = Event()
            event.add('SUMMARY', desc)
            event.add('DTSTART', local.localize(start))
            event.add('DURATION', end - start)
            event.add('DTEND', local.localize(end))
            event.add('DTSTAMP', datetime.now())
            event.add('URL', 'https://new.epresence.grnet.gr')
            event['UID'] = "conf" + confid + "@conferences"

            # add a reminder 30m earlier
            alarm = Alarm()
            alarm.add("action", "DISPLAY")
            alarm.add('description', "Reminder")
            alarm.add("TRIGGER;RELATED=START", "-PT30M")
            event.add_component(alarm)

            cal.add_component(event)

        return cal.to_ical()
Пример #19
0
def generate_event(subject: str, payment_date: datetime.date) -> Event:
    evt = Event()
    evt.add("summary", subject)
    notification_time = datetime.time(11, 0)
    payment_datetime = datetime.datetime.combine(payment_date,
                                                 notification_time)
    evt.add("dtstart", payment_datetime)
    evt.add("dtend", payment_datetime + datetime.timedelta(hours=1))
    evt.add("dtstamp", datetime.datetime.now())
    alarm = Alarm()
    alarm.add("trigger", datetime.timedelta(minutes=0))
    evt.add_component(alarm)
    return evt
Пример #20
0
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)
Пример #21
0
def genCalendarFromEventsFile( events_file, cal_file ):
	try:
		events = SimpleEvents( events_file )
		cal = Calendar()
		cal.add('prodid', '-//calgen.py//xmpp.org//')
		cal.add('version', '2.0')
		day = timedelta(days=1)
	
		for ev in events.getEventList():
			event = Event()
			if "date" in ev:
				ev["date"] = ev["date"].rstrip("Z")
			
			if "all-day" in ev:
				start = datetime.strptime(ev["date"], "%Y-%m-%d") # T%H:%M:%S
				event.add('dtstart', start.date())
				event.add('dtend', (start + day).date())
				event.add("dtstamp", (start + day).date())
			else:
				start = datetime.strptime(ev["date"], "%Y-%m-%dT%H:%M:%S")
				start = start.replace(tzinfo=UTC)
				duration = timedelta(minutes=int(ev["duration"]))
				event.add('dtstart', start)
				event.add('dtend', (start + duration))
				event.add("dtstamp", (start + duration))
			if "alarm" in ev:
				alarm = Alarm()
				alarm_time = datetime.strptime(ev["date"], "%Y-%m-%dT%H:%M:%S")
				alarm_time = alarm_time.replace(tzinfo=UTC)
				alarm_time = alarm_time - timedelta(minutes=15)
				alarm.add("trigger", alarm_time)
				alarm.add("action", "display")
				event.add_component(alarm)
			if "summary" in ev:
				event.add('summary', ev["summary"])
			if "description" in ev:
				event.add('description', ev["description"])
			if "url" in ev:
				event.add('url', ev["url"])
			
			cal.add_component(event)
			allevents.append(event)
	
		f = open( cal_file , 'wb')
		f.write(cal.as_string())
		f.close()
	except:
		print "File not found! - " + events_file
		print "Unexpected error:", sys.exc_info()[0]
		traceback.print_exc(file=sys.stdout)
Пример #22
0
def genCalendarFromEventsFile(events_file, cal_file):
    try:
        events = SimpleEvents(events_file)
        cal = Calendar()
        cal.add('prodid', '-//calgen.py//xmpp.org//')
        cal.add('version', '2.0')
        day = timedelta(days=1)

        for ev in events.getEventList():
            event = Event()
            if "date" in ev:
                ev["date"] = ev["date"].rstrip("Z")

            if "all-day" in ev:
                start = datetime.strptime(ev["date"], "%Y-%m-%d")  # T%H:%M:%S
                event.add('dtstart', start.date())
                event.add('dtend', (start + day).date())
                event.add("dtstamp", (start + day).date())
            else:
                start = datetime.strptime(ev["date"], "%Y-%m-%dT%H:%M:%S")
                start = start.replace(tzinfo=UTC)
                duration = timedelta(minutes=int(ev["duration"]))
                event.add('dtstart', start)
                event.add('dtend', (start + duration))
                event.add("dtstamp", (start + duration))
            if "alarm" in ev:
                alarm = Alarm()
                alarm_time = datetime.strptime(ev["date"], "%Y-%m-%dT%H:%M:%S")
                alarm_time = alarm_time.replace(tzinfo=UTC)
                alarm_time = alarm_time - timedelta(minutes=15)
                alarm.add("trigger", alarm_time)
                alarm.add("action", "display")
                event.add_component(alarm)
            if "summary" in ev:
                event.add('summary', ev["summary"])
            if "description" in ev:
                event.add('description', ev["description"])
            if "url" in ev:
                event.add('url', ev["url"])

            cal.add_component(event)
            allevents.append(event)

        f = open(cal_file, 'wb')
        f.write(cal.as_string())
        f.close()
    except:
        print "File not found! - " + events_file
        print "Unexpected error:", sys.exc_info()[0]
        traceback.print_exc(file=sys.stdout)
Пример #23
0
def html_to_ical(html_string):
    """Convert an html string from the pointstreak website to ical format
    
    Args: html_string - String representing the entire pointstreak schedule page
    
    Returns: Calendar object representing schedule
    """
    tree = html.fromstring(html_string)
    team = tree.xpath("//title")[0].text_content().split('-')[0].strip()
    schedule_tables = tree.xpath("//table/tr/td[contains(.,'Team Schedule')]")
    # First match is the table that contains all tables, second is the header in a td
    schedule_table = schedule_tables[1].getparent().getparent().getnext()
    # Get home v away, date, time, rink
    now = datetime.now()
    calendar = Calendar()
    calendar.add('x-wr-calname', 'Schedule for %s' % (team))
    for row in schedule_table.iter('tr'):
        try:
            #print etree.tostring(row)
            rink = row[4].text_content()
            if rink.startswith('final'):
                # Game is already played
                continue
            rink = rink.strip()
            home = row[0].text_content()
            away = row[1].text_content()
            date_str = ' '.join(
                [row[2].text_content(), row[3].text_content(),
                 str(now.year)])
            tstamp = datetime.strptime(date_str, "%a, %b %d %I:%M %p %Y")
            # For whatever reason, the year is never printed
            if tstamp < now:
                tstamp.replace(year=tstamp.year + 1)
            uid = tstamp.strftime('%Y%m%d%H%M') + '@pugswald.com'
            event = Event()
            event.add('uid', uid)
            event.add('dtstart', tstamp)
            event.add('summary', 'Hockey game %s vs %s' % (home, away))
            event.add('dtend', tstamp + timedelta(minutes=90))
            event.add('location', rink)
            alarm = Alarm()
            alarm.add('action', 'AUDIO')
            alarm.add('trigger', timedelta(minutes=-60))
            event.add_component(alarm)
            calendar.add_component(event)
        except:
            #print sys.exc_info()
            pass  # This block is not good data
    return calendar
Пример #24
0
def festival_instance_to_event(festival_instance,
                               languages,
                               scripts,
                               panchaanga,
                               all_day=False):
    rules_collection = rules.RulesCollection.get_cached(
        repos_tuple=tuple(
            panchaanga.computation_system.festival_options.repos),
        julian_handling=panchaanga.computation_system.festival_options.
        julian_handling)
    fest_details_dict = rules_collection.name_to_rule
    fest_name = festival_instance.get_best_transliterated_name(
        languages=languages,
        scripts=scripts,
        fest_details_dict=rules_collection.name_to_rule)["text"].replace(
            "~", " ")
    if festival_instance.ordinal is not None:
        fest_name += ' #%s' % custom_transliteration.tr(
            str(festival_instance.ordinal), scripts[0])
    event = Event()
    event.add('summary', fest_name)
    desc = get_description(festival_instance=festival_instance,
                           script=scripts[0],
                           fest_details_dict=fest_details_dict,
                           header_md="##")
    event.add('description', desc.strip().replace('\n', '<br/>'))

    if all_day or not festival_instance._show_interval():
        t1 = panchaanga.city.get_timezone_obj().julian_day_to_local_datetime(
            jd=festival_instance.interval.jd_start)
        t2 = panchaanga.city.get_timezone_obj().julian_day_to_local_datetime(
            jd=festival_instance.interval.jd_end)
        event.add('dtstart', t1.date())
        event.add('dtend', t2.date())
        event['X-MICROSOFT-CDO-ALLDAYEVENT'] = 'TRUE'
        event['TRANSP'] = 'TRANSPARENT'
        event['X-MICROSOFT-CDO-BUSYSTATUS'] = 'FREE'
    elif festival_instance.interval is not None and festival_instance.interval.jd_end is not None and festival_instance.interval.jd_start is not None:
        # Starting or ending time is empty, e.g. harivasara, so no ICS entry
        t1 = panchaanga.city.get_timezone_obj().julian_day_to_local_datetime(
            jd=festival_instance.interval.jd_start)
        t2 = panchaanga.city.get_timezone_obj().julian_day_to_local_datetime(
            jd=festival_instance.interval.jd_end)
        event.add('dtstart', t1)
        event.add('dtend', t2)

    alarm = get_4_hr_display_alarm()
    event.add_component(alarm)
    return event
Пример #25
0
def get_day_summary_event(d, panchaanga, script):
  daily_panchaanga = panchaanga.daily_panchaangas_sorted()[d]
  event = Event()
  (title, details) = day_summary(d=d, panchaanga=panchaanga, script=script, subsection_md="##")
  event.add('summary', title)
  event.add('description', details)
  tz = daily_panchaanga.city.get_timezone_obj()
  dt_start = tz.julian_day_to_local_datetime(jd=daily_panchaanga.jd_sunrise)
  event.add('dtstart', dt_start)
  event.add('dtend', tz.julian_day_to_local_datetime(jd=daily_panchaanga.jd_next_sunrise))
  event.add_component(util.get_4_hr_display_alarm())
  event['X-MICROSOFT-CDO-ALLDAYEVENT'] = 'TRUE'
  event['TRANSP'] = 'TRANSPARENT'
  event['X-MICROSOFT-CDO-BUSYSTATUS'] = 'FREE'
  return event
Пример #26
0
 def create_event(self, summary, description, start):
     """Create a 30 minute calendar event without a reminder"""
     event = Event()
     no_alarm = Alarm()
     event.add('summary', summary)
     event.add('description', description)
     event.add('dtstart', start)
     event.add('dtend', start + relativedelta(minutes=30))
     event.add('dtstamp', start)
     #    event.add('location', location)
     no_alarm.add('action', 'NONE')
     no_alarm.add('trigger', start - relativedelta(
         years=1))  # Set an alarm date before the event to remove reminder
     event.add_component(no_alarm)
     self.cal.add_component(event)
Пример #27
0
def create_timetable_ical(semester: Semester, lectures: List[Lecture],
                          language: str):
    is_english = language and ("en" in language)

    timezone = pytz.timezone("Asia/Seoul")

    calendar = Calendar()
    calendar.add("prodid", "-//SPARCS//OTL Plus//")
    calendar.add("version", "2.0")
    calendar.add("x-wr-timezone", timezone)

    title = f"[OTL] {semester.get_name(language='en').title()}"
    calendar.add("summary", title)
    calendar.add("x-wr-calname", title)

    for l in lectures:
        for ct in l.classtimes.all():
            event = Event()
            event.add("summary", l.title if not is_english else l.title_en)
            event.add(
                "location",
                ct.get_classroom_strs()[2]
                if not is_english else ct.get_classroom_strs()[3])

            days_ahead = ct.day - semester.beginning.weekday()
            if days_ahead < 0:
                days_ahead += 7
            first_class_date = semester.beginning + datetime.timedelta(
                days=days_ahead)
            event.add(
                "dtstart",
                datetime.datetime.combine(first_class_date, ct.begin,
                                          timezone))
            event.add(
                "dtend",
                datetime.datetime.combine(first_class_date, ct.end, timezone))
            event.add("rrule", {"freq": "weekly", "until": semester.end})

            alarm = Alarm()
            alarm.add("action", "DISPLAY")
            alarm.add("trigger", datetime.timedelta(minutes=-15))
            event.add_component(alarm)

            calendar.add_component(event)

    return calendar
Пример #28
0
 def getiCalFromEventlist(self, eventlist, alarm):
     cal = Calendar()
     cal.add('prodid', 'trashpyle')
     cal.add('version', '0.1')
     for event in eventlist:
         icalevent = Event()
         icalevent.add('dtstart', event[0])
         icalevent.add('dtend', event[0] + timedelta(days=1))
         icalevent.add('summary', self.getNameStringFromTrashType(event[1]))
         if alarm != '':
             alarmtime = timedelta(minutes=-int(alarm))
             icalalarm = Alarm()
             icalalarm.add('action','DISPLAY')
             icalalarm.add('trigger',alarmtime)
             icalevent.add_component(icalalarm)
         cal.add_component(icalevent)
     return cal.to_ical()
Пример #29
0
def gen_ical(packet):
    cal = Calendar()
    cal['version'] = '2.0'
    cal['prodid'] = '-//Zhejiang University//LIU Gengming+Chen Yuan//ZH'  # *mandatory elements* where the prodid can be changed, see RFC 5445
    courses = packet[0]
    exams = packet[1]

    for course in courses:
        for lesson in course['lessons']:
            weeks = lesson['weeks']
            for recur in weeks:
                event = Event()
                event.add('summary', unify_brackets(course['name']))
                offset_days = lesson['day'] - 1 + 7 * (int(recur) - 1)
                offset = timedelta(days=offset_days)
                classdate = week_start + offset
                start = lesson_time[lesson['start']]['start']
                end = lesson_time[lesson['end']]['end']
                event.add('dtstart', datetime.combine(classdate, start))
                event.add('dtend', datetime.combine(classdate, end))
                event.add('location', lesson['location'])
                event.add('description', u'教师:' + course['teacher'])
                event['uid'] = str(uuid1()) + '@ZJU'
                cal.add_component(event)

    for exam in exams:
        event = Event()
        event.add('summary', unify_brackets(exam['name']) + u' 考试')
        event.add('dtstart', exam['start'])
        event.add('dtend', exam['end'])
        event.add('location', exam['location'] + ' ' + exam['seat'])
        event.add('description', u'学分:' + exam['credit'])
        event['uid'] = str(uuid1()) + '@ZJU'

        alarm = Alarm()
        alarm.add('action', 'DISPLAY')
        alarm.add('trigger', timedelta(days=-7))
        alarm.add('description',
                  u'距离[%s]考试还有一周时间' % unify_brackets(exam['name']))
        alarm['uid'] = str(uuid1()) + '@ZJU'
        event.add_component(alarm)

        cal.add_component(event)

    return cal.to_ical()
Пример #30
0
def setCalendarEvent(calendar, uid, summary, location, startTime, endTime):
    event = Event()

    event.add('UID', uid)
    event.add('DTSTART;VALUE=DATE', startTime)
    event.add('DTEND;VALUE=DATE', endTime)
    event.add('SUMMARY', summary)
    event.add('SEQUENCE', '0')
    event.add('DESCRIPTION', '')
    event.add('LOCATION', location)

    alarm = Alarm()
    alarm.add('ACTION', 'NONE')
    alarm.add('TRIGGER;VALUE=DATE-TIME', '19760401T005545Z')
    alarm.add('DESCRIPTION', 'This is an event reminder')

    event.add_component(alarm)
    calendar.add_component(event)
Пример #31
0
def __add_event(name, times, location, teacher, student_id, day, time):
    """
    把 `Event` 对象添加到 `calendar` 对象中

    :param name: 课程名
    :param times: 开始和结束时间
    :param location: 课程地点
    :param teacher: 任课教师
    :param student_id: 学号
    :return: `Event` 对象
    """

    event = Event()
    event.add('transp', 'TRANSPARENT')
    summary = name
    if location != 'None':
        summary = name + '@' + location
        event.add('location', location)
    description = times[4] + times[5]
    if teacher != 'None':
        description += '\n教师:' + teacher + '\n'
    description += '由 EveryClass 每课 (https://everyclass.xyz) 导入'
    event.add('summary', summary)
    event.add('description', description)
    event.add('dtstart', times[0])
    event.add('dtend', times[1])
    event.add('last-modified', datetime.now())

    # day、time、课程名、老师、周次、地点所有元素才能组成一组超码,因此用它们字符串拼接得到的 MD5 作为唯一识别码
    event_sk = str(day) + '-' + str(
        time
    ) + '-' + name + '-' + teacher + '-' + times[4] + times[5] + '-' + location
    event['uid'] = hashlib.md5(
        event_sk.encode('utf-8')).hexdigest() + '@everyclass.xyz'
    event.add('rrule', {
        'freq': 'weekly',
        'interval': times[2],
        'until': times[3]
    })
    alarm = Alarm()
    alarm.add('action', 'none')
    alarm.add('trigger', datetime(1980, 1, 1, 3, 5, 0))
    event.add_component(alarm)
    return event
Пример #32
0
 def __getiCalFromEventlist(self, eventlist, alarm):
     cal = Calendar()
     cal.add('prodid', 'libhbtrash')
     cal.add('version', '0.1')
     for event in eventlist:
         icalevent = Event()
         icalevent.add('dtstart', event[0])
         icalevent.add('dtend', event[0] + timedelta(days=1))
         icalevent.add('summary', str(event[1]))
         if alarm != '':
             alarmtime = timedelta(minutes=-int(alarm))
             icalalarm = Alarm()
             icalalarm.add('action', 'DISPLAY')
             icalalarm.add('trigger', alarmtime)
             icalevent.add_component(icalalarm)
         cal.add_component(icalevent)
     cal = cal.to_ical()
     cal = cal.decode("utf-8")
     return cal
Пример #33
0
    def _event_to_ics(e):
        event = Event()
        if 'ics_feed_title' in e:
            event.add('summary', e['ics_feed_title'])

        if 'description' in e:
            desc_status = ""
            if 'status' in e:
                if e['status'] == 'preparation':
                    desc_status = '\nStatus: This talk is in preparation - details may change\n'
                if e['status'] == 'cancelled':
                    desc_status = '\nStatus: This talk has been cancelled\n'

            desc_with_speakers = e['description']
            speakers_list = ""
            if 'various_speakers' in e and e['various_speakers'] is True:
                speakers_list = "\nSpeakers:\n Various Speakers"
            elif 'speakers' in e:
                if len(e['speakers']):
                    speakers_list = "\nSpeakers:\n" + ", ".join(
                        speaker['get_name_with_bio']
                        for speaker in e['speakers'])
            event.add('description',
                      desc_status + desc_with_speakers + speakers_list)

        if 'start' in e:
            event.add('dtstart', dt_string_to_object(e['start']))
        if 'end' in e:
            event.add('dtend', dt_string_to_object(e['end']))
        if 'full_url' in e:
            event.add('url', e['full_url'])
            event.add('uid', e['full_url'])
        if 'location' in e:
            event.add('location', e['location'])

        alarm = Alarm()
        alarm.add('action', 'display')
        alarm.add('trigger', timedelta(hours=-1))
        if 'ics_feed_title' in e:
            alarm.add('description', "Talk:" + e['ics_feed_title'])
        event.add_component(alarm)

        return event
Пример #34
0
 def __getiCalFromEventlist(self, eventlist, alarm):
     cal = Calendar()
     cal.add('prodid', 'libhbtrash')
     cal.add('version', '0.1')
     for event in eventlist:
         icalevent = Event()
         icalevent.add('dtstart', event[0])
         icalevent.add('dtend', event[0] + timedelta(days=1))
         icalevent.add('summary', str(event[1]))
         if alarm != '':
             alarmtime = timedelta(minutes=-int(alarm))
             icalalarm = Alarm()
             icalalarm.add('action','DISPLAY')
             icalalarm.add('trigger',alarmtime)
             icalevent.add_component(icalalarm)
         cal.add_component(icalevent)
     cal = cal.to_ical()
     cal = cal.decode("utf-8")
     return cal
Пример #35
0
def session_ical(session):
    # This function is only called with scheduled sessions.
    # If for some reason it is used somewhere else and called with an unscheduled session,
    # this function should fail.
    if not session.scheduled:
        raise Exception(u"{0!r} is not scheduled".format(session))

    event = Event()
    event.add('summary', session.title)
    event.add('uid', "/".join([session.project.name, session.url_name]) + '@' + request.host)
    event.add('dtstart', utc.localize(session.start).astimezone(session.project.timezone))
    event.add('dtend', utc.localize(session.end).astimezone(session.project.timezone))
    event.add('dtstamp', utc.localize(datetime.now()).astimezone(session.project.timezone))
    event.add('created', utc.localize(session.created_at).astimezone(session.project.timezone))
    event.add('last-modified', utc.localize(session.updated_at).astimezone(session.project.timezone))
    if session.venue_room:
        location = [session.venue_room.title + " - " + session.venue_room.venue.title]
        if session.venue_room.venue.city:
            location.append(session.venue_room.venue.city)
        if session.venue_room.venue.country:
            location[len(location) - 1] += ", " + session.venue_room.venue.country
        else:
            location.append(session.venue_room.venue.country)
        event.add('location', "\n".join(location))
        if session.venue_room.venue.latitude and session.venue_room.venue.longitude:
            event.add('geo', (session.venue_room.venue.latitude, session.venue_room.venue.longitude))
    if session.description_text:
        event.add('description', session.description_text)
    if session.proposal:
        event.add('url', session.url_for(_external=True))
        if session.proposal.section:
            event.add('categories', [session.proposal.section.title])
    alarm = Alarm()
    alarm.add('trigger', timedelta(minutes=-5))
    alarm.add('action', 'display')
    desc = session.title
    if session.venue_room:
        desc += " in " + session.venue_room.title
    desc += " in 5 minutes"
    alarm.add('description', desc)
    event.add_component(alarm)
    return event
Пример #36
0
 def getEvent(self):
     event = Event()
     alarm = Alarm()
     alarm.add('UID', uuid.uuid4())
     alarm.add('TRIGGER', timedelta(minutes=-15))
     alarm.add('ACTION', 'AUDIO')
     event.add('summary', self.c_name)
     event.add('dtstart', self.getStartTime(self.time_zone))
     event.add('dtend', self.getEndTime(self.time_zone))
     event.add('dtstamp', datetime.now(tz=utc))
     event.add('location', self.classroom + ' ' + self.c_teacher)
     event['uid'] = str(uuid.uuid4())
     event.add(
         'rrule', {
             'freq': 'weekly',
             'interval': str(self.step),
             'count': str(self.end_week - self.start_week + 1)
         })
     event.add('description', self.getDescription())
     event.add_component(alarm)
     return event
Пример #37
0
def create_simple_event(basedate):
    event = Event()
    event.add('summary', 'Simple event')
    event.add('description', 'This is a simple meeting generated by an awesome script')
    event.add('uid', "simple-event-1")
    event.add('location', "Delft")

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

    event.add('dtstart', start)
    event.add('dtend', end)
    event.add('dtstamp', basedate)

    alarm = Alarm()
    alarm.add('trigger', timedelta(minutes=-5))
    alarm.add('action', 'display')
    alarm.add('description', 'meeting coming up in 5 minutes')
    event.add_component(alarm)

    return event
Пример #38
0
    def createAnIcs(self, title, starttime, endtime, place):
        '''
			title:日历的标题
			start:日历的开始时间
			endtime:日历持续的时间
			place:地点

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

        event.add('uid', str(uuid1()) + '@COUT')
        event.add('summary', title)
        event.add('dtstamp', datetime.now())
        event.add('dtstart', ev_start_datetime)
        event.add('dtend', ev_end_datetime)
        event.add('location', place)
        alarm.add('TRIGGER', ev_start_datetime)
        alarm.add('action', 'DISPLAY')
        event.add_component(alarm)
        '''
		BEGIN:VALARM
		TRIGGER:-PT15M
		ACTION:DISPLAY
		END:VALARM
		'''
        cal.add_component(event)
        with open("记忆事件.ics", "w+") as file:
            file.write(cal.to_ical().decode('utf-8'.replace('\r\n',
                                                            '\n').strip()))
            file.close()
Пример #39
0
def _build_event(course_name: str, times: Tuple[datetime, datetime],
                 classroom: str, teacher: str, current_week: int,
                 week_string: str, cid: str) -> Event:
    """
    生成 `Event` 对象

    :param course_name: 课程名
    :param times: 开始和结束时间
    :param classroom: 课程地点
    :param teacher: 任课教师
    :return: `Event` 对象
    """

    event = Event()
    event.add('transp', 'TRANSPARENT')
    summary = course_name
    if classroom != 'None':
        summary = course_name + '@' + classroom
        event.add('location', classroom)

    description = week_string
    if teacher != 'None':
        description += '\n教师:' + teacher
    description += '\n由 EveryClass 每课 (https://everyclass.xyz) 导入'

    event.add('summary', summary)
    event.add('description', description)
    event.add('dtstart', times[0])
    event.add('dtend', times[1])
    event.add('last-modified', datetime.now())

    # 使用"cid-当前周"作为事件的超码
    event_sk = cid + '-' + str(current_week)
    event['uid'] = hashlib.md5(
        event_sk.encode('utf-8')).hexdigest() + '@everyclass.xyz'
    alarm = Alarm()
    alarm.add('action', 'none')
    alarm.add('trigger', datetime(1980, 1, 1, 3, 5, 0))
    event.add_component(alarm)
    return event
Пример #40
0
    def _event_to_ics(e):
        event = Event()
        event.add('summary', e['ics_feed_title'])

        if 'description' in e:
            print 'got a description'
            desc_status = ""
            if 'status' in e:
                if e['status'] == 'preparation':
                    desc_status = '\nStatus: This talk is in preparation - details may change\n'
                if e['status'] == 'cancelled':
                    desc_status = '\nStatus: This talk has been cancelled\n'

            desc_with_speakers = e['description']
            speakers_list = ""
            if 'various_speakers' in e and e['various_speakers'] is True:
                speakers_list = "\nSpeakers:\n Various Speakers"
            elif 'speakers' in e:
                if len(e['speakers']):
                    speakers_list = "\nSpeakers:\n" + ", ".join(speaker['get_name_with_bio'] for speaker in e['speakers'])
            event.add('description', desc_status + desc_with_speakers + speakers_list)

        if 'start' in e:
            event.add('dtstart', dt_string_to_object(e['start']))
        if 'end' in e:
            event.add('dtend', dt_string_to_object(e['end']))
        if 'full_url' in e:
            event.add('url', e['full_url'])
            event.add('uid', e['full_url'])
        if 'location' in e:
            event.add('location', e['location'])

        alarm = Alarm()
        alarm.add('action', 'display')
        alarm.add('trigger', timedelta(hours=-1))
        alarm.add('description', "Talk:" + e['ics_feed_title'])
        event.add_component(alarm)

        return event
Пример #41
0
def eventFromMatch(match, team, reminder=None):
    if team == None:
        color = match.white + ' (white)'
        opponent = match.dark + ' (dark)'
    elif match.white == team:
        color = 'White'
        opponent = match.dark
    elif match.dark == team:
        color = 'Dark'
        opponent = match.white
    else:
        return None

    evt = Event()
    evt.add('summary', 'Soccer - {0} vs. {1}'.format(color, opponent))
    evt.add('dtstart', match.time)
    evt.add('dtend', match.time + timedelta(hours = 1))

    if reminder:
        evt.add_component(createReminder(reminder))

    return evt
Пример #42
0
def eventFromMatch(match, team, reminder=None):
    if team == None:
        color = match.white + ' (white)'
        opponent = match.dark + ' (dark)'
    elif match.white == team:
        color = 'White'
        opponent = match.dark
    elif match.dark == team:
        color = 'Dark'
        opponent = match.white
    else:
        return None

    evt = Event()
    evt.add('summary', 'Soccer - {0} vs. {1}'.format(color, opponent))
    evt.add('dtstart', match.time)
    evt.add('dtend', match.time + timedelta(hours=1))

    if reminder:
        evt.add_component(createReminder(reminder))

    return evt
Пример #43
0
def festival_instance_to_event(festival_instance,
                               scripts,
                               panchaanga,
                               all_day=False):
    rules_collection = rules.RulesCollection.get_cached(
        repos_tuple=tuple(panchaanga.computation_system.options.fest_repos))
    fest_details_dict = rules_collection.name_to_rule
    fest_name = festival_instance.get_best_transliterated_name(
        scripts=scripts,
        fest_details_dict=rules_collection.name_to_rule)["text"].replace(
            "~", " ")
    event = Event()
    event.add('summary', fest_name)
    desc = get_description(festival_instance=festival_instance,
                           script=scripts[0],
                           fest_details_dict=fest_details_dict)
    event.add('description', desc.strip().replace('\n', '<br/>'))

    if festival_instance.interval is not None and festival_instance.interval.jd_end is not None and festival_instance.interval.jd_start is not None:
        # Starting or ending time is empty, e.g. harivasara, so no ICS entry
        t1 = panchaanga.city.get_timezone_obj().julian_day_to_local_time(
            julian_day=festival_instance.interval.jd_start)
        t2 = panchaanga.city.get_timezone_obj().julian_day_to_local_time(
            julian_day=festival_instance.interval.jd_end)
        # we know that t1 is something like 'textsf{hh:mm(+1)}{'
        # so we know the exact positions of min and hour
        event.add('dtstart', t1.to_datetime())
        event.add('dtend', t2.to_datetime())
    if all_day:
        event['X-MICROSOFT-CDO-ALLDAYEVENT'] = 'TRUE'
        event['TRANSP'] = 'TRANSPARENT'
        event['X-MICROSOFT-CDO-BUSYSTATUS'] = 'FREE'
    alarm = Alarm()
    alarm.add('action', 'DISPLAY')
    alarm.add('trigger',
              timedelta(hours=-4))  # default alarm, with a 4 hour reminder
    event.add_component(alarm)
    return event
Пример #44
0
def session_ical(session):
    event = Event()
    event.add("summary", session.title)
    event.add("uid", "/".join([session.proposal_space.name, session.url_name]) + "@" + request.host)
    event.add("dtstart", utc.localize(session.start).astimezone(timezone(session.proposal_space.timezone)))
    event.add("dtend", utc.localize(session.end).astimezone(timezone(session.proposal_space.timezone)))
    event.add("dtstamp", utc.localize(datetime.now()).astimezone(timezone(session.proposal_space.timezone)))
    event.add("created", utc.localize(session.created_at).astimezone(timezone(session.proposal_space.timezone)))
    event.add("last-modified", utc.localize(session.updated_at).astimezone(timezone(session.proposal_space.timezone)))
    if session.venue_room:
        location = [session.venue_room.title + " - " + session.venue_room.venue.title]
        if session.venue_room.venue.city:
            location.append(session.venue_room.venue.city)
        if session.venue_room.venue.country:
            location[len(location) - 1] += ", " + session.venue_room.venue.country
        else:
            location.append(session.venue_room.venue.country)
        event.add("location", "\n".join(location))
        if session.venue_room.venue.latitude and session.venue_room.venue.longitude:
            event.add("geo", (session.venue_room.venue.latitude, session.venue_room.venue.longitude))
    if session.description_text:
        event.add("description", session.description_text)
    if session.proposal:
        event.add("url", session.url_for(_external=True))
        if session.proposal.section:
            event.add("categories", [session.proposal.section.title])
    alarm = Alarm()
    alarm.add("trigger", timedelta(minutes=-5))
    alarm.add("action", "display")
    desc = session.title
    if session.venue_room:
        desc += " in " + session.venue_room.title
    desc += " in 5 minutes"
    alarm.add("description", desc)
    event.add_component(alarm)
    return event
Пример #45
0
def add_game(cal, game):
    now_dt = datetime.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
    )

    event = Event()
    summary = '%s vs. %s' % (game.home_team, game.away_team)

    if game.color_conflict:
        desc = 'Color conflict! ({} vs. {})'.format(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 + datetime.timedelta(hours=1))
    event.add('dtstamp', datetime.datetime.now())
    event.add('location', "{}".format(game.field.short_name))
    event['uid'] = '{}/{}@breakawaysports.com'.format(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')
    if game.color_conflict:
        alarm.add('description', 'Color Conflict! - bring alternate color')

    event.add_component(alarm)
    cal.add_component(event)
Пример #46
0
def session_ical(session):
    event = Event()
    event.add('summary', session.title)
    event.add('uid', "/".join([session.proposal_space.name, session.url_name]) + '@' + request.host)
    event.add('dtstart', utc.localize(session.start).astimezone(timezone(session.proposal_space.timezone)))
    event.add('dtend', utc.localize(session.end).astimezone(timezone(session.proposal_space.timezone)))
    event.add('dtstamp', utc.localize(datetime.now()).astimezone(timezone(session.proposal_space.timezone)))
    event.add('created', utc.localize(session.created_at).astimezone(timezone(session.proposal_space.timezone)))
    event.add('last-modified', utc.localize(session.updated_at).astimezone(timezone(session.proposal_space.timezone)))
    if session.venue_room:
        location = [session.venue_room.title + " - " + session.venue_room.venue.title]
        if session.venue_room.venue.city:
            location.append(session.venue_room.venue.city)
        if session.venue_room.venue.country:
            location[len(location) - 1] += ", " + session.venue_room.venue.country
        else:
            location.append(session.venue_room.venue.country)
        event.add('location', "\n".join(location))
        if session.venue_room.venue.latitude and session.venue_room.venue.longitude:
            event.add('geo', (session.venue_room.venue.latitude, session.venue_room.venue.longitude))
    if session.description_text:
        event.add('description', session.description_text)
    if session.proposal:
        event.add('url', session.url_for(_external=True))
        if session.proposal.section:
            event.add('categories', [session.proposal.section.title])
    alarm = Alarm()
    alarm.add('trigger', timedelta(minutes=-5))
    alarm.add('action', 'display')
    desc = session.title
    if session.venue_room:
        desc += " in " + session.venue_room.title
    desc += " in 5 minutes"
    alarm.add('description', desc)
    event.add_component(alarm)
    return event
Пример #47
0
    def createEvent(self, dicEvent, UID = None):
        
        event = Event()
        ok = True 
        if self.dicCal["CalendarCreate"] =="YES":
            #print ' start create event '
            try:
                if dicEvent.has_key('summary'):
                    event.add('summary', dicEvent['summary'])
                    #print 'Summary', dicEvent['summary']
                if dicEvent.has_key('dtstart'):
                    s = time.strptime(dicEvent['dtstart'], dicEvent['DateTimeformatString'])
                    event.add('dtstart', datetime(s[0],s[1],s[2],s[3],s[4],s[5]))
                    
                    #print 'dtstart', datetime(s[0],s[1],s[2],s[3],s[4],s[5])
                else:
                    ok = False
                    
                if dicEvent.has_key('dtend'):
                    s = time.strptime(dicEvent['dtend'], dicEvent['DateTimeformatString'])
                    event.add('dtend', datetime(s[0],s[1],s[2],s[3],s[4],s[5]))
                    #print 'dtend', datetime(s[0],s[1],s[2],s[3],s[4],s[5])
                if dicEvent.has_key('dtstamp'):
                    event.add('dtstamp', dicEvent['dtstamp'])
                    #print 'stamp',  dicEvent['dtstamp']
                if not UID:
                    dicEvent['uid'] = `dicEvent['id']` + '#### ' + self.createUID()
                else:
                    dicEvent['uid'] = UID

                event.add('uid',dicEvent['uid'])

                #print 'UID', dicEvent['uid']
                if dicEvent.has_key('priority'):
                    event.add('priority',dicEvent['priority'] )
                if dicEvent.has_key('location'):
                    event.add('location',dicEvent['location'] )
                if dicEvent.has_key('status'):
                    event.add('status',dicEvent['status'] )
                if dicEvent.has_key('description'):
                    event.add('description',dicEvent['description'] )    
                if dicEvent.has_key('valarm') and dicEvent['valarm'] == True:
                    #print 0
                    oAlarm=Alarm()
                    
                    #print 1, oAlarm
                    oAlarm.add('action',"DISPLAY")
                    #oAlarm.add('value').value='DURATION'
                    #print 2, oAlarm
                    total_minutes = dicEvent['trigger']
                    idays = int(total_minutes/86400)
                    ihours  = int( (total_minutes - idays*86400) / 3600)
                    iminutes = int (total_minutes - idays*86400 - ihours*3600 )
                    #print idays, ihours, iminutes
                    #oAlarm.add('trigger',timedelta(minutes=-total_minutes  ))
                    td = timedelta(days=-idays, hours=-ihours,minutes=-iminutes)
                    #print td
                                   
                    oAlarm.add('trigger',td )
                    
                    #print 3,oAlarm
                    event.add_component(oAlarm)
                    #print 4, event, oAlarm
            except Exception, param:
                print 'Except error 55'
                print Exception
                print param

                if not ok:
                    event = None
Пример #48
0
def get(JSESSIONID,zc):
    fp=open('zc%s.ics'%zc,'wb')
    cal = Calendar()
    cal.add('version','2.0')
    word ='JSESSIONID='+JSESSIONID
    params = urllib.urlencode({'xnxqdm': 1369, 'zc': zc})
    headers = {"Content-type": "application/x-www-form-urlencoded","Cookie": word}  
    conn = httplib.HTTPConnection("192.168.176.246:8080")
    conn.request("POST", "/ntss/xskbxx!xskbList.action", params, headers)
    response = conn.getresponse()
    print response.status, response.reason
    data = response.read()
    weekdate1 = data.split('星期一<br>')
    weekdate = weekdate1[1][0:10]
    monthdate = 31
    if weekdate[5:7]=='04' or weekdate[5:7]=='06' or weekdate[5:7]=='09' or  weekdate[5:7]=='11' :
        monthdate = 30
    elif weekdate[5:7]=='02':
        monthdate = 28
    print(weekdate)
    word = data.split('[{')
    if 	len(word) == 1:
		data = ''
    else:
		word1= word[1].split('}]')
		data = '[{'+word1[0]+'}]'
		js=json.loads(data)
		for i in js:
			kcmc = i["kcmc"]
			jxcdmc = i["jxcdmc"]
			teaxm = i["teaxm"]
			jcdm = i["jcdm"]
			xq = i["xq"]
			al = Alarm()     
			al.add('TRIGGER', timedelta(0, 600))
			al.add('ACTION','DISPLAY')
			event= Event()
			event.add('summary', kcmc)
			hstart = 8
			hend = 9
			mstart = 00
			mend = 30
			day = (int(weekdate[8:10])+int(xq)-1)
			month = int(weekdate[5:7])
			if jcdm =='0304':
				hstart = 9
				hend = 11
				mstart = 40
				mend = 20
			elif jcdm == '030405':
				hstart = 9
				hend = 12
				mstart = 40
				mend = 00
			elif jcdm == '0607':
				hstart = 14
				hend = 16
				mstart = 30
				mend = 10
			elif jcdm == '060708':
				hstart = 14
				hend = 16
				mstart = 30
				mend = 40
			elif jcdm == '0809':
				hstart = 16
				hend = 17
				mstart = 10
				mend = 40
			elif jcdm == '1011':
				hstart = 18
				hend = 20
				mstart = 30
				mend = 30
			elif jcdm == '01020304':
				hstart = 8
				hend = 11
				mstart = 00
				mend = 10
			elif jcdm == '06070809':
				hstart = 14
				hend = 17
				mstart = 30
				mend = 40
			elif jcdm == '0102030405':
				hstart = 8
				hend = 12
				mstart = 00
				mend = 00
			if day>monthdate:
				day = day-monthdate
				print day
				month = month+1
			event.add('dtstart', datetime(int(weekdate[0:4]),month,day,hstart,mstart,0,tzinfo=timezone('Asia/Shanghai')))
			event.add('dtend', datetime(int(weekdate[0:4]),month,day,hend,mend,0,tzinfo=timezone('Asia/Shanghai')))
			event.add('description', jxcdmc + '--'+teaxm)
			event.add_component(al)
			cal.add_component(event)
    a=cal.to_ical()    
    fp.write(a)    
    fp.close()
    conn.close()
    pass
Пример #49
0
    def get_ics_file(self, events_exported, partner):
        """
        Returns iCalendar file for the event invitation.
        @param event: event object (browse record)
        @return: .ics file content
        """
        ics = Event()
        event = self[0]

        #~ raise Warning(self.env.cr.dbname)
        #~ The method below needs som proper rewriting to avoid overusing libraries.
        def ics_datetime(idate, allday=False):
            if idate:
                if allday:
                    return str(vDatetime(datetime.fromtimestamp(mktime(strptime(idate, DEFAULT_SERVER_DATETIME_FORMAT)))).to_ical())[:8]
                else:
                    return vDatetime(datetime.fromtimestamp(mktime(strptime(idate, DEFAULT_SERVER_DATETIME_FORMAT)))).to_ical() + 'Z'
            return False

        #~ try:
            #~ # FIXME: why isn't this in CalDAV?
            #~ import vobject
        #~ except ImportError:
            #~ return res

        #~ cal = vobject.iCalendar()
        
        #~ event = cal.add('vevent')
        if not event.start or not event.stop:
            raise osv.except_osv(_('Warning!'), _("First you have to specify the date of the invitation."))
        ics['summary'] = event.name
        if event.description:
            ics['description'] = event.description
        if event.location:
            ics['location'] = event.location
        if event.rrule:
            ics['rrule'] = event.rrule
            #~ ics.add('rrule', str(event.rrule), encode=0)
            #~ raise Warning(ics['rrule'])
        
        if event.alarm_ids:
            for alarm in event.alarm_ids:
                if alarm.type == 'notification':
                    valarm = Alarm()
                    valarm.add('ACTION', 'DISPLAY')
                    if alarm.interval == 'days':
                        delta = timedelta(days=alarm.duration)
                    elif alarm.interval == 'hours':
                        delta = timedelta(hours=alarm.duration)
                    elif alarm.interval == 'minutes':
                        delta = timedelta(minutes=alarm.duration)
                    trigger = valarm.add('TRIGGER', -delta) #fields.Datetime.from_string(event.start) - 
                    valarm.add('DESCRIPTION', event.name)
                    ics.add_component(valarm)
        if event.attendee_ids:
            for attendee in event.attendee_ids:
                attendee_add = ics.get('attendee')
                attendee_add = attendee.cn and ('CN=' + attendee.cn) or ''
                if attendee.cn and attendee.email:
                    attendee_add += ':'
                attendee_add += attendee.email and ('MAILTO:' + attendee.email) or ''
                
                ics.add('attendee', attendee_add, encode=0)
                
        if events_exported:
            event_not_found = True
            
            for event_comparison in events_exported:
                #~ raise Warning('event_comparison = %s ics = %s' % (event_comparison, ics))
                if str(ics) == event_comparison:
                    event_not_found = False
                    break
            
            if event_not_found:
                events_exported.append(str(ics))
                
                ics['uid'] = '%s@%s-%s' % (event.id, self.env.cr.dbname, partner.id)
                ics['created'] = ics_datetime(strftime(DEFAULT_SERVER_DATETIME_FORMAT))
                tmpStart = ics_datetime(event.start, event.allday)
                tmpEnd = ics_datetime(event.stop, event.allday)
                
                if event.allday:
                    ics['dtstart;value=date'] = tmpStart
                else:
                    ics['dtstart'] = tmpStart
                    
                if tmpStart != tmpEnd or not event.allday:
                    if event.allday:
                        ics['dtend;value=date'] = str(vDatetime(datetime.fromtimestamp(mktime(strptime(event.stop, DEFAULT_SERVER_DATETIME_FORMAT))) + timedelta(hours=24)).to_ical())[:8]
                    else:
                        ics['dtend'] = tmpEnd
                
                return [ics, events_exported]
            
        else:
            events_exported.append(str(ics))
            
            ics['uid'] = '%s@%s-%s' % (event.id, self.env.cr.dbname, partner.id)
            ics['created'] = ics_datetime(strftime(DEFAULT_SERVER_DATETIME_FORMAT))
            tmpStart = ics_datetime(event.start, event.allday)
            tmpEnd = ics_datetime(event.stop, event.allday)
            
            if event.allday:
                ics['dtstart;value=date'] = tmpStart
            else:
                ics['dtstart'] = tmpStart
                
            if tmpStart != tmpEnd or not event.allday:
                if event.allday:
                    ics['dtend;value=date'] = str(vDatetime(datetime.fromtimestamp(mktime(strptime(event.stop, DEFAULT_SERVER_DATETIME_FORMAT))) + timedelta(hours=24)).to_ical())[:8]
                else:
                    ics['dtend'] = tmpEnd
            
            return [ics, events_exported]