Exemple #1
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()
Exemple #2
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
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
Exemple #4
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()
Exemple #5
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)
Exemple #6
0
def addreminder():
    form = IcsForm()
    content = render_template('index.html', form=form)
    file = form.icsfile.data
    if not file:
        return content

    hours = form.hours.data
    minutes = form.minutes.data
    try:
        calendar = Calendar.from_ical(file.read())
    except ValueError:
        error = 'can\'t read file'
        return render_template('index.html', form=form, error=error)

    for component in calendar.walk('VEVENT'):
        valarm_found = False
        for k, v in component.property_items():
            if k == 'BEGIN' and v == 'VALARM':
                valarm_found = True

        if not valarm_found:
            alarm = Alarm()
            alarm.add('ACTION', 'DISPLAY')
            alarm.add('DESCRIPTION', component.get('SUMMARY'))
            alarm.add('TRIGGER;VALUE=DURATION', '-PT%dH%dM' % (hours, minutes))
            component.add_component(alarm)

    new_ics = tempfile.TemporaryFile()
    new_ics.write(calendar.to_ical())
    new_ics.seek(0)
    new_filename = file.filename.rstrip('.ics') + '_with_reminders' + '.ics'
    return send_file(new_ics,
                     as_attachment=True,
                     attachment_filename=new_filename)
Exemple #7
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)
Exemple #8
0
    def _create_event(self, match):
        """
        Creates a calendar event for the given match

        :paran match: A Match object holding the match data
        """
        #    print(self.team_data)
        #    print(team_data)

        event = Event()
        event["uid"] = match.id()
        event["location"] = match.location
        event.add("priority", 5)

        event.add("summary", match.summary())
        event.add("description", str(match))
        event.add("dtstart", match.match_start)
        event.add("dtend", match.match_end)
        event.add("dtstamp", datetime.utcnow())

        alarm = Alarm()
        alarm.add("action", "DISPLAY")
        alarm.add("description", "Reminder")
        alarm.add("trigger", timedelta(hours=-1))
        event.add_component(alarm)

        return event
Exemple #9
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()
Exemple #10
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
Exemple #11
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()
Exemple #12
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
Exemple #13
0
def create_alarm(message, relative_timedelta):
    alarm = Alarm()
    alarm.add('ACTION', 'DISPLAY')
    alarm.add('DESCRIPTION', message)
    #print(relative_timedelta);
    alarm.add('TRIGGER', relative_timedelta, parameters={'VALUE':'DURATION'})

    return alarm
Exemple #14
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
Exemple #15
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()
Exemple #16
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()
Exemple #17
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')
Exemple #18
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()
Exemple #19
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()
Exemple #20
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
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)
    def check_login_response(self, response):
        self.log('Add reminder')

        gcal = Calendar.from_ical(response.body)
        for component in gcal.walk():
            if component.name == "VEVENT":
                a = Alarm({
                    'ACTION': 'DISPLAY',
                    'TRIGGER;VALUE=DURATION': '-PT15M'
                })
                component.add_component(a)
                b = Alarm({
                    'ACTION': 'DISPLAY',
                    'TRIGGER;VALUE=DURATION': 'PT0S'
                })
                component.add_component(b)

        self.log('Save to file')
        f = open('calendar.ics', 'wb')
        f.write(gcal.to_ical())
        f.close()
Exemple #23
0
def get_alarm(description, minutes):
    """
    Get an Alarm object with description displayed
    :param description: description stirng
    :param minutes: the minutes before the event (int)
    :return: an alarm object
    """
    alarm = Alarm()
    alarm['trigger'] = '-PT{}M'.format(minutes)
    alarm['action'] = 'DISPLAY'
    alarm['description'] = description
    return alarm
Exemple #24
0
def AddAlarm(event, desc, minutesBefore):
    alarm = Alarm()
    alarm.add('action', 'DISPLAY')
    alarm.add('DESCRIPTION', desc)
    dur = icalendar.vDuration(datetime.timedelta(0, 0, 0, 0, -minutesBefore))
    alarm.add('TRIGGER', dur)
    event.add_component(alarm)
