From 604581cf7e4900f52e132012a98874d771c9deca Mon Sep 17 00:00:00 2001 From: Daniel O'Connor Date: Fri, 13 Jun 2014 10:39:38 +0930 Subject: [PATCH] Add a service account based helper library for publishing google calendar events. --- lib/google_calendar.rb | 68 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 lib/google_calendar.rb diff --git a/lib/google_calendar.rb b/lib/google_calendar.rb new file mode 100644 index 00000000..6a19d125 --- /dev/null +++ b/lib/google_calendar.rb @@ -0,0 +1,68 @@ +require "google-api-client" + +class GoogleCalendar + + def initialize(config, logger) + @config = config + @key = Google::APIClient::PKCS12.load_key(@config['google']['key_file'], @config['google']['key_secret']) + @client = Google::APIClient.new(application_name: "Huginn", application_version: "0.0.1") + @client.retries = 2 + @logger ||= logger + + @calendar = @client.discovered_api('calendar','v3') + + @logger.info("Setup") + @logger.debug @calendar.inspect + end + + def auth_as(who) + @client.authorization = Signet::OAuth2::Client.new({ + token_credential_uri: 'https://accounts.google.com/o/oauth2/token', + audience: 'https://accounts.google.com/o/oauth2/token', + scope: 'https://www.googleapis.com/auth/calendar', + issuer: @config['google']['service_account_email'], + signing_key: @key, + person: who # Who are we emulating? + }); + + @client.authorization.fetch_access_token! + end + + # who - String: email of user to add event + # details - JSON String: see https://developers.google.com/google-apps/calendar/v3/reference/events/insert + def publish_as(who, details) + auth_as(who) + + @logger.info("Attempting to create event for " + who) + @logger.debug details.to_yaml + + ret = @client.execute( + api_method: @calendar.events.insert, + parameters: {'calendarId' => who, 'sendNotifications' => true}, + body: details, + headers: {'Content-Type' => 'application/json'} + ) + @logger.debug ret.to_yaml + ret + end + + def events_as(who, date) + auth_as(who) + + date ||= Date.today + + @logger.info("Attempting to receive events for "+who) + @logger.debug details.to_yaml + + ret = @client.execute( + api_method: @calendar.events.list, + parameters: {'calendarId' => who, 'sendNotifications' => true}, + body: details, + headers: {'Content-Type' => 'application/json'} + ) + + @logger.debug ret.to_yaml + ret + end + +end \ No newline at end of file