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
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 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
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
def calculate_result(self, stamp, **kwargs): logit("[Calendar] GenerateCalendarTask: starting up! - - - - - - - - - -") sessionTypeValue = SessionType.objects.get(name="Race") currentSeason = Season.objects.filter(year=date.today().year) # logit("[Calendar] Current Season: " + str(currentSeason[0].year)) localtz = dateutil.tz.tzlocal() localoffset = localtz.utcoffset(datetime.datetime.now(localtz)) offsetHours = localoffset.total_seconds() / 3600 # logit("[Calendar] Offset: " + str(offsetHours)) calendar = Calendar() calendar.creator = unicode("IndyBot, a product of /r/INDYCAR on Reddit") raceList = Race.objects.filter(season=currentSeason) for i in xrange(len(raceList)): # logit("[Calendar] ----------------------------------------------- ") # logit("[Calendar] " + raceList[i].title) event = Event() event.name = raceList[i].title event.location = raceList[i].course.name event.description = "Coverage on " + raceList[i].channel startTime = False endTime = False raceSession = Session.objects.get(race_id=raceList[i].id, type_id=sessionTypeValue) startTime = raceSession.tvstarttime + timedelta(hours=offsetHours) if raceSession.tvendtime == None: endTime = startTime + timedelta(hours=3) else: endTime = raceSession.tvendtime + timedelta(hours=offsetHours) event.begin = arrow.get(startTime, 'US/Eastern') event.end = arrow.get(endTime, 'US/Eastern') # logit("[Calendar] Start Time: " + str(event.begin.format('YYYY-MM-DD HH:mm:ss ZZ'))) # logit("[Calendar] End Time: " + str(event.end.format('YYYY-MM-DD HH:mm:ss ZZ'))) calendar.events.append(event) with open('static/races.ics', 'w') as f: f.writelines(calendar) logit("[Calendar] Finished.") return 1
def add_to_calendar(request, pk, slug): conference = Conference.objects.get(id=pk) e = Event() c = Calendar() e.name = conference.name e.begin = conference.start_date.isocalendar() e.end = conference.end_date.isocalendar() e.location = conference.venue c.events.add(e) c.creator = conference.organizer.user.username with open('my.ics', 'w') as my_file: my_file.writelines(c) mail_ics_file.delay(file_name='my.ics', to=request.user.email) return redirect('events:conference-detail', pk=pk, slug=slug)
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
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
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
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
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 event_generator(units): # set up a calendar c = Calendar() c.creator = "The Null Pointers" # set up a dictionary for the general week events weekly = {} for i in range(1,14): weekly[i] = [] # set up a list of formal exams final_exams = [] for unit in units: for assessment in unit.list_of_assessments: # if the assessment has a due date we want to create an event # for it if assessment.due_date != None: e = Event() e.name = unit.code + ": " + assessment.description_title + " (" + "weighting: " + assessment.weight + ")" date = arrow.get(assessment.due_date, "DD MMM YYYY") e.begin = date e.description = assessment.description_body c.events.add(e) if assessment.due_str.startswith("Week "): week = int(assessment.due_str.split()[1]) weekly[week].append(assessment) if assessment.is_final: final_exams.append(assessment) # loop through the general weekly assessments for week in sorted(weekly.keys()): if weekly[week] == []: continue e = Event() e.name = "Week " + str(week) + " Assessments" desc = "" for assessment in weekly[week]: desc += assessment.unit.code +": " + assessment.description_title + " (weighting: " + assessment.weight + ")"+ "\n" # shift by 1 to account for midsem break if week > 7: week += 1 date = start_sem.shift(weeks=week-1) e.begin = date e.description = desc c.events.add(e) if final_exams != []: e = Event() e.name = "Your final exams" desc = "" for assessment in final_exams: desc += assessment.unit.code + ": " + assessment.description_title + " (weighting: " + assessment.weight + ")" + "\n" e.description = desc e.begin = formal_exam_period c.events.add(e) with open('static_files/calendar.ics', 'w+') as my_file: my_file.writelines(c)
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import TimeoutException, WebDriverException from bs4 import BeautifulSoup from io import open from ics import Calendar, Event from ics.alarm import AudioAlarm from datetime import timedelta c = Calendar() e = Event() c.creator = "cher" e.name = 'First Event' e.begin = '2019-11-08T22:00:00+07' e.duration = {"minutes": 100} e.description = "This is my first event" e.location = "404-Not Found" c.events.add(e) # print(c) with open('my.ics', 'w') as f: f.writelines(c)
def ical(request): # This should be a comma-separated list with values corresponding to # Committee's abbreviation_short field. abbreviations = request.GET.get( 'committee', '').split(',') if 'committee' in request.GET else [] committees = Committee.objects.filter( parliaments__parliament_num=CURRENT_PARLIAMENT_NUM) if len(abbreviations) > 0: committees = committees.filter(abbreviation_short__in=abbreviations) cal = Calendar() cal.creator = '-//Alþingi//NONSGML Fastanefndir Alþingis//IS' cal.scale = 'GREGORIAN' cal.method = 'PUBLISH' agendas = CommitteeAgenda.objects.select_related( 'committee').prefetch_related('committee_agenda_items').filter( parliament__parliament_num=CURRENT_PARLIAMENT_NUM, committee__in=committees).order_by('timing_start_planned') for agenda in agendas: # Short-hand. agenda_id = agenda.committee_agenda_xml_id description = 'Dagskrá:\n\n' for item in agenda.committee_agenda_items.select_related( 'issue__parliament'): description += '%d. %s\n' % (item.order, capfirst(item.name)) # Add URL of issue, if any. if item.issue is not None: description += '%s\n' % external_issue_url( item.issue.parliament.parliament_num, item.issue.issue_num) description += '\n' event = Event() event.uid = '*****@*****.**' % agenda_id event.name = capfirst(agenda.committee.name) event.description = description event.begin = agenda.timing_start_planned event.end = agenda.timing_end event.url = 'https://www.althingi.is/thingnefndir/dagskra-nefndarfunda/?nfaerslunr=%d' % agenda_id # Committee agendas are never planned at midnight (or damn well # hopefully not). So when a committee agenda is planned without a time # factor, or in other words, is timed at midnight, we'll assume that # the timing is actually not precisely determined and turn it into an # all-day event instead, using the timing text (determined below) to # elaborate instead. if event.begin.hour == 0 and event.begin.minute == 0 and event.begin.second == 0: event.make_all_day() if agenda.timing_text: # If agenda.timing_text is just a representation of what is # already known from the planned starting time, we'll want to # nullify it so that we don't clutter the name with it # unnecessarily. To do this, we have to re-construct the text that # is typically provided and compare it against agenda.timing_text. # If they match, we won't include it. If they don't match, then # what's provided in agenda.timing_text is presumably more # meaningful than simply a (badly) reformatted version of # agenda.timing_start_planned. timing = agenda.timing_start_planned day = timing.day month_name = ICELANDIC_MONTHS[timing.month] year = str(timing.year)[2:] time = timing.strftime('%-I:%M') am_pm = icelandic_am_pm(timing) # Known inconsistencies are whether there is a space in the # beginning, and whether there is one space or two between "kl." # and the time-of-day. We strip and replace to compensate. timing_text_test = '%d. %s %s, kl. %s %s' % (day, month_name, year, time, am_pm) if agenda.timing_text.strip().replace(' ', ' ') != timing_text_test: event.name += ' (%s)' % agenda.timing_text.strip() cal.events.add(event) ical_text = monkey_patch_ical( cal.__str__(), 'Fastanefndir Alþingis', 'Dagatal sem inniheldur boðaða fundi fastanefnda Alþingis ásamt dagskrá í lýsingu.', 'Reykjavik/Iceland', 'PT10M') if request.GET.get('plaintext', False): content_type = 'text/plain' else: content_type = 'text/calendar' return HttpResponse(ical_text, content_type='%s; charset=utf-8' % content_type)