Esempio n. 1
0
    def export_menu_calendar(self):
        c = Calendar()
        shopping_list = []
        # create calendar event
        for _, row in self.menu.iterrows():
            e = Event()
            e.name = '[' + row['meal'].capitalize() + '] ' + row['recipe']
            t = datetime.datetime.strptime(row['date'], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(hours=2)
            e.begin = t.strftime("%Y-%m-%d %H:%M:%S")
            if row['meal'] == 'lunch':
                e.duration = {"minutes": 30}
            else:
                e.duration = {"minutes": 60}
            try:
                e.description = '\n'.join(row['ingredients']) + f"\n\n{row['notes']}"
                shopping_list.append('\n'.join(row['ingredients']))
            except TypeError:
                e.description = "Please fill the ingredientes for this recipe!"
                shopping_list.append(f"Ingredients for {row['recipe']}")
            c.events.add(e)

        e = Event()
        e.name = "Shopping List"
        e.begin = self.start_date
        e.description = '\n'.join(shopping_list)
        e.make_all_day()
        c.events.add(e)
        fname = "menus/menu_{}.ics".format(self.start_date)
        with open(fname, 'w') as my_file:
            my_file.writelines(c)
        os.system(f"open {fname}")
Esempio n. 2
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)
Esempio n. 3
0
    def post(self):
        data = request.get_json()
        if data is None:
            abort(400, 'Trip Data not received')
        itinerary = data.get('itinerary')

        # start_date = data.get('startdate')
        # start = datetime.strptime(start_date,'%y-%m-%d %H:%M:%S')
        # # account for gmt, sydney+11
        # start = start - timedelta(hours=-11)
        # # assume starting day at 9am
        # start = start + timedelta(hours=9)

        c = Calendar()
        for event in itinerary:
            e = Event()
            e.name = event['name']
            e.begin = datetime.strptime(
                event['start'], '%Y-%m-%dT%H:%M:%S.000Z'
            )  #+timedelta(hours=-11) #account for tz
            e.duration = timedelta(minutes=event['duration'])
            c.events.add(e)
        # with open('my.ics', 'w') as f:
        #     f.write(str(c))
        return {"content": str(c)}
Esempio n. 4
0
def create_birthday_event(uid: str, name: str,
                          birthday_date: datetime) -> Event:
    """ Create a birthday event with the provided parameters.
    :param uid:             Friend's FB UID
    :param name:            Friend's FB name
    :param birthday_date:   Friend's birthday date
    :return:                Birthday event
    """
    # Initialize birthday_event to a new event
    birthday_event = Event()
    birthday_event.uid = uid
    birthday_event.name = f"{name}'s Birthday"
    today = datetime.today()
    # Calculate the year as this year or next year based on if its past
    # current month or not
    year = today.year if birthday_date.month >= today.month else (
        today + relativedelta(years=1)).year
    # Pad day, month with leading zeros to 2dp
    month = '{:02d}'.format(birthday_date.month)
    day = '{:02d}'.format(birthday_date.day)
    birthday_event.begin = f'{year}-{month}-{day} 00:00:00'
    birthday_event.make_all_day()
    birthday_event.duration = timedelta(days=1)
    birthday_event.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY'))
    return birthday_event
Esempio n. 5
0
def create_ics(confs, stream):
    cal = Calendar()
    """
    # For standard compliance
    cal.add('prodid', '-//NLP CFP DB calendar//xx.url//')
    cal.add('version', '2.0')
    """

    for name, data in confs.items():
        begin = correct_date(data.get('begin', ''), far_future)
        end = correct_date(data.get('end', ''), far_future)
        location = data['location']
        url = data['url']

        for field_name in ('submission', 'notification', 'camera-ready'):
            add_event(cal, name, location, url, field_name.upper(), field_name,
                      data, far_future)

        if begin is not None:
            if end < begin:
                end = begin

            # Conference
            e = Event(name=name,
                      begin=datetime.combine(begin, datetime.min.time()),
                      location=location,
                      url=url)
            e.make_all_day()
            e.duration = end - begin + timedelta(days=1)
            cal.events.add(e)

    stream.writelines(cal)
Esempio n. 6
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()
Esempio n. 7
0
def populate_birthdays_calendar(birthdays):
    """ Populate a birthdays calendar using birthday objects """

    c = Calendar()
    c.scale = 'GREGORIAN'
    c.method = 'PUBLISH'
    c.creator = f'fb2cal v{__version__} ({__status__}) [{__website__}]'
    c.extra.append(
        ContentLine(name='X-WR-CALNAME', value='Facebook Birthdays (fb2cal)'))
    c.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT12H'))
    c.extra.append(
        ContentLine(name='X-ORIGINAL-URL', value='/events/birthdays/'))

    cur_date = datetime.now()

    for birthday in birthdays:
        e = Event()
        e.uid = birthday.uid
        e.name = f"{birthday.name}'s Birthday"

        # Calculate the year as this year or next year based on if its past current month or not
        # Also pad day, month with leading zeros to 2dp
        year = cur_date.year if birthday.month >= cur_date.month else (
            cur_date + relativedelta(years=1)).year
        month = '{:02d}'.format(birthday.month)
        day = '{:02d}'.format(birthday.day)
        e.begin = f'{year}-{month}-{day} 00:00:00'
        e.make_all_day()
        e.duration = timedelta(days=1)
        e.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY'))

        c.events.add(e)

    return c
