Пример #1
0
def make_ics(query, url, *, recurrence_series=()):
    today = datetime.date.today()

    query = query.options(joinedload(tables.Event.city))
    query = query.options(joinedload(tables.Event.venue))

    events = []
    last_series_date = {}

    for event in query:
        if event.venue:
            location = '{}, {}, {}'.format(
                event.venue.name,
                event.venue.short_address,
                event.city.name,
            )
            geo_obj = event.venue
        else:
            location = event.city.name
            geo_obj = event.city
        cal_event = ics.Event(
            name=event.title,
            location=location,
            begin=event.start,
            uid='{}-{}@pyvo.cz'.format(event.series_slug, event.date),
        )
        cal_event.geo = '{}:{}'.format(geo_obj.latitude,
                                       geo_obj.longitude)
        events.append(cal_event)

        if (event.series in last_series_date and
                last_series_date[event.series] < event.date):
            last_series_date[event.series] = event.date

    for series in recurrence_series:
        since = last_series_date.get(series, today)
        since += datetime.timedelta(days=1)

        # XXX: We should use the Series recurrence rule directly,
        # but ics doesn't allow that yet:
        # https://github.com/C4ptainCrunch/ics.py/issues/14
        # Just show the 6 next events.
        for occurence in series.next_occurrences(n=6, since=since):
            cal_event = ics.Event(
                name='({}?)'.format(series.name),
                begin=occurence,
                uid='{}-{}@pyvo.cz'.format(series.slug, occurence.date()),
            )
            events.append(cal_event)

    return ics.Calendar(events=events)
Пример #2
0
def create_lesson(lesson):
    name = lesson['kc_name']
    description = f"{lesson['teachernames']} {lesson['js_name']}"
    weeks = lesson['pkzcmx'].split(',')
    weekday = int(lesson['pksjmx'][0][0])
    weeks = map(lambda x: int(x), weeks)
    try:
        for week in weeks:
            date = start_date + datetime.timedelta(weeks=week - 1,
                                                   days=weekday - 1)
            print(name, date, description)
            btime = datetime.time.fromisoformat(adjust_time(lesson['idjkssj']))
            etime = datetime.time.fromisoformat(adjust_time(lesson['idjjssj']))

            e = ics.Event(name,
                          datetime.datetime.combine(date, btime),
                          datetime.datetime.combine(date, etime),
                          description=description,
                          location=lesson['js_name'],
                          organizer=lesson['teachernames'],
                          attendees=lesson['ktmc_name'].split(','))
            #e = ics.Event(name, datetime.datetime.combine(date,btime), datetime.datetime.combine(date,etime), description=description)
            c.events.add(e)
    except Exception as err:
        print(name, err)
 def make_event( self, entry ):
     """Creates an ics.Event object from the provided entry"""
     e = ics.Event()
     e.name = entry.name
     e.begin = '%s %s' % (entry.date, entry.start)
     e.end = '%s %s' % (entry.date, entry.end)
     return e
Пример #4
0
def add_events(path):
    courses = config.courses
    c = ics.Calendar()
    start_date = datetime.datetime.strptime(config.start_time, '%Y-%m-%d')
    tz = pytz.timezone('Asia/Taipei')
    for course in courses:
        course_name = course[0]
        course_description = '学分:' + str(course[1])
        course_weeks = course[2]
        course_week = course[3]
        course_section = course[4]
        course_location = course[5]
        for week in course_weeks:
            e = ics.Event()
            e.location = course_location
            e.description = course_description
            e.name = course_name
            delta = datetime.timedelta(days=(week - 1) * 7 + course_week)
            temp = start_date + delta
            s_time = temp.strftime('%Y:%m:%d') + ' ' + classStartTimeJA[
                course_section[0] - 1]
            e_time = temp.strftime('%Y:%m:%d') + ' ' + classEndTimeJA[
                course_section[-1] - 1]
            d1 = datetime.datetime.strptime(s_time, '%Y:%m:%d %H:%M:%S')
            d2 = datetime.datetime.strptime(e_time, '%Y:%m:%d %H:%M:%S')
            d1 = d1.replace(tzinfo=tz)
            d2 = d2.replace(tzinfo=tz)
            delta = datetime.timedelta(minutes=6)
            d1 = d1 + delta
            d2 = d2 + delta
            e.begin = d1
            e.end = d2
            c.events.append(e)
    with open(path, 'w') as f:
        f.writelines(c)
