コード例 #1
0
ファイル: ical.py プロジェクト: filips123/GimVicUrnik
def create_schedule_calendar(query, name):
    logger = logging.getLogger(__name__)

    calendar = Calendar()
    calendar.add("prodid", "gimvicurnik")
    calendar.add("version", "2.0")
    calendar.add("X-WR-TIMEZONE", "Europe/Ljubljana")
    calendar.add("X-WR-CALNAME", name)
    calendar.add("X-WR-CALDESC", name)
    calendar.add("NAME", name)
    calendar.add("X-PUBLISHED-TTL", vDuration(timedelta(hours=1)))
    calendar.add("REFRESH-INTERVAL", vDuration(timedelta(hours=1)))

    for model in query:
        with start_span(op="event") as span:
            span.set_tag("event.type", "lunch-schedule")
            span.set_tag("event.date", model.date)
            span.set_tag("event.time", model.time)
            span.set_data("event.source", model)

            logger.info("Preparing iCalendar event",
                        extra={
                            "type": "lunch-schedule",
                            "source": model
                        })

            event = Event()
            event.add("dtstamp", datetime.now())
            event.add("CATEGORIES", vText("LUNCH"))
            event.add("COLOR", vText("darkblue"))
            event.add(
                "UID",
                sha256((str(model.date) + str(model.time) +
                        str(model.class_.name) +
                        str(model.location)).encode()).hexdigest(),
            )

            event.add("summary", "Kosilo")
            event.add("description", model.notes or "")
            event.add("location", vText(model.location))
            event.add("dtstart", datetime.combine(model.date, model.time))
            event.add(
                "dtend",
                datetime.combine(model.date, model.time) +
                timedelta(minutes=15))

            calendar.add_component(event)

    response = make_response(calendar.to_ical().decode("utf-8").replace(
        "\\", ""))
    response.headers[
        "Content-Disposition"] = "attachment; filename=calendar.ics"
    response.headers["Content-Type"] = "text/calendar; charset=utf-8"
    return response
コード例 #2
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)
コード例 #3
0
ファイル: taskmanager.py プロジェクト: jmandreoli/PYTOOLS
def calendar(content=None,method='PUBLISH',version='2.0',reminder=None):
  r"""
:param content: list of events
:type content: list(:class:`icalendar.Event`)
:param reminder: reminder
:type reminder: :class:`datetime.timedelta`
:param method: ics method for the icalendar
:type method: :const:`str`
:param version: icalendar version;should not be changed
:type version: :const:`str`
:rtype: :class:`icalendar.Calendar`

Return a calendar object listing all the events in *content*, possibly augmented, for those confirmed, with a reminder specified by *reminder* (from start).
  """
  cal = icalendar.Calendar()
  cal.add('prodid','-//ChronoManager//0.1')
  cal.add('version',version)
  cal.add('method',method)
  alarm = None
  if reminder is not None:
    rmdr = icalendar.vDuration(reminder)
    rmdr.params['related'] = icalendar.vText('START')
    alarm = icalendar.Alarm()
    alarm.add('action','DISPLAY')
    alarm.add('description','REMINDER')
    alarm.add('trigger',rmdr,0)
  for evt in content:
    if evt.get('status')=='CONFIRMED' and alarm is not None:
      evt.add_component(alarm)
    cal.add_component(evt)
  return cal
コード例 #4
0
def generate_calendar(classes):
    cal = icalendar.Calendar()
    cal.add('prodid', '-//WPI Calender Generator//adamgoldsmith.name//')
    cal.add('version', '2.0')

    tz = create_eastern_vtimezone()
    cal.add_component(tz)

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

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

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

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

    tz = create_eastern_vtimezone()
    cal.add_component(tz)

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

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

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

        cal.add_component(event)
    return cal
コード例 #6
0
ファイル: webcal.py プロジェクト: Bwc9876/BerksDental
def setup_calendar():
    """
    This function sets up a calendar object with some required attributes

    @return: A new Calendar that's properly configured
    @rtype: Calendar
    """

    cal = Calendar()
    cal.add('prodid', '-//Berks Dental Assistant Society//Berks Dental Assistant Society Webpage//EN')
    cal.add('version', '2.0')
    cal.add('X-WR-CALNAME', "Berks Dental Assistants Society")
    cal.add('name', "Berks Dental Assistants Society")
    cal.add("X-WR-CALDESC", "Events relating to the Berks Dental Assistants Society")
    cal.add("description", "Events relating to the Berks Dental Assistants Society")
    cal.add("X-WR-TIMEZONE", "America/New_York")
    cal.add("timezone-id", "America/New_York")
    cal.add("color", "dodgerblue")
    cal.add('refresh-interval', vDuration(timedelta(hours=12)))
    if not settings.DEBUG:
        cal.add('url', f"webcal://{settings.ALLOWED_HOSTS[0]}/{CALENDAR_URL}")
    return cal