Esempio n. 8
0
    def scheduler(self):
        c = Calendar()

        for x in range(Calc.dates.__len__()):
            e = Event()
            calc1 = Calc()
            date = Calc.dates[x]
            name = ""
            for y in range(4):
                name += str(calc1.assignShifts(calc1.dates[x])) + " "
            time = " 21:30:00"
            date_time = str(date) + time
            datetime_obj_naive = datetime.strptime(
                date_time, "%Y-%m-%d %H:%M:%S")  #Get date and time
            datetime_obj_eastern = timezone('US/Eastern').localize(
                datetime_obj_naive)  #Convert to EST
            Calc.dates[x] = datetime_obj_eastern.strftime(
                "%Y-%m-%d %H:%M:%S %Z%z")
            print(Calc.dates[x])
            e.begin = datetime_obj_eastern
            e.name = "Designated Drivers"
            e.duration = timedelta(hours=5)
            e.description = " "
            e.description = e.description + str(name)
            c.events.add(e)
            c.events
        with open('DD_Calendar.ics', 'a') as my_file:
            my_file.writelines(c)
Esempio n. 9
0
def team_ics(team):
    matches = Matches().get_matches(lambda m: m.doesFeature(team))
    c = Calendar()
    for m in matches:
        if not m._date:
            continue

        e = Event(uid=fixture_uid(m), location=m.venue)
        e.name = "%s vs %s" % (m.home, m.away)


        if not m._time:
            m._time = time(0,0,0)

        begin = datetime(m._date.year,
                         m._date.month,
                         m._date.day,
                         m._time.hour,
                         m._time.minute,
                         m._time.second)
        begin = arrow.get(begin, 'Europe/London')
        e.begin = begin
        e.duration = timedelta(minutes=90)
        c.events.append(e)
    return Response(c, mimetype='text/calendar')
Esempio n. 10
0
    def add_session(self, session):
        e = Event()
        e.name = session.name
        e.begin = session.begin
        e.duration = session.duration
        e.location = session.location

        self.c.events.add(e)
Esempio n. 11
0
def populate_birthdays_calendar(birthdays):
    """ Populate a birthdays calendar using birthday objects """

    c = Calendar()
    c.scale = 'GREGORIAN'
    c.method = 'PUBLISH'
    c.creator = f'fb2cal v{__version__} ({__status__}) [{__website__}]'
    c.extra.append(
        ContentLine(name='X-WR-CALNAME', value='Facebook Birthdays (fb2cal)'))
    c.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT12H'))
    c.extra.append(
        ContentLine(name='X-ORIGINAL-URL', value='/events/birthdays/'))

    cur_date = datetime.now()
    backburner = []
    rearrange = False

    logger.info("Saving birthdays to local cache...")
    with open('birthdays.pkl', 'wb') as pkl_file:
        pickle.dump(birthdays, pkl_file)
        logger.info("Saved to cache (src/birthdays.pkl)")

    for birthday_i in range(0, len(birthdays)):

        birthday = birthdays[birthday_i]

        if (birthday.month == 2 and birthday.day == 29):
            rearrange = True
            backburner.append(birthday)
            del birthdays[birthday_i]
            birthday_i -= 1
            continue
        if rearrange:
            if not (birthday.month == 2 and birthday.day == 28):
                birthdays.insert(birthday_i, backburner)
                rearrange = False
                birthday_i -= 1
                continue

        e = Event()
        e.uid = birthday.uid
        e.name = f"{birthday.name}'s Birthday"

        # Calculate the year as this year or next year based on if its past current month or not
        # Also pad day, month with leading zeros to 2dp
        year = cur_date.year if birthday.month >= cur_date.month else (
            cur_date + relativedelta(years=1)).year
        month = '{:02d}'.format(birthday.month)
        day = '{:02d}'.format(birthday.day)
        e.begin = f'{year}-{month}-{day} 00:00:00'
        e.make_all_day()
        e.duration = timedelta(days=1)
        e.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY'))

        c.events.add(e)

    return c
Esempio n. 12
0
    def generate(self):
        c = Calendar()
        c.scale = 'GREGORIAN'
        c.method = 'PUBLISH'
        c.creator = f'fb2cal v{__version__} ({__status__}) [{__website__}]'
        c.extra.append(
            ContentLine(name='X-WR-CALNAME',
                        value='Facebook Birthdays (fb2cal)'))
        c.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT12H'))
        c.extra.append(
            ContentLine(name='X-ORIGINAL-URL', value='/events/birthdays/'))

        cur_date = datetime.now()

        for facebook_user in self.facebook_users:
            # Don't add extra 's' if name already ends with 's'
            formatted_username = f"{facebook_user.name}'s" if facebook_user.name[
                -1] != 's' else f"{facebook_user.name}'"
            formatted_username = f'{formatted_username} Birthday'

            # Set date components
            day = facebook_user.birthday_day
            month = facebook_user.birthday_month
            year = facebook_user.birthday_year

            # Feb 29 special case:
            # If event year is not a leap year, use Feb 28 as birthday date instead
            if facebook_user.birthday_month == 2 and facebook_user.birthday_day == 29 and not calendar.isleap(
                    year):
                day = 28

            # The birth year may not be visible due to privacy settings
            # In this case, calculate the year as this year or next year based on if its past current month or not
            if year is None:
                year = cur_date.year if facebook_user.birthday_month >= cur_date.month else (
                    cur_date + relativedelta(years=1)).year

            # Format date components as needed
            month = f'{month:02}'
            day = f'{day:02}'

            # Event meta data
            e = Event()

            e.uid = facebook_user.id
            e.name = formatted_username
            e.created = cur_date
            e.description = f'{facebook_user}\n{generate_facebook_profile_url_permalink(facebook_user)}'
            e.begin = f'{year}-{month}-{day} 00:00:00'
            e.make_all_day()
            e.duration = timedelta(days=1)
            e.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY'))

            c.events.add(e)

        self.birthday_calendar = c