Пример #5
0
def class_cal(sched):
	cal = ics.Calendar()
	rows = re.split(r"(^\d{2}:\d{2}$)", sched, flags = re.MULTILINE)
	dates = [23,24,25,26,
			23,24,25,26,
			27,
			23,25,
			25,
			27,
			25]
			
	idx = 0
	for row in rows[2::2]:
		row = tuple(filter(not_empty, row.splitlines()))
		for name, full_name, type_, duration, location in chunks(row, 5):
			def parse_time(time_str):
				nonlocal idx
				time = arrow.get(f"{dates[idx]} {time_str}", "D HH:mm", **arrow_cfg)
				return time.replace(**{attr: getattr(arrow.now(), attr) for attr in ("year", "month")})
			begin, end = map(parse_time, duration.replace(" ", "").split("-"))
			idx+=1
			logging.debug(name)
			logging.debug(begin.humanize())
			cal.events.add(ics.Event(name=name+"\n"+full_name, begin = begin, end = end, location = location))
		logging.debug("\n")
	return cal
Пример #6
0
    def ical(self, session, **params):
        icalendar = ics.Calendar()

        if 'locations' not in params or not params['locations']:
            locations = [id for id, name in c.EVENT_LOCATION_OPTS]
            calname = "full"
        else:
            locations = json.loads(params['locations'])
            if len(locations) > 3:
                calname = "partial"
            else:
                calname = "_".join([name for id, name in c.EVENT_LOCATION_OPTS
                                    if str(id) in locations])

        calname = '{}_{}_schedule'.format(c.EVENT_NAME, calname).lower().replace(' ', '_')

        for location in locations:
            for event in session.query(Event)\
                    .filter_by(location=int(location))\
                    .order_by('start_time').all():
                icalendar.events.add(ics.Event(
                    name=event.name,
                    begin=event.start_time,
                    end=(event.start_time + timedelta(minutes=event.minutes)),
                    description=normalize_newlines(event.description),
                    created=event.created.when,
                    location=event.location_label))

        cherrypy.response.headers['Content-Type'] = \
            'text/calendar; charset=utf-8'
        cherrypy.response.headers['Content-Disposition'] = \
            'attachment; filename="{}.ics"'.format(calname)

        return icalendar
Пример #7
0
 def to_ics_event(self):
     return ics.Event(name=self.get_name(),
                      begin=self.get_start_date(),
                      end=self.get_end_date(),
                      uid=str(self.get_id()),
                      url=self.get_link(),
                      location=self.get_city() + ", " + self.get_country())
Пример #8
0
def course_calendar_ics(course_slug):
    try:
        course = g.model.courses[course_slug]
    except KeyError:
        abort(404)

    if not course.start_date:
        abort(404)

    events = []
    for session in course.sessions.values():
        time = getattr(session, 'time', None)
        if time is None:
            # Sessions without times don't show up in the calendar
            continue

        created = os.environ.get('NAUCSE_CALENDAR_DTSTAMP', None)
        cal_event = ics.Event(
            name=session.title,
            begin=time['start'],
            end=time['end'],
            uid=session.get_url(external=True),
            created=created,
        )
        events.append(cal_event)

    cal = ics.Calendar(events=events)
    return Response(str(cal), mimetype="text/calendar")
Пример #9
0
    def make_ical_events(self, events: List[Dict]) -> List[ics.Event]:
        current_time = datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
        alarms = self.ical_alarms

        events_list = []
        for event in events:
            all_day = event['all_day'] == 1
            if len(event['end']) == 0:
                event['end'] = event['start']

            cal_event = ics.Event(
                event['title'],
                schoology_to_datetime(event['start'], self.timezone, all_day),
                schoology_to_datetime(event['end'], self.timezone, all_day),
                uid=str(event['id']),
                description=event['description'],
                alarms=alarms[event['id']]
            )
            cal_event.extra.append(ContentLine(name="DTSTAMP", value=current_time))

            if all_day:
                cal_event.make_all_day()

            events_list.append(cal_event)
        return events_list