コード例 #7
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
コード例 #8
0
ファイル: ical.py プロジェクト: filips123/GimVicUrnik
def create_school_calendar(details,
                           timetables,
                           hours,
                           name,
                           timetable=True,
                           substitutions=True):
    logger = logging.getLogger(__name__)

    calendar = Calendar()
    calendar.add("prodid", "gimvicurnik")
    calendar.add("version", "2.0")
    calendar.add("X-WR-TIMEZONE", "Europe/Ljubljana")
    calendar.add("X-WR-CALNAME", name)
    calendar.add("X-WR-CALDESC", name)
    calendar.add("NAME", name)
    calendar.add("X-PUBLISHED-TTL", vDuration(timedelta(hours=1)))
    calendar.add("REFRESH-INTERVAL", vDuration(timedelta(hours=1)))

    year = datetime.now().year if datetime.now().date() >= date(
        datetime.now().year, 9, 1) else datetime.now().year - 1

    weekdays = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"]
    weektable = [[None for i in range(10)] for j in range(6)]

    if timetable:
        for subject in timetables:
            with start_span(op="event") as span:
                span.set_tag("event.type", "timetable")
                span.set_tag("event.day", subject["day"])
                span.set_tag("event.time", subject["time"])
                span.set_data("event.source", subject)

                logger.info("Preparing iCalendar event",
                            extra={
                                "type": "timetable",
                                "source": subject
                            })
                event = Event()

                event.add("dtstamp", datetime.now())
                event.add("CATEGORIES", vText("NORMAL"))
                event.add("COLOR", vText("green"))
                event.add(
                    "UID",
                    sha256((str(subject["day"]) + str(subject["time"]) +
                            str(subject["subject"]) + str(subject["class"]) +
                            str(subject["teacher"])).encode()).hexdigest(),
                )

                start = datetime(year, 8,
                                 31) + hours[subject["time"]]["hour"]["start"]
                event.add("dtstart", start)
                event["EXDATE"] = vDatetime(start).to_ical().decode("utf-8")
                event["DURATION"] = "PT45M"
                event["RRULE"] = (
                    "FREQ=WEEKLY;BYDAY=" +
                    weekdays[subject["day"]] + ";UNTIL=" + vDatetime(
                        datetime(year + 1, 6, 25)).to_ical().decode("utf-8"))

                event.add("summary", subject["subject"])
                event["organizer"] = vText(subject["teacher"])
                event["location"] = vText(subject["classroom"])

                weektable[subject["day"]][subject["time"]] = event

    if substitutions:
        for subject in details:
            with start_span(op="event") as span:
                span.set_tag("event.type", "substitution")
                span.set_tag("event.date", subject["date"])
                span.set_tag("event.day", subject["day"])
                span.set_tag("event.time", subject["time"])
                span.set_data("event.source", subject)

                logger.info("Preparing iCalendar event",
                            extra={
                                "type": "substitution",
                                "source": subject
                            })

                event = Event()
                event.add("dtstamp", datetime.now())
                event.add("CATEGORIES", vText("SUBSTITUTION"))
                event.add("COLOR", vText("darkred"))
                event.add(
                    "UID",
                    sha256((str(subject["date"]) + str(subject["day"]) +
                            str(subject["time"]) + str(subject["subject"]) +
                            str(subject["class"]) +
                            str(subject["teacher"])).encode()).hexdigest(),
                )

                date_ = datetime.strptime(subject["date"], "%Y-%m-%d")
                event.add("dtstart",
                          date_ + hours[subject["time"]]["hour"]["start"])
                event.add("dtend",
                          date_ + hours[subject["time"]]["hour"]["end"])

                event.add("summary", subject["subject"])
                event["organizer"] = vText(subject["teacher"])
                event["location"] = vText(subject["classroom"])

                if weektable[datetime.strptime(
                        subject["date"],
                        "%Y-%m-%d").isoweekday()][subject["time"]]:
                    original = weektable[datetime.strptime(
                        subject["date"],
                        "%Y-%m-%d").isoweekday()][subject["time"]]
                    original["EXDATE"] += "," + event.get(
                        "dtstart").to_ical().decode("utf-8")

                calendar.add_component(event)

    for i in range(len(weektable)):
        for j in range(len(weektable[0])):
            if weektable[i][j]:
                calendar.add_component(weektable[i][j])

    response = make_response(calendar.to_ical().decode("utf-8").replace(
        "\\", ""))
    response.headers[
        "Content-Disposition"] = "attachment; filename=calendar.ics"
    response.headers["Content-Type"] = "text/calendar; charset=utf-8"
    return response
