class Nylas::API

Constants

EXPANDED_OBJECTS_TABLE

It’s possible to ask the API to expand objects. In this case, we do the right thing and return an expanded object.

OBJECTS_TABLE

Attributes

access_token[R]
api_server[RW]
app_id[R]
app_secret[R]

Public Class Methods

new(app_id, app_secret, access_token = nil, api_server = 'https://api.nylas.com', service_domain = 'api.nylas.com') click to toggle source
# File lib/nylas.rb, line 105
def initialize(app_id, app_secret, access_token = nil, api_server = 'https://api.nylas.com',
               service_domain = 'api.nylas.com')
  raise "When overriding the Nylas API server address, you must include https://" unless api_server.include?('://')
  @api_server = api_server
  @access_token = access_token
  @app_secret = app_secret
  @app_id = app_id
  @service_domain = service_domain
  @version = Nylas::VERSION

  if ::RestClient.before_execution_procs.empty?
    ::RestClient.add_before_execution_proc do |req, params|
      req.add_field('X-Inbox-API-Wrapper', 'ruby')
      req['User-Agent'] = "Nylas Ruby SDK #{@version} - #{RUBY_VERSION}"
    end
  end
end

Public Instance Methods

_build_exclude_types(exclude_types) click to toggle source
# File lib/nylas.rb, line 271
def _build_exclude_types(exclude_types)
  exclude_string = "&exclude_types="

  exclude_types.each do |value|
    count = 0
    if OBJECTS_TABLE.has_value?(value)
      param_name = OBJECTS_TABLE.key(value)
      exclude_string += "#{param_name},"
    end
  end

  exclude_string = exclude_string[0..-2]
end
account() click to toggle source
# File lib/nylas.rb, line 214
def account
  path = self.url_for_path("/account")

  RestClient.get(path, {}) do |response,request,result|
    json = Nylas.interpret_response(result, response, {:expected_class => Object})
    model = APIAccount.new(self)
    model.inflate(json)
    model
  end
end
accounts() click to toggle source
# File lib/nylas.rb, line 229
def accounts
      if self.using_hosted_api?
           @accounts ||= ManagementModelCollection.new(Account, self)
      else
           @accounts ||= RestfulModelCollection.new(APIAccount, self)
      end
end
calendars() click to toggle source
# File lib/nylas.rb, line 198
def calendars
  @calendars ||= RestfulModelCollection.new(Calendar, self)
end
contacts() click to toggle source
# File lib/nylas.rb, line 194
def contacts
  @contacts ||= RestfulModelCollection.new(Contact, self)
end
delta_stream(cursor, exclude_types=[], timeout=0, expanded_view=false) { |delta, obj| ... } click to toggle source
# File lib/nylas.rb, line 339
def delta_stream(cursor, exclude_types=[], timeout=0, expanded_view=false)
  raise 'Please provide a block for receiving the delta objects' if !block_given?

  exclude_string = ""

  if exclude_types.any?
    exclude_string = _build_exclude_types(exclude_types)
  end

  # loop and yield deltas indefinitely.
  path = self.url_for_path("/delta/streaming?exclude_folders=false&cursor=#{cursor}#{exclude_string}")
  if expanded_view
    path += '&view=expanded'
  end

  parser = Yajl::Parser.new(:symbolize_keys => false)
  parser.on_parse_complete = proc do |data|
    delta = Nylas.interpret_response(OpenStruct.new(:code => '200'), data, {:expected_class => Object, :result_parsed => true})

    if not OBJECTS_TABLE.has_key?(delta['object'])
      next
    end

    cls = OBJECTS_TABLE[delta['object']]
    if EXPANDED_OBJECTS_TABLE.has_key?(delta['object']) and expanded_view
      cls = EXPANDED_OBJECTS_TABLE[delta['object']]
    end

    obj = cls.new(self)

    case delta["event"]
      when 'create', 'modify'
        obj.inflate(delta['attributes'])
        obj.cursor = delta["cursor"]
        yield delta["event"], obj
      when 'delete'
        obj.id = delta["id"]
        obj.cursor = delta["cursor"]
        yield delta["event"], obj
    end
  end

  http = EventMachine::HttpRequest.new(path, :connect_timeout => 0, :inactivity_timeout => timeout).get(:keepalive => true)

  # set a callback on the HTTP stream that parses incoming chunks as they come in
  http.stream do |chunk|
    parser << chunk
  end

  http.errback do
    raise UnexpectedResponse.new http.error
  end

