Class: Cronofy::Client

Inherits:
Object
  • Object
show all
Includes:
TimeEncoding
Defined in:
lib/cronofy/client.rb

Overview

Public: Primary class for interacting with the Cronofy API.

Direct Known Subclasses

Cronofy

Defined Under Namespace

Classes: BatchBuilder, PagedResultIterator

Constant Summary collapse

DEFAULT_OAUTH_SCOPE =

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

%w{
  read_account
  read_events
  create_event
  delete_event
}.freeze

Instance Method Summary collapse

Methods included from TimeEncoding

#encode_event_time, #to_iso8601

Constructor Details

#initialize(options = {}) ⇒ Client

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_centre   - An identifier to override the default data
                 centre (optional).

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/cronofy/client.rb', line 30

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_centre   = options[:data_centre]

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

Instance Method Details

#accountObject

Public: Retrieves the details of the account.

See www.cronofy.com/developers/api#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.


544
545
546
547
# File 'lib/cronofy/client.rb', line 544

def 
  response = get("/v1/account")
  parse_json(Account, "account", response)
end

#add_to_calendar(args = {}) ⇒ Object

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 www.cronofy.com/developers/api#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.


953
954
955
956
957
958
959
960
961
# File 'lib/cronofy/client.rb', line 953

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) ⇒ Object

Public: Obtains access to an application calendar

See www.cronofy.com/developers/alpha/api#application-calendar 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.


717
718
719
# File 'lib/cronofy/client.rb', line 717

def application_calendar(application_calendar_id)
  @auth.application_calendar(application_calendar_id)
end

#authorize_with_service_account(email, scope, callback_url) ⇒ Object

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.


633
634
635
636
637
638
639
640
641
642
643
644
645
# File 'lib/cronofy/client.rb', line 633

def (email, scope, callback_url)
  if scope.respond_to?(:join)
    scope = scope.join(' ')
  end

  params = {
    email: email,
    scope: scope,
    callback_url: callback_url
  }
  post("/v1/service_account_authorizations", params)
  nil
end

#availability(options = {}) ⇒ Object

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.
:available_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            - An Hash containing the buffer to apply to
                     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.


814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
# File 'lib/cronofy/client.rb', line 814

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

  translate_available_periods(options[:available_periods])

  response = post("/v1/availability", options)
  parse_collection(AvailablePeriod, "available_periods", response)
end

#batch {|builder = BatchBuilder.new| ... } ⇒ Object

Yields:


359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/cronofy/client.rb', line 359

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 = {}) ⇒ Object

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 www.cronofy.com/developers/alpha/api#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.


1315
1316
1317
1318
1319
# File 'lib/cronofy/client.rb', line 1315

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) ⇒ Object

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 www.cronofy.com/developers/api#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.


609
610
611
612
613
614
615
616
# File 'lib/cronofy/client.rb', line 609

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) ⇒ Object

Public: Closes a notification channel.

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

See www.cronofy.com/developers/api#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.


526
527
528
529
# File 'lib/cronofy/client.rb', line 526

def close_channel(channel_id)
  delete("/v1/channels/#{channel_id}")
  nil
end

#create_calendar(profile_id, name, options = {}) ⇒ Object

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 www.cronofy.com/developers/api/#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.


70
71
72
73
74
# File 'lib/cronofy/client.rb', line 70

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 = {}) ⇒ Object

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 www.cronofy.com/developers/api#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.


465
466
467
468
469
470
# File 'lib/cronofy/client.rb', line 465

def create_channel(callback_url, options = {})
  params = options.merge(callback_url: callback_url)

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

#delete_all_events(options = nil) ⇒ Object

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

See www.cronofy.com/developers/api/#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.


430
431
432
433
434
# File 'lib/cronofy/client.rb', line 430

def delete_all_events(options = nil)
  options ||= { delete_all: true }
  delete("/v1/events", options)
  nil
end

#delete_event(calendar_id, event_id) ⇒ Object

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 www.cronofy.com/developers/api#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.


308
309
310
311
# File 'lib/cronofy/client.rb', line 308

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) ⇒ Object

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.


401
402
403
404
# File 'lib/cronofy/client.rb', line 401

def delete_external_event(calendar_id, event_uid)
  delete("/v1/calendars/#{calendar_id}/events", event_uid: event_uid)
  nil
end

#elevated_permissions(args = {}) ⇒ Object

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.


760
761
762
763
764
765
766
767
768
769
770
# File 'lib/cronofy/client.rb', line 760

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 = {}) ⇒ Object

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 www.cronofy.com/developers/api/#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.


276
277
278
279
280
281
282
283
284
285
# File 'lib/cronofy/client.rb', line 276

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_smart_invite(smart_invite_id, recipient_email) ⇒ Object

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 www.cronofy.com/developers/alpha/api#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.


1337
1338
1339
1340
# File 'lib/cronofy/client.rb', line 1337

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) ⇒ Object

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 www.cronofy.com/developers/api#token-issue 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.


683
684
685
# File 'lib/cronofy/client.rb', line 683

def get_token_from_code(code, redirect_url)
  @auth.get_token_from_code(code, redirect_url)
end

#hmac_match?(args) ⇒ Boolean

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 of the HMAC of the notification taken from the
        Cronofy-HMAC-SHA256 header.

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

Returns:

  • (Boolean)

481
482
483
484
485
486
487
488
489
490
# File 'lib/cronofy/client.rb', line 481