Пример #10
0
def ical_output(promo, classes):
    cal = ics.Calendar(creator=PRODID)

    for c in classes:
        name = '{}-{}'.format(c.get('name'), c.get('prof'))
        name = re.sub(r"[^\w]", "_", name)
        uid = 'chronos-{}-{}-{}'.format(promo, c.get('start'), name)
        uid = uid.replace(' ', '_')

        summary = '{}'.format(c.get('name'))
        if c.get('prof') != '-':
            summary += ' - {}'.format(c.get('prof'))
        summary += ' ({})'.format(c.get('room'))

        description = '\n'.join({
            "Cours: {}".format(c.get('name')),
            "Prof: {}".format(c.get('prof')),
            "Salle: {}".format(c.get('room')),
            "Groupes: {}".format('-'.join(c.get('groups'))),
        }).replace(',', '\\,')

        paris = pytz.timezone('Europe/Paris')
        begin, end = map(paris.localize, [c.get('start'), c.get('end')])

        cal.events.append(
            ics.Event(name=summary,
                      begin=begin,
                      end=end,
                      uid=uid,
                      description=description,
                      location=c.get('room').capitalize()))

    return cal
Пример #11
0
def _get_events(path,
                rounds=5,
                location='750 Daly St S, Winnipeg, MB R3L 2N2',
                organizer_email='*****@*****.**',
                organizer_name='Cam Barth'):
    contacts = get_teams(path)

    for game in get_games(path, rounds):
        skips = [contacts[game['teams'][idx]] for idx in [0, 1]]
        # print(game)
        yield ics.Event(
            name=
            f"{skips[0]['name']} vs {skips[1]['name']} on Sheet {game['sheet']}",
            begin=_get_datetime(game['day'], game['month'], game['time']),
            duration={"hours": 2},
            location=location,
            alarms=[ics.alarm.DisplayAlarm(trigger=timedelta(minutes=90))],
            categories=['FRCC Friday Night Mixed', 'Curling', 'Sports'],
            organizer=ics.Organizer(email=organizer_email,
                                    common_name=organizer_name),
            attendees=[
                ics.Attendee(email=skip['email'], common_name=skip['name'])
                for skip in skips
            ],
            description=
            f"Contact Details: {skips[0]['name']} ({skips[0]['email']}) Ph: {skips[0]['phone']} /// {skips[1]['name']} ({skips[1]['email']}) Ph: {skips[1]['phone']}"
        )
Пример #12
0
    def save(self, **kwargs):
        if self.date and self.start_time and self.end_time:
            begin = datetime.datetime(year=self.date.year,
                                      month=self.date.month,
                                      day=self.date.day,
                                      hour=self.start_time.hour,
                                      minute=self.start_time.minute)

            end = datetime.datetime(year=self.date.year,
                                    month=self.date.month,
                                    day=self.date.day,
                                    hour=self.end_time.hour,
                                    minute=self.end_time.minute)

            tz = pytz.timezone(settings.TIME_ZONE)
            begin = tz.localize(begin)
            end = tz.localize(end)

            sout = cStringIO.StringIO()
            sout.writelines(
                ics.Calendar(events=[
                    ics.Event(name=self.title,
                              begin=begin,
                              end=end,
                              location=str(self.location),
                              description=str(self))
                ]))

            self.ics_file = django.core.files.File(sout, 'event.ics')
        else:
            self.ics_file = None

        super(Event, self).save(**kwargs)
Пример #13
0
 def as_ical(self):
     ical = ics.Calendar()
     for day in self.days:
         event = ics.Event(name=day.description,
                           description=day.source,
                           begin=day.date)
         event.make_all_day()
         ical.events.add(event)
     return ical
