<commit_before><commit_msg>Add a service account based helper library for publishing google calendar events.<commit_after>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
{'fraction_non_alphanumeric': 0.13619227144203583, 'fraction_numerical': 0.0051837888784165885, 'mean_word_length': 3.0592734225621414, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 4, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3588088', 'n_tokens_mistral': 669, 'n_tokens_neox': 653, 'n_words': 136}