def hmac_match?(args)
  body = args[:body]
  hmac = args[:hmac]

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

  calculated == hmac
end

Public: Creates a link_token to allow explicitly linking of an account

See www.cronofy.com/developers/api/alpha/#auth-explicit-linking for reference.

Returns a link 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.


1194
1195
1196
1197
# File 'lib/cronofy/client.rb', line 1194

def link_token
  response = post("/v1/link_tokens", nil)
  parse_json(String, 'link_token', response)
end

#list_calendarsObject

Public: Lists all the calendars for the account.

See www.cronofy.com/developers/api#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.


87
88
89
90
# File 'lib/cronofy/client.rb', line 87

def list_calendars
  response = get("/v1/calendars")
  parse_collection(Calendar, "calendars", response)
end

#list_channelsObject

Public: Lists all the notification channels for the account.

See www.cronofy.com/developers/api#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.


505
506
507
508
# File 'lib/cronofy/client.rb', line 505

def list_channels
  response = get("/v1/channels")
  parse_collection(Channel, "channels", response)
end

#list_profilesObject

Public: Lists all the profiles for the account.

See www.cronofy.com/developers/api/#profiles 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.


560
561
562
563
# File 'lib/cronofy/client.rb', line 560

def list_profiles
  response = get("/v1/profiles")
  parse_collection(Profile, "profiles", response)
end

#read_events(options = {}) ⇒ Object

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 www.cronofy.com/developers/api#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.


228
229
230
231
232
233
234
235
236
237
# File 'lib/cronofy/client.rb', line 228

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 = {}) ⇒ Object

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
:available_periods - A hash stating the available periods for the event
: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 },
     available_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 www.cronofy.com/developers/api#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.


1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
# File 'lib/cronofy/client.rb', line 1073

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

  translate_available_periods(availability[:available_periods])
  body[:availability] = availability

  response = post("/v1/real_time_scheduling", body)
  parse_json(AddToCalendarResponse, nil , response)
end

#real_time_sequencing(args) ⇒ Object

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).
:available_periods - A hash stating the available 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.


1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
# File 'lib/cronofy/client.rb', line 1168

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])
    translate_available_periods(availability[:available_periods]) if availability[:available_periods]
  end

  body[:availability] = availability

  response = post("/v1/real_time_sequencing", body)
  parse_json(AddToCalendarResponse, nil , response)
end

#refresh_access_tokenObject

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 www.cronofy.com/developers/api#token-refresh 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.


702
703
704
# File 'lib/cronofy/client.rb', line 702

def refresh_access_token
  @auth.refresh!
end

#resourcesObject

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.


784
785
786
787
# File 'lib/cronofy/client.rb', line 784

def resources
  response = get("/v1/resources")
  parse_collection(Resource, "resources", response)
end

#revoke_authorizationObject

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 www.cronofy.com/developers/api#revoke-authorization for reference.

Returns nothing.

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


734
735
736
# File 'lib/cronofy/client.rb', line 734

def revoke_authorization
  @auth.revoke!
end

#revoke_profile_authorization(profile_id) ⇒ Object

Public: Revokes the authorization to the given profile.

See www.cronofy.com/developers/api/alpha/#revoke-profile for reference.

Returns nothing.

Raises Cronofy::CredentialsMissingError if no credentials available.


1207
1208
1209
1210
# File 'lib/cronofy/client.rb', line 1207

def revoke_profile_authorization(profile_id)
  post("/v1/profiles/#{profile_id}/revoke", nil)
  nil
end

#sequenced_availability(options = {}) ⇒ Object

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.
:available_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.


863
864
865
866
867
868
869
870
# File 'lib/cronofy/client.rb', line 863

def sequenced_availability(options = {})
  options[:sequence] = map_availability_sequence(options[:sequence])

  translate_available_periods(options[:available_periods])

  response = post("/v1/sequenced_availability", options)
  parse_collection(Sequence, "sequences", response)
end

#upsert_event(calendar_id, event) ⇒ Object Also known as: create_or_update_event

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 www.cronofy.com/developers/api#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.


163
164
165
166
167
168
169
170
171
# File 'lib/cronofy/client.rb', line 163

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

#upsert_smart_invite(body = {}) ⇒ Object

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",
  attendee: {
    email: "[email protected]"
  },
  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 www.cronofy.com/developers/alpha/api#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.


1288
1289
1290
1291
1292
1293
1294
# File 'lib/cronofy/client.rb', line 1288

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

Public: Generates a URL to send the user to in order to perform the OAuth 2.0 authorization process.

redirect_uri - A String specifing the URI to return the user to once they

have completed the authorization steps.

options - The Hash options used to refine the selection

(default: {}):
:scope - Array or String of scopes describing the access to
         request from the user to the users calendars
         (default: DEFAULT_OAUTH_SCOPE).
:state - Array of states to retain during the OAuth
         authorization process (optional).

See www.cronofy.com/developers/api#authorization for reference.

Returns the URL as a String.


663
664
665
666
# File 'lib/cronofy/client.rb', line 663

def user_auth_link(redirect_url, options = {})
  options = { scope: DEFAULT_OAUTH_SCOPE }.merge(options)
  @auth.user_auth_link(redirect_url, options)
end

#userinfoObject

Public: Retrieves the userinfo for the account

See openid.net/specs/openid-connect-core-1_0.html#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.


579
580
581
582
# File 'lib/cronofy/client.rb', line 579

def userinfo
  response = get("/v1/userinfo")
  parse_json(UserInfo, nil, response)
end