Esempio n. 13
0
def ics_event(name, start_date, duration=None, alarm_start=0.5):
    a = add_alarm(alarm_start)
    e = Event(alarms=[a])
    e.name = name
    u = start_date
    e.begin = u
    if duration:
        d = datetime.timedelta(days=duration)
        e.duration = d
    return e
Esempio n. 14
0
    def build_calendar(self, stream=None):
        '''
    Build calendar from sessions
    '''

        cal = Calendar()
        # Add sessions and dates to lines
        for week_pos in range(0, self.plan.get_weeks_nb()):
            dates = []
            week = []

            for day_pos in range(0, 7):
                sessions = []

                date = self.plan.calc_date(week_pos, day_pos)

                # Render sessions using html template
                for session in self.plan.sessions.filter(week=week_pos,
                                                         day=day_pos):
                    e = Event()
                    e.name = session.name

                    e.description = session.sport.name + " - " + session.type + "\n"
                    # [TODO] check hour planned for training
                    e.begin = datetime.combine(
                        date, datetime.min.time()) + timedelta(hours=19)
                    if session.distance is not None:
                        e.description += "Distance: %f \n " % session.distance
                    if session.time is not None:
                        e.description += "Duration: %s \n " % session.time
                        e.duration = session.time
                    else:
                        e.duration = timedelta(hours=2)

                    cal.events.append(e)

                week.append(sessions or '')

        stream.write(str(cal))
Esempio n. 15
0
def bis_cal(team):

    mt = pytz.timezone('US/Mountain')
    utc = pytz.utc

    link, team_name, session, league = getUrl(team)

    if link:
        with requests.Session() as s:
            url_root = 'http://www.boulderindoorsoccer.com/schedules/'
            url = url_root + link + "&l={}".format(league.strip().replace(
                ' ', '+'))
            soup = BeautifulSoup(s.get(url).text, 'html.parser')
            table = soup.find("table", attrs={"class": "scheduleTable"})
            c = Calendar()
            for tr in table.findAll("tr"):
                good_line = False
                column = 1
                for td in tr.findAll("td"):
                    if good_line == True:
                        if column == 2:
                            home_team = td.text.strip()
                        elif column == 5:
                            away_team = td.text.strip()
                        column += 1
                    for span in td.findAll("span"):
                        date = span.text[9:-1].strip()
                    if td.text[0].isdigit() and good_line == False:
                        time = td.text
                        good_line = True
                        column += 1
                # Create calendar event
                if good_line:
                    e = Event()
                    e.name = "Soccer: " + home_team + " v.s. " + away_team
                    timestamp = parse(date + " " + time)
                    mt_time = mt.localize(timestamp)
                    e.begin = mt_time  #.astimezone(utc)
                    e.duration = timedelta(minutes=50)
                    e.location = "Boulder Indoor Soccer, 3203 Pearl Street, Boulder, CO 80301, United States"
                    c.events.add(e)

            cname = team_name.replace(' ', '-') + '-' + session.replace(
                ' ', '-') + '.ics'
            with open(cname, 'w') as ics_file:
                ics_file.writelines(c)
            print(
                "Calendar succesfully written for {team_name}, {session}: \"{cname}\""
                .format(**locals()))
    else:
        return None
Esempio n. 16
0
def generate_event(event_name="New Event",
                   event_date=datetime.now(),
                   event_duration="1:00",
                   event_description=""):
    """Generates event object using event elements as parameters"""
    e = Event()
    e.name = event_name
    e.begin = event_date
    dur = [int(t) for t in event_duration.split(":")]
    e.duration = timedelta(hours=dur[0], minutes=dur[1])
    e.description = event_description
    print(e)
    print('------')
    return e
Esempio n. 17
0
File: ics.py Progetto: La0/coach
    def build_calendar(self, stream=None):
        """
    Build calendar from sessions
    """

        cal = Calendar()
        # Add sessions and dates to lines
        for week_pos in range(0, self.plan.weeks_nb):
            week = []

            for day_pos in range(0, 7):
                sessions = []

                date = self.plan.calc_date(week_pos, day_pos)

                # Render sessions using html template
                for session in self.plan.sessions.filter(week=week_pos, day=day_pos):
                    e = Event()
                    e.name = session.name

                    e.description = session.sport.name + " - " + session.type + "\n"
                    # [TODO] check hour planned for training
                    e.begin = datetime.combine(date, datetime.min.time()) + timedelta(hours=19)
                    if session.distance is not None:
                        e.description += "Distance: %f \n " % session.distance
                    if session.time is not None:
                        e.description += "Duration: %s \n " % session.time
                        e.duration = session.time
                    else:
                        e.duration = timedelta(hours=2)

                    cal.events.append(e)

                week.append(sessions or "")

        stream.write(str(cal))
