google_calendar.rb 2.0 KB

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