Class: Appwrite::Client

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

Instance Method Summary collapse

Constructor Details

#initialize ⇒ Client

Returns a new instance of Client.



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/appwrite/client.rb', line 10

def initialize
    @chunk_size = 5 * 1024 * 1024
    @headers = {
        'user-agent' => RUBY_PLATFORM + ':ruby-' + RUBY_VERSION,
        'x-sdk-name' => 'Ruby',
        'x-sdk-platform' => 'server',
        'x-sdk-language' => 'ruby',
        'x-sdk-version' => '30.7.0',
        'X-Appwrite-Response-Format' => '2.7.2'
    }
    @endpoint = 'https://cloud.appwrite.io/v1'
    @config = {}
end

Instance Method Details

#add_header(key, value) ⇒ self

Add Header

Parameters:

  • key (String) —

    The key for the header to add

  • value (String) —

    The value for the header to add

Returns:

  • (self)


239
240
241
242
243
# File 'lib/appwrite/client.rb', line 239

def add_header(key, value)
    @headers[key.downcase] = value

    self
end

#call(method:, path: '', headers: {}, params: {}, response_type: nil) ⇒ self

Send the HTTP request.

Parameters:

  • method (String) —

    The HTTP method for the request

  • path (String) (defaults to: '') —

    The path for the request

  • headers (Hash) (defaults to: {}) —

    The headers to send with the request

  • params (Hash) (defaults to: {}) —

    The parameters to send with the request

  • response_type (Class) (defaults to: nil) —

    The type of response to return

Returns:

  • (self)


276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/appwrite/client.rb', line 276

def call(
    method:,
    path: '',
    headers: {},
    params: {},
    response_type: nil
)
    params = params.transform_values { |value| Query._flatten(value) }

    separator = path.include?('?') ? '&' : '?'
    uri = URI.parse(@endpoint + path + ((method == "GET" && params.length) ? separator + encode(params) : ''))

    fetch(method, uri, headers, params, response_type)
end

#chunked_upload(path:, headers:, params:, param_name: '', id_param_name: nil, on_progress: nil, response_type: nil, method: 'POST') ⇒ Object



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/appwrite/client.rb', line 291

def chunked_upload(
    path:,
    headers:,
    params:,
    param_name: '',
    id_param_name: nil,
    on_progress: nil,
    response_type: nil,
    method: 'POST'
)
    input_file = params[param_name.to_sym]

    if input_file.nil?
        return call(
            method: method,
            path: path,
            headers: headers,
            params: params,
            response_type: response_type,
        )
    end

    case input_file.source_type
    when 'path'
        size = ::File.size(input_file.path)
    when 'string'
        size = input_file.data.bytesize
    end

    if size <= @chunk_size || response_type == "text"
        if input_file.source_type == 'path'
            input_file.data = IO.read(input_file.path)
        end
        params[param_name.to_sym] = input_file
        return call(
            method: method,
            path: path,
            headers: headers,
            params: params,
            response_type: response_type,
        )
    end

    offset = 0
    id_param_name = id_param_name.to_sym if id_param_name
    upload_id = nil
    chunks_uploaded = 0
    if id_param_name&.empty? == false
        upload_id = params[id_param_name]
    end
    if upload_id && !upload_id.empty?
        # Make a request to check if a file already exists
        begin
            current = call(
                method: "GET",
                path: "#{path}/#{encode_path(upload_id)}",
                headers: headers,
                params: {}
            )
            chunks_uploaded = current['chunksUploaded'].to_i
            offset = chunks_uploaded * @chunk_size
        rescue Appwrite::Exception => error
            raise error unless error.code.to_i == 404
        end
    end

    total_chunks = (size.to_f / @chunk_size).ceil
    chunks = []
    while offset < size
        chunks << {
            index: chunks_uploaded.to_i,
            start: offset,
            ending: [offset + @chunk_size, size].min
        }
        offset += @chunk_size
        chunks_uploaded = chunks_uploaded.to_i + 1
    end

    result = current if defined?(current)
    return result unless chunks.any?

    upload_chunk = lambda do |chunk, current_upload_id|
        case input_file.source_type
        when 'path'
            string = IO.read(input_file.path, chunk[:ending] - chunk[:start], chunk[:start])
        when 'string'
            string = input_file.data.byteslice(chunk[:start], chunk[:ending] - chunk[:start])
        end

        chunk_params = params.merge(param_name.to_sym => InputFile::from_string(
            string,
            filename: input_file.filename,
            mime_type: input_file.mime_type
        ))

        chunk_headers = headers.merge('content-range' => "bytes #{chunk[:start]}-#{chunk[:ending] - 1}/#{size}")
        chunk_headers['x-appwrite-id'] = current_upload_id if current_upload_id

        call(
            method: method,
            path: path,
            headers: chunk_headers,
            params: chunk_params,
        )
    end

    result = upload_chunk.call(chunks.first, upload_id)
    upload_id = result['$id'] if result['$id']
    completed_count = chunks.first[:index] + 1
    uploaded_size = chunks.first[:ending]

    upload_complete = lambda do |chunk_result|
        chunks_uploaded = chunk_result['chunksUploaded']
        return false if chunks_uploaded.nil?

        chunks_total = chunk_result['chunksTotal'] || total_chunks
        chunks_uploaded.to_i >= chunks_total.to_i
    end

    progress = {
        id: result['$id'],
        progress: uploaded_size.to_f / size.to_f * 100.0,
        size_uploaded: uploaded_size,
        chunks_total: result['chunksTotal'] || total_chunks,
        chunks_uploaded: result['chunksUploaded'] || completed_count
    }
    on_progress.call(progress) unless on_progress.nil?

    mutex = Mutex.new
    queue = Queue.new
    chunks.drop(1).each { |chunk| queue << chunk }
    first_error = nil
    last_result = result
    completed_result = nil

    workers = [8, queue.size].min.times.map do
        Thread.new do
            loop do
                break if mutex.synchronize { !first_error.nil? }

                chunk = begin
                    queue.pop(true)
                rescue ThreadError
                    nil
                end
                break unless chunk

                begin
                    chunk_result = upload_chunk.call(chunk, upload_id)
                rescue => error
                    mutex.synchronize { first_error ||= error }
                    break
                end
                mutex.synchronize do
                    completed_count += 1
                    uploaded_size += chunk[:ending] - chunk[:start]
                    last_result = chunk_result
                    completed_result = chunk_result if upload_complete.call(chunk_result)
                    progress = {
                        id: upload_id,
                        progress: uploaded_size.to_f / size.to_f * 100.0,
                        size_uploaded: uploaded_size,
                        chunks_total: chunk_result['chunksTotal'] || total_chunks,
                        chunks_uploaded: chunk_result['chunksUploaded'] || completed_count
                    }
                    on_progress.call(progress) unless on_progress.nil?
                end
            end
        end
    end

    workers.each(&:join)
    raise first_error if first_error

    result = completed_result || last_result

    return result unless response_type.respond_to?("from")

    response_type.from(map: result)