Пример #14
0
 def to_ics(self):
     event_url = front_url("view_event", args=[self.pk], auto_login=False)
     return ics.Event(
         name=self.name,
         begin=self.start_time,
         end=self.end_time,
         uid=str(self.pk),
         description=self.description + f"<p>{event_url}</p>",
         location=self.short_address,
         url=event_url,
     )
Пример #15
0
def prepare_calendar_event(seminar):
    cal = ics.Calendar()
    event = ics.Event()
    event.begin = seminar.date
    event.name = seminar.title
    event.location = seminar.place
    description = "; ".join(
        [seminar.author, seminar.affiliation, seminar.language, seminar.abstract]
    )
    event.description = description
    cal.events.add(event)
    return cal
Пример #16
0
    def mk_ics(self, filename):
        import ics
        import arrow
        from io import StringIO
        try:
            # make sure that table is not empty
            if self.table == []:
                print('fill the list first')
                return None

            #convert table to a csv and turn
            STR = ''
            for row in self.table:
                STR += '"' + '","'.join(row) + '"\n'
            csvF = StringIO(STR)
            table = csv.DictReader(
                csvF)  #use a dict to easily find specific headers
            cal = ics.Calendar()
            for row in table:
                # create a new calendar Event and fill it
                ev = ics.Event()
                #-# Get the different attributes necessary for an event in the Calendar #-#
                if row['SUMMARY'] != None:
                    ev.name = row['SUMMARY']
                else:
                    ev.name = ''

                # No calender event is complete without start and end date
                if row['DTSTART'] != None and row['DTEND'] != None:
                    form = 'MM-DD-YYYY HH:mm a'  #Format
                    ev.begin = arrow.get(row['DTSTART'], form)
                    ev.end = arrow.get(row['DTEND'], form)
                else:
                    raise Exception('Must Have both start and end dates')
                if row['NOTES'] != None:
                    ev.description = row['NOTES']
                elif row['DESCRIPTION'] != None:
                    ev.description = row['DESCRIPTION']

                if row['LOCATION'] != None:
                    ev.location = row['LOCATION']

                #Now save the event in the Calendar
                cal.events.add(ev)
            # create and save the ics file
            f = open('../New_Files/' + filename + '.ics', 'w')
            f.writelines(cal)
            f.close()
            print("Succesfully Created", '../New_Files/' + filename + '.ics')
        except KeyError:
            print('Check that the file head structure follows:\n',
                  'SUMMARY,DTSTART,DTEND,NOTES,LOCATION')
Пример #17
0
def get_event_ics(service, event_id):
    event = get_event(service, event_id)
    calendar = ics.Calendar()
    event_info = parse_event_info(event)

    event = ics.Event(name=event_info['summary'],
                      begin=event_info['start'],
                      description=event_info['description'],
                      end=event_info['end'],
                      organizer=event_info['creator'])

    calendar.events.add(event)
    return calendar
Пример #18
0
 def make_events(dates: List[str], names: List[str],
                 descriptions: List[str]) -> ics.Calendar:
     """
     Make calendar with events
     :param iter dates: iter of dates in string format
     :param names: iter of event names in string format
     :param descriptions: iter of event descriptions in string format
     :return ics.Calendar: calendar object
     """
     cal = ics.Calendar()
     for date, name, desc in zip(dates, names, descriptions):
         e = ics.Event(name=name, begin=date, description=desc)
         e.make_all_day()
         cal.events.add(e)
     return cal
Пример #19
0
def create_file(lessons):
    # Create the .ics file from the parsed month

    calendar = ics.Calendar(imports='BEGIN:VCALENDAR\nPRODID:ics.py - http://git.io/lLljaA'
                                    '\nVERSION:1\nX-WR-CALDESC:Расписание\nEND:VCALENDAR')

    for lesson in lessons:
        event = ics.Event()
        event.begin = lesson.datetime
        event.duration = timedelta(hours=1, minutes=30)
        event.location = lesson.location
        event.name = lesson.short_name
        event.description = '%s - %s' % (lesson.prof, lesson.long_name)
        calendar.events.add(event)

    return bytes(str(calendar), 'utf-8')
