Exemple #1
0
def gen_ics():
    data = json.load(open("assets/data/timings.json"))
    os.system("rm -rf assets/calendars")
    os.system("mkdir assets/calendars")
    for offset in time_offsets:
        for fiqh in data.keys():
            os.system("mkdir assets/calendars/" + fiqh)
            c = Calendar()
            for d in data[fiqh].keys():
                es = Event()
                ei = Event()
                stime = arrow.get(
                    dt.fromtimestamp(data[fiqh][d]["sehri_timestamp"] +
                                     (offset * 60)),
                    'Asia/Kolkata').strftime("%Y-%m-%d %H:%M:00")
                itime = arrow.get(
                    dt.fromtimestamp(data[fiqh][d]["iftar_timestamp"] +
                                     (offset * 60)),
                    "Asia/Kolkata").strftime("%Y-%m-%d %H:%M:00")
                time = dt.now()
                es.name = "Sahar Ending"
                es.begin = stime
                es.created = time
                es.end = stime
                ei.name = "Iftar Beginning"
                ei.created = time
                ei.begin = itime
                ei.end = itime
                c.events.add(es)
                c.events.add(ei)
            with open(
                    "assets/calendars/%s/timings%s.ics" %
                (fiqh, get_offset_string(offset)), "w") as my_file:
                my_file.writelines(c)
Exemple #2
0
def create_calendar(token, enrollment_id, options):
    file_list = []
    if options['academicCal'] or options['careerCal']:
        academic_calendar = Calendar()
        career_calendar = Calendar()
        for sess in get_sessions(token, enrollment_id)['calendarSessions']:
            e = Event()
            if (sess['context']['id'] == 1) and options['academicCal']:
                start_time = datetime.strptime(sess['session']['startTime'], '%Y-%m-%dT%H:%M:%SZ')
                end_time = datetime.strptime(sess['session']['endTime'], '%Y-%m-%dT%H:%M:%SZ')
                e.name = str(sess['session']['chapter']) + ': ' + sess['session']['name']
                e.transparent = True if options['academicIsTrans'] else False
                if options['officeHours']:
                    e.begin = start_time - timedelta(minutes=45)
                    e.end = end_time + timedelta(minutes=30)
                else:
                    e.begin = start_time
                    e.end = end_time
                academic_calendar.events.add(e)

            elif (sess['context']['id'] == 2) and options['careerCal']:
                e.name = sess['session']['name']
                e.begin = sess['session']['startTime']
                e.end = sess['session']['endTime']
                e.transparent = True if options['careerIsTrans'] else False
                career_calendar.events.add(e)

        if len(academic_calendar.events) > 0:
            academic_file_name = str(enrollment_id) + '-academic-calendar'
            academic_file_name = academic_file_name + '-oh.ics' if options['officeHours'] else academic_file_name + '.ics'
            file_list.append(academic_file_name)
            with open('files/' + academic_file_name, 'w') as f:
                f.writelines(academic_calendar)

        if len(career_calendar.events) > 0:
            career_file_name = str(enrollment_id) + '-career-calendar.ics'
            file_list.append(career_file_name)
            with open('files/' + career_file_name, 'w') as f:
                f.writelines(career_calendar)

    if options['assignmentCal']:
        assignment_calendar = Calendar()
        for assignment in get_assignments(token, enrollment_id)['calendarAssignments']:
            e = Event()
            if assignment['context']['id'] == 1:
                e.name = assignment['title']
                e.begin = datetime.strptime(assignment['effectiveDueDate'], '%Y-%m-%dT%H:%M:%SZ') - timedelta(days=1)
                e.end = datetime.strptime(assignment['effectiveDueDate'], '%Y-%m-%dT%H:%M:%SZ') - timedelta(days=1)
                e.make_all_day()
                e.transparent = True if options['assignmentsIsTrans'] else False
                assignment_calendar.events.add(e)
        assignment_file_name = str(enrollment_id) + '-assignment-calendar.ics'
        file_list.append(assignment_file_name)
        with open('files/' + assignment_file_name, 'w') as f:
            f.writelines(assignment_calendar)

    return file_list
Exemple #3
0
def matrix_to_ics(matrix_dict, group, begin, end, directory):
    c = Calendar()

    day, month, year = begin.split(" ")
    begin = "{} {} {}".format(day if int(day) > 9 else '0%s' % (day),
                              MONTHS[month], year)

    day, month, year = end.split(" ")
    end = "{} {} {}".format(day if int(day) > 9 else '0%s' % (day),
                            MONTHS[month], year)

    begin = arrow.get("{} {}".format(begin, HOURS[0]), 'DD MM YYYY HH:mm')
    end = arrow.get("{} {}".format(end, HOURS[-1]), 'DD MM YYYY HH:mm')

    # for each day of the week
    for i, day in enumerate(matrix_dict[group]):
        # for each course of the day
        for j, course in enumerate(day):

            if course:
                # get begin hour
                hour = int(HOURS[j].split(':')[0])
                minute = int(HOURS[j].split(':')[1])

                e = Event()

                e.name = course
                e.begin = begin.replace(hour=hour, minute=minute)
                e.end = e.begin.replace(hours=+1)

                c.events.append(e)

                while (e.begin <= end):
                    e = e.clone()

                    e.end = e.end.replace(days=+7)
                    e.begin = e.begin.replace(days=+7)
                    e.uid = uid_gen()

                    c.events.append(e)

        # next day
        begin = begin.replace(days=+1)

    holidays = convert_holidays()
    for event in c.events:
        for date in holidays:
            if str(event.begin.date()) == str(date):
                c.events.remove(event)

    if not os.path.exists("ics/" + directory):
        os.makedirs("ics/" + directory)

    with open('ics/{}/{}.ics'.format(directory, group), 'w') as f:
        f.writelines(c)
