def _get_holidays(self, api_key, start_date, end_date): srv = Google(serviceName='calendar', version='v3', developerKey=api_key) calendar_id = '*****@*****.**' cal = srv.events().list(calendarId=calendar_id, maxResults=30, orderBy="startTime", singleEvents=True, timeMin=start_date.strftime('%Y-%m-%dT%H:%M:%SZ'), timeMax=end_date.strftime('%Y-%m-%dT%H:%M:%SZ')).execute() return [dt.datetime.strptime(e["start"]["date"], '%Y-%m-%d').replace(tzinfo=pytz.timezone("Asia/Tokyo")) for e in cal["items"]]
def _get_holidays(self, api_key, start_date, end_date): srv = Google(serviceName='calendar', version='v3', developerKey=api_key) calendar_id = '*****@*****.**' cal = srv.events().list( calendarId=calendar_id, maxResults=30, orderBy="startTime", singleEvents=True, timeMin=start_date.strftime('%Y-%m-%dT%H:%M:%SZ'), timeMax=end_date.strftime('%Y-%m-%dT%H:%M:%SZ')).execute() return [ dt.datetime.strptime( e["start"]["date"], '%Y-%m-%d').replace(tzinfo=pytz.timezone("Asia/Tokyo")) for e in cal["items"] ]
def update_individual_event(google: discovery.build, event_id: str, parameter: str, new_text: str) -> None: """ Update individual event by event id :param google: authenticated Google session :param event_id: Event's id :param parameter: Parameter to update :param new_text: Text to update the new parameter with :return: None """ event = google.events().get(calendarId='*****@*****.**', eventId=event_id).execute() event[parameter] = new_text if debug: print('Updated {}'.format(event['summary'])) google.events().update(calendarId='*****@*****.**', eventId=event['id'], body=event).execute()
def get_youtube_duration(url): def video_id(value): """ Examples: - http://youtu.be/SA2iWivDJiE - http://www.youtube.com/watch?v=_oPAwA_Udwc&feature=feedu - http://www.youtube.com/embed/SA2iWivDJiE - http://www.youtube.com/v/SA2iWivDJiE?version=3&hl=en_US """ query = urllib.parse.urlparse(value) if query.hostname == 'youtu.be': return query.path[1:] if query.hostname in ('www.youtube.com', 'youtube.com'): if query.path == '/watch': p = urllib.parse.parse_qs(query.query) return p['v'][0] if query.path[:7] == '/embed/': return query.path.split('/')[2] if query.path[:3] == '/v/': return query.path.split('/')[2] return None youtube = Apiclient('youtube', 'v3', developerKey=getattr(settings, 'GOOGLE_API_KEY')) search_response = youtube.videos().list(part='contentDetails', id=video_id(url), maxResults=1).execute() result = search_response.get("items", []) duration = re.split('\D', result[0].get('contentDetails').get('duration')) duration = [int(d) for d in duration if d != ''] if len(duration) == 1: duration = datetime.timedelta(seconds=duration[0]) elif len(duration) == 2: duration = datetime.timedelta(minutes=duration[0], seconds=duration[1]) elif len(duration) == 3: duration = datetime.timedelta(hours=duration[0], minutes=duration[1], seconds=duration[2]) return duration.seconds
def get_youtube_duration(url): def video_id(value): """ Examples: - http://youtu.be/SA2iWivDJiE - http://www.youtube.com/watch?v=_oPAwA_Udwc&feature=feedu - http://www.youtube.com/embed/SA2iWivDJiE - http://www.youtube.com/v/SA2iWivDJiE?version=3&hl=en_US """ query = urllib.parse.urlparse(value) if query.hostname == 'youtu.be': return query.path[1:] if query.hostname in ('www.youtube.com', 'youtube.com'): if query.path == '/watch': p = urllib.parse.parse_qs(query.query) return p['v'][0] if query.path[:7] == '/embed/': return query.path.split('/')[2] if query.path[:3] == '/v/': return query.path.split('/')[2] return None youtube = Apiclient('youtube', 'v3', developerKey=getattr(settings, 'GOOGLE_API_KEY')) search_response = youtube.videos().list( part='contentDetails', id=video_id(url), maxResults=1 ).execute() result = search_response.get("items", []) duration = re.split('\D', result[0].get('contentDetails').get('duration')) duration = [int(d) for d in duration if d != ''] if len(duration) == 1: duration = datetime.timedelta(seconds=duration[0]) elif len(duration) == 2: duration = datetime.timedelta(minutes=duration[0], seconds=duration[1]) elif len(duration) == 3: duration = datetime.timedelta(hours=duration[0], minutes=duration[1], seconds=duration[2]) return duration.seconds
def create_event(google: discovery.build, match_bundle: list) -> None: """ Create a Google Calendar event :param google: authenticated Google session :param match_bundle: list of opponent, venue, time, competition :return: None """ opponent = match_bundle[0] venue = match_bundle[1] time = match_bundle[2] watch = match_bundle[3] competition = match_bundle[4] if venue == 'MERCEDES-BENZ STADIUM': filler = 'vs' else: filler = 'at' event = { 'summary': 'Atlanta United {} {} ({})'.format(filler, opponent, competition), 'location': '{}'.format(venue), 'description': 'TV: {}\nAtlanta United {} {} ({})'.format(watch, filler, opponent, competition), 'start': { 'dateTime': '{0:%Y-%m-%dT%H:%M:00}'.format(time), 'timeZone': 'America/New_York', }, 'end': { 'dateTime': '{0:%Y-%m-%dT%H:%M:00}'.format(time + datetime.timedelta(hours=2)), 'timeZone': 'America/New_York', }, 'recurrence': [], 'attendees': [], 'reminders': {}, } calendar_id = '*****@*****.**' google.events().insert(calendarId=calendar_id, body=event).execute()
def update_events(google: discovery.build, event_list: list, match_bundle: list) -> None: """ Compare Google Events to match_bundle matches and update events :param google: authenticated Google session (discovery.build) :param event_list: master list of event ids (list) :param match_bundle: list of opponent, venue, time, competition (list) :return: None """ calendar_id = '*****@*****.**' for index, event in enumerate(event_list): opponent = match_bundle[index][0] venue = match_bundle[index][1] time = match_bundle[index][2] watch = match_bundle[index][3] competition = match_bundle[index][4] if venue == 'MERCEDES-BENZ STADIUM': filler = 'vs' else: filler = 'at' old_event = google.events().get(calendarId=calendar_id, eventId=event).execute() old_event_summary = old_event['summary'] old_event_location = old_event['location'] old_event_description = old_event['description'] old_event_start_time = old_event['start'].get('dateTime', old_event['start'].get('date')) bundle_event_summary = 'Atlanta United {} {} ({})'.format(filler, opponent, competition) bundle_event_location = '{}'.format(venue) bundle_event_description = 'TV: {}\nAtlanta United {} {} ({})'.format(watch, filler, opponent, competition) bundle_event_start_time = '{0:%Y-%m-%dT%H:%M:00-05:00}'.format(time) if old_event_start_time != bundle_event_start_time: update_individual_event(google, event, 'start.dateTime', bundle_event_start_time) if old_event_summary != bundle_event_summary: update_individual_event(google, event, 'summary', bundle_event_summary) if old_event_location != bundle_event_location: update_individual_event(google, event, 'location', bundle_event_location) if old_event_description != bundle_event_description: update_individual_event(google, event, 'description', bundle_event_description)