Пример #20
0
def detail(request, id):
    event = Event.objects.get(tweet_id=id)
    dt_format = "%Y-%m-%d %H:%M"
    end = event.datetime + datetime.timedelta(hours=1)
    c = ics.Calendar()
    e = ics.Event(name=event.title,
                  begin=event.datetime.strftime(dt_format),
                  end=end.strftime(dt_format),
                  created=datetime.datetime.now().strftime(dt_format),
                  url=event.link)
    c.events.add(e)

    cal_str = codecs.encode(str(c), encoding='utf-8')
    response = HttpResponse(cal_str, content_type="application/ics")
    response['Content-Disposition'] = 'inline; filename=%s.ics' % e.name
    return response
Пример #21
0
def generate_calendar(args, week_parity, street_sweeping_day, dates):
    """Generate an ICS Calendar and save to disk."""
    cal = ics.Calendar()

    for month in dates:
        for day in month:
            event = ics.Event()
            event.name = "Street Sweeping"
            event.begin = day
            event.end = day + timedelta(hours=(args.end - args.start))
            cal.events.add(event)

    filename = "{}_{}_{}_street_sweeping.ics".format(str(args.year),
                                                     week_parity,
                                                     street_sweeping_day)
    with open(filename, "w") as ics_file:
        ics_file.writelines(cal)
Пример #22
0
def _to_ics(start: datetime.date, stop: datetime.date, lang: str, liturgycal,
            stream, **options) -> bool:
    """Turn data into a ics file.
    liturgycal is a liturgical calendar with requested start and stop
    stream is a stream where ics calendar will be written
    Return True"""
    calendar = ics.Calendar()
    for day in liturgycal[start:stop]:
        for i, feast in enumerate(day):
            if not feast.pal or options.get('pal', False):
                event = ics.Event()
                raw_data = _data_wrapper(feast, lang, i)
                event.name = raw_data[0]
                event.description = raw_data[1]
                event.begin = raw_data[2]
                calendar.events.append(event)
    stream.writelines(calendar)
    return True
Пример #23
0
 def generate_date_ics(self):
     if self.date:
         cal = ics.Calendar()
         cal_event = ics.Event()
         cal_event.name = self.title
         cal_event.begin = self.date
         cal_event.created = datetime.datetime.today()
         cal_event.description = self.description
         cal_event.location = self.location
         if self.url_string:
             cal_event.url = self.url_string
         cal_event.make_all_day()
         cal.events.add(cal_event)
         ics_memory_buffer = io.StringIO()
         ics_memory_buffer.writelines(cal)
         ics_memory_buffer.seek(0, 0)
         return ics_memory_buffer
     return None
Пример #24
0
def chronos(promo, group):
    logging.warning('{} {}'.format(group, promo))
    r = requests.get('{}/Planning/GetRangeWeek/{}/{}'.format(
        API, group, RANGE),
                     headers=headers)
    if r.status_code != 200:
        logging.error('cannot get API informations for {}'.format(group))
        return

    cal = ics.Calendar(creator=PRODID)
    for week in r.json():
        for day in week.get('DayList'):
            for c in day.get('CourseList'):
                prof = join_names(c.get('StaffList'))
                room = join_names(c.get('RoomList'))
                groups = join_names(c.get('GroupList'))

                name = '{}'.format(c.get('Name'))
                name = re.sub(r"[^\w]", "_", name)
                uid = 'chronos-{}-{}-{}'.format(promo, c.get('BeginDate'),
                                                name)
                uid = uid.replace(' ', '_')

                summary = '{}'.format(c.get('Name'))
                if prof:
                    summary += ' - {}'.format(prof)
                summary += ' ({})'.format(room)

                description = '\n'.join({
                    "Cours: {}".format(c.get('Name')),
                    "Prof: {}".format(prof),
                    "Salle: {}".format(room),
                    "Groupes: {}".format(groups),
                }).replace(',', '\\,')

                cal.events.append(
                    ics.Event(name=summary,
                              begin=c.get('BeginDate'),
                              end=c.get('EndDate'),
                              uid=uid,
                              description=description,
                              location=room.capitalize()))

    return cal