Exemple #4
0
def matrix_to_ics(matrix_dict, group, begin, end, directory):
    c = Calendar()

    day, month, year = begin.split(" ")
    begin = "{} {} {}".format(day if int(day) > 9 else '0%s' % (day), MONTHS[month], year)

    day, month, year = end.split(" ")
    end = "{} {} {}".format(day if int(day) > 9 else '0%s' % (day), MONTHS[month], year)

    begin = arrow.get("{} {}".format(begin, HOURS[0]), 'DD MM YYYY HH:mm')
    end = arrow.get("{} {}".format(end, HOURS[-1]), 'DD MM YYYY HH:mm')

    # for each day of the week
    for i, day in enumerate(matrix_dict[group]):
        # for each course of the day
        for j, course in enumerate(day):

            if course:
                # get begin hour
                hour = int(HOURS[j].split(':')[0])
                minute = int(HOURS[j].split(':')[1])

                e = Event()

                e.name = course
                e.begin = begin.replace(hour=hour, minute=minute)
                e.end = e.begin.replace(hours=+1)

                c.events.append(e)

                while (e.begin <= end):
                    e = e.clone()

                    e.end = e.end.replace(days=+7)
                    e.begin = e.begin.replace(days=+7)
                    e.uid = uid_gen()

                    c.events.append(e)

        # next day
        begin = begin.replace(days=+1)

    holidays = convert_holidays()
    for event in c.events:
        for date in holidays:
            if str(event.begin.date()) == str(date):
                c.events.remove(event)

    if not os.path.exists("ics/" + directory):
        os.makedirs("ics/" + directory)

    with open('ics/{}/{}.ics'.format(directory, group), 'w') as f:
        f.writelines(c)
Exemple #5
0
def create_ics(sender, instance, **kwargs):
    c = Calendar()
    alarm = [DisplayAlarm(trigger=timedelta(minutes=30))]

    e = Event()
    e.name = instance.title
    e.begin = instance.date
    e.end = instance.dateend
    e.alarms = alarm
    if instance.duration != None:
        e.duration = instance.duration
    if (instance.cost == 0 or instance.cost == None):
        cost = 'Бесплатно'
        e.description = str(instance.intro) + ' Стоимость: ' + str(cost)
    else:
        e.description = str(instance.intro) + ' Стоимость: ' + str(instance.cost)+  'р.'
    e.location = instance.location
    if instance.timepad != None:
        e.url = instance.timepad
    c.events.add(e)

    instance.ics.delete(save=False)
    instance.ics.save(instance.title +'.ics', ContentFile(str(c)), save=True)
    #Формирование глобального файла со всеми мероприятиями
    global_ics = EventIndex.objects.all()[0]
    events = global_ics.get_children()
    c = Calendar()
    for event in events:
        if (event.specific.date < timezone.now()):
            pass
        else:
            e = Event()
            e.name = event.title
            e.begin = event.specific.date
            e.end = event.specific.dateend
            e.alarms = alarm
            if event.specific.duration != None:
                e.duration = event.specific.duration
            if (event.specific.cost == 0 or event.specific.cost == None):
                cost = 'Бесплатно'
                e.description = str(event.specific.intro.strip("<p>*</p>")) + ' Стоимость: ' + str(cost)
            else:
                e.description = str(event.specific.intro.strip("<p>*</p>")) + ' Стоимость: ' + str(event.specific.cost)+  'р.'
            e.location = event.specific.location
            if event.specific.timepad != None:
                e.url = event.specific.timepad
            c.events.add(e)
    global_ics.calenadar_file.delete(save=False)
    global_ics.calenadar_file.save('global.ics', ContentFile(str(c)), save=True)
    def add_course(self, course_name, start):
        local = self.info[start].lstrip(
            str(re.search(r'<td>|<td rowspan=\"\d\">',
                          self.info[start]))).rstrip('</td>')
        weekday = re.findall(r"星期.", self.info[start + 1])[0].lstrip('星期')
        weekday = self.map.index(weekday)
        time = re.findall(r"\d+", self.info[start + 1])
        week = self.info[start + 2].lstrip('</td>第').rstrip('周</td>')
        remark = self.info[start + 3].lstrip('</td>').rstrip('</td>')

        e = Event()
        if ('-' in week):
            week = week.split('-')
            #print(week)
            week_cur = int(week[0])
            week_end = int(week[1])
            while week_cur <= week_end:
                e = Event()
                e.name = course_name
                e.location = local
                e.description = remark
                offset = datetime.timedelta(days=(week_cur - 1) * 7 + weekday,
                                            hours=self.start_h[int(time[0])],
                                            minutes=self.start_m[int(time[0])])
                e.begin = self.term_start_time + offset
                offset = datetime.timedelta(days=(week_cur - 1) * 7 + weekday,
                                            hours=self.end_h[int(time[1])],
                                            minutes=self.end_m[int(time[1])])
                e.end = self.term_start_time + offset
                week_cur += 1
                self.c.events.add(e)
        else:
            week = week.split(',')
            #print(week)
            for we in week:
                e = Event()
                e.name = course_name
                e.location = local
                e.description = remark
                offset = datetime.timedelta(days=(int(we) - 1) * 7 + weekday,
                                            hours=self.start_h[int(time[0])],
                                            minutes=self.start_m[int(time[0])])
                e.begin = self.term_start_time + offset
                offset = datetime.timedelta(days=(int(we) - 1) * 7 + weekday,
                                            hours=self.end_h[int(time[1])],
                                            minutes=self.end_m[int(time[1])])
                e.end = self.term_start_time + offset
                self.c.events.add(e)
