Class: Aspera::Api::AoC

Inherits:
Rest
  • Object
show all
Defined in:
lib/aspera/api/aoc.rb

Constant Summary collapse

PRODUCT_NAME =
'Aspera on Cloud'
DEFAULT_WORKSPACE =
''
SAAS_DOMAIN_PROD =

Production domain of AoC

'ibmaspera.com'
SCOPE_FILES_SELF =

various API scopes supported

'self'
SCOPE_FILES_USER =
'user:all'
SCOPE_FILES_ADMIN =
'admin:all'
SCOPE_FILES_ADMIN_USER =
'admin-user:all'
SCOPE_FILES_ADMIN_USER_USER =
"#{SCOPE_FILES_ADMIN_USER}+#{SCOPE_FILES_USER}"
FILES_APP =
'files'
PACKAGES_APP =
'packages'
API_V1 =
'api/v1'
ID_AK_ADMIN =
'ASPERA_ACCESS_KEY_ADMIN'

Constants inherited from Rest

Rest::ENTITY_NOT_FOUND, Rest::JSON_DECODE

Instance Attribute Summary collapse

Attributes inherited from Rest

#auth_params, #base_url

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Rest

array_params, array_params?, basic_token, build_uri, #call, #cancel, #create, decode_query, #delete, io_http_session, #lookup_by_name, #oauth, #params, parse_header, #read, remote_certificate_chain, set_parameters, start_http_session, #update, user_agent

Constructor Details

#initialize(url:, auth:, subpath: API_V1, client_id: nil, client_secret: nil, scope: nil, redirect_uri: nil, private_key: nil, passphrase: nil, username: nil, password: nil, workspace: nil, secret_finder: nil) ⇒ AoC

Returns a new instance of AoC.

Raises:

  • (ArgumentError)


138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/aspera/api/aoc.rb', line 138

def initialize(url:, auth:, subpath: API_V1, client_id: nil, client_secret: nil, scope: nil, redirect_uri: nil, private_key: nil, passphrase: nil, username: nil,
  password: nil, workspace: nil, secret_finder: nil)
  # test here because link may set url
  raise ArgumentError, 'Missing mandatory option: url' if url.nil?
  raise ArgumentError, 'Missing mandatory option: scope' if scope.nil?
  # default values for client id
  client_id, client_secret = self.class.get_client_info if client_id.nil?
  # access key secrets are provided out of band to get node api access
  # key: access key
  # value: associated secret
  @secret_finder = secret_finder
  @workspace_name = workspace
  @cache_user_info = nil
  @cache_url_token_info = nil
  @context_cache = nil
  auth_params = {
    type:          :oauth2,
    client_id:     client_id,
    client_secret: client_secret,
    scope:         scope
  }
  # analyze type of url
  url_info = AoC.link_info(url)
  Log.log.debug{Log.dump(:url_info, url_info)}
  @private_link = url_info[:private_link]
  auth_params[:grant_method] = if url_info.key?(:token)
    :url_json
  else
    raise ArgumentError, 'Missing mandatory option: auth' if auth.nil?
    auth
  end
  # this is the base API url
  api_url_base = self.class.api_base_url(api_domain: url_info[:instance_domain])
  # auth URL
  auth_params[:base_url] = "#{api_url_base}/#{OAUTH_API_SUBPATH}/#{url_info[:organization]}"

  # fill other auth parameters based on OAuth method
  case auth_params[:grant_method]
  when :web
    raise ArgumentError, 'Missing mandatory option: redirect_uri' if redirect_uri.nil?
    auth_params[:redirect_uri] = redirect_uri
  when :jwt
    raise ArgumentError, 'Missing mandatory option: private_key' if private_key.nil?
    raise ArgumentError, 'Missing mandatory option: username' if username.nil?
    auth_params[:private_key_obj] = OpenSSL::PKey::RSA.new(private_key, passphrase)
    auth_params[:payload] = {
      iss: auth_params[:client_id], # issuer
      sub: username, # subject
      aud: JWT_AUDIENCE
    }
    # add jwt payload for global client id
    auth_params[:payload][:org] = url_info[:organization] if GLOBAL_CLIENT_APPS.include?(auth_params[:client_id])
  when :url_json
    auth_params[:url] = {grant_type: 'url_token'} # URL arguments
    auth_params[:json] = {url_token: url_info[:token]} # JSON body
    # password protection of link
    auth_params[:json][:password] = password unless password.nil?
    # basic auth required for /token
    auth_params[:auth] = {type: :basic, username: auth_params[:client_id], password: auth_params[:client_secret]}
  else Aspera.error_unexpected_value(auth_params[:grant_method])
  end
  super(
    base_url: "#{api_url_base}/#{subpath}",
    auth: auth_params
    )