Esempio n. 18
0
def BuildCalendar(TimeTable):
    c = Calendar()
    for i in range(len(TimeTable)):
        entry = TimeTable[i]
        for j in range(len(entry.Dates)):
            e = Event()
            date = entry.Dates[j]
            start = entry.Start
            end = entry.End
            e.name = str(entry.Description + " (" + entry.Type + ")")
            e.begin = GenerateArrow(date, start)
            e.duration = GenerateArrow(date, end) - GenerateArrow(date, start)
            e.location = str(entry.Room)
            e.description = str(entry.Staff)
            c.events.add(e)
    return c
Esempio n. 19
0
def bis_cal(team):

    mt = pytz.timezone('US/Mountain')
    utc = pytz.utc

    link, team_name, session = getUrl(team)

    if link:
        with requests.Session() as s:
            url_root = 'http://www.boulderindoorsoccer.com/schedules/'
            url = url_root + link
            soup = BeautifulSoup(s.get(url).text)
            table = soup.find("table", attrs={"class":"scheduleTable"})
            c = Calendar()
            for tr in table.findAll("tr"):
                good_line = False
                column = 1
                for td in tr.findAll("td"):
                    if good_line == True:
                        if column == 2:
                            home_team = td.text.strip()
                        elif column == 5:
                            away_team = td.text.strip()
                        column += 1
                    for span in td.findAll("span"):
                        date = span.text[9:-1].strip()
                    if td.text[0].isdigit() and good_line == False:
                        time = td.text
                        good_line = True
                        column += 1
                # Create calendar event
                if good_line:
                    e = Event()
                    e.name = "Soccer: " + home_team + " v.s. " + away_team
                    timestamp = parse(date + " " + time)
                    mt_time = mt.localize(timestamp)
                    e.begin = mt_time#.astimezone(utc)
                    e.duration = timedelta(minutes=50)
                    e.location = "Boulder Indoor Soccer, 3203 Pearl Street, Boulder, CO 80301, United States"
                    c.events.append(e)

            cname = team_name + ' ' + session + '.ics'
            with open(cname, 'w') as ics_file:
                ics_file.writelines(c)
            print "Calendar succesfully written for {team_name}, {session}: \"{cname}\"".format(**locals())
    else:
        return None
Esempio n. 20
0
    def generate(self):
        c = Calendar()
        c.scale = 'GREGORIAN'
        c.method = 'PUBLISH'
        c.creator = f'fb2cal v{__version__} ({__status__}) [{__website__}]'
        c.extra.append(
            ContentLine(name='X-WR-CALNAME',
                        value='Facebook Birthdays (fb2cal)'))
        c.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT12H'))
        c.extra.append(
            ContentLine(name='X-ORIGINAL-URL', value='/events/birthdays/'))

        cur_date = datetime.now()

        for facebook_user in self.facebook_users:
            e = Event()
            e.uid = facebook_user.id
            e.created = cur_date

            # Don't add extra 's' if name already ends with 's'
            formatted_username = f"{facebook_user.name}'s" if facebook_user.name[
                -1] != 's' else f"{facebook_user.name}'"
            e.name = f"{formatted_username} Birthday"

            # Calculate the year as this year or next year based on if its past current month or not
            # Also pad day, month with leading zeros to 2dp
            year = cur_date.year if facebook_user.birthday_month >= cur_date.month else (
                cur_date + relativedelta(years=1)).year

            # Feb 29 special case:
            # If event year is not a leap year, use Feb 28 as birthday date instead
            if facebook_user.birthday_month == 2 and facebook_user.birthday_day == 29 and not calendar.isleap(
                    year):
                facebook_user.birthday_day = 28

            month = '{:02d}'.format(facebook_user.birthday_month)
            day = '{:02d}'.format(facebook_user.birthday_day)
            e.begin = f'{year}-{month}-{day} 00:00:00'
            e.make_all_day()
            e.duration = timedelta(days=1)
            e.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY'))

            c.events.add(e)

        self.birthday_calendar = c
Esempio n. 21
0
def populate_birthdays_calendar(birthdays):
    """ Populate a birthdays calendar using birthday objects """

    c = Calendar()
    c.scale = 'GREGORIAN'
    c.method = 'PUBLISH'
    c.creator = f'fb2cal v{__version__} ({__status__}) [{__website__}]'
    c.extra.append(
        ContentLine(name='X-WR-CALNAME', value='Facebook Birthdays (fb2cal)'))
    c.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT12H'))
    c.extra.append(
        ContentLine(name='X-ORIGINAL-URL', value='/events/birthdays/'))

    cur_date = datetime.now()

    for birthday in birthdays:
        e = Event()
        e.uid = birthday.uid
        e.name = f"{birthday.name}'s Birthday"

        # Calculate the year as this year or next year based on if its past current month or not
        # Also pad day, month with leading zeros to 2dp
        year = cur_date.year if birthday.month >= cur_date.month else (
            cur_date + relativedelta(years=1)).year
        month = '{:02d}'.format(birthday.month)
        day = '{:02d}'.format(birthday.day)
        try:
            e.begin = f'{year}-{month}-{day} 00:00:00'
        except ValueError as err:
            # Check if this is due to leap year. If so, move to Feb 28.
            if birthday.month == 2 and birthday.day == 29:
                day = '{:02d}'.format(birthday.day - 1)
                logger.warning(
                    f"{birthday.name}'s birthday landed on a missing leap day. Moving 1 day earlier ({year}-{month}-{day}) instead."
                )
                e.begin = f'{year}-{month}-{day} 00:00:00'
            else:
                raise err
        e.make_all_day()
        e.duration = timedelta(days=1)
        e.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY'))

        c.events.add(e)

    return c