Exemple #7
0
def get_events(item):
    time_table = [
        [8, 30],  #1
        [10, 20],  #3
        [14, 30],  #5
        [16, 20],  #7
        [19, 30]  #9
    ]
    course_long = [0, 0, 95, 145, 205]
    begin_time = time_table[item['begin_time'] // 2]

    event_list = []
    for i in range(item['begin_week'], item['end_week'] + 1):
        b_time = datetime(2019, 9, 2, begin_time[0], begin_time[1],
                          0) + timedelta(
                              hours=-8, days=item['week'] - 1, weeks=i - 1)
        e_time = b_time + timedelta(minutes=course_long[item['num']])
        ##print(b_time,'-------',e_time)
        e = Event()
        e.name = item['name']
        e.location = item['location']
        e.begin = str(b_time)
        e.end = str(e_time)
        event_list.append(e)
    return event_list
Exemple #8
0
    def save_ics_file(self, ics_file: str, n_events: int = 50) -> None:
        """
        Saves n_events random events in the ics file with path ics_file
        :param ics_file (str): path of the ics file
        :param n_events (int): number of events to generate
        """
        c = Calendar()
        for i in range(0, n_events):

            sys.stdout.write("\rCreating event %i of %i" % (i, n_events))
            sys.stdout.flush()

            e = Event()
            e.name = self.get_rnd_title()
            (start, end, duration, created) = self.get_rnd_event_time()
            e.begin = start
            e.end = end
            e.duration = duration
            e.created = created
            e.description = self.get_rnd_description()
            e.url = self.get_rnd_url()
            e.location = self.get_rnd_address()
            c.events.add(e)

        with open(ics_file, 'w') as f:
            f.writelines(c)

        sys.stdout.write("\rDone")
        sys.stdout.flush()
Exemple #9
0
 def convertToICS(self):
     '''
     Convert data into ics file
     '''
     importantInfor = [
         (date, detail)
         for date, detail in zip(self._getDateAndTime(), self._getDetail())
     ]
     print(importantInfor)
     for idx, infor in enumerate(importantInfor):
         '''
         infor[0]: (starting time, ending time)
         infor[1]: event's detail
         '''
         event = Event()
         todo = Calendar()
         event.name = infor[1]  # Header of the file
         event.begin = infor[0][0]  # Time event starts
         event.end = infor[0][1]  # Time event ends
         event.description = infor[1]
         todo.events.add(event)
         todo.events
         filename = infor[1].replace(" ", "")  #reformat to create the file
         with open(filename + '.ics', 'w') as f:
             f.write(str(todo))
def _add_event(c, title, year, month, day, start_time):
    e = Event()
    e.name = title
    e.begin = _build_arrow(
        f'{year}/{month.zfill(2)}/{day.zfill(2)} {start_time}')
    e.end = _build_arrow(f'{year}/{month.zfill(2)}/{day.zfill(2)} 20:00:00')
    c.events.add(e)
 def exportClass(self, day):
     e = Event()
     e.name = self.name
     e.begin = datetime.combine(day, self.begin) + timedelta(hours=4)
     e.end = datetime.combine(day, self.end) + timedelta(hours=4)
     e.location = self.location
     return (e)
Exemple #12
0
def convert_to_ics(event):
    ev = Event()

    # name
    if event['significant'] == 'Nazionale':
        ev.name = "Sciopero {} Nazionale".format(event['sector'])
    else:
        ev.name = "Sciopero {} {} ({})".format(event['sector'],
                                               event['region'],
                                               event['province'])

    # date and time
    ev.begin = convert_format(event['start_date'], event['start_time'])
    ev.end = convert_format(event['end_date'], event['end_time'])
    if event['start_time'] == None:
        ev.make_all_day()

    # description
    ev.description = DESCRIPTION.format(
        get_default(event, 'modality'), get_default(event, 'labor_unions'),
        get_default(event, 'categories'),
        get_default(event, 'proclamation_date'),
        get_default(event, 'date_of_receipt'))

    return ev
Exemple #13
0
def create_ical_event_from_session(session):
    e = Event()
    e.name = session.title
    e.begin = session.start_time
    e.end = session.end_time
    e.location = session.location
    return e
Exemple #14
0
    def make_event(self):

        ics = Calendar()
        event = Event()

        # check for existing work shift
        # if there is one, delete it and replace with the new one
        # because it's possible the shift has changed
        split = self.date.split('-')
        # print("looking in calendar for date: " + self.date)

        try:
            todayshift = calendar.date_search(
                datetime(int(split[0]), int(split[1]), int(split[2])),
                datetime(int(split[0]), int(split[1]),
                         int(split[2]) + 1))
        except ValueError:
            print("it's next month for next day.")
            todayshift = calendar.date_search(
                datetime(int(split[0]), int(split[1]), int(split[2])),
                datetime(int(split[0]),
                         int(split[1]) + 1, 1))
        for e in todayshift:
            e.load()
            if "<SUMMARY{}work" in str(e.instance.vevent):
                # print("deleting existing shift")
                e.delete()
        event.name = "work - " + self.position
        event.begin = self.date + " " + self.start_time
        event.end = self.date + " " + self.end_time
        ics.events.add(event)
        # we need to get rid of the Z in the times because it implies we're using UTC
        # we are just using 'local' time, no time zone and ics module only supports UTC
        calendar.add_event(str(ics).replace("Z", ""))
Exemple #15
0
def add_course(kurs):
    r = requests.get(f"https://www.fu-berlin.de/vv/de/search?query={kurs}")
    soup = BeautifulSoup(r.text)
    dates = [(text.text.strip().split(" ")[1], text.text.strip().split(" ")[2],
              text.text.strip().split(" ")[4])
             for text in soup.find_all(class_="course_date_time")]
    for date in dates:
        e = Event()
        e.name = soup.find_all("h1")[1].text
        year = date[0].split(".")[2]
        month = date[0].split(".")[1]
        day = date[0].split(".")[0]

        starthours = date[1].split(":")[0]
        startminutes = date[1].split(":")[1]

        endhours = date[2].split(":")[0]
        endminutes = date[2].split(":")[1]

        seconds = "00"
        begin = arrow.get(
            year + "-" + month + "-" + day + " " + starthours + ":" +
            startminutes + ":" + seconds, 'YYYY-MM-DD HH:mm:ss')
        begin = begin.replace(tzinfo='Europe/Paris')
        begin = begin.to("utc")
        e.begin = begin.format('YYYY-MM-DD HH:mm:ss')
        end = arrow.get(
            year + "-" + month + "-" + day + " " + endhours + ":" +
            endminutes + ":" + seconds, 'YYYY-MM-DD HH:mm:ss')
        end = end.replace(tzinfo='Europe/Paris')
        end = end.to("utc")
        e.end = end.format('YYYY-MM-DD HH:mm:ss')
        c.events.add(e)
Exemple #16
0
def CreateCalendar(groups, Classes, periods):
    global NbEventsCreated
    cal = Calendar()
    dateFormat = "%Y-%m-%d %H:%M:%S"
    for period in periods:
        FirstWeekDay = period[0].weekday()
        LastWeekDay = period[1].weekday()
        for i in range(FirstWeekDay, LastWeekDay + 1):
            for Class in Classes:
                if Class[2] == i:
                    if Class[5] == 1 or getGroupOfClass(
                            groups, Classes.index(Class)
                    ) == period[
                            2]:  #if frequency is 1 (class occuring each week) or if group matches period
                        e = Event()
                        startDT = period[0] + timedelta(Class[2] -
                                                        period[0].weekday())
                        startDT = startDT.replace(
                            hour=int(Class[3][:Class[3].index(':')]))
                        startDT = startDT.replace(
                            minute=int(Class[3][Class[3].index(':') + 1:]))
                        endDT = startDT.replace(
                            hour=int(Class[4][:Class[4].index(':')]))
                        endDT = endDT.replace(
                            minute=int(Class[4][Class[4].index(':') + 1:]))
                        e.begin = startDT.strftime(dateFormat)
                        e.end = endDT.strftime(dateFormat)
                        e.location = Class[6]
                        e.name = Class[0] + " (" + Class[1] + ")"
                        cal.events.add(e)
                        NbEventsCreated += 1
    return cal
Exemple #17
0
def send_appointment_reminder(signup: AppointmentSignup):
    appointment = signup.appointment
    user = signup.user

    c = Calendar()
    e = Event()
    e.name = f"{format_coursecode(get_course())} Appointment"
    e.begin = pytz.timezone("America/Los_Angeles").localize(appointment.start_time)
    e.end = e.begin + appointment.duration
    e.location = appointment.location.name
    c.events.add(e)

    helper_msg = (
        f"It will be led by {appointment.helper.name}.\n" if appointment.helper else ""
    )

    send_email(
        sender="OH Queue <*****@*****.**>",
        target=user.email,
        subject=f"{format_coursecode(get_course())} Appointment Scheduled",
        body=(
            f"""
    Hi {user.short_name},

    An appointment has been scheduled for you using the {format_coursecode(get_course())} OH Queue. 
    It is at {appointment.start_time.strftime('%A %B %-d, %I:%M%p')} Pacific Time, at location {appointment.location.name}.
    {helper_msg}
    To edit or cancel this appointment, go to https://{get_domain()}.

    Best,
    The 61A Software Team
    """.strip()
        ),
        attachments={"invite.ics": b64encode(str(c).encode("utf-8")).decode("ascii")},
    )
Exemple #18
0
def main(args):
    res = requests.get('http://www.febclub2017.com/events')
    print "Encoding: {}".format(res.encoding)
    soup = BeautifulSoup(res.text, 'html.parser')

    cal = Calendar()

    for link in soup.find_all("div", { "class" : "detail" }):
        # Parse and format data
        paragraphs = [p.text for p in link.find_all('p')]
        date = paragraphs[2].split('\n')

        start_date = dp.parse("{} {}".format(date[0], date[1].split('-')[0].strip()))
        end_date = dp.parse("{} {}".format(date[0], date[1].split('-')[1].strip()))

        if end_date < start_date:
            end_date = end_date + timedelta(days=1)

        start_date = pytz.timezone('US/Eastern').localize(start_date)
        end_date = pytz.timezone('US/Eastern').localize(end_date)

        description = paragraphs[1].encode('ascii', errors='backslashreplace')

        event = Event()
        event.name = link.h1.text
        event.begin = start_date.isoformat()
        event.end = end_date.isoformat()
        event.description = u"{}\n{}\n\n{}".format(paragraphs[0], paragraphs[4], description)
        event.location = paragraphs[3]

        cal.events.append(event)
        print "Added event {}".format(link.h1.text)

    with open('febclub.ics', 'w') as f:
        f.writelines(cal)
Exemple #19
0
 def as_ical(self):
     event = Event()
     event.name = ' and '.join(collection.type
                               for collection in self._collections)
     event.begin = self.date
     event.end = self.date.replace(hour=8, minute=10)
     return event
Exemple #20
0
    def loadCal(self):
        with open("CAL_REQ.json", "r") as f:
            global c
            c2 = Calendar()
            data = json.load(f)
            headers = {"Authorization": "basic T64Mdy7m["}
            r = requests.post(
                "https://opentimetable.dcu.ie/broker/api/categoryTypes/241e4d36-60e0-49f8-b27e-99416745d98d/categories/events/filter",
                json=data,
                headers=headers,
            )
            if r.status_code == 200:
                response = json.loads(r.text)
                for event in response[0]["CategoryEvents"]:
                    e = Event()
                    e.begin = event["StartDateTime"]
                    e.end = event["EndDateTime"]
                    e.location = event["Location"]
                    e.description = ""
                    for item in event["ExtraProperties"]:
                        if item["DisplayName"] == "Module Name":
                            e.name = "{} - {}".format(item["Value"],
                                                      event["EventType"])
                        e.description += "{}: {}\n".format(
                            item["DisplayName"], item["Value"])

                    c2.events.add(e)
                c = c2
                return True
            else:
                print("Request Failed: %d" % r.status_code)
                return False
Exemple #21
0
def unibo_calendar():
    print("Options:")
    print("Year: " + YEAR)
    print("Course: " + COURSE)

    # Get data
    print("Getting json data...")
    url = 'https://corsi.unibo.it/laurea/' + \
        str(COURSE) + "/orario-lezioni/@@orario_reale_json?anno=" + str(YEAR)
    events = requests.get(url).json()
    print(str(len(events)) + " events found!")

    # Build calendar
    calendar = Calendar()
    for event in events:
        # Build event
        e = Event(location=event.get("aule")[0].get("des_ubicazione"),
                  alarms=None)
        e.name = event.get("title").title() + " - " + \
            event.get("aule")[0].get("des_risorsa")
        e.begin = arrow.get(event.get("start")).replace(tzinfo="Europe/Rome")
        e.end = arrow.get(event.get("end")).replace(tzinfo="Europe/Rome")

        # Add event to calendar
        calendar.events.add(e)

    # Print file
    print("Writing .ics...")
    with open('UniboCalendar.ics', 'w') as file:
        file.writelines(calendar)
        print("Done!")
Exemple #22
0
def make(parsed, monday):
    calendar = Calendar()
    calendar.creator = "eAUrnik - Fork me on GitHub: https://git.io/JO5Za"
    
    durations = []
    for duration in parsed[0]:
        start, end = duration.split(" - ")
        start_hours, start_minutes = map(int, start.split(":"))
        end_hours, end_minutes = map(int, end.split(":"))
        durations.append(((start_hours, start_minutes), (end_hours, end_minutes)))
        
    data = parsed[1]
    for day_index in range(0, len(data)):
        day = monday + timedelta(days = day_index)
        lessons = data[day_index]
        for lesson_index in range(0, len(lessons)):
            for lesson in lessons[lesson_index]:
                title = lesson[0]
                subtitle = lesson[1]
                
                duration = durations[lesson_index]
                timezone = ZoneInfo("Europe/Ljubljana")
                start = datetime(day.year, day.month, day.day, duration[0][0], duration[0][1], tzinfo = timezone)
                end = datetime(day.year, day.month, day.day, duration[1][0], duration[1][1], tzinfo = timezone)

                event = Event()
                event.name = title
                event.location = subtitle
                event.begin = start
                event.end = end
                calendar.events.add(event)

    return string(calendar)
def send_mail_sendgrid(description, agenda: Agenda):
    c = Calendar()
    e = Event()
    e.name = 'Atendimento Aset Terapias'

    str_begin = '-'.join(reversed(agenda.date.split('/')))
    str_begin = f'{str_begin} {agenda.time}'
    e.begin = (datetime.strptime(str_begin, '%Y-%m-%d %H:%M') +
               timedelta(hours=3))
    e.end = (datetime.strptime(str_begin, '%Y-%m-%d %H:%M') +
             timedelta(hours=4))

    e.attendees = [agenda.appointment.customer.email, agenda.therapist.email]
    e.description = description
    c.events.add(e)

    curdir = os.getcwd()

    with open(f'{curdir}{os.sep}go.ics', 'w') as f:
        f.writelines(c)

    with open(
            f'{curdir}{os.sep}apps{os.sep}agenda{os.sep}email_templates{os.sep}appointment-confirmation.html',
            encoding='utf-8') as templ:
        body = ''.join(templ.readlines())
        body = body.replace('{{nome}}', agenda.appointment.customer.name)
        body = body.replace('{{nome_terapia}}', agenda.appointment.specialty)
        body = body.replace('{{nome_terapeuta}}', agenda.therapist.name)
        body = body.replace('{{data}}', agenda.date)
        body = body.replace('{{hora}}', agenda.time)

        body = body.replace('{{api}}', os.getenv("API_ENDPOINT"))
        body = body.replace('{{calendar}}', agenda.calendar.name)
        body = body.replace('{{therapist_mail}}', agenda.therapist.email)
        body = body.replace('{{date}}', agenda.date.replace('/', '-'))
        body = body.replace('{{hour}}', agenda.time)
        body = body.replace('{{text}}', agenda.appointment.text)

        message = Mail(from_email=os.getenv("EMAIL_SENDER"),
                       to_emails=agenda.appointment.customer.email,
                       subject='Aset Terapias : Confirmação de consulta',
                       html_content=body)
        try:
            message.add_bcc(agenda.therapist.email)
            with open(f'{curdir}{os.sep}go.ics', 'rb') as f:
                data = f.read()
                f.close()
            encoded = base64.b64encode(data).decode()
            attachment = Attachment()
            attachment.file_content = FileContent(encoded)
            attachment.file_name = FileName('go.ics')
            attachment.disposition = Disposition('attachment')
            attachment.content_id = ContentId('Unique Content ID')
            message.attachment = attachment
            sg = SendGridAPIClient(api_key=os.getenv('EMAIL_TOKEN'))
            sg.send(message=message)
        except Exception as e:
            print('Erro no envio de e-mail')
            print(e)
Exemple #24
0
def generate_ics():
    c = Calendar()
    e = Event()
    e.name = "Fireapp shift details: "
    e.begin = '2021-01-01 00:00:00'
    e.end = '2021-05-01 00:00:00'
    c.events.add(e)
    return c
Exemple #25
0
def json2ics(inputfile):
    """ convert json containing tuebix 2016 papers to ics """
    cal = Calendar()
    with open(inputfile) as data_file:
        data = json.load(data_file)
    next120 = datetime(2016, 5, 1, 8, 0)
    next55 = datetime(2016, 5, 4, 8, 0)
    next25 = datetime(2016, 5, 7, 10, 0)
    for talk in data:
        event = Event()
        event.name = talk["titel"]
        event.description = talk["name"] + "\n" + talk["inhalt"]
        # keep Ingo out and use him as a Joker at the end
        if talk["type"]["workshop"] and talk["name"] != "Ingo Blechschmidt":
            event.begin = next120
            event.end = next120 + timedelta(hours=2)
            next120 += timedelta(hours=2)
            if next120.hour > 15:
                next120 += timedelta(hours=16)
            cal.events.append(event)
            for cfptype, possible in talk["type"].items():
                if possible and cfptype != "workshop":
                    event.name += " ### " + cfptype
        elif talk["type"]["v55"] and talk["name"] != "Ingo Blechschmidt":
            event.begin = next55
            event.end = next55 + timedelta(hours=1)
            next55 += timedelta(hours=1)
            if next55.hour > 15:
                next55 += timedelta(hours=16)
            cal.events.append(event)
            for cfptype, possible in talk["type"].items():
                if possible and cfptype != "v55":
                    event.name += " ### " + cfptype
        elif talk["type"]["v25"] and talk["name"] != "Ingo Blechschmidt":
            event.begin = next25
            event.end = next25 + timedelta(minutes=30)
            next25 += timedelta(minutes=30)
            if next25.hour > 15:
                next25 += timedelta(hours=16)
            cal.events.append(event)
            for cfptype, possible in talk["type"].items():
                if possible and cfptype != "v25":
                    event.name += " ### " + cfptype

    with open(icsfile, 'w') as my_file:
        my_file.writelines(cal)
Exemple #26
0
 def add_event_from_dtime(self, day_str, message="在宅"):
     event = Event()
     ini_dtime = self.day_parser(day_str)
     fin_dtime = add_n_day(ini_dtime, 1)
     event.name = message
     event.begin = self.from_datetime_to_etime_str(ini_dtime)
     event.end = self.from_datetime_to_etime_str(fin_dtime)
     self._internal_cal.events.add(event)
def create_calendar_event(date, name, description):
    e = Event()
    e.name = name
    e.description = description
    e.begin = date
    e.end = date + timedelta(hours=24)
    e.url = EVENT_URL
    return e
Exemple #28
0
 def createICS(typ,deb,fin,matiere,salle,prof):
     e = Event()
     e.name = "{} - {}".format(salle,matiere)
     e.begin = deb
     e.end = fin
     e.location = salle
     e.description = "{}: {} en {} par {}".format(typ,matiere,salle,prof)
     self.c.events.add(e)
Exemple #29
0
def printerToCalendar(planning, csv_file):
    for creneau in planning["creneau"]:
        c = Calendar()
        e = Event()
        e.name = 'piscine ' + planning['nom']
        heureCreneau = list(creneau[0])
        for elem in heureCreneau:
            if elem == ':':
                heureCreneau = heureCreneau[:heureCreneau.index(elem)]
                pass
        heureCreneau = ''.join(str(elem) for elem in heureCreneau)
        heureCreneauend = list(creneau[1])
        for elem in heureCreneauend:
            if elem == ':':
                heureCreneauend = heureCreneauend[:heureCreneauend.index(elem)]
                pass
        heureCreneauend = ''.join(str(elem) for elem in heureCreneauend)
        minute = ''.join(str(elem) for elem in creneau[0][-2:])
        minuteEnd = ''.join(str(elem) for elem in creneau[1][-2:])
        #print(f"heure : {heureCreneau}  et la minute : {minute}, creneau : {creneau[1]}")
        date = creneau[2].split(' ')
        # print(f" la date : {date}")
        datetime_object = datetime.datetime.strptime(date[2], "%B")
        date[2] = datetime_object.month

        e.begin = datetime.datetime(int(date[3]),
                                    int(date[2]),
                                    int(date[1]),
                                    int(heureCreneau),
                                    int(minute),
                                    0,
                                    tzinfo=paris)
        # e.begin = creneauStr[0]
        # e.end = creneauStr[1]
        #print(date,heureCreneauend+':'+minute)
        e.end = datetime.datetime(int(date[3]),
                                  int(date[2]),
                                  int(date[1]),
                                  int(heureCreneauend),
                                  int(minuteEnd),
                                  0,
                                  tzinfo=paris)

        # e.begin = creneauStr[0]
        # e.end = creneauStr[1]
        c.events.add(e)
        c.events
        os.chdir(r'../')
        if not os.path.exists('tmp'):
            os.mkdir('tmp')
        os.chdir('tmp')
        #planning['nom'] = nom
        with open(planning["nom"] + '.ics', 'a') as my_file:
            my_file.writelines(c)
        os.chdir('../fichiersAtraiter')
    planning['nom'] = None
    planning['creneau'] = []
    csv_file.seek(0)
Exemple #30
0
 def AppendEvent():
     e = Event()
     e.name = kc[0]
     e.begin = d1.isoformat() + 'T' + st[int(kc[4]) - 1]
     e.end = d1.isoformat() + 'T' + et[int(kc[5]) - 1]
     e.location = kc[2]
     c.events.append(e)
     print('ok')
     return
def generate_event(name, begin, end, description, uid):
	e = Event()
	e.name = name
	e.begin = datetime.strptime(begin, "%Y%m%d")
	e.end = datetime.strptime(end, "%Y%m%d") + timedelta(days=1)
	e.description = description
	e.uid = uid
	e.make_all_day()
	return e
Exemple #32
0
 def convert_to_event(self):
     for period in self.__class_list:
         e = Event()
         e.name = period.name
         e.begin = period.ics_formatted_plus_eight_start
         e.end = period.ics_formatted_plus_eight_end
         e.location = period.location
         e.description = period.class_type
         self.__calendar.events.add(e)
Exemple #33
0
def parseEvents(events, curEvent):
    c = Calendar()
    for e in events:
        event = Event()
        event.name = e['Subject']
        event.begin = e['Start']['DateTime']
        event.end = e['End']['DateTime']
        if event.begin >= curEvent.startDate and event.end <= curEvent.endDate:
          c.events.append(event)
    return c
# style times in ical format
for i in range(len(stime)):
    stime[i] = stime[i].replace(":", "") + "00"


for i in range(len(etime)):
    etime[i] = etime[i].replace(":", "") + "00"


"""########################### FILE CREATION ###########################"""
output_file = open(output_path + output_filename, 'w+')

# LOGIC

c = Calendar()
e = Event()

# ics library stuff, generates the ics format
for i in range(len(sesh)):
    e = Event()
    e.name = str(sesh[i])
    e.description = stype[i]
    e.begin = date[i] + "T" + stime[i] + "+0100"  # "20170906T140000"
    e.end = date[i] + "T" + etime[i] + "+0100"  # "20170906T15000"
    e.location = loc[i]
    c.events.append(e)

output_file.writelines(c)

output_file.close()
    try:
        for each in range(len(subject)):
            subject[each] = str(subject[each])[:n.search(str(subject[each])).start()]+"/"+str(subject[each])[n.search(str(subject[each])).end():]
    except Exception as e:
        break;
for each in subject:
    subject[num] = each.split("/")
    num = num + 1
d = datetime.datetime.today()
today = datetime.date.today()
begindate = []
c = Calendar()
num = 0
for r in range(10):
    num = 0
    for i in range(1):
        for each in subject:
            e = Event()
            if(r == 0):
                juli = abs(int(changeWeekday(each[2]))-1)
                begindate.append(today + datetime.timedelta(days = juli))
            e.name = each[1]
            e.begin = str(begindate[num]).replace("-","") +" "+changeTimeStart(each[2])
            e.end = str(begindate[num]) +changeTimeEnd(each[2])
            begindate[num] = begindate[num]+datetime.timedelta(days = 7)
            num = num + 1
            e.location = each[4]
            c.events.append(e)
            

 def save(self, item):
     e = Event()
     e.name = item['title'][0].strip()
     e.begin = time.strftime('%Y%m%dT%H%M00Z', time.strptime(item['startDate'][0].strip() + ' ' + item['startTime'][0].strip(), "%d-%m-%Y %H:%M"))
     e.end = time.strftime('%Y%m%dT%H%M00Z',time.strptime(item['startDate'][0].strip() + ' ' + item['endTime'][0].strip(), "%d-%m-%Y %H:%M"))
     self.c.events.append(e)
Exemple #37
0
                            locode = locode + otherevent['locCode'][-2:-1]
                            ids.append(otherevent['id'])

            #I wanted to add the tye of lecture to the start of the title, Again this could probably be improved
            if "[" in event['desc2']:
                class_name = event['desc2'].split('[')
                e.name = '[' + class_name[1] + ' ' \
                    + (class_name[0])[:-2] + ' (' + event['desc1'] + ')'
            else:
                class_name = event['desc2']
                e.name = class_name + ' (' + event['desc1'] + ')'
#That mess of a code is over now, lets just add everything to the event now

            logging.debug(e.name + ' - ' + locode)
            e.begin = event['start']
            e.end = event['end']
            e.description = event.get('teacherName', '')
            e.location = locode
            c.events.append(e)


#write it all to file
icalfile = ical_loc + username + '.ics'
open(icalfile, 'w').writelines(c)
with open(icalfile, 'r') as file:
    lines = file.readlines()
    lines[1] = lines[1] + 'X-WR-CALNAME: ' + student_name \
        + ' Uni Timetable\nX-PUBLISHED-TTL:PT12H'

with open(icalfile, 'w') as file:
    for line in lines:
for grow in gwsheet.get_all_records():
	if grow["ICSDate"]!="":
		try:
			# print "%s | %s | %s " % (grow["DESC"], grow["ICSDate"], grow["ICSTime"])
			evt = Event()
			# evt.name = unicodedata.normalize('NFKD', unicode(grow["DESC"]))
			# evt.name = "Nombre evento"
			# evt.name = grow["DESC"].encode('ascii', 'replace')
			# evt.name = grow["DESC"]
			evt.name = unidecode(grow['DESC'])
			evt.location = unidecode(grow['SALA'])
			(t_begin, t_end) = grow["TIME"].split("-")
			d_begin = "%sT%s:00%s" % (grow["ICSDate"], t_begin.strip(), utc_offset)
			evt.begin = d_begin.replace(":","").replace(".","")
			d_end = "%sT%s:00%s" % (grow["ICSDate"], t_end.strip(), utc_offset)
			evt.end = d_end.replace(":","").replace(".","")
			cal.events.append(evt)
			print "Added %s starting %s ending %s" % (evt.name, d_begin, d_end)
			# print "Added %s, event %s" % (grow['DESC'],evt)
		except:
			print grow
			raise
# END for grow

# Write ics file to disk
with codecs.open("lacnic27.ics", "w", encoding="utf-8") as fn:
	fn.writelines(cal)

## END MAIN ###############################################################################

## END FILE ###############################################################################