end

Instance Attribute Details

Returns the value of attribute private_link.



136
137
138
# File 'lib/aspera/api/aoc.rb', line 136

def private_link
  @private_link
end

Class Method Details

.api_base_url(organization: 'api', api_domain: SAAS_DOMAIN_PROD) ⇒ Object

base API url depends on domain, which could be “qa.xxx”



76
77
78
# File 'lib/aspera/api/aoc.rb', line 76

def api_base_url(organization: 'api', api_domain: SAAS_DOMAIN_PROD)
  return "https://#{organization}.#{api_domain}"
end

.get_client_info(client_name = nil) ⇒ Object

strings /Applications/Aspera\ Drive.app/Contents/MacOS/AsperaDrive|grep -E ‘.100==$’|base64 –decode



70
71
72
73
# File 'lib/aspera/api/aoc.rb', line 70

def get_client_info(client_name=nil)
  client_key = client_name.nil? ? GLOBAL_CLIENT_APPS.first : client_name.to_sym
  return client_key, DataRepository.instance.item(client_key)
end

Returns information about public link, or nil if not a public link.

Parameters:

  • url (String)

    URL of AoC public link

Returns:

  • (Hash)

    information about public link, or nil if not a public link



90
91
92
93
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
124
125
126
127
128
129
130
131
132
133
# File 'lib/aspera/api/aoc.rb', line 90

def link_info(url)
  final_uri = Rest.new(base_url: url, redirect_max: MAX_AOC_URL_REDIRECT).read('')[:http].uri
  raise 'AoC shall redirect to login page' if final_uri.query.nil?
  decoded_query = Rest.decode_query(final_uri.query)
  # is that a public link ?
  if decoded_query.key?('token')
    Log.log.warn{"Unknown pub link path: #{final_uri.path}"} unless PUBLIC_LINK_PATHS.include?(final_uri.path)
    # ok we get it !
    return {
      instance_domain: url_parts(final_uri)[1],
      url:             "https://#{final_uri.host}",
      token:           decoded_query['token']
    }
  end
  Log.log.debug{"path=#{final_uri.path} does not end with /login"} unless final_uri.path.end_with?('/login')
  if decoded_query['state']
    # can be a private link
    state_uri = URI.parse(decoded_query['state'])
    if state_uri.query && decoded_query['redirect_uri']
      decoded_state = Rest.decode_query(state_uri.query)
      if decoded_state.key?('short_link_url')
        if (m = state_uri.path.match(%r{/files/workspaces/([0-9]+)/all/([0-9]+):([0-9]+)}))
          redirect_uri = URI.parse(decoded_query['redirect_uri'])
          parts = url_parts(redirect_uri)
          return {
            instance_domain: parts[1],
            organization:    parts[0],
            url:             "https://#{redirect_uri.host}",
            private_link:    {
              workspace_id: m[1],
              node_id:      m[2],
              file_id:      m[3]
            }
          }
        end
      end
    end
  end
  parts = url_parts(URI.parse(url))
  return {
    instance_domain: parts[1],
    organization:    parts[0]
  }
end

.url_parts(uri) ⇒ Object

split host of myorg.asperafiles.com in org and domain



81
82
83
84
85
86
# File 'lib/aspera/api/aoc.rb', line 81

def url_parts(uri)
  raise "No host found in URL.Please check URL format: https://myorg.#{SAAS_DOMAIN_PROD}" if uri.host.nil?
  parts = uri.host.split('.', 2)
  Aspera.assert(parts.length == 2){"expecting a public FQDN for #{PRODUCT_NAME}"}
  return parts
end

Instance Method Details

#add_ts_tags(transfer_spec:, app_info:) ⇒ Object

Add transfer spec callback in Node (transfer_spec_gen4)



477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# File 'lib/aspera/api/aoc.rb', line 477