Esempio n. 22
0
    def generateCalendar(self):
        calendar = Calendar(creator=self.username)

        for event in self.schedule:
            evt = Event()
            evt.name = event['name']
            evt.location = event['location']
            evt.begin = event['date_time']

            evt.duration = datetime.timedelta(minutes=45 * event['duration'])

            evt.description = '{}, {}'.format(event['professor'],
                                              event['type'])
            calendar.events.add(evt)
        self.calendar = calendar

        with open('{}.ics'.format(self.username), 'w') as f:
            f.writelines(calendar)
Esempio n. 23
0
def add_event(event, c, group=None):
    weeks = []
    for w in event['weeks']:
        if re.search('-', w) is not None:
            start, end = w.split('-')
            weeks += [i for i in range(int(start), int(end) + 1)]
        else:
            weeks.append(int(w))
    for week in list(set(weeks)):
        e = Event()
        e.name = event['title']
        e.begin = find_datetime(week, event['day'], event['time'])
        e.duration = timedelta(minutes=event['duration'])
        if 'location' in event:
            e.location = event['location']
        if event['staff'] is not None:
            e.description = str(event['staff'].replace(r'\n', ' '))
        c.events.add(e)
    return c
Esempio n. 24
0
def generate_ical_for_job(job):
    # Used https://icalendar.org/validator.html to validate output
    # Gmail will not update or cancel the existing event, but add a new one if the method is PUBLISH,
    # However, using REQUEST as the method would cause more confusion as it would look to the members as if they could
    # actually cancel their participation, be declining the event.
    # Thunderbird recognizes the changes correctly
    # On Android Gmail will show the same behaviour as on the desktop when using the event widget. Opening the attached
    # ics with a Calender App (e.g. Google Calendar) yields the correct behaviour (existing event is overwritten).
    # Using a non Gmail account in the Gmail app seems to break the ics file, for some reason.
    # K9-Mail shows the attachment and opening it in a calendar app works fine.
    # Outlook and Microsoft Mail do not show the event nicely, however the ics attachment can be opened and added to
    # calendar.
    # Not tested yet: Apples
    c = Calendar()
    c.extra.append(
        ContentLine(name="METHOD",
                    value="CANCEL" if job.canceled else "PUBLISH"))
    e = Event()
    # By giving it a UID the calendar will (hopefully) replace previous versions of this event.
    e.uid = f'{repr(job)}@{Config.server_url()}'
    # DTSTAMP is required: https://tools.ietf.org/html/rfc5545#section-3.6.1
    e.extra.append(
        ContentLine(name="DTSTAMP",
                    value=timezone.now().astimezone(
                        timezone.utc).strftime('%Y%m%dT%H%M%SZ')))
    e.name = Config.organisation_name() + ' ' + _(
        'Einsatz') + ': ' + job.type.get_name
    e.location = job.type.location
    e.description = job.type.description
    # Using FORM 2: https://tools.ietf.org/html/rfc5545#section-3.3.5
    e.begin = job.start_time()
    e.duration = {'hours': job.duration}
    e.extra.append(
        ContentLine(name=f"ORGANIZER;CN={Config.organisation_name()}",
                    value=f"mailto:{job.type.activityarea.get_email()}"))
    if job.canceled:
        e.status = 'CANCELLED'
    c.events.add(e)
    content = re.sub(r"\r?\n", "\r\n", str(c))
    # Fold lines https://tools.ietf.org/html/rfc5545#section-3.1
    content = re.sub("(.{74})", "\\1\r\n ",
                     content)  # fold at 74 such that the whitespace fits
    return ical("{}.ics".format(_('Einsatz')), content)
Esempio n. 25
0
def calendar_view(request, whatever):
    from ics import Calendar, Event
    actions, ctx = _get_actions(request, include_future=True, include_past=30)
    thecal = Calendar()
    thecal.creator = 'XR Mass Events'
    for action in actions:
        evt = Event()
        evt.uid = '{}@{}'.format(action.id, request.get_host())
        evt.name = action.html_title
        evt.description = action.description
        evt.categories = action.tags.names()
        evt.last_modified = action.modified
        evt.url = request.build_absolute_uri(action.get_absolute_url())
        evt.begin = action.when
        evt.duration = timedelta(hours=1)
        # evt.end = action.when + timedelta(hours=1)
        evt.location = action.location
        thecal.events.add(evt)
    response = HttpResponse(thecal, content_type='text/calendar')
    return response
