class Cronofy::Client

Public: Primary class for interacting with the Cronofy API.

Constants

AVAILABLE_PERIODS_TIME_PARAMS
DEFAULT_OAUTH_SCOPE

Public: The scope to request if none is explicitly specified by the caller.

FREE_BUSY_DEFAULT_PARAMS
FREE_BUSY_TIME_PARAMS
QUERY_SLOTS_TIME_PARAMS
READ_EVENTS_DEFAULT_PARAMS
READ_EVENTS_TIME_PARAMS

Public Class Methods

new(options = {}) click to toggle source

Public: Initialize a new Cronofy::Client.

options - A Hash of options used to initialize the client (default: {}):

:access_token  - An existing access token String for the user's
                 account (optional).
:client_id     - The client ID String of your Cronofy OAuth
                 application (default:
                 ENV["CRONOFY_CLIENT_ID"]).
:client_secret - The client secret String of your Cronofy OAuth
                 application (default:
                 ENV["CRONOFY_CLIENT_SECRET"]).
:refresh_token - An existing refresh token String for the user's
                 account (optional).
:data_center   - An identifier to override the default data
                 center (optional).
# File lib/cronofy/client.rb, line 32
def initialize(options = {})
  access_token  = options[:access_token]
  refresh_token = options[:refresh_token]

  @client_id     = options.fetch(:client_id, ENV["CRONOFY_CLIENT_ID"])
  @client_secret = options.fetch(:client_secret, ENV["CRONOFY_CLIENT_SECRET"])
  @data_center   = options[:data_center] || options[:data_centre]

  @auth = Auth.new(
    client_id: @client_id,
    client_secret: @client_secret,
    access_token: access_token,
    refresh_token: refresh_token,
    data_center: @data_center
  )
end

Public Instance Methods

account() click to toggle source

Public: Retrieves the details of the account.

See docs.cronofy.com/developers/api/identity/account/ for reference.

Returns an Account.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 573
def account
  response = get("/v1/account")
  parse_json(Account, "account", response)
end
add_to_calendar(args = {}) click to toggle source

Public: Generates an add to calendar link to start the OAuth process with an event to be automatically upserted

oauth - A Hash describing the OAuth flow required:

:scope             - A String representing the scopes to ask for
                     within the OAuth flow
:redirect_uri      - A String containing a url to redirect the
                     user to after completing the OAuth flow.
:scope             - A String representing additional state to
                     be passed within the OAuth flow.

event - A Hash describing the event with symbolized keys:

:event_id          - A String uniquely identifying the event for
                     your application (note: this is NOT an ID
                     generated by Cronofy).
:summary           - A String to use as the summary, sometimes
                     referred to as the name or title, of the
                     event.
:description       - A String to use as the description, sometimes
                     referred to as the notes or body, of the
                     event.
:start             - The Time or Date the event starts.
:end               - The Time or Date the event ends.
:url               - The URL associated with the event.
:location          - A Hash describing the location of the event
                     with symbolized keys (optional):
                     :description - A String describing the
                                    location.
                     :lat - A String of the location's latitude.
                     :long - A String of the location's longitude.
:reminders         - An Array of Hashes describing the desired
                     reminders for the event. Reminders should be
                     specified in priority order as, for example,
                     when the underlying provider only supports a
                     single reminder then the first reminder will
                     be used.
                     :minutes - An Integer specifying the number
                                of minutes before the start of the
                                event that the reminder should
                                occur.
:transparency      - The transparency state for the event (optional).
                     Accepted values are "transparent" and "opaque".
:attendees         - A Hash of :invite and :reject, each of which is
                     an array of invitees to invite to or reject from
                     the event. Invitees are represented by a hash of
                     :email and :display_name (optional).

Example