def add_ts_tags(transfer_spec:, app_info:)
  # translate transfer direction to upload/download
  transfer_type = Transfer::Spec.direction_to_transfer_type(transfer_spec['direction'])
  # Analytics tags
  ################
  transfer_spec.deep_merge!({
    'tags' => {
      Transfer::Spec::TAG_RESERVED => {
        'usage_id' => "aspera.files.workspace.#{app_info[:workspace_id]}", # activity tracking
        'files'    => {
          'files_transfer_action' => "#{transfer_type}_#{app_info[:app].gsub(/s$/, '')}",
          'workspace_name'        => app_info[:workspace_name], # activity tracking
          'workspace_id'          => app_info[:workspace_id]
        }
      }
    }
  })
  # Console cookie
  ################
  # we are sure that fields are not nil
  cookie_elements = [app_info[:app], ['name'] || 'public link', ['email'] || 'none'].map{|e|Base64.strict_encode64(e)}
  cookie_elements.unshift(COOKIE_PREFIX_CONSOLE_AOC)
  transfer_spec['cookie'] = cookie_elements.join(':')
  # Application tags
  ##################
  case app_info[:app]
  when FILES_APP
    file_id = transfer_spec['tags'][Transfer::Spec::TAG_RESERVED]['node']['file_id']
    transfer_spec.deep_merge!({'tags' => {Transfer::Spec::TAG_RESERVED => {'files' => {'parentCwd' => "#{app_info[:node_info]['id']}:#{file_id}"}}}}) \
      unless transfer_spec.key?('remote_access_key')
  when PACKAGES_APP
    transfer_spec.deep_merge!({
      'tags' => {
        Transfer::Spec::TAG_RESERVED => {
          'files' => {
            'package_id'        => app_info[:package_id],
            'package_name'      => app_info[:package_name],
            'package_operation' => transfer_type
          }
        }
      }
    })
  end
  transfer_spec['tags'][Transfer::Spec::TAG_RESERVED]['files']['node_id'] = app_info[:node_info]['id']
  transfer_spec['tags'][Transfer::Spec::TAG_RESERVED]['app'] = app_info[:app]
end

#additional_persistence_idsObject



217
218
219
220
# File 'lib/aspera/api/aoc.rb', line 217

def additional_persistence_ids
  return [['id']] if public_link.nil?
  return [] # TODO : public_link['id'] ?
end


213
214
215
# File 'lib/aspera/api/aoc.rb', line 213

def assert_public_link_types(expected)
  Aspera.assert_values(public_link['purpose'], expected){'public link type'}
end

#context(application = nil) ⇒ Hash

Returns current context information: workspace, and home node/file if app is “Files”.

Parameters:

  • application (Symbol) (defaults to: nil)

    :files or :packages

Returns:

  • (Hash)

    current context information: workspace, and home node/file if app is “Files”



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/aspera/api/aoc.rb', line 240

def context(application = nil)
  return @context_cache unless @context_cache.nil?
  Aspera.assert(!application.nil?){'application must be set once'}
  Aspera.assert_values(application, %i[files packages])
  ws_id =
    if !public_link.nil?
      Log.log.debug('Using workspace of public link')
      public_link['data']['workspace_id']
    elsif !private_link.nil?
      Log.log.debug('Using workspace of private link')
      private_link[:workspace_id]
    elsif @workspace_name.eql?(DEFAULT_WORKSPACE)
      Log.log.debug('Using default workspace'.green)
      raise 'User does not have default workspace, please specify workspace' if ['default_workspace_id'].nil?
      ['default_workspace_id']
    elsif @workspace_name.nil?
      nil
    else
      lookup_by_name('workspaces', @workspace_name)['id']
    end
  ws_info =
    if ws_id.nil?
      nil
    else
      read("workspaces/#{ws_id}")[:data]
    end
  @context_cache = if ws_info.nil?
    {
      workspace_id:   nil,
      workspace_name: 'Shared folders'
    }
  else
    {
      workspace_id:   ws_info['id'],
      workspace_name: ws_info['name']
    }
  end
  return @context_cache unless application.eql?(:files)
  if !public_link.nil?
    assert_public_link_types(['view_shared_file'])
    @context_cache[:home_node_id] = public_link['data']['node_id']
    @context_cache[:home_file_id] = public_link['data']['file_id']
  elsif !private_link.nil?
    @context_cache[:home_node_id] = private_link[:node_id]
    @context_cache[:home_file_id] = private_link[:file_id]
  elsif ws_info
    @context_cache[:home_node_id] = ws_info['home_node_id']
    @context_cache[:home_file_id] = ws_info['home_file_id']
  else
    # not part of any workspace, but has some folder shared
     = (exception: true) rescue {'read_only_home_node_id' => nil, 'read_only_home_file_id' => nil}
    @context_cache[:home_node_id] = ['read_only_home_node_id']
    @context_cache[:home_file_id] = ['read_only_home_file_id']
  end
  raise "Cannot get user's home node id, check your default workspace or specify one" if @context_cache[:home_node_id].to_s.empty?
  Log.log.debug{Log.dump(:context, @context_cache)}
  return @context_cache