Esempio n. 26
0
def ics_parser(bday_info_tuple, enable_date_swap):

    # Set calender info.
    c = Calendar()
    c.scale = 'GREGORIAN'
    c.method = 'PUBLISH'
    c.creator = 'Hardeep Singh Narang @hardeepnarang10'
    c._unused.append(ContentLine(name='X-WR-CALNAME', params={}, value='Facebook Birthdays Calendar (fb2ics)'))
    c._unused.append(ContentLine(name='X-PUBLISHED-TTL', params={}, value='PT12H'))
    c._unused.append(ContentLine(name='X-ORIGINAL-URL', params={}, value='/events/birthdays/'))

    # Get present date.
    present_date = datetime.now()

    # Process and add individual Events to the Calender object.
    for each_tuple in bday_info_tuple:
        # Calculate year for next birthday.
        # Add padding for day and month (2 digits - leading zero).
        tuple_date = each_tuple[2]
        year = present_date.year if int(tuple_date[0:tuple_date.index('/')]) >= present_date.month else (present_date + relativedelta(years=1)).year

        if enable_date_swap:
            day = '{:02d}'.format(int(tuple_date[0:tuple_date.index('/')]))
            month = '{:02d}'.format(int(tuple_date[tuple_date.index('/') + 1:]))
        else:
            month = '{:02d}'.format(int(tuple_date[0:tuple_date.index('/')]))
            day = '{:02d}'.format(int(tuple_date[tuple_date.index('/')+1:]))

        # Create Event object.
        e = Event()
        e.uid = each_tuple[0]
        e.name = f"{each_tuple[1]}'s Birthday!"
        e.description = "Facebook friend's birthday! Wish them well!"
        e.begin = f'{year}-{month}-{day} 00:00:00'
        e.make_all_day()
        e.duration = timedelta(days=1)
        e._unused.append(ContentLine(name='RRULE', params={}, value='FREQ=YEARLY'))

        c.events.add(e)

    return c
Esempio n. 27
0
def writeICS():
    conn = sqlite3.connect('xueshu.sqlite3', detect_types=sqlite3.PARSE_DECLTYPES)
    c = conn.cursor()
    now = datetime.now()
    future = now + timedelta(days=60)
    items = c.execute('select * from xueshu where startdate>=? and startdate<=?', (now.date(), future.date()))
    c = Calendar()
    c.creator = 'meelo'
    for item in items:
        e = Event()
        e.name = item[1].replace(' ','') + '【{}】'.format(item[10]) + item[9]
#        e.begin = arrow.get(item[3], 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=tz.gettz('Asia/Chongqing'))
        e.begin = arrow.get(item[3], 'YYYY-MM-DD HH:mm:ss').replace(tzinfo='+08:00')
        e.duration = timedelta(hours=2)
        e.location = item[4]
        e.description = item[12]
        c.events.append(e)
#    print(c.events)
    conn.close()
    with open('xueshu.ics', 'w', encoding='utf-8') as f:
        f.writelines(c)
def resolve_event(evt_html):
    title = evt_html('.event_title a').text()
    if title.endswith('Test'):
        return None

    evt = Event(
        name=(f'MotoGP {_FLAGS[evt_html(".location span").eq(1).text()]} '
              f'{title} ({os.environ["SESSIONS"]})'),
        location=evt_html('.location span').eq(0).text(),
        url=f'{evt_html(".event_title a").attr("href")}#schedule')

    desc = []
    begin = None
    end = None
    sched_html = pq(url=evt.url, encoding='utf-8')
    for e in sched_html('.c-schedule__table-row').items():
        sessions = e(
            '.c-schedule__table-cell:nth-child(3) span.hidden-xs').text()
        if not sessions.startswith(os.environ['SESSIONS']):
            continue

        category = e('.c-schedule__table-cell').eq(1).text().strip()
        ini_time = e('.c-schedule__time span').eq(0).attr('data-ini-time')
        if begin is None:
            begin = ini_time
        else:
            end = ini_time

        desc.append(f'{ini_time} {category} {sessions}')

    td = datetime.strptime(end, TIME_FMT) - datetime.strptime(begin, TIME_FMT)
    evt.begin = begin
    evt.description = '\n'.join(desc)
    evt.duration = timedelta(seconds=td.seconds + 7200)

    print(f'{evt.name}\n'
          f'Circuit: {evt.location}\n'
          f'Schedule:\n{evt.description}\n{"-" * 46}')

    return evt
Esempio n. 29
0
def genrate_ics(sClassSet, role, id, calendar):  # role = {studentG, prof}
    for i in sClassSet:
        if id in i[role]:
            e = Event()
            now = datetime.datetime.now()

            name = str(i['subject']) + ' ' + i['classroom']
            year = time.strftime("%Y", time.localtime())
            month = time.strftime("%m", time.localtime())
            today = time.strftime("%d", time.localtime())
            today_weekday = weekday[time.strftime("%a", time.localtime())]
            classday_whole = now + datetime.timedelta(
                ((-today_weekday + i['weekday'])))
            classday = classday_whole.strftime('%d')
            start_time = day_slot[i['startTime']]

            ics_start = year + month + classday + 'T' + start_time + '+08:00'
            duration = i['duration']
            e.name = name
            e.begin = ics_start
            e.duration = {'days': 0, 'hours': duration}
            calendar.events.add(e)
