1
0

google_calendar.rb 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. require 'googleauth'
  2. require 'google/apis/calendar_v3'
  3. class GoogleCalendar
  4. def initialize(config, logger)
  5. @config = config
  6. if @config['google']['key'].present?
  7. # https://github.com/google/google-auth-library-ruby/issues/65
  8. # https://github.com/google/google-api-ruby-client/issues/370
  9. ENV['GOOGLE_PRIVATE_KEY'] = @config['google']['key']
  10. ENV['GOOGLE_CLIENT_EMAIL'] = @config['google']['service_account_email']
  11. ENV['GOOGLE_ACCOUNT_TYPE'] = 'service_account'
  12. elsif @config['google']['key_file'].present?
  13. ENV['GOOGLE_APPLICATION_CREDENTIALS'] = @config['google']['key_file']
  14. end
  15. @logger ||= logger
  16. # https://github.com/google/google-api-ruby-client/blob/master/MIGRATING.md
  17. @calendar = Google::Apis::CalendarV3::CalendarService.new
  18. # https://developers.google.com/api-client-library/ruby/auth/service-accounts
  19. # https://developers.google.com/identity/protocols/application-default-credentials
  20. scopes = [Google::Apis::CalendarV3::AUTH_CALENDAR]
  21. @authorization = Google::Auth.get_application_default(scopes)
  22. @logger.info("Setup")
  23. @logger.debug @calendar.inspect
  24. end
  25. def self.open(*args, &block)
  26. instance = new(*args)
  27. block.call(instance)
  28. ensure
  29. instance&.cleanup!
  30. end
  31. def auth_as
  32. @authorization.fetch_access_token!
  33. @calendar.authorization = @authorization
  34. end
  35. # who - String: email of user to add event
  36. # details - JSON String: see https://developers.google.com/google-apps/calendar/v3/reference/events/insert
  37. def publish_as(who, details)
  38. auth_as
  39. @logger.info("Attempting to create event for " + who)
  40. @logger.debug details.to_yaml
  41. event = Google::Apis::CalendarV3::Event.new(**details.deep_symbolize_keys)
  42. ret = @calendar.insert_event(
  43. who,
  44. event,
  45. send_notifications: true
  46. )
  47. @logger.debug ret.to_yaml
  48. ret.to_h
  49. end
  50. def events_as(who, date)
  51. auth_as
  52. date ||= Date.today
  53. @logger.info("Attempting to receive events for "+who)
  54. @logger.debug details.to_yaml
  55. ret = @calendar.list_events(
  56. who
  57. )
  58. @logger.debug ret.to_yaml
  59. ret.to_h
  60. end
  61. def cleanup!
  62. ENV.delete('GOOGLE_PRIVATE_KEY')
  63. ENV.delete('GOOGLE_CLIENT_EMAIL')
  64. ENV.delete('GOOGLE_ACCOUNT_TYPE')
  65. ENV.delete('GOOGLE_APPLICATION_CREDENTIALS')
  66. end
  67. end