Exemple #25
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
Exemple #26
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())
Exemple #27
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()
Exemple #28
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)
Exemple #29
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)
 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
Exemple #31
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
Exemple #32
0
class XlsxEvent:
    summary = date_start = date_end = location = ''
    DATE_FORMAT = '%Y-%m-%d %H:%M:%S'

    ALARM = Alarm()
    ALARM.add('action', 'display')
    ALARM.add('trigger', datetime.timedelta(minutes=-30))

    def __init__(self, header, row):
        for i, cell in enumerate(row):
            field = constants.get(header[i])
            if field:
                setattr(self, field, cell.value)
        self.validate()
        self.set_values()

    def set_values(self):
        self.location = self.stadium
        self.summary = '%s - %s' % (self.home, self.away)
        self.date_start = datetime.datetime.combine(self.date, self.time)
        self.date_end = self.date_start + datetime.timedelta(hours=2)

    def __str__(self):
        return '%s - %s - %s - %s' % (
            self.summary,
            self.date_start,
            self.date_end,
            self.location,
        )

    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

    def validate(self):
        # We should have all constants now
        assert all([hasattr(self, field) for field in constants.values()])
Exemple #33
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)
Exemple #34
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
Exemple #35
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)
Exemple #36
0
def create_alarm(diff: timedelta, related: str) -> Alarm:
    """ Return a new alarm

    Args:
        diff (timedelta): The delta between the alarm and
                        the start/end of the event
        related (str):  Is the delta related to the START
                        or the END of the event

    Returns:
        Alarm: The Alarm itself
    """
    alarm = Alarm()
    alarm.add('ACTION', 'DISPLAY')
    alarm.add('TRIGGER', diff, parameters={'RELATED': related})
    return alarm
Exemple #37
0
def EventFromLine(line):
    fields = line.split('\t')
    event = Event()
    dtstart = parser.parse(fields[0])
    params = GetParamDict(fields[1])
    event.add('dtstart', dtstart, params)

    dtend = parser.parse(fields[2])
    params = GetParamDict(fields[3])
    event.add('dtend', dtend, params)

    event.add('summary', fields[4])
    event.add('location', fields[5].replace('|', "\r\n"))

    alarm = Alarm()
    alarm.add('action', 'DISPLAY')
    desc = "Rockies Home Game at " + dtstart.strftime("%I:%M %p")
    alarm.add('DESCRIPTION', desc)
    dur = icalendar.vDuration(datetime.timedelta(0, 0, 0, 0, -180))
    alarm.add('TRIGGER', dur)
    event.add_component(alarm)
    
    return event
Exemple #38
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
    def toICalEvents(self, startdate, dayofweek: int, weeknum: int = 0):
        if not WITH_ICAL:
            raise RuntimeError("Not configured with icalnedar support")

        startweekday = (7, 30)
        startweekend = (8, 0)

        event = Event()
        # add in summary and description
        if dayofweek == 0:
            event.add("summary", "Week {} - {}".format(weeknum, self.summary))
        else:
            event.add("summary", self.summary)
        event.add("description", self.description)

        # add in the start
        start = startdate + timedelta(days=dayofweek)
        if dayofweek < 5:  # weekday
            start = datetime.combine(start, time(*startweekday))
        else:  # weekend
            start = datetime.combine(start, time(*startweekend))
        event.add("dtstart", start)

        # add the end
        delta = self.toTimeDelta()
        if delta is not None:
            event.add("dtend", start + delta)

        # add the alarm
        if delta is not None and dayofweek < 5:  # weekday
            alarm = Alarm()
            alarm.add("ACTION", "DISPLAY")
            alarm.add("DESCRIPTION", "REMINDER")
            alarm.add("TRIGGER", timedelta(minutes=-15))
            event.add_component(alarm)

        return event