end

#create_package_simple(package_data, validate_meta, new_user_option) ⇒ Object

create a package

Parameters:

  • package_data (Hash)

    package creation (with extensions…)

  • validate_meta (TrueClass, FalseClass)

    true to validate parameters locally

  • new_user_option (Hash, NilClass)

    options if an unknown user is specified

Returns:

  • transfer spec, node api and package information



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
471
472
473
# File 'lib/aspera/api/aoc.rb', line 444

def create_package_simple(package_data, validate_meta, new_user_option)
  (package_data)
  # list of files to include in package, optional
  # package_data['file_names']||=[..list of filenames to transfer...]

  # lookup users
  resolve_package_recipients(package_data, package_data['workspace_id'], 'recipients', new_user_option)
  resolve_package_recipients(package_data, package_data['workspace_id'], 'bcc_recipients', new_user_option)

  (package_data) if validate_meta

  #  create a new package container
  created_package = create('packages', package_data)[:data]

  package_node_api = node_api_from(
    node_id: created_package['node_id'],
    workspace_id: created_package['workspace_id'],
    package_info: created_package)

  # tell AoC what to expect in package: 1 transfer (can also be done after transfer)
  # TODO: if multi session was used we should probably tell
  # also, currently no "multi-source" , i.e. only from client-side files, unless "node" agent is used
  update("packages/#{created_package['id']}", {'sent' => true, 'transfers_expected' => 1})[:data]

  return {
    spec: package_node_api.transfer_spec_gen4(created_package['contents_file_id'], Transfer::Spec::DIRECTION_SEND),
    node: package_node_api,
    info: created_package
  }
end

#current_user_info(exception: false) ⇒ Object

cached user information



223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/aspera/api/aoc.rb', line 223

def (exception: false)
  return @cache_user_info unless @cache_user_info.nil?
  # get our user's default information
  @cache_user_info =
    begin
      read('self')[:data]
    rescue StandardError => e
      raise e if exception
      Log.log.debug{"ignoring error: #{e}"}
      {}
    end
  USER_INFO_FIELDS_MIN.each{|f|@cache_user_info[f] = nil if @cache_user_info[f].nil?}
  return @cache_user_info
end

#node_api_from(node_id:, workspace_id: nil, workspace_name: nil, scope: Node::SCOPE_USER, package_info: nil) ⇒ Object

Parameters:

  • node_id (String)

    identifier of node in AoC

  • workspace_id (String) (defaults to: nil)

    workspace identifier

  • workspace_name (String) (defaults to: nil)

    workspace name

  • scope (defaults to: Node::SCOPE_USER)

    e.g. Node::SCOPE_USER, or nil (requires secret)

  • package_info (Hash) (defaults to: nil)

    created package information



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
# File 'lib/aspera/api/aoc.rb', line 305

def node_api_from(node_id:, workspace_id: nil, workspace_name: nil, scope: Node::SCOPE_USER, package_info: nil)
  Aspera.assert_type(node_id, String)
  node_info = read("nodes/#{node_id}")[:data]
  if workspace_name.nil? && !workspace_id.nil?
    workspace_name = read("workspaces/#{workspace_id}")[:data]['name']
  end
  app_info = {
    api:            self, # for callback
    app:            package_info.nil? ? FILES_APP : PACKAGES_APP,
    node_info:      node_info,
    workspace_id:   workspace_id,
    workspace_name: workspace_name
  }
  if PACKAGES_APP.eql?(app_info[:app])
    raise 'package info required' if package_info.nil?
    app_info[:package_id] = package_info['id']
    app_info[:package_name] = package_info['name']
  end
  node_params = {base_url: node_info['url']}
  # if secret is available
  if scope.nil?
    node_params[:auth] = {
      type:     :basic,
      username: node_info['access_key'],
      password: @secret_finder&.lookup_secret(url: node_info['url'], username: node_info['access_key'], mandatory: true)
    }
  else
    # OAuth bearer token
    node_params[:auth] = auth_params.clone
    node_params[:auth][:scope] = Node.token_scope(node_info['access_key'], scope)
    # special header required for bearer token only
    node_params[:headers] = {Node::HEADER_X_ASPERA_ACCESS_KEY => node_info['access_key']}
  end
  node_params[:app_info] = app_info
  return Node.new(**node_params)