Esempio n. 30
0
def appointment_notice(name, id, dtof, stage):
    c = Calendar()
    atte = (['*****@*****.**', '*****@*****.**'])
    esubj = f'Appointment of patient {name}'
    mobile = patients.find_one({'HKID': id})['mobile']
    progress = ['Baseline 1', 'Baseline 2', 'Month 4', 'Month 8',
                'Month 12'][stage]
    econt = f"""
            Name: {name}, ID: {id}, phone no.: {mobile}
            Progress: {progress}
            """
    e = Event(name=esubj, description=econt, attendees=atte)
    e.begin = dtof.astimezone(timezone('Asia/Hong_Kong'))
    e.duration = timedelta(hours=3)
    c.events.add(e)
    with open('appt.ics', 'w') as f:
        f.write(str(c))
    subj = f'New Appointment of patient {name}'
    recip = ['*****@*****.**', '*****@*****.**']
    text = f"""
            System generated notification.
            Patient: {name} 
            ID: {id}
            Phone: {mobile} 
            has a new appointment at:
            Date: {dtof: %d-%m-%Y}({dtof: %A}) 
            Time: {dtof:%H:%M}.
            Progress: {progress}
            Please add to calendar.
            """
    msg = Message(subj, recip, text)
    with open("appt.ics") as fp:
        msg.attach("appt.ics", "appt/ics", fp.read())
        mail.send(msg)
        flash('New appointment. Email notification sent', 'info')
        return redirect(url_for('index'))