コード例 #9
0
ファイル: yamlical.py プロジェクト: psimonyi/yamlical
def make_ical(data, lang, old):
    caldata = TranslatedMap(data['calendar'], lang=lang)

    cal = Calendar()
    cal.add('prodid', 'yamlical.py')
    cal.add('version', '2.0')
    cal.add('method', 'PUBLISH')
    if 'name' in caldata:
        cal.add('name', caldata['name'])
        cal.add('x-wr-calname', caldata['name'])
    if 'description' in caldata:
        cal.add('description', caldata['description'])
        cal.add('x-wr-caldesc', caldata['description'])
    if 'url' in caldata:
        cal.add('url', caldata['url'])
    if 'published' in caldata:
        pubdata = TranslatedMap(caldata['published'], lang=lang)
        url = vUri(pubdata['url'])
        url.params['value'] = 'URI'
        cal.add('source', url)
        # Todo: make this come from calendar.published.refresh_interval.
        refresh_interval = vDuration(timedelta(days=1))
        refresh_interval.params['VALUE'] = 'DURATION'
        cal.add('x-published-ttl', refresh_interval)
        cal.add('refresh-interval', refresh_interval)

    add_timezone(cal)

    if 'organizer' in caldata:
        organizer = vCalAddress(caldata['organizer']['uri'])
        organizer.params['cn'] = vText(caldata['organizer']['cn'])
    else:
        organizer = None

    for evdata_raw in data['events']:
        evdata = TranslatedMap(evdata_raw, lang=lang)
        if 'overlay' in evdata:
            apply_overlay(evdata, TranslatedMap(evdata['overlay'], lang=lang))

        end = None  # default if not specified
        if 'date' in evdata:
            # Calculate the start and end timestamps from time/endtime.
            date = arrow.get(evdata['date'], DATE_FORMATS).date()
            a_start = arrow.get(evdata['time'], TIME_FORMATS)
            start = datetime.combine(date, a_start.time())
            if 'endtime' in evdata:
                a_end = arrow.get(evdata['endtime'], TIME_FORMATS)
                end = datetime.combine(date, a_end.time())
        else:
            start = arrow.get(evdata['start'], DT_FORMATS)
            if 'end' in evdata:
                end = arrow.get(evdata['end'], DT_FORMATS)

        event = Event()
        uid = evdata.setdefault('uid', make_uid())  # Add uid if needed.
        event.add('uid', uid)
        event.add('dtstart', dt_ical(start))
        if end: event.add('dtend', dt_ical(end))
        event.add('summary', apply_template(evdata, 'title'))
        if 'location' in evdata:
            event.add('location', apply_template(evdata, 'location'))
        if 'url' in evdata:
            event.add('url', apply_template(evdata, 'url'))
        if 'description' in evdata:
            event.add('description', apply_template(evdata, 'description'))
        if organizer:
            event.add('organizer', organizer)
        if evdata.get('cancelled', False):
            event.add('status', 'CANCELLED')

        if old and uid in old and events_equal(event, old[uid]):
            event['DTSTAMP'] = old[uid]['DTSTAMP']
        else:
            event.add('dtstamp', datetime.utcnow())

        cal.add_component(event)

    return cal
コード例 #10
0
ファイル: testCal.py プロジェクト: rmorgan1711/calendarCode
event = Event()
event.add('dtstart', tz.localize(datetime.datetime(2018, 1, 13, 10, 00, 00)))
event.add('dtend', tz.localize(datetime.datetime(2018, 1, 13, 11, 15, 00)))
event.add('dtstamp', tz.localize(datetime.datetime(2018, 1, 9, 6, 27, 00)))
event.add('created', tz.localize(datetime.datetime(2018, 1, 9, 6, 27, 00)))
event.add('description', 'Description is really cool!')
event.add('comment', 'Commentary about this event is that it\'s the bomb!')
event.add('summary', 'In summary, come!')

imgPath = "/Users/Bowen/Documents/calendar/propose.PNG"
AttachPNG(event, imgPath)
event.add('url', 'www.google.com')

geo = icalendar.vGeo([39.743476, -105.003218])
event.add('geo', geo)
event.add('location', '1900 16th Street\nDenver, CO 80220')

alarm = Alarm()
alarm.add('action', 'DISPLAY')
alarm.add('description', 'Event starting soon')
dur = icalendar.vDuration(datetime.timedelta(0, 0, 0, 0, -23))
alarm.add('trigger', dur)
event.add_component(alarm)

cal.add_component(event)

calPath = "/Users/Bowen/Documents/calendar/testCal.ics"
with open(calPath, 'wb') as f:
    f.write(cal.to_ical())