end

#permissions_send_event(created_data:, app_info:, types: PERMISSIONS_CREATED) ⇒ Object

Callback from Plugins::Node send shared folder event to AoC

Parameters:

  • created_data (Hash)

    response from permission creation

  • app_info (Hash)

    hash with app info

  • types (Array) (defaults to: PERMISSIONS_CREATED)

    event types



573
574
575
576
577
578
579
580
581
582
583
584
585
586
# File 'lib/aspera/api/aoc.rb', line 573

def permissions_send_event(created_data:, app_info:, types: PERMISSIONS_CREATED)
  Aspera.assert_type(types, Array)
  Aspera.assert(!types.empty?)
  event_creation = {
    'types'        => types,
    'node_id'      => app_info[:node_info]['id'],
    'workspace_id' => app_info[:workspace_id],
    'data'         => created_data
  }
  # (optional). The name of the folder to be displayed to the destination user.
  # Use it if its value is different from the "share_as" field.
  event_creation['link_name'] = app_info[:opt_link_name] unless app_info[:opt_link_name].nil?
  create('events', event_creation)
end

#permissions_set_create_params(create_param:, app_info:) ⇒ Object

Callback from Plugins::Node add application specific tags to permissions creation

Parameters:

  • create_param (Hash)

    parameters for creating permissions

  • app_info (Hash)

    application information



529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
# File 'lib/aspera/api/aoc.rb', line 529

def permissions_set_create_params(create_param:, app_info:)
  # workspace shared folder:
  # access_id = "#{ID_AK_ADMIN}_WS_#{app_info[:workspace_id]}"
  default_params = {
    # 'access_type'   => 'user', # mandatory: user or group
    # 'access_id'     => access_id, # id of user or group
    'tags' => {
      Transfer::Spec::TAG_RESERVED => {
        'files' => {
          'workspace' => {
            'id'                => app_info[:workspace_id],
            'workspace_name'    => app_info[:workspace_name],
            'user_name'         => ['name'],
            'shared_by_user_id' => ['id'],
            'shared_by_name'    => ['name'],
            'shared_by_email'   => ['email'],
            # 'shared_with_name'  => access_id,
            'access_key'        => app_info[:node_info]['access_key'],
            'node'              => app_info[:node_info]['name']
          }
        }
      }
    }
  }
  create_param.deep_merge!(default_params)
  if create_param.key?('with')
    contact_info = lookup_by_name(
      'contacts',
      create_param['with'],
      {'current_workspace_id' => app_info[:workspace_id], 'context' => 'share_folder'})
    create_param.delete('with')
    create_param['access_type'] = contact_info['source_type']
    create_param['access_id'] = contact_info['source_id']
    create_param['tags'][Transfer::Spec::TAG_RESERVED]['files']['workspace']['shared_with_name'] = contact_info['email']
  end
  # optional
  app_info[:opt_link_name] = create_param.delete('link_name')
end


205
206
207
208
209
210
211
# File 'lib/aspera/api/aoc.rb', line 205

def public_link
  return nil unless auth_params[:grant_method].eql?(:url_json)
  return @cache_url_token_info unless @cache_url_token_info.nil?
  # TODO: can there be several in list ?
  @cache_url_token_info = read('url_tokens')[:data].first
  return @cache_url_token_info
end

#resolve_package_recipients(package_data, ws_id, recipient_list_field, new_user_option) ⇒ Object

Normalize package creation recipient lists as expected by AoC API AoC expects {type: , id: }, but ascli allows providing either the native values or just a name in that case, the name is resolved and replaced with {type: , id: }

Parameters:

  • package_data

    The whole package creation payload

  • recipient_list_field

    The field in structure, i.e. recipients or bcc_recipients

Returns:

  • nil package_data is modified



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
# File 'lib/aspera/api/aoc.rb', line 378