end
deltas(cursor, exclude_types=[], expanded_view=false) { |delta, obj| ... } click to toggle source
# File lib/nylas.rb, line 285
def deltas(cursor, exclude_types=[], expanded_view=false)
  return enum_for(:deltas, cursor, exclude_types, expanded_view) unless block_given?

  exclude_string = ""

  if exclude_types.any?
    exclude_string = _build_exclude_types(exclude_types)
  end

  # loop and yield deltas until we've come to the end.
  loop do
    path = self.url_for_path("/delta?exclude_folders=false&cursor=#{cursor}#{exclude_string}")
    if expanded_view
      path += '&view=expanded'
    end

    json = nil

    RestClient.get(path) do |response,request,result|
      json = Nylas.interpret_response(result, response, {:expected_class => Object})
    end

    start_cursor = json["cursor_start"]
    end_cursor = json["cursor_end"]

    json["deltas"].each do |delta|
      if not OBJECTS_TABLE.has_key?(delta['object'])
        next
      end

      cls = OBJECTS_TABLE[delta['object']]
      if EXPANDED_OBJECTS_TABLE.has_key?(delta['object']) and expanded_view
        cls = EXPANDED_OBJECTS_TABLE[delta['object']]
      end

      obj = cls.new(self)

      case delta["event"]
      when 'create', 'modify'
          obj.inflate(delta['attributes'])
          obj.cursor = delta["cursor"]
          yield delta["event"], obj
      when 'delete'
          obj.id = delta["id"]
          obj.cursor = delta["cursor"]
          yield delta["event"], obj
      end
    end

    break if start_cursor == end_cursor
    cursor = end_cursor
  end
end
drafts() click to toggle source
# File lib/nylas.rb, line 190
def drafts
  @drafts ||= RestfulModelCollection.new(Draft, self)
end
events() click to toggle source
# File lib/nylas.rb, line 202
def events
  @events ||= RestfulModelCollection.new(Event, self)
end
files() click to toggle source
# File lib/nylas.rb, line 186
def files
  @files ||= RestfulModelCollection.new(File, self)
end
folders() click to toggle source
# File lib/nylas.rb, line 206
def folders
  @folders ||= RestfulModelCollection.new(Folder, self)
end
labels() click to toggle source
# File lib/nylas.rb, line 210
def labels
  @labels ||= RestfulModelCollection.new(Label, self)
end
latest_cursor() click to toggle source
# File lib/nylas.rb, line 237
def latest_cursor
  # Get the cursor corresponding to a specific timestamp.
  path = self.url_for_path("/delta/latest_cursor")

  cursor = nil

  RestClient.post(path, :content_type => :json) do |response,request,result|
    json = Nylas.interpret_response(result, response, {:expected_class => Object})
    cursor = json["cursor"]
  end

  cursor
end
messages(expanded: false) click to toggle source
# File lib/nylas.rb, line 174
def messages(expanded: false)
  @messages ||= Hash.new do |h, is_expanded|
    h[is_expanded] = \
      if is_expanded
        RestfulModelCollection.new(ExpandedMessage, self, view: 'expanded')
      else
        RestfulModelCollection.new(Message, self)
      end
  end
  @messages[expanded]
end
set_access_token(token) click to toggle source
# File lib/nylas.rb, line 151
def set_access_token(token)
  @access_token = token
end
threads() click to toggle source

API Methods

# File lib/nylas.rb, line 170
def threads
  @threads ||= RestfulModelCollection.new(Thread, self)
end
token_for_code(code) click to toggle source
# File lib/nylas.rb, line 155
def token_for_code(code)
  data = {
      'client_id' => app_id,
      'client_secret' => app_secret,
      'grant_type' => 'authorization_code',
      'code' => code
  }

  ::RestClient.post("https://#{@service_domain}/oauth/token", data) do |response, request, result|
    json = Nylas.interpret_response(result, response, :expected_class => Object)
    return json['access_token']
  end
end
url_for_authentication(redirect_uri, login_hint = '', options = {}) click to toggle source
# File lib/nylas.rb, line 129
def url_for_authentication(redirect_uri, login_hint = '', options = {})
  params = {
    :client_id => @app_id,
    :trial => options.fetch(:trial, false),
    :response_type => 'code',
    :scope => 'email',
    :login_hint => login_hint,
    :redirect_uri => redirect_uri,
  }

  if options.has_key?(:state) then
    params[:state] = options[:state]
  end

  "https://#{@service_domain}/oauth/authorize?" + params.to_query
end
url_for_management() click to toggle source
# File lib/nylas.rb, line 146
def url_for_management
  protocol, domain = @api_server.split('//')
  accounts_path = "#{protocol}//#{@app_secret}:@#{domain}/a/#{@app_id}/accounts"
end
url_for_path(path) click to toggle source
# File lib/nylas.rb, line 123
def url_for_path(path)
  raise NoAuthToken.new if @access_token == nil and (@app_secret != nil or @app_id != nil)
  protocol, domain = @api_server.split('//')
  "#{protocol}//#{@access_token}:@#{domain}#{path}"
end
using_hosted_api?() click to toggle source
# File lib/nylas.rb, line 225
def using_hosted_api?
   return !@app_id.nil?
end