client.add_to_calendar(
 oauth: {
   scopes: 'read_events delete_events',
   redirect_uri: 'http://www.example.com',
   state: 'example_state'
 },
 event: {
  event_id: "qTtZdczOccgaPncGJaCiLg",
  summary: "Board meeting",
  description: "Discuss plans for the next quarter.",
  start: Time.utc(2014, 8, 5, 15, 30),
  end:   Time.utc(2014, 8, 5, 17, 30),
  location: {
    description: "Board room",
    lat: "1.2345",
    long: "0.1234"
  })

See docs.cronofy.com/developers/api/events/upsert-event/ for reference.

Returns a AddToCalendarResponse.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::NotFoundError if the calendar does not exist. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1004
def add_to_calendar(args = {})
  body = args.merge(client_id: @client_id, client_secret: @client_secret)

  body[:event][:start] = encode_event_time(body[:event][:start])
  body[:event][:end] = encode_event_time(body[:event][:end])

  response = post("/v1/add_to_calendar", body)
  parse_json(AddToCalendarResponse, nil , response)
end
application_calendar(application_calendar_id) click to toggle source

Public: Obtains access to an application calendar

See docs.cronofy.com/developers/api/calendars/application-calendars/ for reference.

Returns a set of Cronofy::Credentials for the account.

Raises Cronofy::BadRequestError if refresh token code is unknown or has been revoked. Raises Cronofy::AuthenticationFailureError if the client ID and secret are not valid. Raises Cronofy::CredentialsMissingError if no credentials available.

# File lib/cronofy/client.rb, line 747
def application_calendar(application_calendar_id)
  @auth.application_calendar(application_calendar_id)
end
authorize_with_service_account(email, scope, callback_url, state) click to toggle source

Public: Attempts to authorize the email with impersonation from a service account

email - the email address to impersonate scope - Array or String of scopes describing the access to

request from the user to the users calendars (required).

callback_url - the url to callback to

Returns nothing

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 662
def authorize_with_service_account(email, scope, callback_url, state)
  if scope.respond_to?(:join)
    scope = scope.join(' ')
  end

  params = {
    email: email,
    scope: scope,
    callback_url: callback_url,
    state: state
  }
  post("/v1/service_account_authorizations", params)
  nil
end
availability(options = {}) click to toggle source

Public: Performs an availability query.

options - The Hash options used to refine the selection (default: {}):

:participants      - An Array of participant groups or a Hash
                     for a single participant group.
:required_duration - An Integer representing the minimum number
                     of minutes of availability required.
:query_periods     - An Array of available time periods Hashes,
                     each must specify a start and end Time.
:start_interval    - An Integer representing the start interval
                     of minutes for the availability query.
:buffer            - A Hash containing the buffer to apply to
                     the availability query.
:query_slots       - A Hash containing the query slots to be
                     used in the availability query.

Returns an Array of AvailablePeriods.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 854
def availability(options = {})
  options[:participants] = map_availability_participants(options[:participants])
  options[:required_duration] = map_availability_required_duration(options[:required_duration])

  if options[:start_interval]
    options[:start_interval] = map_availability_required_duration(options[:start_interval])
  end

  if buffer = options[:buffer]
    options[:buffer] = map_availability_buffer(buffer)
  end

  if query_periods = options[:query_periods] || options[:available_periods]
    translate_available_periods(query_periods)
  end

  if query_slots = options[:query_slots]
    translate_query_slots(query_slots)
  end

  response = availability_post("/v1/availability", options)

  parse_collections(
    response,
    available_periods: AvailablePeriod,
    available_slots: AvailableSlot,
  )
end
batch() { |builder = batch_builder| ... } click to toggle source
# File lib/cronofy/client.rb, line 379
def batch
  yield builder = BatchBuilder.new

  requests = builder.build

  response = post("/v1/batch", batch: requests)
  responses = parse_collection(BatchEntryResponse, "batch", response)

  entries = requests.zip(responses).map do |request, response|
    response.request = request
    response
  end

  result = BatchResponse.new(entries)

  if result.errors?
    msg = "Batch contains #{result.errors.count} errors"
    raise BatchResponse::PartialSuccessError.new(msg, result)
  end

  result
end
cancel_smart_invite(body={}) click to toggle source

Public: Cancels a smart invite

smart_invite_id - A String uniquely identifying the event for your

application (note: this is NOT an ID generated
by Cronofy).

recipient - A Hash containing the intended recipient of the invite

:email      - A String for thee email address you are
              going to send the Smart Invite to.

See docs.cronofy.com/developers/api/smart-invites/cancel-invite/ for reference.

Returns a SmartInviteResponse.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1429
def cancel_smart_invite(body={})
  body[:method] = 'cancel'
  response = wrapped_request { api_key!.post("/v1/smart_invites", json_request_args(body)) }
  parse_json(SmartInviteResponse, nil, response)
end
change_participation_status(calendar_id, event_uid, status) click to toggle source

Public: Changes the participation status for a calendar event

calendar_id - The String Cronofy ID for the calendar to delete the event

from.

event_uid - A String uniquely identifying the event for your application

(note: this is NOT an ID generated by Cronofy).

status - A String or Symbol to set the participation status of the

invite to

See docs.cronofy.com/developers/api/events/delete-event/ for reference.

Returns nothing.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::NotFoundError if the calendar does not exist. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 638
def change_participation_status(calendar_id, event_uid, status)
  body = {
    status: status.to_s,
  }

  url = "/v1/calendars/#{calendar_id}/events/#{event_uid}/participation_status"
  post(url, body)
end
close_channel(channel_id) click to toggle source

Public: Closes a notification channel.

channel_id - The String Cronofy ID for the channel to close.

See docs.cronofy.com/developers/api/push-notifications/close-channel/ for reference.

Returns nothing.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::NotFoundError if the channel does not exist. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 555
def close_channel(channel_id)
  delete("/v1/channels/#{channel_id}")
  nil
end
create_calendar(profile_id, name, options = {}) click to toggle source

Public: Creates a new calendar for the profile.

profile_id - The String ID of the profile to create the calendar within. name - The String to use as the name of the calendar. options - The Hash options used to customize the calendar

(default: {}):
:color - The color to make the calendar (optional).

See docs.cronofy.com/developers/api/calendars/create-calendar/ for reference.

Returns the created Calendar

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::AccountLockedError if the profile is not in a writable state and so a calendar cannot be created. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 72
def create_calendar(profile_id, name, options = {})
  request = options.merge(profile_id: profile_id, name: name)
  response = post("/v1/calendars", request)
  parse_json(Calendar, "calendar", response)
end
create_channel(callback_url, options = {}) click to toggle source

Public: Creates a notification channel with a callback URL

callback_url - A String specifing the callback URL for the channel. options - The Hash options used to refine the notifications of the

channel (default: {}):
:filters - A Hash of filters to use for the notification
           channel (optional):
           :calendar_ids - An Array of calendar ID strings
                           to restrict the returned events
                           to (optional).
           :only_managed - A Boolean specifying whether
                           only events that you are
                           managing for the account should
                           trigger notifications
                           (optional).

See docs.cronofy.com/developers/api/push-notifications/create-channel/ for reference.

Returns a Channel.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 485
def create_channel(callback_url, options = {})
  params = options.merge(callback_url: callback_url)

  response = post("/v1/channels", params)
  parse_json(Channel, "channel", response)
end
create_or_update_event(calendar_id, event)

Public: Alias for upsert_event

Alias for: upsert_event
create_scheduling_conversation(body) click to toggle source

Public: Creates a scheduling conversation

pre release end-point documentation to follow

# File lib/cronofy/client.rb, line 1686
def create_scheduling_conversation(body)
  response = wrapped_request { post("/v1/scheduling_conversations", body) }
  parse_json(SchedulingConversation, 'scheduling_conversation', response)
end
delete_all_events(options = nil) click to toggle source

Public: Deletes all events you are managing for the account.

See docs.cronofy.com/developers/api/events/bulk-delete-events/ for reference.

options - The Hash options used to refine the selection (optional):

:calendar_ids - An Array of calendar ids to delete managed
                events from returned events.

If no options are specified it defaults to deleting all the events you are managing.

Returns nothing.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::NotFoundError if the calendar does not exist. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 450
def delete_all_events(options = nil)
  options ||= { delete_all: true }
  delete("/v1/events", options)
  nil
end
delete_availability_rule(availability_rule_id) click to toggle source

Public: Deletes an AvailabilityRule.

availability_rule_id - A String uniquely identifying the availability rule

for the authenticated user in your application

Returns nothing.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1599
def delete_availability_rule(availability_rule_id)
  wrapped_request { delete("/v1/availability_rules/#{availability_rule_id}") }
  nil
end
delete_available_period(available_period_id) click to toggle source

Public: Deletes an AvailablePeriod.

available_period_id - A String uniquely identifying the available period

for the authenticated user in your application

Returns nothing.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1677
def delete_available_period(available_period_id)
  wrapped_request { delete("/v1/available_periods", available_period_id: available_period_id) }
  nil
end
delete_event(calendar_id, event_id) click to toggle source

Public: Deletes an event from the specified calendar

calendar_id - The String Cronofy ID for the calendar to delete the event

from.

event_id - A String uniquely identifying the event for your application

(note: this is NOT an ID generated by Cronofy).

See docs.cronofy.com/developers/api/events/delete-event/ for reference.

Returns nothing.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::NotFoundError if the calendar does not exist. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 310
def delete_event(calendar_id, event_id)
  delete("/v1/calendars/#{calendar_id}/events", event_id: event_id)
  nil
end
delete_external_event(calendar_id, event_uid) click to toggle source

Public: Deletes an external event from the specified calendar

calendar_id - The String Cronofy ID for the calendar to delete the event

from.

event_uid - The unique ID of the event to delete.

Returns nothing.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope or the client has not been granted elevated permissions to the calendar. Raises Cronofy::NotFoundError if the calendar does not exist. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 421
def delete_external_event(calendar_id, event_uid)
  delete("/v1/calendars/#{calendar_id}/events", event_uid: event_uid)
  nil
end
disable_real_time_scheduling(args = {}) click to toggle source

Public: Disables a Real-Time Scheduling link.

id - A String uniquely identifying the link, returned

on initial creation

display_message - A message to display to visitors of the disabled link

See docs.cronofy.com/developers/api/scheduling/real-time-scheduling/disable/ for reference.

Returns a RealTimeSchedulingStatus.

Raises ArgumentError if no ‘id’ argument is passed. Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1200
def disable_real_time_scheduling(args = {})
  id = args.delete(:id)

  raise ArgumentError.new('id argument is required') unless id

  response = wrapped_request { api_key!.post("/v1/real_time_scheduling/#{id}/disable", json_request_args(args)) }
  parse_json(RealTimeSchedulingStatus, 'real_time_scheduling' , response)
end
element_token(options) click to toggle source

Public: Creates an element_token to pass to a UI Element

options - A Hash of options for the token

:permissions -  An Array of strings describing the
                permissions required for the token
:subs        -  An Array of sub values for the account(s)
                the element will be accessing
:origin      -  The scheme://hostname where the token will
                be used.
                https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin

See docs.cronofy.com/developers/ui-elements/authentication for reference.

Returns an element token

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1503
def element_token(options)
  response = wrapped_request { api_key!.post("/v1/element_tokens", json_request_args(options)) }
  parse_json(ElementToken, "element_token", response)
end
elevated_permissions(args = {}) click to toggle source

Public: Requests elevated permissions for a set of calendars.

args - A Hash of options used to initialize the request (default: {}):

:permissions  - An Array of calendar permission hashes to set on
                the each hash must contain symbols for both
                `calendar_id` and `permission_level`
:redirect_uri - A uri to redirect the end user back to after they
                have either granted or rejected the request for
                elevated permission.

In the case of normal accounts: After making this call the end user will have to grant the extended permissions to their calendar via rhe url returned from the response.

In the case of service accounts: After making this call the exteneded permissions will be granted provided the relevant scope has been granted to the account

Returns a extended permissions response.

Raises Cronofy::AuthenticationFailureError if the client ID and secret are not valid.

# File lib/cronofy/client.rb, line 798
def elevated_permissions(args = {})
  filtered_permissions = args[:permissions].map do |permission|
    { calendar_id: permission[:calendar_id], permission_level: permission[:permission_level] }
  end

  body = { permissions: filtered_permissions }
  body[:redirect_uri] = args[:redirect_uri] if args[:redirect_uri]

  response = post("/v1/permissions", body)
  parse_json(PermissionsResponse, "permissions_request", response)
end
free_busy(options = {}) click to toggle source

Public: Returns a lazily-evaluated Enumerable of FreeBusy that satisfy the given query criteria.

options - The Hash options used to refine the selection (default: {}):

:from            - The minimum Date from which to return events
                   (optional).
:to              - The Date to return events up until (optional).
:tzid            - A String representing a known time zone
                   identifier from the IANA Time Zone Database
                   (default: Etc/UTC).
:include_managed - A Boolean specifying whether events that you
                   are managing for the account should be
                   included or excluded from the results
                   (optional).
:localized_times - A Boolean specifying whether the start and
                   end times should be returned with any
                   available localization information
                   (optional).
:calendar_ids    - An Array of calendar ids for restricting the
                   returned events (optional).

The first page will be retrieved eagerly so that common errors will happen inline. However, subsequent pages (if any) will be requested lazily.

See docs.cronofy.com/developers/api/events/free-busy/ for reference.

Returns a lazily-evaluated Enumerable of FreeBusy

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 278
def free_busy(options = {})
  params = FREE_BUSY_DEFAULT_PARAMS.merge(options)

  FREE_BUSY_TIME_PARAMS.select { |tp| params.key?(tp) }.each do |tp|
    params[tp] = to_iso8601(params[tp])
  end

  url = api_url + "/v1/free_busy"
  PagedResultIterator.new(PagedFreeBusyResult, :free_busy, access_token!, url, params)
end
get_availability_rule(availability_rule_id) click to toggle source

Public: Gets an AvailabilityRule.

availability_rule_id - A String uniquely identifying the availability rule

for the authenticated user in your application

Returns an AvailabilityRuleResponse.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1568
def get_availability_rule(availability_rule_id)
  response = wrapped_request { get("/v1/availability_rules/#{availability_rule_id}") }
  parse_json(AvailabilityRule, 'availability_rule', response)
end
get_availability_rules() click to toggle source

Public: Gets all AvailabilityRules for an account.

Returns an array of AvailabilityRules.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1582
def get_availability_rules
  response = wrapped_request { get("/v1/availability_rules") }
  parse_collection(AvailabilityRule, 'availability_rules', response)
end
get_available_periods(options={}) click to toggle source

Public: Gets all AvailablePeriods for an account.

options - The Hash options used to refine the selection (default: {}):

:from            - The minimum Date from which to return periods
                   (optional).
:to              - The Date to return periods up until (optional).
:tzid            - A String representing a known time zone
                   identifier from the IANA Time Zone Database
                   (default: Etc/UTC).
:localized_times - A Boolean specifying whether the start and
                   end times should be returned with any
                   available localization information
                   (optional).

Returns an array of AvailablePeriods.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1651
def get_available_periods(options={})
  query = {}
  query[:from] = to_iso8601(options[:from]) if options[:from]
  query[:to] = to_iso8601(options[:to]) if options[:to]
  query[:tzid] = options[:tzid] if options[:tzid]
  query[:localized_times] = options[:localized_times] if options[:localized_times]
  if query.any?
    query_string = "?#{URI.encode_www_form(query)}"
  end

  response = wrapped_request { get("/v1/available_periods#{query_string}") }
  parse_collection(AvailablePeriod, 'available_periods', response)
end
get_conferencing_service_authorizations(redirect_uri) click to toggle source

Public: Returns an URL where users can authorize access to their conferencing services.

See docs.cronofy.com/developers/api/conferencing-services/authorization/ for reference.

Returns Cronofy::ConferencingServiceAuthorizationResponse with the generated URL

Raises Cronofy::BadRequestError if refresh token code is unknown or has been revoked. Raises Cronofy::AuthenticationFailureError if the client ID and secret are not valid. Raises Cronofy::CredentialsMissingError if no credentials available.

# File lib/cronofy/client.rb, line 326
def get_conferencing_service_authorizations(redirect_uri)
  data = { redirect_uri: redirect_uri }

  response = post "/v1/conferencing_service_authorizations", data
  parse_json(ConferencingServiceAuthorizationResponse, "authorization_request", response)
end
get_real_time_scheduling_status(args = {}) click to toggle source

Public: Gets the status of a Real-Time Scheduling link.

Provide one of the following arguments to identify the link: id - A String uniquely identifying the link, returned on initial

creation

token - The token portion of the link’s URL

See docs.cronofy.com/developers/api/scheduling/real-time-scheduling/status/ for reference.

Returns a RealTimeSchedulingStatus.

Raises ArgumentError if neither ‘id’ nor ‘token’ arguments are passed. Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1171
def get_real_time_scheduling_status(args = {})
  if args[:token]
    url = "/v1/real_time_scheduling?token=#{args[:token]}"
  elsif args[:id]
    url = "/v1/real_time_scheduling/#{args[:id]}"
  else
    raise ArgumentError.new("Must pass either token or id argument")
  end

  response = wrapped_request { api_key!.get(url) }
  parse_json(RealTimeSchedulingStatus, 'real_time_scheduling' , response)
end
get_scheduling_conversation(id) click to toggle source

Public: Creates a scheduling conversation

pre release end-point documentation to follow

# File lib/cronofy/client.rb, line 1695
def get_scheduling_conversation(id)
  response = wrapped_request { get("/v1/scheduling_conversations/#{id}") }
  parse_json(SchedulingConversation, 'scheduling_conversation', response)
end
get_smart_invite(smart_invite_id, recipient_email) click to toggle source

Public: Gets the details for a smart invite.

smart_invite_id - A String uniquely identifying the event for your

application (note: this is NOT an ID generated
by Cronofy).

recipient_email - The email address for the recipient to get details for.

See docs.cronofy.com/developers/api/smart-invites/invite-status/ for reference.

Returns a SmartInviteResponse.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1477
def get_smart_invite(smart_invite_id, recipient_email)
  response = wrapped_request { api_key!.get("/v1/smart_invites?recipient_email=#{recipient_email}&smart_invite_id=#{smart_invite_id}") }
  parse_json(SmartInviteResponse, nil, response)
end
get_token_from_code(code, redirect_url) click to toggle source

Public: Retrieves the OAuth credentials authorized for the given code and redirect URL pair.

code - String code returned to redirect_url after authorization. redirect_url - A String specifing the URL the user returned to once they

had completed the authorization steps.

See docs.cronofy.com/developers/api/authorization/request-token/ for reference.

Returns a set of Cronofy::Credentials for the account.

Raises Cronofy::BadRequestError if the code is unknown, has been revoked, or the code and redirect URL do not match. Raises Cronofy::AuthenticationFailureError if the client ID and secret are not valid.

# File lib/cronofy/client.rb, line 713
def get_token_from_code(code, redirect_url)
  @auth.get_token_from_code(code, redirect_url)
end
hmac_match?(args) click to toggle source

DEPRECATED: Please use hmac_valid instead.

# File lib/cronofy/client.rb, line 493
def hmac_match?(args)
  warn "[DEPRECATION] `hmac_match?` is deprecated. Please use `hmac_valid?` instead."
  hmac_valid?(args)
end
hmac_valid?(args) click to toggle source

Public: Verifies a HMAC from a push notification using the client secret.

args - A Hash containing the details of the push notification:

:body - A String of the body of the notification.
:hmac - A String containing comma-separated values describing HMACs of the notification taken from the
        Cronofy-HMAC-SHA256 header.

Returns true if one of the HMAC provided matches the one calculated using the client secret, otherwise false.

# File lib/cronofy/client.rb, line 507
def hmac_valid?(args)
  body = args[:body]
  hmac = args[:hmac]

  return false if hmac.nil? || hmac.empty?

  sha256 = OpenSSL::Digest.new('sha256')
  digest = OpenSSL::HMAC.digest(sha256, @client_secret, body)
  calculated = Base64.encode64(digest).strip

  hmac_list = hmac.split(',')
  hmac_list.include?(calculated)
end
list_calendars() click to toggle source

Public: Lists all the calendars for the account.

See docs.cronofy.com/developers/api/calendars/list-calendars/ for reference.

Returns an Array of Calendars

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 89
def list_calendars
  response = get("/v1/calendars")
  parse_collection(Calendar, "calendars", response)
end
list_channels() click to toggle source

Public: Lists all the notification channels for the account.

See docs.cronofy.com/developers/api/push-notifications/list-channels/ for reference.

Returns an Array of Channels.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 534
def list_channels
  response = get("/v1/channels")
  parse_collection(Channel, "channels", response)
end
list_profiles() click to toggle source

Public: Lists all the profiles for the account.

See docs.cronofy.com/developers/api/identity/profile/ for reference.

Returns an Array of Profiles

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 589
def list_profiles
  response = get("/v1/profiles")
  parse_collection(Profile, "profiles", response)
end
list_scheduling_conversation_participant_slots(url) click to toggle source

Public: List available slots for a scheduling conversation

pre release end-point documentation to follow

# File lib/cronofy/client.rb, line 1713
def list_scheduling_conversation_participant_slots(url)
  response = wrapped_request { get(url) }
  parse_collection(SchedulingConversationSlot, "slots", response )
end
lookup_scheduling_conversation(token) click to toggle source

Public: Looks up a scheduling conversation with a token returned by a redirect

pre release end-point documentation to follow

# File lib/cronofy/client.rb, line 1704
def lookup_scheduling_conversation(token)
  response = wrapped_request { get("/v1/scheduling_conversations?token=#{token}") }
  parse_json(SchedulingConversationResponse, nil, response)
end
read_events(options = {}) click to toggle source

Public: Returns a lazily-evaluated Enumerable of Events that satisfy the given query criteria.

options - The Hash options used to refine the selection (default: {}):

:from            - The minimum Date from which to return events
                   (optional).
:to              - The Date to return events up until (optional).
:tzid            - A String representing a known time zone
                   identifier from the IANA Time Zone Database
                   (default: Etc/UTC).
:include_deleted - A Boolean specifying whether events that have
                   been deleted should be included or excluded
                   from the results (optional).
:include_moved   - A Boolean specifying whether events that have
                   ever existed within the given window should
                   be included or excluded from the results
                   (optional).
:include_managed - A Boolean specifying whether events that you
                   are managing for the account should be
                   included or excluded from the results
                   (optional).
:only_managed    - A Boolean specifying whether only events that
                   you are managing for the account should
                   trigger notifications (optional).
:localized_times - A Boolean specifying whether the start and
                   end times should be returned with any
                   available localization information
                   (optional).
:last_modified   - The Time that events must be modified on or
                   after in order to be returned (optional).
:calendar_ids    - An Array of calendar ids for restricting the
                   returned events (optional).
:include_geo     - A Boolean specifying whether the events should
                   have their location.lat and location.long
                   returned where available (optional).

The first page will be retrieved eagerly so that common errors will happen inline. However, subsequent pages (if any) will be requested lazily.

See docs.cronofy.com/developers/api/events/read-events/ for reference.

Returns a lazily-evaluated Enumerable of Events

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 230
def read_events(options = {})
  params = READ_EVENTS_DEFAULT_PARAMS.merge(options)

  READ_EVENTS_TIME_PARAMS.select { |tp| params.key?(tp) }.each do |tp|
    params[tp] = to_iso8601(params[tp])
  end

  url = api_url + "/v1/events"
  PagedResultIterator.new(PagedEventsResult, :events, access_token!, url, params)
end
real_time_scheduling(args = {}) click to toggle source

Public: Generates an real time scheduling link to start the OAuth process with an event to be automatically upserted

oauth - A Hash describing the OAuth flow required:

:scope             - A String representing the scopes to ask for
                     within the OAuth flow
:redirect_uri      - A String containing a url to redirect the
                     user to after completing the OAuth flow.
:scope             - A String representing additional state to
                     be passed within the OAuth flow.

event - A Hash describing the event with symbolized keys:

:event_id          - A String uniquely identifying the event for
                     your application (note: this is NOT an ID
                     generated by Cronofy).
:summary           - A String to use as the summary, sometimes
                     referred to as the name or title, of the
                     event.
:description       - A String to use as the description, sometimes
                     referred to as the notes or body, of the
                     event.
:url               - The URL associated with the event.
:location          - A Hash describing the location of the event
                     with symbolized keys (optional):
                     :description - A String describing the
                                    location.
                     :lat - A String of the location's latitude.
                     :long - A String of the location's longitude.
:reminders         - An Array of Hashes describing the desired
                     reminders for the event. Reminders should be
                     specified in priority order as, for example,
                     when the underlying provider only supports a
                     single reminder then the first reminder will
                     be used.
                     :minutes - An Integer specifying the number
                                of minutes before the start of the
                                event that the reminder should
                                occur.
:transparency      - The transparency state for the event (optional).
                     Accepted values are "transparent" and "opaque".
:attendees         - A Hash of :invite and :reject, each of which is
                     an array of invitees to invite to or reject from
                     the event. Invitees are represented by a hash of
                     :email and :display_name (optional).

availability - A Hash describing the availability details for the event:

:participants      - A hash stating who is required for the availability
                     call
:required_duration - A hash stating the length of time the event will
                     last for
:query_periods     - A Hash stating the available periods for the event
:query_slots       - A Hash containing the query slots to be
                     used in the availability query.
:start_interval    - An Integer representing the start interval
                     of minutes for the availability query.
:buffer            - An Hash containing the buffer to apply to
                     the availability query.

target_calendars - An array of hashes stating into which calendars to insert the created

event

Examples

  • Availability example client.add_to_calendar(

    oauth: {
     redirect_uri: 'http://www.example.com'
    },
    event: {
     event_id: "qTtZdczOccgaPncGJaCiLg",
     summary: "Board meeting",
     description: "Discuss plans for the next quarter.",
     location: {
       description: "Board room",
       lat: "1.2345",
       long: "0.1234"
     }
    },
    availability: {
      participants: [
       {
         members: [{
           sub: "acc_567236000909002",
           calendar_ids: ["cal_n23kjnwrw2_jsdfjksn234"]
         }],
         required: 'all'
       }
     ],
     required_duration: { minutes: 60 },
     query_periods: [{
       start: Time.utc(2017, 1, 1, 9, 00),
       end:   Time.utc(2017, 1, 1, 17, 00),
     }]
    },
    target_calendars: [{
     sub: "acc_567236000909002",
     calendar_id: "cal_n23kjnwrw2_jsdfjksn234"
    }]

    )

See docs.cronofy.com/developers/api/scheduling/real-time-scheduling/ for reference.

Returns a AddToCalendarResponse.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::NotFoundError if the calendar does not exist. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1126
def real_time_scheduling(args = {})
  body = args.merge(client_id: @client_id, client_secret: @client_secret)

  if availability = args[:availability]
    availability[:participants] = map_availability_participants(availability[:participants])
    availability[:required_duration] = map_availability_required_duration(availability[:required_duration])

    if value = availability[:start_interval]
      availability[:start_interval] = map_availability_required_duration(value)
    end

    if buffer = availability[:buffer]
      availability[:buffer] = map_availability_buffer(buffer)
    end
  end

  if query_periods = availability[:query_periods] || availability[:available_periods]
    translate_available_periods(query_periods)
  end

  if query_slots = availability[:query_slots]
    translate_query_slots(query_slots)
  end

  body[:availability] = availability

  response = raw_post("/v1/real_time_scheduling", body)
  parse_json(AddToCalendarResponse, nil , response)
end
real_time_sequencing(args) click to toggle source

Public: Generates an real time sequencing link to start the OAuth process with an event to be automatically upserted

oauth - A Hash describing the OAuth flow required:

:scope             - A String representing the scopes to ask for
                     within the OAuth flow
:redirect_uri      - A String containing a url to redirect the
                     user to after completing the OAuth flow.
:scope             - A String representing additional state to
                     be passed within the OAuth flow.

availability - A Hash describing the availability details for the event:

 :sequence          - An Array of sequence defintions containing
                      a Hash of:
   :sequence_id       - A String to uniquely identify this part
                      of the proposed sequence.
   :ordinal           - An integer to define the ordering of the
                      proposed sequence. (Optional)
   :participants      - An Array of participant groups or a Hash
                      for a single participant group.
   :required_duration - An Integer representing the minimum
                      number of minutes of availability required.
   :start_interval    - An Integer representing the start interval
                      of minutes for the availability query.
   :buffer            - An Hash containing the buffer to apply to
                      the availability query.
   :event            - A Hash describing the event:
          :event_id          - A String uniquely identifying the event for
                               your application (note: this is NOT an ID
                               generated by Cronofy).
          :summary           - A String to use as the summary, sometimes
                               referred to as the name or title, of the
                               event.
          :description       - A String to use as the description, sometimes
                               referred to as the notes or body, of the
                               event.
          :url               - The URL associated with the event.
          :location          - A Hash describing the location of the event
                               with symbolized keys (optional):
                               :description - A String describing the
                                              location.
                               :lat - A String of the location's latitude.
                               :long - A String of the location's longitude.
          :reminders         - An Array of Hashes describing the desired
                               reminders for the event. Reminders should be
                               specified in priority order as, for example,
                               when the underlying provider only supports a
                               single reminder then the first reminder will
                               be used.
                               :minutes - An Integer specifying the number
                                          of minutes before the start of the
                                          event that the reminder should
                                          occur.
          :transparency      - The transparency state for the event (optional).
                               Accepted values are "transparent" and "opaque".
          :attendees         - A Hash of :invite and :reject, each of which is
                               an array of invitees to invite to or reject from
                               the event. Invitees are represented by a hash of
                               :email and :display_name (optional).
:query_periods - A hash stating the query periods for the event

target_calendars - An array of hashes stating into which calendars to insert the created

event

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::NotFoundError if the calendar does not exist. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1281
def real_time_sequencing(args)
  body = args.merge(client_id: @client_id, client_secret: @client_secret)

  if availability = args[:availability]
    availability[:sequence] = map_availability_sequence(availability[:sequence])
    periods = availability[:query_periods] || availability[:available_periods]
    translate_available_periods(periods) if periods
  end

  body[:availability] = availability

  response = raw_post("/v1/real_time_sequencing", body)
  parse_json(AddToCalendarResponse, nil , response)
end
refresh_access_token() click to toggle source

Public: Refreshes the credentials for the account’s access token.

Usually called in response to a Cronofy::AuthenticationFailureError as these usually occur when the access token has expired and needs refreshing.

See docs.cronofy.com/developers/api/authorization/refresh-token/ for reference.

Returns a set of Cronofy::Credentials for the account.

Raises Cronofy::BadRequestError if refresh token code is unknown or has been revoked. Raises Cronofy::AuthenticationFailureError if the client ID and secret are not valid. Raises Cronofy::CredentialsMissingError if no credentials available.

# File lib/cronofy/client.rb, line 732
def refresh_access_token
  @auth.refresh!
end
remove_recipient_smart_invite(body={}) click to toggle source

Public: Removes an individual recipient from a multiple recipient smart invite

smart_invite_id - A String uniquely identifying the event for your

application (note: this is NOT an ID generated
by Cronofy).

recipient - A Hash containing the recipient to be removed

:email      - A String for the email address of
              the recipient to remove.

See docs.cronofy.com/developers/api-alpha/smart-invites/multiple-recipients/#remove-invite-recipient for reference.

Returns a SmartInviteResponse

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1455
def remove_recipient_smart_invite(body={})
  body[:method] = 'remove'
  response = wrapped_request { api_key!.post("/v1/smart_invites", json_request_args(body)) }
  parse_json(SmartInviteResponse, nil, response)
end
resources() click to toggle source

Public: Lists all the resources for the service account.

Returns an Array of Resources.

Raises Cronofy::CredentialsMissingError if no credentials available or if non-service account credentials are provided. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 822
def resources
  response = get("/v1/resources")
  parse_collection(Resource, "resources", response)
end
revoke_authorization() click to toggle source

Public: Revokes the account’s refresh token and access token.

After making this call the Client will become unusable. You should also delete the stored credentials used to create this instance.

See docs.cronofy.com/developers/api/authorization/revoke/ for reference.

Returns nothing.

Raises Cronofy::AuthenticationFailureError if the client ID and secret are not valid. Raises Cronofy::CredentialsMissingError if no credentials available.

# File lib/cronofy/client.rb, line 764
def revoke_authorization
  @auth.revoke!
end
revoke_by_sub(sub) click to toggle source
# File lib/cronofy/client.rb, line 768
def revoke_by_sub(sub)
  @auth.revoke_by_sub(sub)
end
revoke_by_token(token) click to toggle source
# File lib/cronofy/client.rb, line 772
def revoke_by_token(token)
  @auth.revoke_by_token(token)
end
revoke_profile_authorization(profile_id) click to toggle source

Public: Revokes the authorization to the given profile.

See docs.cronofy.com/developers/api/authorization/revoke-profile/ for reference.

Returns nothing.

Raises Cronofy::CredentialsMissingError if no credentials available.

# File lib/cronofy/client.rb, line 1321
def revoke_profile_authorization(profile_id)
  post("/v1/profiles/#{profile_id}/revoke", nil)
  nil
end
select_scheduling_conversation_participant_slots(url, args) click to toggle source

Public: Choose one or more slots for a scheduling conversation

pre release end-point documentation to follow

# File lib/cronofy/client.rb, line 1722
def select_scheduling_conversation_participant_slots(url, args)
  response = wrapped_request { post(url, args)}
  parse_json(SchedulingConversation, 'scheduling_conversation', response)
end
sequenced_availability(options = {}) click to toggle source

Public: Performs an sequenced availability query.

options - The Hash options used to refine the selection (default: {}):

:sequence          - An Array of sequence defintions containing
                   a Hash of:
:sequence_id       - A String to uniquely identify this part
                   of the proposed sequence.
:ordinal           - An integer to define the ordering of the
                   proposed sequence. (Optional)
:participants      - An Array of participant groups or a Hash
                   for a single participant group.
:required_duration - An Integer representing the minimum
                   number of minutes of availability required.
:start_interval    - An Integer representing the start interval
                   of minutes for the availability query.
:buffer            - An Hash containing the buffer to apply to
                   the availability query.
:query_periods     - An Array of available time periods Hashes,
                   each must specify a start and end Time.

Returns an Array of Sequences.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 914
def sequenced_availability(options = {})
  options[:sequence] = map_availability_sequence(options[:sequence])

  translate_available_periods(options[:query_periods] || options[:available_periods])

  response = availability_post("/v1/sequenced_availability", options)
  parse_collection(Sequence, "sequences", response)
end
upsert_availability_rule(body) click to toggle source

Public: Creates or updates an AvailabilityRule.

availability_rule_id - A String uniquely identifying the availability rule

for the authenticated user in your application
(note: this is NOT an ID generated by Cronofy).

tzid - The time zone identifier for the rule. calendar_ids - An optional array of calendar_ids that should impact the

user's availability.

weekly_periods - An array of objects describing a weekly recurring available period

:day        - A String for the week day
:start_time - A String for 24hr time that period starts eg: 09:30
:end_time   - A String for 24hr time that period ends eg: 17:30

Examples

client.upsert_availability_rule(
  availability_rule_id: "qTtZdczOccgaPncGJaCiLg",
  tzid: "America/Chicago",
  calendar_ids: [
    "cal_n23kjnwrw2_jsdfjksn234"
  ],
  weekly_periods: [
    {
      day: "monday",
      start_time: "09:30",
      end_time: "12:30",
    },
    {
      day: "tuesday",
      start_time: "09:30",
      end_time: "12:30",
    }
  ]
)

See docs.cronofy.com/developers/api/scheduling/availability-rules/ for reference.

Returns an AvailabilityRuleResponse.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1551
def upsert_availability_rule(body)
  response = wrapped_request { post("/v1/availability_rules", body) }
  parse_json(AvailabilityRule, 'availability_rule', response)
end
upsert_available_period(available_period_id, body) click to toggle source

Public: Creates or updates an AvailablePeriod.

available_period_id - A String uniquely identifying the available period

for the authenticated user in your application
(note: this is NOT an ID generated by Cronofy).

body - A Hash describing the available period with

symbolized keys:
:start - A String (ISO-8601 date/time)
:end   - A String (ISO-8601 date/time)

See docs.cronofy.com/developers/api/scheduling/available-periods/upsert/ for reference.

Returns nothing.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1624
def upsert_available_period(available_period_id, body)
  payload = body.merge(available_period_id: available_period_id)
  wrapped_request { post("/v1/available_periods", payload) }
  nil
end
upsert_event(calendar_id, event) click to toggle source

Public: Creates or updates an event for the event_id in the calendar relating to the given calendar_id.

calendar_id - The String Cronofy ID for the calendar to upsert the event

to.

event - A Hash describing the event with symbolized keys:

:event_id     - A String uniquely identifying the event for
                your application (note: this is NOT an ID
                generated by Cronofy).
:summary      - A String to use as the summary, sometimes
                referred to as the name or title, of the
                event.
:description  - A String to use as the description, sometimes
                referred to as the notes or body, of the
                event.
:start        - The Time or Date the event starts.
:end          - The Time or Date the event ends.
:url          - The URL associated with the event.
:location     - A Hash describing the location of the event
                with symbolized keys (optional):
                :description - A String describing the
                               location.
                :lat - A String of the location's latitude.
                :long - A String of the location's longitude.
:reminders    - An Array of Hashes describing the desired
                reminders for the event. Reminders should be
                specified in priority order as, for example,
                when the underlying provider only supports a
                single reminder then the first reminder will
                be used.
                :minutes - An Integer specifying the number
                           of minutes before the start of the
                           event that the reminder should
                           occur.
:transparency - The transparency state for the event (optional).
                Accepted values are "transparent" and "opaque".
:color        - The color of the event (optional).
:attendees    - A Hash of :invite and :reject, each of which is
                an array of invitees to invite to or reject from
                the event. Invitees are represented by a hash of
                :email and :display_name (optional).

Examples

client.upsert_event(
  "cal_n23kjnwrw2_jsdfjksn234",
  event_id: "qTtZdczOccgaPncGJaCiLg",
  summary: "Board meeting",
  description: "Discuss plans for the next quarter.",
  start: Time.utc(2014, 8, 5, 15, 30),
  end:   Time.utc(2014, 8, 5, 17, 30),
  location: {
    description: "Board room",
    lat: "1.2345",
    long: "0.1234"
  })

See docs.cronofy.com/developers/api/events/upsert-event/ for reference.

Returns nothing.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::NotFoundError if the calendar does not exist. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 165
def upsert_event(calendar_id, event)
  body = event.dup

  body[:start] = encode_event_time(body[:start])
  body[:end] = encode_event_time(body[:end])

  post("/v1/calendars/#{calendar_id}/events", body)
  nil
end
Also aliased as: create_or_update_event
upsert_smart_invite(body={}) click to toggle source

Public: Creates or updates smart invite.

smart_invite_id - A String uniquely identifying the event for your

application (note: this is NOT an ID generated
by Cronofy).

callback_url - The URL within your application you want Cronofy to

send notifications to about user interactions with
the Smart Invite.

recipient - A Hash containing the intended recipient of the invite

:email      - A String for the email address you are
              going to send the Smart Invite to.

event - A Hash describing the event with symbolized keys:

:summary      - A String to use as the summary, sometimes
                referred to as the name or title, of the
                event.
:description  - A String to use as the description, sometimes
                referred to as the notes or body, of the
                event.
:start        - The Time or Date the event starts.
:end          - The Time or Date the event ends.
:url          - The URL associated with the event.
:location     - A Hash describing the location of the event
                with symbolized keys (optional):
                :description - A String describing the
                               location.
                :lat - A String of the location's latitude.
                :long - A String of the location's longitude.
:reminders    - An Array of Hashes describing the desired
                reminders for the event. Reminders should be
                specified in priority order as, for example,
                when the underlying provider only supports a
                single reminder then the first reminder will
                be used.
                :minutes - An Integer specifying the number
                           of minutes before the start of the
                           event that the reminder should
                           occur.
:transparency - The transparency state for the event (optional).
                Accepted values are "transparent" and "opaque".
:color        - The color of the event (optional).

organizer - A Hash containing the details of the organizer.

:name - A String value for the display name of the
        event organizer

Examples

client.upsert_smart_invite(
  smart_invite_id: "qTtZdczOccgaPncGJaCiLg",
  callback_url: "http://www.example.com",
  recipient: {
    email: "example@example.com"
  },
  event: {
    summary: "Board meeting",
    description: "Discuss plans for the next quarter.",
    start: Time.utc(2014, 8, 5, 15, 30),
    end:   Time.utc(2014, 8, 5, 17, 30),
    location: {
      description: "Board room",
      lat: "1.2345",
      long: "0.1234"
  },
  organizer: {
    name: "Smart invite application"
  }
)

See docs.cronofy.com/developers/api/smart-invites/create-smart-invite/ for reference.

Returns a SmartInviteResponse.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::InvalidRequestError if the request contains invalid parameters. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 1402
def upsert_smart_invite(body={})
  body[:event][:start] = encode_event_time(body[:event][:start])
  body[:event][:end] = encode_event_time(body[:event][:end])

  response = wrapped_request { api_key!.post("/v1/smart_invites", json_request_args(body)) }
  parse_json(SmartInviteResponse, nil, response)
end
userinfo() click to toggle source

Public: Retrieves the userinfo for the account

See docs.cronofy.com/developers/api/identity/userinfo/ for reference.

Returns an UserInfo.

Raises Cronofy::CredentialsMissingError if no credentials available. Raises Cronofy::AuthenticationFailureError if the access token is no longer valid. Raises Cronofy::AuthorizationFailureError if the access token does not include the required scope. Raises Cronofy::TooManyRequestsError if the request exceeds the rate limits for the application.

# File lib/cronofy/client.rb, line 608
def userinfo
  response = get("/v1/userinfo")
  parse_json(UserInfo, nil, response)
end

Private Instance Methods

access_token!() click to toggle source
# File lib/cronofy/client.rb, line 1892
def access_token!
  raise CredentialsMissingError.new unless @auth.access_token
  @auth.access_token
end
api_key!() click to toggle source
# File lib/cronofy/client.rb, line 1897
def api_key!
  raise CredentialsMissingError.new unless @auth.api_key
  @auth.api_key
end
api_url() click to toggle source
# File lib/cronofy/client.rb, line 2015
def api_url
  ::Cronofy.api_url(@data_center)
end
availability_post(url, body) click to toggle source

Availability Query could originally be authenticated via an access_token Whilst it should be authed via an API key now, we try access_token first for backward compatibility

# File lib/cronofy/client.rb, line 1921
def availability_post(url, body)
  if @auth.access_token
    post(url, body)
  else
    wrapped_request { api_key!.post(url, json_request_args(body)) }
  end
end
delete(url, body = nil) click to toggle source
# File lib/cronofy/client.rb, line 1910
def delete(url, body = nil)
  wrapped_request { access_token!.delete(url, json_request_args(body)) }
end
get(url, opts = {}) click to toggle source
# File lib/cronofy/client.rb, line 1902
def get(url, opts = {})
  wrapped_request { access_token!.get(url, opts) }
end
json_request_args(body_hash) click to toggle source
# File lib/cronofy/client.rb, line 1947
def json_request_args(body_hash)
  if body_hash
    {
      body: JSON.generate(body_hash),
      headers: { "Content-Type" => "application/json; charset=utf-8" },
    }
  else
    {}
  end
end
map_availability_buffer(buffer) click to toggle source
# File lib/cronofy/client.rb, line 1803
def map_availability_buffer(buffer)
  result = {}

  unless buffer.is_a?(Hash)
    return result
  end

  if before_buffer = buffer[:before]
    result[:before] = map_buffer_details(before_buffer)
  end

  if after_buffer = buffer[:after]
    result[:after] = map_buffer_details(after_buffer)
  end

  result
end
map_availability_member(member) click to toggle source
# File lib/cronofy/client.rb, line 1780
def map_availability_member(member)
  case member
  when String
    { sub: member }
  when Hash
    if member[:available_periods]
      translate_available_periods(member[:available_periods])
    end
    member
  else
    member
  end
end
map_availability_participants(participants) click to toggle source
# File lib/cronofy/client.rb, line 1745
def map_availability_participants(participants)
  case participants
  when Hash
    # Allow one group to be specified without being nested
    [map_availability_participants_group(participants)]
  when Enumerable
    participants.map do |group|
      map_availability_participants_group(group)
    end
  else
    participants
  end
end
map_availability_participants_group(participants) click to toggle source
# File lib/cronofy/client.rb, line 1759
def map_availability_participants_group(participants)
  case participants
  when Hash
    participants[:members].map! do |member|
      map_availability_member(member)
    end

    unless participants.key?(:required)
      participants[:required] = :all
    end

    participants
  when Array
    participants.map do |group|
      map_availability_participants(group)
    end
  else
    participants
  end
end
map_availability_required_duration(required_duration) click to toggle source
# File lib/cronofy/client.rb, line 1794
def map_availability_required_duration(required_duration)
  case required_duration
  when Integer
    { minutes: required_duration }
  else
    required_duration
  end
end
map_availability_sequence(sequence) click to toggle source
# File lib/cronofy/client.rb, line 1835
def map_availability_sequence(sequence)
  case sequence
  when Enumerable
    sequence.map do |sequence_item|
      hash = {}

      if value = sequence_item[:participants]
        hash[:participants] = map_availability_participants(value)
      end

      if value = sequence_item[:required_duration]
        hash[:required_duration] = map_availability_required_duration(value)
      end

      periods = sequence_item[:query_periods] || sequence_item[:available_periods]

      if periods
        translate_available_periods(periods)
      end

      if value = sequence_item[:start_interval]
        hash[:start_interval] = map_availability_required_duration(value)
      end

      if buffer = sequence_item[:buffer]
        hash[:buffer] = map_availability_buffer(buffer)
      end

      sequence_item.merge(hash)
    end
  else
    sequence
  end
end
map_buffer_details(buffer) click to toggle source
# File lib/cronofy/client.rb, line 1821
def map_buffer_details(buffer)
  result = map_availability_required_duration(buffer)

  if minimum_buffer = buffer[:minimum]
    result[:minimum] = map_availability_required_duration(minimum_buffer)
  end

  if maximum_buffer = buffer[:maximum]
    result[:maximum] = map_availability_required_duration(maximum_buffer)
  end

  result
end
parse_collection(type, attr, response) click to toggle source
# File lib/cronofy/client.rb, line 1935
def parse_collection(type, attr, response)
  ResponseParser.new(response).parse_collection(type, attr)
end
parse_collections(response, mappings) click to toggle source
# File lib/cronofy/client.rb, line 1939
def parse_collections(response, mappings)
  ResponseParser.new(response).parse_collections(mappings)
end
parse_json(type, attr = nil, response) click to toggle source
# File lib/cronofy/client.rb, line 1943
def parse_json(type, attr = nil, response)
  ResponseParser.new(response).parse_json(type, attr)
end
post(url, body) click to toggle source
# File lib/cronofy/client.rb, line 1906
def post(url, body)
  wrapped_request { access_token!.post(url, json_request_args(body)) }
end
raw_post(url, body) click to toggle source
# File lib/cronofy/client.rb, line 1914
def raw_post(url, body)
  wrapped_request { @auth.api_client.request(:post, url, json_request_args(body)) }
end
translate_available_periods(periods) click to toggle source
# File lib/cronofy/client.rb, line 1729
def translate_available_periods(periods)
  periods.each do |params|
    AVAILABLE_PERIODS_TIME_PARAMS.select { |tp| params.key?(tp) }.each do |tp|
      params[tp] = to_iso8601(params[tp])
    end
  end
end
translate_query_slots(query_slots) click to toggle source
# File lib/cronofy/client.rb, line 1737
def translate_query_slots(query_slots)
  query_slots.each do |params|
    QUERY_SLOTS_TIME_PARAMS.select { |tp| params.key?(tp) }.each do |tp|
      params[tp] = to_iso8601(params[tp])
    end
  end
end
wrapped_request() { || ... } click to toggle source
# File lib/cronofy/client.rb, line 1929
def wrapped_request
  yield
rescue OAuth2::Error => e
  raise Errors.map_error(e)
end