Esempio n. 31
0
def add_event(date, location, my_name):

        for specific_event in date:

                #       If there is a specified date
                if specific_event["date"]["start_date"]:

                        if specific_event["date"]["start_date"] != \
                           specific_event["date"]["end_date"]:
                                print "Error! Unexpected api return! Start date not same as end date!"
                                break

                        start_time = specific_event["date"]["start_time"]
                        end_time = specific_event["date"]["end_time"]

                        format_time = '%H:%M'
                        time_dur = datetime.strptime(end_time, format_time) - \
                                   datetime.strptime(start_time, format_time)

                        if specific_event["location"]["building"] and \
                           specific_event["location"]["room"]:
                                location_str = str(specific_event["location"]["building"]) \
                                               + " " + str(specific_event["location"]["room"])
                        else:
                                location_str = " "

                        start_date = specific_event["date"]["start_date"]
                        date_year = term_dates[str(term_num)]["start"].year

                        my_time_zone = timezone('US/Eastern')
                        dt = my_time_zone.localize(datetime(date_year, int(start_date[:2]),
                                                            int(start_date[-2:]), int(start_time[:2]),
                                                            int(start_time[-2:]),0,0))
                        datetime_str_start = arrow.get(dt)

                        new_event = Event()
                        new_event.name = my_name
                        new_event.location = location_str
                        new_event.begin = datetime_str_start
                        new_event.duration = {"hours":time_dur.seconds//3600,
                                              "minutes":(time_dur.seconds//60)%60}


                        if datetime_str_start in events_stack:
                                print "Warning! Duplicate event detected! Event: " \
                                      + my_name + " discarded!"
                        else:
                                events_stack.append(datetime_str_start)
                                cal.events.append(new_event)

                #       If there is no specified date (interates through every day in term)
                else:
                        start_time = specific_event["date"]["start_time"]
                        end_time = specific_event["date"]["end_time"]

                        format_time = '%H:%M'
                        time_dur = datetime.strptime(end_time, format_time) - \
                                   datetime.strptime(start_time, format_time)


                        location_str = str(specific_event["location"]["building"]) \
                                       + " " + str(specific_event["location"]["room"])

                        start_date = term_dates[str(term_num)]["start"]
                        end_date = term_dates[str(term_num)]["end"]

                        weekdays = specific_event["date"]["weekdays"]

                        counter = 0;
                        date_days = [0,0,0,0,0,0,0]
                        while  counter < len(weekdays):
                                if weekdays[counter] == "T":
                                        if (counter + 1) != len(weekdays):
                                                if weekdays[counter + 1] == "h":
                                                        date_days[3] = 1
                                                        counter += 1
                                                else:
                                                        date_days[1] = 1
                                        else:
                                                date_days[3] = 1
                                elif weekdays[counter] == "S":
                                        date_days[5] = 1
                                elif weekdays[counter] == "M":
                                        date_days[0] = 1
                                elif weekdays[counter] == "W":
                                        date_days[2] = 1
                                elif weekdays[counter] == "F":
                                        date_days[4] = 1
                                elif weekdays[counter] == "U":
                                        date_days[6] = 1

                                counter += 1


                        days_in_term = (end_date - start_date).days + 1

                        for index in range(days_in_term):

                                one_day = timedelta(days = 1)
                                current_date = start_date + one_day * index

                                if date_days[current_date.weekday()] == 1:

                                        my_time_zone = timezone('US/Eastern')
                                        dt = my_time_zone.localize\
                                             (datetime(current_date.year, current_date.month,
                                                       current_date.day, int(start_time[:2]),
                                                       int(start_time[-2:]), 0, 0))
                                        datetime_str_start = arrow.get(dt)

                                        new_event = Event()
                                        new_event.name = my_name
                                        new_event.location = location_str
                                        new_event.begin = datetime_str_start
                                        new_event.duration = {"hours":time_dur.seconds//3600,
                                                              "minutes":(time_dur.seconds//60)%60}

                                        if datetime_str_start in events_stack:
                                                print "Warning! Duplicate event detected! Event: " \
                                                      + my_name + " discarded!"
                                        else:
                                                events_stack.append(datetime_str_start)
                                                cal.events.append(new_event)
        return
Esempio n. 32
0
NUM_MONTHS = 12
TIME = 18

cal = Calendar()
today = datetime.today()

pacific = pytz.timezone('US/Pacific')


def dayOfNthMonth(n, day):
    today = datetime.today()
    year = today.year
    month = (today.month + n) % 12 + 1
    year += int((today.month + n) / 12)
    return datetime(year, month, day, TIME)


for month in range(NUM_MONTHS):
    for day in (5, 20):
        the_date = dayOfNthMonth(month, day)
        if the_date.weekday() == 6:
            the_date -= timedelta(days=2)
        elif the_date.weekday() == 5:
            the_date -= timedelta(days=1)
        e = Event(name="Submit expense report")
        e.begin = pacific.localize(the_date).astimezone(timezone.utc)
        e.duration = timedelta(minutes=15)
        cal.events.add(e)

open("expense_reports.ics", "w").writelines(cal)
    if(len(result) < 2):
        return '0'+result
    else:
        return result

def convertTime(Time_Data_List):
    starttime = Time_Data_List[-2] if "." in Time_Data_List[-2] else Time_Data_List[-2] + ".0"
    minutes = "30" if ".5" in starttime else "00"
    hours = int(starttime[:-2])
    if Time_Data_List[2].lower() == "pm":
        hours += 12
    return "0" * (2-len(str(hours))) + str(hours) + minutes


begin = '2016%s%sT%s00' % (convertMonth(Time_Data_List),Time_Data_List[1],convertTime(Time_Data_List))
hours = int(begin[9:11])
day   = int(begin[6:8])
hours += 4
if hours >= 24:
    hours -= 24
    day += 1
begin = begin[:6] + "0" * (2-len(str(day))) + str(day) + "T"  + "0" * (2-len(str(hours))) + str(hours) + begin[11:]
e.begin = begin
e.duration = {"hours": Time_Data_List[-1]}
e.location = location

c.events.append(e)
c.events
with open('event.ics', 'w') as my_file:
    my_file.writelines(c)
Esempio n. 34
0
def makeFile(week=5):
    c = Calendar()
    today = datetime.date.today()
    chetn = 0  # UserParams.getChetn()
    current_date = today - datetime.timedelta(
        days=today.isoweekday()) + datetime.timedelta(days=1)

    days_in_week = list(response.keys())
    days_in_week.sort()

    current_week = 0
    while (current_week <= week):
        for key in days_in_week:
            if (current_date.month == 12
                    and current_date.day == 30) or (current_date.month == 7
                                                    and current_date.day == 1):
                break
            for row in response[key]:
                dayDate = row["dayDate"].rstrip().lower()
                chetnost = True if (
                    datetime.date(current_date.year, current_date.month,
                                  current_date.day).isocalendar()[1] +
                    chetn) % 2 else False  # Если True чет, False - неч
                prefix = ""
                if (dayDate == 'чет' and not chetn) or (dayDate == 'неч'
                                                        and chetn):
                    continue
                elif dayDate == 'чет/неч':
                    if chetnost:
                        prefix = " (1) гр."
                    else:
                        prefix = " (2) гр."
                elif dayDate == 'неч/чет':
                    if chetnost:
                        prefix = " (2) гр."
                    else:
                        prefix = " (1) гр."

                e = Event()
                tt = row["dayTime"].rstrip() if len(row["dayTime"].rstrip(
                )) < 6 else row["dayTime"].rstrip()[:5]
                tt = tt_dict[tt]
                begin_time = str(current_date) + " {}:00".format(tt)
                # end_time = str(current_date) + " {}:00".format(time_dict[row["dayTime"].rstrip()])
                e.name = prefix + row["disciplType"].rstrip().upper(
                ) + " " + row["disciplName"].rstrip()
                e.begin = begin_time
                e.duration = datetime.timedelta(
                    minutes=190 if row["disciplType"].rstrip().upper() ==
                    'Л.Р.' else 90)
                e.location = "В {} ауд. {} зд".format(row["audNum"].rstrip(),
                                                      row["buildNum"].rstrip())
                e.description = "В {} ауд. {} зд".format(
                    row["audNum"].rstrip(), row["buildNum"].rstrip())
                c.events.add(e)

            current_date = current_date + datetime.timedelta(days=1)
            if str(current_date.isoweekday()) not in days_in_week:
                current_date = current_date + datetime.timedelta(days=1)
                continue
        current_week += 1
    with open('my.ics', 'w') as f:
        f.write(str(c))
            game = Game(clean_team(game_match['home']),
                        clean_team(game_match['away']),
                        clean_time(year, month, day, game_match['tod']),
            )
            logging.info('Parsed: %s' % str(game))

            games.append(game)

# Collect games by team
teams = defaultdict(list)

# Exhibition Games
games.append(Game('Trois-Rivières', 'Ottawa', arrow.get(datetime.datetime(year, 5, 16, 13, 35, 0), 'US/Eastern')))
games.append(Game('Ottawa', 'Trois-Rivières', arrow.get(datetime.datetime(year, 5, 17, 13, 35, 0), 'US/Eastern')))

for g in games:
    teams[g.home].append(g)
    teams[g.away].append(g)

# Create calendars
for team in ical_teams:
    c = Calendar()
    for g in teams[team]:
        e = Event()
        e.name = g.away if g.home == team else '@ %s' % g.home
        e.begin = g.time
        e.duration = {'hours': 3}
        c.events.append(e)
        with open('%s.ics' % team, 'w') as ical:
            ical.writelines(c)