google_calendar.rb 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. class GoogleCalendar
  2. def initialize(config, logger)
  3. @config = config
  4. @key = Google::APIClient::PKCS12.load_key(@config['google']['key_file'], @config['google']['key_secret'])
  5. @client = Google::APIClient.new(application_name: "Huginn", application_version: "0.0.1")
  6. @client.retries = 2
  7. @logger ||= logger
  8. @calendar = @client.discovered_api('calendar','v3')
  9. @logger.info("Setup")
  10. @logger.debug @calendar.inspect
  11. end
  12. def auth_as
  13. @client.authorization = Signet::OAuth2::Client.new({
  14. token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
  15. audience: 'https://accounts.google.com/o/oauth2/token',
  16. scope: 'https://www.googleapis.com/auth/calendar',
  17. issuer: @config['google']['service_account_email'],
  18. signing_key: @key
  19. });
  20. @client.authorization.fetch_access_token!
  21. end
  22. # who - String: email of user to add event
  23. # details - JSON String: see https://developers.google.com/google-apps/calendar/v3/reference/events/insert
  24. def publish_as(who, details)
  25. auth_as
  26. @logger.info("Attempting to create event for " + who)
  27. @logger.debug details.to_yaml
  28. ret = @client.execute(
  29. api_method: @calendar.events.insert,
  30. parameters: {'calendarId' => who, 'sendNotifications' => true},
  31. body: details.to_json,
  32. headers: {'Content-Type' => 'application/json'}
  33. )
  34. @logger.debug ret.to_yaml
  35. ret
  36. end
  37. def events_as(who, date)
  38. auth_as
  39. date ||= Date.today
  40. @logger.info("Attempting to receive events for "+who)
  41. @logger.debug details.to_yaml
  42. ret = @client.execute(
  43. api_method: @calendar.events.list,
  44. parameters: {'calendarId' => who, 'sendNotifications' => true},
  45. body: details.to_json,
  46. headers: {'Content-Type' => 'application/json'}
  47. )
  48. @logger.debug ret.to_yaml
  49. ret
  50. end
  51. end