def resolve_package_recipients(package_data, ws_id, recipient_list_field, new_user_option)
  return unless package_data.key?(recipient_list_field)
  Aspera.assert_type(package_data[recipient_list_field], Array){recipient_list_field}
  new_user_option = {'package_contact' => true} if new_user_option.nil?
  Aspera.assert_type(new_user_option, Hash){'new_user_option'}
  # list with resolved elements
  resolved_list = []
  package_data[recipient_list_field].each do |short_recipient_info|
    case short_recipient_info
    when Hash # native API information, check keys
      Aspera.assert(short_recipient_info.keys.sort.eql?(%w[id type])){"#{recipient_list_field} element shall have fields: id and type"}
    when String # CLI helper: need to resolve provided name to type/id
      # email: user, else dropbox
      entity_type = short_recipient_info.include?('@') ? 'contacts' : 'dropboxes'
      begin
        full_recipient_info = lookup_by_name(entity_type, short_recipient_info, {'current_workspace_id' => ws_id})
      rescue RuntimeError => e
        raise e unless e.message.start_with?(ENTITY_NOT_FOUND)
        # dropboxes cannot be created on the fly
        raise "No such shared inbox in workspace #{ws_id}" if entity_type.eql?('dropboxes')
        # unknown user: create it as external user
        full_recipient_info = create('contacts', {
          'current_workspace_id' => ws_id,
          'email'                => short_recipient_info
        }.merge(new_user_option))[:data]
      end
      short_recipient_info = if entity_type.eql?('dropboxes')
        {'id' => full_recipient_info['id'], 'type' => 'dropbox'}
      else
        {'id' => full_recipient_info['source_id'], 'type' => full_recipient_info['source_type']}
      end
    else # unexpected extended value, must be String or Hash
      raise "#{recipient_list_field} item must be a String (email, shared inbox) or Hash (id,type)"
    end
    # add original or resolved recipient info
    resolved_list.push(short_recipient_info)
  end
  # replace with resolved elements
  package_data[recipient_list_field] = resolved_list
  return nil
end

#update_package_metadata_for_api(pkg_data) ⇒ Object

CLI allows simplified format for metadata: transform if necessary for API



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/aspera/api/aoc.rb', line 421

def (pkg_data)
  case pkg_data['metadata']
  when Array, NilClass # no action
  when Hash
    api_meta = []
    pkg_data['metadata'].each do |k, v|
      api_meta.push({
        # 'input_type' => 'single-dropdown',
        'name'   => k,
        'values' => v.is_a?(Array) ? v : [v]
      })
    end
    pkg_data['metadata'] = api_meta
  else Aspera.error_unexpected_value(pkg_meta.class)
  end
  return nil
end

#validate_metadata(pkg_data) ⇒ Object

Check metadata: remove when validation is done server side



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
# File 'lib/aspera/api/aoc.rb', line 343

def (pkg_data)
  # validate only for shared inboxes
  return unless pkg_data['recipients'].is_a?(Array) &&
    pkg_data['recipients'].first.is_a?(Hash) &&
    pkg_data['recipients'].first.key?('type') &&
    pkg_data['recipients'].first['type'].eql?('dropbox')
  meta_schema = read("dropboxes/#{pkg_data['recipients'].first['id']}")[:data]['metadata_schema']
  if meta_schema.nil? || meta_schema.empty?
    Log.log.debug('no metadata in shared inbox')
    return
  end
  Aspera.assert(pkg_data.key?('metadata')){"package requires metadata: #{meta_schema}"}
  pkg_meta = pkg_data['metadata']
  Aspera.assert_type(pkg_meta, Array){'metadata'}
  Log.log.debug{Log.dump(:metadata, pkg_meta)}
  pkg_meta.each do |field|
    Aspera.assert_type(field, Hash){'metadata field'}
    Aspera.assert(field.key?('name')){'metadata field must have name'}
    Aspera.assert(field.key?('values')){'metadata field must have values'}
    Aspera.assert_type(field['values'], Array){'metadata field values'}
    Aspera.assert(!meta_schema.none?{|i|i['name'].eql?(field['name'])}){"unknown metadata field: #{field['name']}"}
  end
  meta_schema.each do |field|
    provided = pkg_meta.select{|i|i['name'].eql?(field['name'])}
    raise "only one field with name #{field['name']} allowed" if provided.count > 1
    raise "missing mandatory field: #{field['name']}" if field['required'] && provided.empty?
  end
end