Пример #25
0
 def makeICS(self, playerfilter=None):
     if isinstance(playerfilter, Player):
         playerfilter = playerfilter.discordId
     c = ics.Calendar()
     for quest in self.getAllQuests():
         if not quest.date: continue
         if playerfilter:
             if not any(
                 (playerfilter == quest.dm, playerfilter == quest.commander,
                  playerfilter in list(quest.players.keys()))):
                 continue
         desc = quest.description.replace('\r', '')
         e = ics.Event(
             name=f"Chain Marches - {quest.title}",
             description=f"Dmed by {self.getPlayer(quest.dm).nick}\n{desc}",
             begin=quest.date,
             alarms=[ics.alarm.DisplayAlarm(timedelta(hours=-1))])
         c.events.add(e)
     return c
Пример #26
0
    def make_calendar(self, with_setup_time=False, zoom_info=None):
        calendar = ics.Calendar()
        event = ics.Event()
        session_time = self.session_time()
        event.begin = session_time[0]
        if with_setup_time:
            event.begin -= self.setup_time()
        event.end = session_time[1]
        event.name = self.event_session_title()
        event.description = ""
        # We include the zoom info in the calendar file sent to presenters,
        # put the URL up front in ICS because google calendar limits the length of this
        if zoom_info:
            event.description += "Zoom URL: " + self.timeslot_entry(0, "Zoom URL").value + \
                    "\nZoom Meeting ID: " + self.timeslot_entry(0, "Zoom Meeting ID").value + \
                    "\nZoom Password: "******"Zoom Password").value + "\n"

        event.description += str(self)
        calendar.events.add(event)
        return calendar
Пример #27
0
def generate_calendar_ics(course):
    events = []
    for session in course.sessions.values():
        if session.start_time:
            start_time = session.start_time
            end_time = session.end_time
        else:
            raise ValueError("One of the sessions doesn't have a start time.")

        cal_event = ics.Event(
            name=session.title,
            begin=start_time,
            end=end_time,
            uid=url_for("session_coverpage",
                        course=course,
                        session=session.slug,
                        _external=True),
        )
        events.append(cal_event)

    return ics.Calendar(events=events)
Пример #28
0
def course_calendar_ics(course):
    if not course.start_date:
        abort(404)
    calendar = ics.Calendar()
    for session in course.sessions.values():
        if session.start_time:
            start_time = session.start_time
            end_time = session.end_time
        else:
            abort(404)
        cal_event = ics.Event(
            name=session.title,
            begin=start_time,
            end=end_time,
            uid=url_for("session_coverpage",
                        course=course,
                        session=session.slug,
                        _external=True),
        )
        calendar.events.append(cal_event)
    return Response(str(calendar), mimetype="text/calendar")
Пример #29
0
def workshops_ical():
    import ics
    cal_events = []
    for event in load_events():
        try:
            if not event['date']:
                continue
            cal_event = ics.Event(
                name=event['title'],
                location=event['location'],
                begin=event['date'].isoformat(),
                uid='{}@pyworking.cz'.format(event['slug']),
            )
            #cal_event.geo = '{}:{}'.format(geo_obj.latitude, geo_obj.longitude)
            cal_events.append(cal_event)
        except Exception as e:
            raise Exception('Failed to export event: {!r}; event: {}'.format(
                e, event)) from e
    return Response(ics.Calendar(events=cal_events),
                    mimetype='text/plain'
                    if request.args.get('debug') else 'text/calendar')
Пример #30
0
    def to_ics(self, text_only_description=False):
        event_url = front_url("view_event", args=[self.pk], auto_login=False)
        organizer = Organizer(email=self.contact_email,
                              common_name=self.contact_name)
        if text_only_description:
            description = textify(self.description) + " " + event_url
        else:
            description = self.description + f"<p>{event_url}</p>"

        return ics.Event(
            name=self.name,
            begin=self.start_time,
            end=self.end_time,
            uid=str(self.pk),
            description=description,
            location=self.short_address,
            url=event_url,
            categories=[self.subtype.get_type_display()],
            geo=self.coordinates,
            organizer=organizer,
        )