Created
July 28, 2020 11:15
-
-
Save robertomiranda/b63abc35ac52b945babbc92161d57d51 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "google/apis/calendar_v3" | |
require "googleauth" | |
require "googleauth/stores/file_token_store" | |
require "date" | |
require "fileutils" | |
require "active_support/all" | |
OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze | |
APPLICATION_NAME = "Google Calendar API Ruby Quickstart".freeze | |
CREDENTIALS_PATH = "credentials.json".freeze | |
# The file token.yaml stores the user's access and refresh tokens, and is | |
# created automatically when the authorization flow completes for the first | |
# time. | |
TOKEN_PATH = "token.yaml".freeze | |
SCOPE = "https://www.googleapis.com/auth/calendar.events" | |
## | |
# Ensure valid credentials, either by restoring from the saved credentials | |
# files or intitiating an OAuth2 authorization. If authorization is required, | |
# the user's default browser will be launched to approve the request. | |
# | |
# @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials | |
def authorize | |
client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH | |
token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH | |
authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store | |
user_id = "default" | |
credentials = authorizer.get_credentials user_id | |
if credentials.nil? | |
url = authorizer.get_authorization_url base_url: OOB_URI | |
puts "Open the following URL in the browser and enter the " \ | |
"resulting code after authorization:\n" + url | |
code = gets | |
credentials = authorizer.get_and_store_credentials_from_code( | |
user_id: user_id, code: code, base_url: OOB_URI | |
) | |
end | |
credentials | |
end | |
# Initialize the API | |
service = Google::Apis::CalendarV3::CalendarService.new | |
service.client_options.application_name = APPLICATION_NAME | |
service.authorization = authorize | |
# Fetch the next 10 events for the user | |
calendar_id = "primary" | |
response = service.list_events(calendar_id, | |
max_results: 2500, | |
single_events: true, | |
order_by: "startTime", | |
time_min: 1.month.ago.to_datetime.rfc3339) | |
puts "Upcoming events:" | |
puts "No upcoming events found" if response.items.empty? | |
events = response.items.select{|event| event.summary.match(/^On Call/) && !event.summary.match(/Roberto/)}; | |
events.map do |event| | |
start = event.start.date || event.start.date_time | |
puts "- #{event.summary} (#{start})" | |
service.delete_event(calendar_id, event.id) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment