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 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
def run(output_file): calendar = Calendar() datenames, missiondatas, descriptions = parse_website() for datename, data, desc in zip(datenames, missiondatas, descriptions): mission = get_mission(datename) location = get_location(data) begin, is_all_day = get_full_launchtime(datename, data) if begin: event = Event() event.begin = begin event.description = desc.text event.name = mission if is_all_day: event.make_all_day() event.location = location event.uid = mission.replace(" ", "") calendar.events.add(event) with open(output_file, "w") as outfile: outfile.writelines(calendar) print(calendar.events) print(len(calendar.events))
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
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 add_event(event): e = Event() e.uid = str(event.get('calendar_key', event.get('id'))) e.name = format_title(event) e.begin = event.get('timestamp', time.time()) e.end = event.get('timestamp', time.time()) e.description = format_desc(event) e.location = event.get('country', '') c.events.add(e)
def oneLessonToIcsEvent(self): e = Event() e.name = "({}){}".format(self.addressOfTheLesson, self.nameOfTheLesson) e.uid = self.oneLessonID e.description = "任课老师:{} \n 周数:{}".format(self.teacherNameOfTheLesson, self.__weeks) e.location = self.addressOfTheLesson e.begin = self.startTime e.end = self.endTime return e
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)
def main(req: func.HttpRequest) -> func.HttpResponse: try: api = Trading(appid=os.environ["EBAY_APPID"], devid=os.environ['EBAY_DEVID'], certid=os.environ['EBAY_CERTID'], token=os.environ['EBAY_TOKEN'], siteid=os.environ['EBAY_SITEID'], config_file=None) response = api.execute('GetMyeBayBuying', {'DetailLevel': 'ReturnAll'}) r = response.dict() r_named = namedtuple("object", r.keys())(*r.values()) watchlist = r_named.WatchList["ItemArray"]["Item"] c = Calendar() for item in watchlist: event = Event() event.uid = item["ItemID"] event.name = item["Title"] event.url = item["ListingDetails"]["ViewItemURL"] event.begin = item["ListingDetails"]["EndTime"] event.end = event.begin price = "N/A" if item["SellingStatus"] is not None: try: price = "{} {}".format( item["SellingStatus"]["ConvertedCurrentPrice"] ["_currencyID"], item["SellingStatus"]["CurrentPrice"]["value"]) except KeyError as e: price = "{} {}".format( item["SellingStatus"]["CurrentPrice"]["_currencyID"], item["SellingStatus"]["CurrentPrice"]["value"]) pass event.description = "{}\nPrice: {}\nURL: {}".format( event.name, price, event.url) c.events.add(event) s = ''.join(str(l) for l in c) return func.HttpResponse( s, mimetype="text/calendar", charset="utf-8", headers={ "Content-Disposition": "attachment; filename=\"ebay-watchlist.ics\"" }) except ConnectionError as e: return func.HttpResponse(str(e), status_code=400)
def _generate_calendar(self, checkins, year=None): """ Supplied with a list of checkin data from the API, generates an ics Calendar object and returns it. """ user_url = self._get_user_url() c = Calendar() #for checkin in list(checkins)["checkins"]["items"]: for checkin in checkins: try: venue_name = checkin["venue"]["name"] tz_offset = self._get_checkin_timezone(checkin) e = Event() e.name = "@ {}".format(venue_name) e.location = venue_name e.url = "{}/checkin/{}".format(user_url, checkin["id"]) e.uid = "{}@foursquare.com".format(checkin["id"]) e.begin = checkin["createdAt"] e.end = e.begin # Use the 'shout', if any, and the timezone offset in the # description. description = [] description.append("{}\n".format(e.url)) if "shout" in checkin and len(checkin["shout"]) > 0: description = [checkin["shout"]] description.append("Timezone offset: {}".format(tz_offset)) e.description = "\n".join(description) # Use the venue_name and the address, if any, for the location. location = venue_name if "location" in checkin["venue"]: loc = checkin["venue"]["location"] if "formattedAddress" in loc and len( loc["formattedAddress"]) > 0: address = ", ".join(loc["formattedAddress"]) location = "{}, {}".format(location, address) e.location = location if (year is not None): if (e.begin.year == year): c.events.add(e) else: c.events.add(e) except: print("Error processing {}".format(venue_name)) continue return c
def item_to_ical(item): event_date = datetime.strptime(item['date'], '%Y-%m-%d') city_tz_date = city_tz.localize( datetime(event_date.year, event_date.month, event_date.day, 0, 0, 0)) ical_event = Event() ical_event.name = item_to_name(item) ical_event.begin = city_tz_date ical_event.end = city_tz_date + timedelta(days=1) ical_event.uid = 'veda_daily_panchanga_' + item['date'] ical_event.description = item_to_string(item) return ical_event
def get_ical_event(self, e): ical_event = Event() ical_event.name = self.get_facebook_event_property( e, 'name', '[Some Event]') ical_event.begin = self.get_facebook_event_property( e, 'start_time', '') ical_event.end = self.get_facebook_event_property(e, 'end_time', '') ical_event.uid = self.get_facebook_event_property(e, 'id', '') ical_event.url = 'https://www.facebook.com/events/%s' % self.get_facebook_event_property( e, 'id', '') ical_event.description = '%s\n\n%s' % ( ical_event.url, self.get_facebook_event_property(e, 'description', '')) return ical_event
def _generate_calendar(self, checkins): """Supplied with a list of checkin data from the API, generates an ics Calendar object and returns it. Keyword arguments: checkins -- A list of dicts, each one data about a single checkin. """ user = self._get_user() c = Calendar() for checkin in checkins: if "venue" not in checkin: # I had some checkins with no data other than # id, createdAt and source. continue venue_name = checkin["venue"]["name"] tz_offset = self._get_checkin_timezone(checkin) e = Event() e.name = "@ {}".format(venue_name) e.location = venue_name e.url = "{}/checkin/{}".format(user["canonicalUrl"], checkin["id"]) e.uid = "{}@foursquare.com".format(checkin["id"]) e.begin = checkin["createdAt"] # Use the 'shout', if any, and the timezone offset in the # description. description = [] if "shout" in checkin and len(checkin["shout"]) > 0: description = [checkin["shout"]] description.append("Timezone offset: {}".format(tz_offset)) e.description = "\n".join(description) # Use the venue_name and the address, if any, for the location. location = venue_name if "location" in checkin["venue"]: loc = checkin["venue"]["location"] if "formattedAddress" in loc and len(loc["formattedAddress"]) > 0: address = ", ".join(loc["formattedAddress"]) location = "{}, {}".format(location, address) e.location = location 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 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_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)
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
async def main(): s = spond.Spond(username=username, password=password) c = Calendar() c.method = 'PUBLISH' events = await s.getEvents() for event in events: e = Event() e.uid = event['id'] e.name = event['heading'] e.description = event['description'] e.begin = event['startTimestamp'] e.end = event['endTimestamp'] e.sequence = event['updated'] if 'cancelled' in event and event['cancelled']: e.status = 'Cancelled' if 'location' in event: e.location = "{}, {}".format(event['location']['feature'], event['location']['address']) c.events.add(e) with open(ics_file, 'w') as out_file: out_file.writelines(c) await s.clientsession.close()
def export_file(events: List[EventEntity], file_path: str): c = Calendar() for event in events: e = Event() e.name = event.name e.description = event.description e.begin = event.date_start e.end = event.date_end e.uid = event.uid e.extra.append(ContentLine(name="MYDURATION", value=event.duration)) e.extra.append(ContentLine(name="LOOSE", value=event.loose)) e.extra.append(ContentLine(name="PRIORITY", value=event.priority.name)) e.extra.append(ContentLine(name="DAYTIME", value=event.day_time.name)) e.extra.append(ContentLine(name="TIMEWINDOW", value=event.time_window)) e.extra.append(ContentLine(name="TIMEBEFORE", value=event.time_after)) e.extra.append(ContentLine(name="TIMEAFTER", value=event.time_before)) c.events.add(e) with open(file_path, 'w') as f: f.write(str(c))
dateKey = "event-date" titleKey = "title" uuidKey = "nid" startDateKey = "value" endDateKey = "value2" dateNodeLevel = 0 for eventNasa in resutlHits: eventTitle = eventNasa[sourceNodeKey][titleKey] eventDateBegin = eventNasa[sourceNodeKey][dateKey][dateNodeLevel][ startDateKey] eventDateEnd = eventNasa[sourceNodeKey][dateKey][dateNodeLevel][ endDateKey] eventUuid = eventNasa[sourceNodeKey][uuidKey] """ Event creation """ event = Event() """ Event data """ event.name = eventTitle event.begin = eventDateBegin event.end = eventDateEnd event.uid = eventUuid #unique to event #Add event to calendar calendarObject.events.add(event) """ write calendar file """ wf.writeFile('space-calendar_spaceA.ics', calendarObject) except requests.RequestException as err: print(err)
def index(request): code = request.GET.get('code') step_3 = 'https://foursquare.com/oauth2/access_token?client_id=%s&client_secret=%s&grant_type=authorization_code&redirect_uri=%s&code=%s' % ( YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, YOUR_REGISTERED_REDIRECT_URI, code) resp = requests.get(url=step_3) token = json.loads(resp.content) nowTime = datetime.datetime.now().strftime('%Y%m%d') #现在 # 今天日期 today = datetime.date.today() # 昨天时间 yesterday = today - datetime.timedelta(days=1) # 明天时间 tomorrow = today + datetime.timedelta(days=1) #yesterday_start_time = int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d'))) # 2009-06-01 00:00:00 yesterday_start_time = 1243785600 today_end_time = (int(time.mktime(time.strptime(str(tomorrow), '%Y-%m-%d')))) offset = 0 c = Calendar() while True: url = 'https://api.foursquare.com/v2/users/self/checkins?oauth_token=%s&v=%s&beforeTimestamp=%s&afterTimestamp=%s&limit=250&&offset=%s' % ( token['access_token'], nowTime, today_end_time, yesterday_start_time, offset) resp = requests.get(url=url) data = json.loads(resp.text) if len(data['response']['checkins']['items']) == 0: break for item in data['response']['checkins']['items']: try: e = Event() e.name = item['venue']['name'] e.uid = item['id'] e.begin = item['createdAt'] + item['timeZoneOffset'] e.location = '%s' % '-'.join( [s for s in item['venue']['location']['formattedAddress']]) e.status = 'CONFIRMED' c.events.add(e) print(item['venue']['location']['formattedAddress']) except: continue offset += 250 file_path = os.path.join(settings.MEDIA_ROOT, 'HistoryCheckins', 'HistoryCheckins.ics') [dir_name, file_name] = os.path.split(file_path) if not os.path.exists(dir_name): os.makedirs(dir_name) with open(file_path, 'w', encoding='utf-8') as f: f.writelines(c) return HttpResponse(json.dumps({"success": True}))
description = "Website: https://www.linux-ag.uni-tuebingen.de" location = room + ", Sand, 72076 Tübingen, Germany" time_end = "21:00:00" def get_date(date, time): # We use a strange format (can be copied directly from the website): date_format = "DD.MM.YYYY HH:mm:ss" date = arrow.get(date + " " + time, date_format) date = date.replace(tzinfo='Europe/Berlin') return date # Create the calendar with all events and save the result (iCalendar): c = Calendar() for date in dates: e = Event() e.name = name e.description = description e.location = location e.begin = get_date(date, time_start) e.end = get_date(date, time_end) # To make the output deterministic: e.created = arrow.get("1970-01-01 00:00:00+00:00") e.uid = date + "@www.linux-ag.uni-tuebingen.de" c.events.add(e) with open("linux-ag.ics", "w") as f: f.writelines(c)
def invite_event(self, request, *args, **kwargs): """ a)Request Event uuid, Room uuid, Email - Array b)Identify user type and send relevant emails with link to Registered and Unregistered user """ serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) event_uuid = request.data['event_uuid'] room_uuid = request.data['room_uuid'] emails = request.data['emails'] event_name = request.data['event_name'] organization_name = request.data['organization_name'] start_date_time = request.data['start_date_time'] end_date_time = request.data['end_date_time'] invitation_link_list = [] c = Calendar() e = Event() e.name = str(event_name) e.begin = str(start_date_time) e.end = str(end_date_time) e.uid = event_uuid e.organizer = Organizer(common_name=str(organization_name), email=DEFAULT_FROM_EMAIL) c.events.add(e) for email in emails: user = CoreUser.objects.filter(email=email).first() # if the user is registered if user: """ for registered users send them a test email "Registered Users! Welcome to a new event at organization". """ email_address = email organization = str(user.organization) reg_location = urljoin(settings.FRONTEND_URL, settings.EVENT_LOGIN_URL_PATH) reg_location = reg_location + '?token={}' token = create_invitation_token_event(email_address, organization, room_uuid, event_uuid) invitation_link = self.request.build_absolute_uri( reg_location.format(token)) invitation_link_list.append(invitation_link) subject = 'Welcome to event {} at {}'.format( event_name, organization) context = { 'organization_name': organization, 'event_link': invitation_link, 'event_uuid': event_uuid, 'room_uuid': room_uuid, 'event_name': event_name } template_name = 'email/coreuser/invite_event.txt' html_template_name = 'email/coreuser/invite_event.html' send_email(email_address, subject, context, template_name, html_template_name, str(c)) # if the user is not registered else: """ for unregistered users send them a test email "Unregistered Users! Welcome to a new event at organization'". """ email_address = email organization = organization_name reg_location = urljoin(settings.FRONTEND_URL, settings.EVENT_REGISTRATION_URL_PATH) reg_location = reg_location + '?token={}' token = create_invitation_token_event(email_address, organization, room_uuid, event_uuid) # build the invitation link invitation_link = self.request.build_absolute_uri( reg_location.format(token)) invitation_link_list.append(invitation_link) subject = 'Welcome to event {} at {}'.format( event_name, organization) context = { 'organization_name': organization, 'event_link': invitation_link, 'event_uuid': event_uuid, 'room_uuid': room_uuid, 'event_name': event_name } template_name = 'email/coreuser/invite_event.txt' html_template_name = 'email/coreuser/invite_event.html' send_email(email_address, subject, context, template_name, html_template_name, str(c)) return Response( { 'detail': 'The invitations were sent successfully.', 'event_link': [invitation_link_list], }, status=status.HTTP_200_OK)
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)
def main(): #these dont work for stupid reasons #API_URL_BETA = "https://asu.beta.instructure.com" #API_URL_TEST = "https://asu.test.instructure.com" # url for instructure API_URL = "https://asu.instructure.com" # TODO: token for oath, needs to be generated and maybe saved??? # right now it can be manually generated in instructure -> account -> settings -> new access token API_KEY = "7236~oZM4nVf3JknQyMWQayURperjJPV7Edqn2eo8f8si9zDakF4hqCWmhIsIDQf3whgB" # gets current user information user_id_url = API_URL + "/api/v1/users/self" r = requests.get(url=user_id_url, headers={'Authorization': 'Bearer ' + API_KEY}) user_data = r.json() # gets course list courses_url = API_URL + "/api/v1/courses" course_params = {"include": "term"} #r = requests.get(url = courses_url, headers={'Authorization': 'Bearer '+ API_KEY}) courses_data = get_all_request(courses_url, API_KEY, course_params) course_list = [] # TODO: automate term_id enrollment_term_ids = [1, 92] # creates a dictionary of courses and ids for course in courses_data: course_entry = {} name = course.get("name") if name is not None: #print(course.get("enrollment_term_id")) if (course.get("enrollment_term_id") in enrollment_term_ids): course_entry["id"] = course.get("id") course_entry["name"] = name course_list.append(course_entry) # prints out all assignments for a given course # saves assignments in a list of dictionaries for course in course_list: course_id = course.get("id") course_name = course.get("name") assignment_list = [] #print(course_name) assignments_url = API_URL + "/api/v1/courses/" + str( course_id) + "/assignments" assignments_data = get_all_request(assignments_url, API_KEY) for assignment in assignments_data: assignment_entry = {} assignment_entry["id"] = assignment.get("id") assignment_entry["name"] = assignment.get("name") assignment_entry["due_at"] = assignment.get("due_at") assignment_list.append(assignment_entry) #print("\t" + assignment.get("name")) #if(assignment.get("due_at") is not None): #print("\t\t" + assignment.get("due_at")) course["assignments"] = assignment_list # final structure: # list of dictionaries where every dictionary represents a current course # each dictionary has an id, name and assignment keys # id = course_id # name = course_name # assignment = list of dictionaries, each one representing an assignment # each assignment has an id, name and due_at # id = assignment_id # name = assignment_name # due_at = due date #print(course_list) ################################################################################### ######## # Change dictionary from list of courses (with nested list of assignments) # to list of assignments (with nested course attributes) ######## formattedAssignments = [] for course in course_list: currentCourseID = course['id'] currentCourseName = course['name'] for assignment in course['assignments']: assignmentDict = { 'name': assignment['name'], 'id': assignment['id'], 'due_at': assignment['due_at'], 'course_id': currentCourseID, 'course_name': currentCourseName, } formattedAssignments.append(assignmentDict) ######## #Create calendar ######## cal = Calendar() ######## # Create and add events ######## for assignment in formattedAssignments: #create a new event based on the assignment attributes if assignment['due_at'] != None: event = Event() event.name = (assignment['course_name'] + ': ' + assignment['name']) event.begin = assignment['due_at'] event.end = assignment['due_at'] event.uid = str(assignment['id']) cal.events.add(event) with open('my.ics', 'w') as f: f.writelines(cal)