google_calendar.rb 1.9 KB

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