Class: Box::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/box/client.rb

Constant Summary collapse

VERSION =
'2.0'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(session) ⇒ Client

Returns a new instance of Client.



9
10
11
# File 'lib/box/client.rb', line 9

def initialize(session)
  @session = session
end

Instance Attribute Details

#sessionObject

Returns the value of attribute session.



7
8
9
# File 'lib/box/client.rb', line 7

def session
  @session
end

Instance Method Details

#connectionObject



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/box/client.rb', line 60

def connection
  conn = Faraday.new(Box::API_URL) do |builder|
    builder.request :json
    builder.request :multipart
    # builder.response :logger
    builder.response :json, :content_type => /\bjson$/
    # What a joke. This must be LAST to avoid encoding errors in JSON request body
    builder.adapter  :net_http
  end

  conn.headers['Authorization'] = "Bearer #{@session.access_token}"
  conn
end

#delete(path, params = {}, retries = 0) ⇒ Object



90
91
92
# File 'lib/box/client.rb', line 90

def delete(path, params = {}, retries = 0)
  request('DELETE', path, params)
end

#folder(path) ⇒ Object

Starting at the “root” of Box which is always “All Files”, make successive requests untl you have reached the final path in the input



31
32
33
34
35
36
37
38
39
# File 'lib/box/client.rb', line 31

def folder(path) # /path/to/folder
  path = Pathname(path).each_filename.to_a
  folder = root
  path.each do |name|
    folder = folder.folders.select {|folder| folder.name == name}.first
    return nil unless folder
  end
  folder
end

#get(path, params = {}, retries = 0) ⇒ Object



78
79
80
# File 'lib/box/client.rb', line 78

def get(path, params = {}, retries = 0)
  request('GET', path, params)
end

#handle_response(response) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/box/client.rb', line 153

def handle_response(response)
  case response.status
    when 400
      raise Box::MalformedAuthHeaders, response.headers
    when 404
      raise Box::ResourceNotFound, JSON.dump(response.body)
    when 409
      raise Box::NameConflict,  JSON.dump(response.body)
    when 500
      ap response.body
  end
  return response
end

#make_uri(path) ⇒ Object



74
75
76
# File 'lib/box/client.rb', line 74

def make_uri(path)

end

#parse_items(results) ⇒ Object

Process the Box “items” returned from a request



49
50
51
52
53
54
55
56
57
58
# File 'lib/box/client.rb', line 49

def parse_items(results)
  return [] if results['entries'].empty?
  results['entries'].reduce([]) do |entries, entry|
    entries << case entry['type']
      when 'file'   then Box::File.new(self, entry)
      when 'folder' then Box::Folder.new(self, entry)
    end
    entries
  end
end

#post(path, params = {}, retries = 0) ⇒ Object



82
83
84
# File 'lib/box/client.rb', line 82

def post(path, params = {}, retries = 0)
  request('POST', path, params)
end

#put(path, params = {}, retries = 0) ⇒ Object



86
87
88
# File 'lib/box/client.rb', line 86

def put(path, params = {}, retries = 0)
  request('PUT', path, params)
end

#request(method, path, params = {}, retries = 0) ⇒ Object

Generic HTTP request method with retries for bad authorization



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/box/client.rb', line 126

def request(method, path, params = {}, retries = 0)
  uri = Addressable::URI.parse(::File.join(VERSION, path))
  if method == 'GET'
    uri.query_values = params.reduce({}){|hash, (k,v)| hash[k] = v.to_s; hash}
    # params = {}
  end

  Box.log "#{method} #{::File.join(Box::API_URL, uri.to_s)}"
  response = connection.send(method.downcase, uri.to_s, params)

  case response.status
    when 401
      try_token_refresh!
      return request(method, path, params, retries + 1) if retries == 0
    else
      return handle_response(response)
  end
# TODO: We need to retry connection failures - or at least catch them
# rescue Faraday::ConnectionFailed => e
end

#rootObject



13
14
15
# File 'lib/box/client.rb', line 13

def root
  Folder.new(self, id: 0)
end

#search(query, options = {}) ⇒ Object



41
42
43
44
45
46
# File 'lib/box/client.rb', line 41

def search(query, options = {})
  params = options.merge({query: query})

  response = get('search', params)
  parse_items(response.body)
end

#try_token_refresh!Object



147
148
149
150
151
# File 'lib/box/client.rb', line 147

def try_token_refresh!
  @session.refresh_token!
rescue OAuth2::Error => e
  raise "Sorry, could not refresh tokens: #{e.message}"
end

#upload(params = {}, retries = 0) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/box/client.rb', line 94

def upload(params = {}, retries = 0)
  # Basic parameters
  local_path, content_type, file_name, parent_id = params[:local_path], params[:content_type], params[:file_name], params[:parent_id]
  # If there is a file_id, it means we want to replace it.
  uri = if params[:box_id]
    "https://upload.box.com/api/2.0/files/#{params[:box_id]}/content"
  else
    'https://upload.box.com/api/2.0/files/content'
  end

  Box.log "POST #{uri}"

  # Construct the payload
  payload = {
    filename:  Faraday::UploadIO.new(local_path, content_type, file_name),
    parent_id: parent_id
  }

  response = connection.post(uri, payload) do |request|
    request.headers['Content-Type'] = 'multipart/form-data'
  end

  case response.status
    when 401
      try_token_refresh!
      return upload(params, retries + 1) if retries == 0
    else
      return handle_response(response)
  end
end

#walk(root, &block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/box/client.rb', line 17

def walk(root, &block)
  root.items.each do |item|
    if item.folder?
      walk(item, &block)
    elsif item.file?
      yield item
    else
      Box.log "Unknown item type #{item.id}:#{item.type}"
    end
  end
end