Exemple #40
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
Exemple #41
0
    def finalize(self):
        if not self.start_date or not self.end_date:
            raise InvalidEventError()

        delta = self.end_date - self.start_date
        if delta.days >= 1:
            start_date = date(self.start_date.year, self.start_date.month, self.start_date.day)
            end_date = date(self.end_date.year, self.end_date.month, self.end_date.day)
        else:
            start_date = self.start_date
            end_date = self.end_date

        if self.start_date > datetime.now(tz=EST()):
            alarm = Alarm()
            alarm.add("action", "DISPLAY")
            alarm.add("description", "REMINDER")
            alarm.add("trigger", timedelta(minutes=-15))
            self.add_component(alarm)

        self.add('dtstart', start_date)
        self.add('dtend', end_date)
Exemple #42
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
Exemple #43
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
Exemple #44
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
Exemple #45
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]
#!/usr/bin/env python2
from icalendar import Calendar, Event, Alarm

input_file = 'Abfuhrtermine.ics'
output_file = 'Abfalltermine_mit_Erinnerung.ics'

ical_file = open(input_file,'r')
calendar = Calendar.from_ical(ical_file.read())
for component in calendar.walk('VEVENT'):
    valarm_found = False
    for k,v in component.property_items():
        if k == 'BEGIN' and v == 'VALARM':
            valarm_found = True

    if valarm_found == False:
        alarm = Alarm()
        alarm.add('ACTION', 'DISPLAY')
        alarm.add('DESCRIPTION', component.get('SUMMARY'))
        alarm.add('TRIGGER;VALUE=DURATION', '-PT12H')
        component.add_component(alarm)

ical_file.close()
ical_file_new = open(output_file,'w+')
ical_file_new.write(calendar.to_ical())
ical_file_new.close()
def createReminder(minutes):
    a = Alarm()
    a.add('ACTION', 'DISPLAY')
    a.add('DESCRIPTION', 'starting soon...')
    a.add('TRIGGER', timedelta(minutes = -minutes))
    return a
Exemple #48
0
def create_alarm(message, relative_timedelta):
    alarm = Alarm()
    alarm.add('ACTION', 'DISPLAY')
    alarm.add('DESCRIPTION', message)
    alarm.add('TRIGGER', relative_timedelta, parameters={'VALUE':'DURATION'})
    return alarm
Exemple #49
0
def task_create(task=None, title='Task title', due=None, alarm=None, note='', sequence=0, uid=None, priority=None, next_action=None):
  from uuid import uuid4
  from icalendar import Calendar, Todo, Alarm
  if task is not None:
    title = task.name
    due = task.due
    alarm = task.alarm
    note = task.note
    sequence = task.sequence
    priority = task.priority
    next_action = task.next_action
  if (due is not None and alarm is None):
    # Should not arrive here, this should have already have been handled
    alarm = due
    if is_same_time(due, universe.defaulttime.due):
      # Warning for day events 1800 - 1000 = 8 hours
      alarm = due + universe.defaulttime.alldaydiff
    else: 
      # Default warning of an hour
      alarm = due + universe.defaulttime.diff
  if (alarm is not None and due is None):
    due = alarm
  # alarm now defunct - just use due
  cal = Calendar()
  cal.add('prodid', '-//enoky//v0.1//EN')
  cal.add('version', '2.0')

  todo = Todo()
  todo.add('summary', title)
  if priority is not None:
    todo.add('priority', priority)
  if due is not None:
    todo.add('due', due)
    todo.add('dtstart', due)
  todo.add('status', 'NEEDS-ACTION')
  todo.add('dtstamp', universe.now)
  todo.add('created', universe.now)
  if uid is None:
    uid = uuid4()
  todo['uid'] = uid
  todo.add('sequence', sequence)
  notenext = note
  if (next_action is not None) and (len(next_action) > 0):
    if len(notenext) > 0:
      notenext = notenext + '\n'
    notenext = notenext + universe.next_char + ' ' + next_action.lstrip()
  if len(notenext) > 0:
    todo.add('description', notenext)

  if alarm is not None:
    valarm = Alarm()
    valarm['uid'] = uuid4()
    valarm.add('trigger', alarm)
    # Possibly not needed. How add due date?!
    valarm.add('description', 'Event reminder')
    valarm.add('action', 'DISPLAY')
    todo.add_component(valarm)

  cal.add_component(todo)
  vcal = cal.to_ical()
  return vcal
Exemple #50
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