end

#encode_path(value) ⇒ String

Encode a value as one path segment.

Every byte but letters, digits and -_.!~*'() is escaped, as encodeURIComponent does, so a value fills exactly the segment it replaces.

Parameters:

  • value (String) —

    The path parameter value

Returns:

  • (String)

Raises:



260
261
262
263
264
265
# File 'lib/appwrite/client.rb', line 260

def encode_path(value)
    segment = value.to_s
    raise Appwrite::Exception.new('Path parameter cannot be "." or ".."') if ['.', '..'].include?(segment)

    segment.b.gsub(/[^A-Za-z0-9\-_.!~*'()]/n) { |byte| format('%%%02X', byte.ord) }
end

#get_config(key) ⇒ Object



203
204
205
# File 'lib/appwrite/client.rb', line 203

def get_config(key)
    @config[key] || ''
end

#get_headers ⇒ Hash

Get request headers

Returns:

  • (Hash)


248
249
250
# File 'lib/appwrite/client.rb', line 248

def get_headers
    @headers.dup
end

#set_bearer(value) ⇒ self

Set Bearer

The OAuth access token to authenticate with

Parameters:

  • value (String) —

    The value to set for the Bearer header

Returns:

  • (self)


86
87
88
89
90
91
# File 'lib/appwrite/client.rb', line 86

def set_bearer(value)
    add_header('authorization', "Bearer #{value}")
    @config['bearer'] = value

    self
end

Set Cookie

The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes.

Parameters:

  • value (String) —

    The value to set for the Cookie header

Returns:

  • (self)


154
155
156
157
158
159
# File 'lib/appwrite/client.rb', line 154

def set_cookie(value)
    add_header('cookie', value)
    @config['cookie'] = value

    self
end

#set_endpoint(endpoint) ⇒ self

Set endpoint.

Parameters:

  • endpoint (String) —

    The endpoint to set

Returns:

  • (self)


212
213
214
215
216
217
218
219
220
# File 'lib/appwrite/client.rb', line 212

def set_endpoint(endpoint)
    if not endpoint.start_with?('http://') and not endpoint.start_with?('https://')
        raise Appwrite::Exception.new('Invalid endpoint URL: ' + endpoint)
    end

    @endpoint = endpoint

    self
end

#set_environment(value) ⇒ self

Set Environment

The ID of the project environment to act in, alongside the project ID. Used with Appwrite Cloud projects that have environments.

Parameters:

  • value (String) —

    The value to set for the Environment header

Returns:

  • (self)


112
113
114
115
116
117
# File 'lib/appwrite/client.rb', line 112

def set_environment(value)
    add_header('x-appwrite-environment', value)
    @config['environment'] = value

    self
end

#set_forwarded_user_agent(value) ⇒ self

Set ForwardedUserAgent

The user agent string of the client that made the request

Parameters:

  • value (String) —

    The value to set for the ForwardedUserAgent header

Returns:

  • (self)


140
141
142
143
144
145
# File 'lib/appwrite/client.rb', line 140

def set_forwarded_user_agent(value)
    add_header('x-forwarded-user-agent', value)
    @config['forwardeduseragent'] = value

    self
end

#set_impersonate_user_email(value) ⇒ self

Set ImpersonateUserEmail

Impersonate a user by email

Parameters:

  • value (String) —

    The value to set for the ImpersonateUserEmail header

Returns:

  • (self)


182
183
184
185
186
187
# File 'lib/appwrite/client.rb', line 182

def set_impersonate_user_email(value)
    add_header('x-appwrite-impersonate-user-email', value)
    @config['impersonateuseremail'] = value

    self
end

#set_impersonate_user_id(value) ⇒ self

Set ImpersonateUserId

Impersonate a user by ID

Parameters:

  • value (String) —

    The value to set for the ImpersonateUserId header

Returns:

  • (self)


168
169
170
171
172
173
# File 'lib/appwrite/client.rb', line 168

def set_impersonate_user_id(value)
    add_header('x-appwrite-impersonate-user-id', value)
    @config['impersonateuserid'] = value

    self
end

#set_impersonate_user_phone(value) ⇒ self

Set ImpersonateUserPhone

Impersonate a user by phone

Parameters:

  • value (String) —

    The value to set for the ImpersonateUserPhone header

Returns:

  • (self)


196
197
198
199
200
201
# File 'lib/appwrite/client.rb', line 196

def set_impersonate_user_phone(value)
    add_header('x-appwrite-impersonate-user-phone', value)
    @config['impersonateuserphone'] = value

    self
end

#set_jwt(value) ⇒ self

Set JWT

Your secret JSON Web Token

Parameters:

  • value (String) —

    The value to set for the JWT header

Returns:

  • (self)


72
73
74
75
76
77
# File 'lib/appwrite/client.rb', line 72

def set_jwt(value)
    add_header('x-appwrite-jwt', value)
    @config['jwt'] = value

    self
end

#set_key(value) ⇒ self

Set Key

Your secret API key

Parameters:

  • value (String) —

    The value to set for the Key header

Returns:

  • (self)


44
45
46
47
48
49
# File 'lib/appwrite/client.rb', line 44

def set_key(value)
    add_header('x-appwrite-key', value)
    @config['key'] = value

    self
end

#set_locale(value) ⇒ self

Set Locale

Parameters:

  • value (String) —

    The value to set for the Locale header

Returns:

  • (self)


98
99
100
101
102
103
# File 'lib/appwrite/client.rb', line 98

def set_locale(value)
    add_header('x-appwrite-locale', value)
    @config['locale'] = value

    self
end

#set_organization(value) ⇒ self

Set Organization

Your organization ID

Parameters:

  • value (String) —

    The value to set for the Organization header

Returns:

  • (self)


58
59
60
61
62
63
# File 'lib/appwrite/client.rb', line 58

def set_organization(value)
    add_header('x-appwrite-organization', value)
    @config['organization'] = value

    self
end

#set_project(value) ⇒ self

Set Project

Your project ID

Parameters:

  • value (String) —

    The value to set for the Project header

Returns:

  • (self)


31
32
33
34
35
# File 'lib/appwrite/client.rb', line 31

def set_project(value)
    @config['project'] = value

    self
end

#set_self_signed(self_signed = true) ⇒ self

Set self signed.

Parameters:

  • self_signed (String) (defaults to: true) —

    Whether to allow self signed certificates.

Returns:

  • (self)


227
228
229
230
231
# File 'lib/appwrite/client.rb', line 227

def set_self_signed(self_signed = true)
    @self_signed = self_signed

    self
end

#set_session(value) ⇒ self

Set Session

The user session to authenticate with

Parameters:

  • value (String) —

    The value to set for the Session header

Returns:

  • (self)


126
127
128
129
130
131
# File 'lib/appwrite/client.rb', line 126

def set_session(value)
    add_header('x-appwrite-session', value)
    @config['session'] = value

    self
end