Class: Aspera::Plugins::Aoc::Commands

Inherits:
Cli::Plugins::Base show all
Includes:
Cli::Plugins::Oauth
Defined in:
lib/aspera/plugins/aoc/commands.rb

Constant Summary collapse

AOC_SCHEMA =

Keys of the schemas of the bundle (see plugin.yaml): AoC API, AoC Automation API, options

'aoc'
AUTOMATION_SCHEMA =
'automation'
PACKAGE_FOLDER_OPTIONS =
'aoc_opts:components.schemas.PackageFolderOptions'
APP_TYPES =

Known fixed set of AoC application types (verified against API: activity, automation, files, packages)

%i[activity automation files packages].freeze
ADMIN_ACTIONS =
(%i[bearer_token application ats usage_reports analytics subscription auth_providers integrations] + ADMIN_OBJECTS).freeze
{public: 'token_auth_redirection', private: 'shared_folder_auth_link'}.freeze
Schema::Registry.query_params(AOC_SCHEMA, 'short_links')
AOC_AUTOMATION_GUIDE_URLS =
[
  'https://raw.githubusercontent.com/laurent-martin/aspera-orchestrator-plugins-doc/main/docs/aoc/aoc-automation-development-guide.md'
].freeze

Constants included from Cli::Plugins::Oauth

Cli::Plugins::Oauth::AUTH_OPTIONS, Cli::Plugins::Oauth::AUTH_TYPES

Constants inherited from Cli::Plugins::Base

Cli::Plugins::Base::FILTER_ARGS

Instance Attribute Summary

Attributes inherited from Cli::Plugins::Base

#context, #help_path

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Cli::Plugins::Oauth

included, kwargs_from_options

Methods included from Cli::Option::Declarator

#declare_options, #option, #option_specs, #register_option_spec

Methods included from Cli::Plugins::BasicAuth

#basic_auth_api, #basic_auth_params, included

Methods inherited from Cli::Plugins::Base

#action_for, application_name, #bulk_result, #check_argument_access, command, command_registry, commands_under, #config, #crud_api, crud_commands, declare_options, define_action_method, #dispatch_child, #dispatch_from_registry, #dispatch_leaf, #dispatch_mount, #entity_create, #entity_delete, #entity_list, #entity_modify, entity_noun, #entity_res_path, #entity_show, #execute_action, #execute_leaf, file_matcher, #formatter, #generate_help, #http_config, include_mounts, #invoke_action, operation_description, option_sources, option_specs, #options, #persistency, #poll_result, #presets, #progress_bar, #query_read_delete, register_option_spec, #resolve_argument, #resolve_arguments, #transfer, use_options, used_option_sources, #validate_registry

Constructor Details

#initialize(**_) ⇒ Commands

Returns a new instance of Commands.



288
289
290
291
292
293
294
# File 'lib/aspera/plugins/aoc/commands.rb', line 288

def initialize(**_)
  super
  @cache_workspace_info = nil
  @cache_home_node_file = nil
  @cache_api_aoc = nil
  @scope = Api::Scope::USER
end

Class Method Details

.aoc_res_cfg(res) ⇒ Hash

Returns create_path:, schema_path:, ops:, id_result:, require_ws_id:, list_fields:, schema:, modify_schema:, query_component:.

Returns:

  • (Hash) —

    create_path:, schema_path:, ops:, id_result:, require_ws_id:, list_fields:, schema:, modify_schema:, query_component:



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/aspera/plugins/aoc/commands.rb', line 124

def aoc_res_cfg(res)
  cfg         = ADMIN_OBJECT_CONFIG.fetch(res, {})
  path        = aoc_res_path(res)
  create_path = cfg[:create_path] || path
  schema_path = aoc_schema_path(path)
  ops         = cfg[:ops] || (cfg[:singleton] ? %i[show] : Cli::Plugins::Base::Operations::ALL + (cfg[:extra_ops] || []))
  in_schema   = cfg[:schema] != false
  {
    path:            path,
    create_path:     create_path,
    schema_path:     schema_path,
    ops:             ops,
    id_result:       cfg[:id_result] || 'id',
    require_ws_id:   cfg[:require_ws_id] || false,
    list_fields:     cfg.key?(:list_fields) ? cfg[:list_fields] : %w[id name],
    schema:          (Schema::Registry.req_body(AOC_SCHEMA, "#{aoc_schema_path(create_path)}.post") if in_schema),
    modify_schema:   (Schema::Registry.req_body(AOC_SCHEMA, "#{schema_path}#{'/{id}' unless cfg[:singleton]}.put") if in_schema),
    query_component: AOC_SCHEMA
  }
end

.aoc_res_path(res) ⇒ String

Returns AoC REST path for an admin resource type.

Returns:

  • (String) —

    AoC REST path for an admin resource type



111
112
113
114
115
116
# File 'lib/aspera/plugins/aoc/commands.rb', line 111

def aoc_res_path(res)
  cfg = ADMIN_OBJECT_CONFIG.fetch(res, {})
  return cfg[:path] if cfg[:path]
  return res.to_s if cfg[:singleton]
  "#{res}s".gsub(/ys$/, 'ies')
end

.aoc_schema_path(path) ⇒ String

Path of an endpoint in the OpenAPI description: AoC accepts the prefix admin/ on all endpoints, the description has none

Parameters:

  • path (String) —

    REST path, e.g. admin/client_access_keys

Returns:

  • (String) —

    path in the OpenAPI description, e.g. client_access_keys



121
# File 'lib/aspera/plugins/aoc/commands.rb', line 121

def aoc_schema_path(path) = path.delete_prefix('admin/')

.detect(base_url) ⇒ Hash, NilClass

Returns:



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/aspera/plugins/aoc/commands.rb', line 57

def detect(base_url)
  # no protocol ?
  base_url = "https://#{base_url}" unless base_url.match?(%r{^[a-z]{1,6}://})
  # only org provided ?
  base_url = "#{base_url}.#{Api::SAAS_DOMAIN_PROD}" unless base_url.include?('.')
  # AoC is only https
  return unless base_url.start_with?('https://')
  location = Rest::Client.new(base_url: base_url, redirect_max: 0).call(operation: 'GET', subpath: 'auth/ping', exception: false, ret: :resp)['Location']
  return if location.nil?
  redirect_uri = URI.parse(location)
  od = Api.split_org_domain(URI.parse(base_url))
  return unless redirect_uri.path.end_with?("oauth2/#{od[:organization]}/login")
  # either in standard domain, or product name in page
  return {
    version: Api.saas_url?(base_url) ? 'SaaS' : 'Self-managed',
    url:     base_url
  }
end

.next_available_folder(base, always: false) ⇒ String

Get folder path that does not exist

Parameters:

  • base (String) —

    Base folder path

  • always (Boolean) (defaults to: false) —

    true always add number, false only if base folder already exists

Returns:

  • (String) —

    Folder path that does not exist, with possible . extension



80
81
82
83
84
85
86
87
# File 'lib/aspera/plugins/aoc/commands.rb', line 80

def next_available_folder(base, always: false)
  counter = always ? 1 : 0
  loop do
    result = counter.zero? ? base : "#{base}.#{counter}"
    return result unless Dir.exist?(result)
    counter += 1
  end
end

Optional Hash argument of short link create and modify, merged into the request body

Parameters:

  • endpoint (String) —

    endpoint of the request body schema, e.g. short_links.post

Returns:

  • (Hash) —

    argument declaration



148
149
150
151
152
153
154
# File 'lib/aspera/plugins/aoc/commands.rb', line 148

def short_link_argument(endpoint)
  {
    name: :short_link, type: Hash, mandatory: false, default: {},
    description: 'Merged into the request body, and: `password` (link password), `access_levels` (shared folder only)',
    schema: Schema::Registry.req_body(AOC_SCHEMA, endpoint)
  }
end

DSL class method: declare the 5 short link leaf commands under the given node. The node itself is declared by the caller, with its arguments and setup.

Parameters:

  • parent (Symbol, Array<Symbol>) —

    path relative to current scope, e.g. :short_link



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
# File 'lib/aspera/plugins/aoc/commands.rb', line 159

def short_link_commands(parent)
  commands_under(parent) do
    command(
      :create, description: operation_description(:create, 'short link'),
      arguments: [short_link_argument('short_links.post')],
      action: ->(short_link: {}, **ctx) { short_link_create(short_link, **ctx) }
    )
    command(
      :modify, description: operation_description(:modify, 'short link'),
      arguments: [{name: :short_link_id, type: :identifier}, short_link_argument('short_links/{id}.put')],
      action: ->(short_link: {}, **ctx) { short_link_modify(short_link, **short_link_fetch_list(**ctx), **ctx) }
    )
    command(
      :list, description: operation_description(:list, 'short link'), query_schema: SHORT_LINK_QUERY_SCHEMA,
      action: ->(**ctx) { short_link_list(**short_link_fetch_list(**ctx)) }
    )
    command(
      :show, description: operation_description(:show, 'short link'),
      arguments: [{name: :short_link_id, type: :identifier}],
      action: ->(**ctx) { short_link_show(**short_link_fetch_list(**ctx), **ctx) }
    )
    command(
      :delete, description: operation_description(:delete, 'short link'),
      arguments: [{name: :short_link_id, type: :identifier}],
      action: ->(**ctx) { short_link_delete(**short_link_fetch_list(**ctx), **ctx) }
    )
  end
end

.unique_folder(package_info, destination_folder, fld: nil, seq: false, opt: false) ⇒ String

Get folder path that does not exist If it exists, an extension is added or a sequential number if extension == :seq

Parameters:

  • package_info (Hash) —

    Package information

  • destination_folder (String) —

    Base folder

  • fld (Array) (defaults to: nil) —

    List of fields of package

Returns:

  • (String) —

    Folder path in destination folder



96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/aspera/plugins/aoc/commands.rb', line 96

def unique_folder(package_info, destination_folder, fld: nil, seq: false, opt: false)
  Aspera.assert_array_all(fld, String, type: Cli::BadArgument) { 'fld' }
  Aspera.assert_values(fld.length, [1, 2], type: Cli::BadArgument) { 'fld length' }
  # Existence is checked in the destination folder
  folder = File.join(destination_folder, Environment.instance.sanitized_filename(package_info[fld[0]].to_s))
  if seq
    folder = next_available_folder(folder, always: !opt)
  elsif fld[1] && (Dir.exist?(folder) || !opt)
    # NOTE: it might already exist
    folder = "#{folder}.#{Environment.instance.sanitized_filename(package_info[fld[1]].to_s)}"
  end
  folder
end

Instance Method Details

#access_control_setting(network_policy_id) ⇒ Object

Setting of an access control rule for the type of the policy, as the web app



1756
1757
1758
1759
1760
1761
1762
1763
# File 'lib/aspera/plugins/aoc/commands.rb', line 1756

def access_control_setting(network_policy_id)
  type = aoc_api.read("admin/network_policies/#{network_policy_id}")['access_control_type']
  case type
  when 'allow_following' then :allow
  when 'disallow_following' then :disallow
  else raise Cli::BadArgument, "policy_setting required: access_control_type of the policy is #{type}"
  end
end

#action_admin_analytics_files(event_resource_type:, event_resource_id:, event_uuid:) ⇒ Object

admin > analytics > files



1447
1448
1449
1450
1451
1452
1453
# File 'lib/aspera/plugins/aoc/commands.rb', line 1447

def action_admin_analytics_files(event_resource_type:, event_resource_id:, event_uuid:, **)
  event_resource_id = analytics_resource_id(event_resource_type, event_resource_id)
  filter = query_read_delete(default: {})
  filter['limit'] ||= 100
  events = build_analytics_api.read("#{event_resource_type}/#{event_resource_id}/transfers/#{event_uuid}/files", filter)['files']
  Cli::Result::ObjectList.new(events)
end

#action_admin_analytics_transfers(event_resource_type:, event_resource_id:) ⇒ Object

admin > analytics > transfers



1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
# File 'lib/aspera/plugins/aoc/commands.rb', line 1423

def action_admin_analytics_transfers(event_resource_type:, event_resource_id:, **)
  event_resource_id = analytics_resource_id(event_resource_type, event_resource_id)
  filter = query_read_delete(default: {})
  filter['limit'] ||= 100
  if options.get_option(:once_only, mandatory: true)
    saved_date = []
    start_date_persistency = PersistencyActionOnce.new(
      manager: persistency,
      data:    saved_date,
      id:      IdGenerator.from_list('aoc_ana_date', options.get_option(:url, mandatory: true), aoc_api.workspace_info[:name], event_resource_type.to_s, event_resource_id)
    )
    start_date_time = saved_date.first
    stop_date_time  = Time.now.utc.strftime('%FT%T.%LZ')
    saved_date[0]   = stop_date_time
    filter['start_time'] = start_date_time unless start_date_time.nil?
    filter['stop_time']  = stop_date_time
  end
  events = build_analytics_api.read("#{event_resource_type}/#{event_resource_id}/transfers", filter)['transfers']
  start_date_persistency&.save
  events.each { |tr_event| context.mailer.send_email_template(values: {ev: tr_event}) } if !options.get_option(:notify_to).nil?
  Cli::Result::ObjectList.new(events)
end

#action_admin_application_instance_list ⇒ Object



1367
1368
1369
1370
1371
1372
1373
# File 'lib/aspera/plugins/aoc/commands.rb', line 1367

def action_admin_application_instance_list(**)
  result_list(
    'admin/apps_new',
    fields:        %w[id app_type available workspace_id],
    default_query: {workspace_id: aoc_api.workspace_info[:id]}
  )
end

#action_admin_application_membership_create(membership:) ⇒ Object



1383
1384
1385
1386
1387
1388
1389
# File 'lib/aspera/plugins/aoc/commands.rb', line 1383

def action_admin_application_membership_create(membership:, **)
  data = membership.dup
  app_type = data.delete('app_type')
  Aspera.assert_type(app_type, String, type: Cli::BadArgument) { 'app_type' }
  Aspera.assert_values(app_type.to_sym, APP_TYPES, type: Cli::BadArgument) { 'app_type' }
  Cli::Result::SingleObject.new(aoc_api.create("apps/#{app_type}/app_memberships", data))
end

#action_admin_client_set_pub_key(private_key_pem:, client_id:) ⇒ Object

admin > client > set_pub_key



1725
1726
1727
1728
1729
1730
# File 'lib/aspera/plugins/aoc/commands.rb', line 1725

def action_admin_client_set_pub_key(private_key_pem:, client_id:, **)
  c = aoc_res_cfg(:client)
  the_public_key = OpenSSL::PKey::RSA.new(private_key_pem).public_key.to_s
  aoc_api.update("#{c[:path]}/#{client_id}", {jwt_grant_enabled: true, public_key: the_public_key})
  Cli::Result::Success.new
end

admin > dropbox > update_self_registration_link



1766
1767
1768
# File 'lib/aspera/plugins/aoc/commands.rb', line 1766

def action_admin_dropbox_update_self_registration_link(dropbox_id:, **)
  Cli::Result::SingleObject.new(aoc_api.create("admin/dropboxes/#{dropbox_id}/update_self_registration_link", {}), fields: %w[id name self_register_url_id])
end

#action_admin_kms_profile_nodes(kms_profile_id:) ⇒ Object

admin > kms_profile > nodes



1785
1786
1787
# File 'lib/aspera/plugins/aoc/commands.rb', line 1785

def action_admin_kms_profile_nodes(kms_profile_id:, **)
  Cli::Result::ObjectList.new(aoc_api.read("#{aoc_res_path(:kms_profile)}/#{kms_profile_id}/nodes"))
end

#action_admin_node_bearer_token(scope:, node_id:) ⇒ Object

admin > node > bearer_token



1749
1750
1751
1752
1753
# File 'lib/aspera/plugins/aoc/commands.rb', line 1749

def action_admin_node_bearer_token(scope:, node_id:, **)
  scope ||= Node::Api::Scope::ADMIN
  node_api = aoc_api.node_api_from(node_id: node_id, scope: scope)
  Cli::Result::Text.new(node_api.oauth.authorization)
end

#action_admin_node_update_status(node_id:) ⇒ Object

admin > node > update_status



1796
1797
1798
# File 'lib/aspera/plugins/aoc/commands.rb', line 1796

def action_admin_node_update_status(node_id:, **)
  Cli::Result::SingleObject.new(aoc_api.read("#{aoc_res_path(:node)}/#{node_id}/update_status"), fields: %w[status error_time error_message])
end

#action_admin_package_download_counts(package_id:) ⇒ Object

admin > package > download_counts (also packages > download_counts)



1790
1791
1792
1793
# File 'lib/aspera/plugins/aoc/commands.rb', line 1790

def action_admin_package_download_counts(package_id:, **)
  result_list("packages/#{package_id}/download_counts", base_query: {'embed[]' => 'user'}, fields: %w[user_id user.email full partial failed active],
    query_component: AOC_SCHEMA, schema_path: 'packages/{id}/download_counts')
end

#action_admin_subscription_usage(aggregate:, start_date:, end_date:) ⇒ Object

admin > subscription > usage



1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
# File 'lib/aspera/plugins/aoc/commands.rb', line 1398

def action_admin_subscription_usage(aggregate:, start_date:, end_date:, **)
  today      = Date.today
  aggregate  = :ALL if aggregate.nil?
  start_date = today.prev_year.strftime('%Y-%m-%d') if start_date.nil?
  end_date   = today.strftime('%Y-%m-%d') if end_date.nil?
  org    = aoc_api.read('organization')
  result = GraphQL.execute(
    api_from_options('bss/platform/graphql'), 'bss_subscription_usage',
    {organization_id: org['id'], aggregate: aggregate, startDate: start_date, endDate: end_date}
  )
  Cli::Result::SingleObject.new(result['aoc'])
end

#action_admin_user_invite(user_id:) ⇒ Object

admin > user > invite



1771
1772
1773
1774
# File 'lib/aspera/plugins/aoc/commands.rb', line 1771

def action_admin_user_invite(user_id:, **)
  aoc_api.create('admin/invitations', {'user_id' => user_id})
  Cli::Result::Status.new('invited')
end

#action_admin_workspace_shared_folder_member_list(ws_res_id:, sf_item:) ⇒ Object

admin > workspace > shared_folder > member > list



1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
# File 'lib/aspera/plugins/aoc/commands.rb', line 1829

def action_admin_workspace_shared_folder_member_list(ws_res_id:, sf_item:, **)
  node_api = aoc_api.node_api_from(
    node_id:        sf_item['node_id'],
    workspace_id:   ws_res_id,
    workspace_name: nil,
    scope:          Node::Api::Scope::USER
  )
  result = node_api.read('permissions', {'file_id' => sf_item['file_id'], 'tag' => "aspera.files.workspace.id=#{ws_res_id}"})
  result.each do |item|
    item['member'] = begin
      if Api.workspace_access?(item)
        {'name' => '[Internal permission]'}
      else
        aoc_api.read("admin/#{item['access_type']}s/#{item['access_id']}")
      end
    rescue StandardError => e
      # e.g. member deleted: the error is shown instead of the name
      {'name' => e.to_s}
    end
  end
  # TODO : read users and group name and add, if query "include_members"
  Cli::Result::ObjectList.new(result, fields: %w[access_type access_id access_level last_updated_at member.name member.email member.system_group_type member.system_group])
end

#action_automation_workflows_action_create(workflow_id:, action:) ⇒ Object

automation > workflows > action > create Default action type is manual



1547
1548
1549
1550
1551
1552
1553
1554
# File 'lib/aspera/plugins/aoc/commands.rb', line 1547

def action_automation_workflows_action_create(workflow_id:, action:, **)
  workflow = @automation_api.read("workflows/#{workflow_id}")
  step = @automation_api.create('steps', {'workflow_id' => workflow_id})
  @automation_api.update("workflows/#{workflow_id}", {'step_order' => Array(workflow['step_order']) + [step['id']]})
  new_action = @automation_api.create('actions', {'type' => 'manual'}.merge(action).merge('step_id' => step['id']))
  @automation_api.update("steps/#{step['id']}", {'action_order' => [new_action['id']]})
  Cli::Result::SingleObject.new(new_action)
end

#action_automation_workflows_action_list(workflow_id:) ⇒ Object

automation > workflows > action > list A workflow has ordered steps (step_order), a step has ordered actions (action_order)



1536
1537
1538
1539
1540
1541
1542
1543
# File 'lib/aspera/plugins/aoc/commands.rb', line 1536

def action_automation_workflows_action_list(workflow_id:, **)
  workflow = @automation_api.read("workflows/#{workflow_id}")
  actions = Array(workflow['step_order']).flat_map do |step_id|
    step = @automation_api.read("steps/#{step_id}")
    Array(step['action_order']).map { |action_id| @automation_api.read("actions/#{action_id}") }
  end
  Cli::Result::ObjectList.new(actions)
end

#action_gateway(parameters: {}) ⇒ Object



1865
1866
1867
1868
1869
1870
1871
1872
1873
# File 'lib/aspera/plugins/aoc/commands.rb', line 1865

def action_gateway(parameters: {}, **)
  # Loaded on use: web server
  require_relative '../faspex4/gw_servlet'
  Faspex4::GWServlet.serve(parameters.symbolize_keys, type: Cli::BadArgument) do
    workspace_id = aoc_api.workspace_info[:id]
    ->(faspex_pkg_parameters) { faspex4_send_to_aoc(faspex_pkg_parameters, workspace_id) }
  end
  return Cli::Result::Status.new('Gateway terminated')
end

#action_packages_delete(package_id:) ⇒ Object

packages > delete



1175
1176
1177
1178
1179
1180
# File 'lib/aspera/plugins/aoc/commands.rb', line 1175

def action_packages_delete(package_id:, **)
  bulk_result(package_id, command: :delete) do |one_id|
    Aspera.assert_type(one_id, String, Integer, type: Cli::BadArgument) { 'identifier' }
    aoc_api.delete("packages/#{one_id}")
  end
end

#action_packages_list ⇒ Object

packages > list



1164
1165
1166
1167
1168
1169
1170
1171
1172
# File 'lib/aspera/plugins/aoc/commands.rb', line 1164

def action_packages_list(**)
  result, max_items = list_all_packages_with_query
  skip_ids_persistency = package_persistency
  reject_packages_from_persistency(result[:items], skip_ids_persistency)
  result[:items] = result[:items][0, max_items] if max_items
  display_fields = PACKAGE_LIST_DEFAULT_FIELDS
  display_fields += ['workspace_id'] if aoc_api.workspace_info[:id].nil?
  Cli::Result::ObjectList.new(result[:items], fields: display_fields, total: result[:total])
end

#action_packages_receive(package_id:) ⇒ Object

packages > receive — package_id: from arguments:(:identifier) (or overridden by public_link)



1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
# File 'lib/aspera/plugins/aoc/commands.rb', line 1107

def action_packages_receive(package_id:, **)
  ids_to_download = if aoc_api.public_link.nil?
    package_id
  else
    aoc_api.assert_public_link_types(['view_received_package'])
    aoc_api.public_link['data']['package_id']
  end
  skip_ids_persistency = package_persistency
  case ids_to_download
  when Cli::SpecialValues::INIT
    all_packages, = list_all_packages_with_query
    Aspera.assert(skip_ids_persistency, 'INIT requires option once_only', type: Cli::BadArgument)
    skip_ids_persistency.data.clear.concat(all_packages[:items].map { |e| e['id'] })
    skip_ids_persistency.save
    return Cli::Result::Status.new("Initialized skip for #{skip_ids_persistency.data.count} package(s)")
  when Cli::SpecialValues::ALL
    all_packages, max_items = list_all_packages_with_query
    reject_packages_from_persistency(all_packages[:items], skip_ids_persistency)
    all_packages[:items] = all_packages[:items][0, max_items] if max_items
    ids_to_download = all_packages[:items].map { |e| e['id'] }
    formatter.display_status("Found #{ids_to_download.length} package(s).")
  else
    ids_to_download = Array(ids_to_download)
    Aspera.assert_array_all(ids_to_download, String, type: Cli::BadArgument) { 'Package id(s)' }
  end
  ts_paths = transfer.ts_source_paths(default: ['.'])
  per_package_def = options.get_option(:package_folder).symbolize_keys
   = per_package_def.delete(:inf)
  destination_folder = transfer.destination_folder(Aspera::Transfer::Spec::DIRECTION_RECEIVE)
  result_transfer = []
  ids_to_download.each do |package_id|
    package_info = aoc_api.read("packages/#{package_id}")
    package_node_api = aoc_api.node_api_from(
      node_id: package_info['node_id'],
      package_info: package_info,
      **workspace_id_hash(name: true)
    )
    transfer_spec = package_node_api.transfer_spec_gen4(
      package_info['contents_file_id'],
      Aspera::Transfer::Spec::DIRECTION_RECEIVE,
      {'paths'=> ts_paths}
    )
    transfer.user_transfer_spec['destination_root'] = self.class.unique_folder(package_info, destination_folder, **per_package_def) unless per_package_def.empty?
    dest_folder = transfer.user_transfer_spec['destination_root'] || destination_folder
    formatter.display_status(%Q{Downloading package: [#{package_info['id']}] "#{package_info['name']}" to [#{dest_folder}]})
    statuses = transfer.start(transfer_spec, oauth_api: package_node_api)
    File.write(File.join(dest_folder, "#{package_id}.info.json"), package_info.to_json) if  && !statuses.is_a?(Aspera::Transfer::Result::DryRun)
    result_transfer.push({'package' => package_id, Xfer::TransferAgent::STATUS_FIELD => statuses})
    if skip_ids_persistency && statuses.is_a?(Aspera::Transfer::Result::Success)
      skip_ids_persistency.data.push(package_id)
      skip_ids_persistency.save
    end
  end
  return Xfer::TransferAgent.result_transfer_multiple(result_transfer)
end

#action_packages_send(package:) ⇒ Object

packages > send



1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
# File 'lib/aspera/plugins/aoc/commands.rb', line 1088

def action_packages_send(package:, **)
  # The package is created before the transfer
  transfer.assert_no_dry_run
  package_data = package
  new_user_option = options.get_option(:new_user_option)
  option_validate = options.get_option(:validate_metadata)
  workspace_id_hash(package_data, string: true) unless package_data.key?('workspace_id')
  if !aoc_api.public_link.nil?
    aoc_api.assert_public_link_types(%w[send_package_to_user send_package_to_dropbox])
    box_type = aoc_api.public_link['purpose'].split('_').last
    package_data['recipients'] = [{'id' => aoc_api.public_link['data']["#{box_type}_id"], 'type' => box_type}]
    package_data['workspace_id'] = aoc_api.public_link['data']['workspace_id']
  end
  package_data['encryption_at_rest'] = true if transfer.user_transfer_spec['content_protection'].eql?('encrypt')
  created_package = aoc_api.create_package_simple(package_data, option_validate, new_user_option)
  return Xfer::TransferAgent.result_object_transfer(created_package[:info], transfer.start(created_package[:spec], oauth_api: created_package[:node]))
end

#action_packages_shared_inboxes_list ⇒ Object



1375
1376
1377
1378
1379
1380
1381
# File 'lib/aspera/plugins/aoc/commands.rb', line 1375

def action_packages_shared_inboxes_list(**)
  result_list(
    'dropbox_memberships',
    fields: %w[dropbox_id dropbox.name],
    default_query: workspace_id_hash({'embed[]' => 'dropbox', 'aggregate_permissions_by_dropbox' => true, 'sort' => 'dropbox_name'}, string: true)
  )
end

#action_reminder ⇒ Object

--- handler methods ---



1080
1081
1082
1083
1084
1085
# File 'lib/aspera/plugins/aoc/commands.rb', line 1080

def action_reminder(**)
  user_email = options.get_option(:username, mandatory: true)
  no_auth_api = Api.new(url: options.get_option(:url), auth: :none)
  no_auth_api.create('organization_reminders', {email: user_email})
  return Cli::Result::Status.new("List of organizations user is member of, has been sent by e-mail to #{user_email}")
end

#admin_node_do_plugin(node_id:) ⇒ Object

admin > node > do - mount target: Gen4 commands on the node, admin scope



1744
1745
1746
# File 'lib/aspera/plugins/aoc/commands.rb', line 1744

def admin_node_do_plugin(node_id:, **)
  nodegen4_plugin(node_id, scope: Node::Api::Scope::ADMIN)
end

#admin_workspace_shared_folder_node_plugin(sf_item:) ⇒ Object

admin > workspace > shared_folder > node - mount target: Gen4 commands on the shared folder, admin scope



1824
1825
1826
# File 'lib/aspera/plugins/aoc/commands.rb', line 1824

def admin_workspace_shared_folder_node_plugin(sf_item:, **)
  nodegen4_plugin(sf_item['node_id'], file_id: sf_item['file_id'], scope: Node::Api::Scope::ADMIN)
end

#analytics_resource_id(event_resource_type, event_resource_id) ⇒ String

Returns the given resource id, or the one of the current user if empty.

Returns:

  • (String) —

    the given resource id, or the one of the current user if empty



1412
1413
1414
1415
1416
1417
1418
1419
1420
# File 'lib/aspera/plugins/aoc/commands.rb', line 1412

def analytics_resource_id(event_resource_type, event_resource_id)
  return event_resource_id unless event_resource_id.to_s.empty?
  case event_resource_type
  when :organizations then aoc_api.['organization_id']
  when :users         then aoc_api.['id']
  when :nodes         then aoc_api.['read_only_home_node_id']
  else Aspera.error_unreachable_line
  end
end

#aoc_api ⇒ Api

AoC Rest object

Returns:

  • (Api) —

    API object for AoC (is Rest::Client)



333
334
335
336
337
338
339
340
341
342
343
# File 'lib/aspera/plugins/aoc/commands.rb', line 333

def aoc_api
  if @cache_api_aoc.nil?
    @cache_api_aoc = api_from_options(Api::API_V1)
    transfer.httpgw_url_cb = lambda do
      organization = @cache_api_aoc.read('organization')
      # @cache_api_aoc.current_user_info['connect_disabled']
      organization['http_gateway_server_url'] if organization['http_gateway_enabled'] && organization['http_gateway_server_url']
    end
  end
  return @cache_api_aoc
end

#aoc_res_cfg(res) ⇒ Object



514
# File 'lib/aspera/plugins/aoc/commands.rb', line 514

def aoc_res_cfg(res)      = self.class.aoc_res_cfg(res)

#aoc_res_path(res) ⇒ Object

Instance delegators so instance methods can call aoc_res_path/aoc_res_cfg/aoc_schema_path without self.class.



513
# File 'lib/aspera/plugins/aoc/commands.rb', line 513

def aoc_res_path(res)     = self.class.aoc_res_path(res)

#aoc_schema_path(path) ⇒ Object



515
# File 'lib/aspera/plugins/aoc/commands.rb', line 515

def aoc_schema_path(path) = self.class.aoc_schema_path(path)

#api_from_options(base_path) ⇒ Api

Create an API object with the options from CLI, but with a different subpath

Parameters:

  • base_path (String) —

    Base path for APIs.

Returns:

  • (Api) —

    API object for AoC (is Rest::Client)



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/aspera/plugins/aoc/commands.rb', line 308

def api_from_options(base_path)
  # Get all existing OAuth kwargs from `options`.
  api = Api.new(
    scope:         @scope,
    subpath:       base_path,
    secret_finder: context.secret_finder,
    **Cli::Plugins::Oauth.kwargs_from_options(options)
  )
  # User set a workspace ?
  # @type [String, nil]
  workspace = options.get_option(:workspace)
  if !workspace.nil? && (m = Cli::Parser.percent_selector(workspace))
    case m[:field]
    when 'name' then api.ws_ids[:name] = m[:value]
    when 'id' then api.ws_ids[:id] = m[:value]
    else Aspera.error_unexpected_value(m[:field]) { 'workspace selector: only `name` or `id`' }
    end
  else
    api.ws_ids[:name] = workspace
  end
  api
end

#automation_guide_document ⇒ Object

automation guide methods



1707
1708
1709
1710
# File 'lib/aspera/plugins/aoc/commands.rb', line 1707

def automation_guide_document
  require_relative '../../uri_reader'
  UriReader.read_first(AOC_AUTOMATION_GUIDE_URLS, what: 'AoC Automation Development Guide')
end

#automation_guide_section(anchor) ⇒ Object



1717
1718
1719
1720
1721
1722
# File 'lib/aspera/plugins/aoc/commands.rb', line 1717

def automation_guide_section(anchor)
  require_relative '../../markdown'
  text = Markdown.extract_section(automation_guide_document, anchor)
  Aspera.assert(!text.nil?, type: Cli::Error) { "Section not found: #{anchor}, use `toc` to list anchors" }
  Cli::Result::Text.new(text)
end

#automation_guide_toc(level) ⇒ Object



1712
1713
1714
1715
# File 'lib/aspera/plugins/aoc/commands.rb', line 1712

def automation_guide_toc(level)
  require_relative '../../markdown'
  Cli::Result::ObjectList.new(Markdown.toc(automation_guide_document, max_level: level || 3), fields: %w[level title anchor])
end

#build_analytics_api ⇒ Object

Build analytics REST API (shared by action_admin_analytics_*)



523
524
525
526
527
528
# File 'lib/aspera/plugins/aoc/commands.rb', line 523

def build_analytics_api
  Rest::Client.new(**aoc_api.params.deep_merge({
    base_url: "#{aoc_api.base_url.gsub('/api/v1', '')}/analytics/v2",
    auth:     {params: {scope: Api::Scope::ADMIN_USER}}
  }))
end

#build_ats_plugin ⇒ Ats::Commands

admin > ats — build and return an Ats plugin instance wired to the AoC ATS API. Mount target of admin ats.

Returns:



1735
1736
1737
1738
1739
1740
1741
# File 'lib/aspera/plugins/aoc/commands.rb', line 1735

def build_ats_plugin(**)
  ats_api = Rest::Client.new(**aoc_api.params.deep_merge({
    base_url: "#{aoc_api.base_url}/admin/ats/pub/v1",
    auth:     {params: {scope: Api::Scope::ADMIN_USER}}
  }))
  Ats::Commands.new(context: context, api: ats_api)
end

#change_api_scope(new_scope) ⇒ Object

Change API scope for subsequent calls, re-instantiate API object

Parameters:

  • new_scope (String) —

    New scope



298
299
300
301
302
303
# File 'lib/aspera/plugins/aoc/commands.rb', line 298

def change_api_scope(new_scope)
  # Discard cache
  @cache_api_aoc = nil
  @scope = new_scope
  nil
end

#files_node_plugin ⇒ Object

files - mount target: Gen4 commands on the user's home folder



1349
1350
1351
# File 'lib/aspera/plugins/aoc/commands.rb', line 1349

def files_node_plugin(**)
  nodegen4_plugin(aoc_api.home[:node_id], file_id: aoc_api.home[:file_id], scope: Node::Api::Scope::USER)
end

#list_all_packages_with_query ⇒ Array(Hash, Integer, nil)

List all packages from the API using the current --query option. The special max key is extracted before the API call and returned separately, so callers that apply a post-API filter (e.g. once_only) can enforce the limit after filtering rather than before.

Returns:

  • (Array(Hash, Integer, nil)) —

    [items:,total: paging result, max (or nil)]



425
426
427
428
429
430
431
432
433
# File 'lib/aspera/plugins/aoc/commands.rb', line 425

def list_all_packages_with_query
  query = query_read_delete(default: {}, schema: Schema::Registry.query_params(AOC_SCHEMA, 'packages'))
  Aspera.assert_type(query, Hash, type: Cli::BadArgument) { 'query' }
  PACKAGE_RECEIVED_BASE_QUERY.each { |k, v| query[k] = v unless query.key?(k) }
  resolve_dropbox_name_default_ws_id(query)
  # Extract `max` before paging so callers can apply it after post-API filtering
  max_items = query.delete(Rest::List::MAX_ITEMS)&.to_i
  return aoc_api.read_with_paging('packages', query.compact), max_items
end

#nodegen4_plugin(node_id, file_id: nil, scope: nil) ⇒ Array(Node, Hash)

Node plugin for Gen4 commands on a node, with the seed ctx of its access_keys do sub-tree. Used as instance: of mounts of NODE_GEN4_MOUNT.

Returns:



464
465
466
467
# File 'lib/aspera/plugins/aoc/commands.rb', line 464

def nodegen4_plugin(node_id, file_id: nil, scope: nil)
  node_api, file_id = nodegen4_root(node_id, file_id: file_id, scope: scope)
  [Node::Commands.new(context: context, api: node_api), {do_root_file_id: file_id}]
end

#nodegen4_root(node_id, file_id: nil, scope: nil) ⇒ Array(Node::Api, String)

Node API on a Gen4 node, and its root file id.

Parameters:

  • node_id (String) —

    Node identifier

  • file_id (String, nil) (defaults to: nil) —

    Root file id; if nil, the access key root file id is used

  • scope (String, nil) (defaults to: nil) —

    node scope (Node::Api::Scope::USER/ADMIN), or nil (requires secret)

Returns:



451
452
453
454
455
456
457
458
459
# File 'lib/aspera/plugins/aoc/commands.rb', line 451

def nodegen4_root(node_id, file_id: nil, scope: nil)
  node_api = aoc_api.node_api_from(
    node_id:        node_id,
    scope:          scope,
    **workspace_id_hash(name: true)
  )
  file_id = node_api.read("access_keys/#{node_api.app_info.node_info['access_key']}")['root_file_id'] if file_id.nil?
  [node_api, file_id]
end

#nodegen4_transfer(node_id, direction:, source_folder:, file_id: nil, scope: nil) ⇒ Result

Node-to-node transfer: client side is agent, server side is transfer server, in same workspace.

Parameters:

  • direction (Symbol) —

    :push or :pull

  • source_folder (String) —

    source folder

Returns:

  • (Result)


473
474
475
476
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
# File 'lib/aspera/plugins/aoc/commands.rb', line 473

def nodegen4_transfer(node_id, direction:, source_folder:, file_id: nil, scope: nil)
  top_node_api, file_id = nodegen4_root(node_id, file_id: file_id, scope: scope)
  case direction
  when :push
    client_direction = Aspera::Transfer::Spec::DIRECTION_SEND
    client_folder = source_folder
    server_folder = transfer.destination_folder(client_direction)
  when :pull
    client_direction = Aspera::Transfer::Spec::DIRECTION_RECEIVE
    client_folder = transfer.destination_folder(client_direction)
    server_folder = source_folder
  else Aspera.error_unexpected_value(direction) { 'direction' }
  end
  client_apifid = top_node_api.resolve_api_fid(file_id, client_folder)
  server_apifid = top_node_api.resolve_api_fid(file_id, server_folder)
  # force node as transfer agent
  transfer.agent_instance = Node::Agent.new(
    url:      client_apifid.node_api.base_url,
    username: client_apifid.node_api.app_info.node_info['access_key'],
    password: client_apifid.node_api.oauth.authorization,
    root_id:  client_apifid.file_id
  )
  # additional node to node TS info
  add_ts = {
    'remote_access_key'   => server_apifid.node_api.app_info.node_info['access_key'],
    'destination_root_id' => server_apifid.file_id,
    'source_root_id'      => client_apifid.file_id
  }
  Xfer::TransferAgent.result_transfer(transfer.start(server_apifid.node_api.transfer_spec_gen4(
    server_apifid.file_id,
    client_direction,
    add_ts
  )))
end

#package_node_plugin(package_id:) ⇒ Array(Node, Hash)

Used as instance: of the mount on packages: node of the package contents

Returns:



1184
1185
1186
1187
1188
1189
# File 'lib/aspera/plugins/aoc/commands.rb', line 1184

def package_node_plugin(package_id:, **)
  package_info = aoc_api.read("packages/#{package_id}")
  # An id that is not a single path segment (e.g. `/`) reads the list of packages
  Aspera.assert(package_info.is_a?(Hash), type: Cli::BadArgument) { "invalid package id: #{package_id}" }
  nodegen4_plugin(package_info['node_id'], file_id: package_info['contents_file_id'], scope: Node::Api::Scope::USER)
end

#package_persistency ⇒ PersistencyActionOnce?

Returns persistency object if option once_only is used.

Returns:



551
552
553
554
555
556
557
558
559
560
561
562
563
564
# File 'lib/aspera/plugins/aoc/commands.rb', line 551

def package_persistency
  return unless options.get_option(:once_only, mandatory: true)
  # TODO: add query info to id
  PersistencyActionOnce.new(
    manager: persistency,
    data: [],
    id: IdGenerator.from_list(
      'aoc_recv',
      options.get_option(:url, mandatory: true),
      aoc_api.workspace_info[:id],
      aoc_api.additional_persistence_ids
    )
  )
end

#reject_packages_from_persistency(all_packages, skip_ids_persistency) ⇒ Object



566
567
568
569
570
# File 'lib/aspera/plugins/aoc/commands.rb', line 566

def reject_packages_from_persistency(all_packages, skip_ids_persistency)
  return if skip_ids_persistency.nil?
  skip_package = skip_ids_persistency.data.to_h { |i| [i, true] }
  all_packages.reject! { |pkg| skip_package[pkg['id']] }
end

#remap_references(data, step_map, action_map) ⇒ Object

Replace the step and action identifiers of the manifest by the new ones, in all strings of data (action fields as well as substitutions[].template). One pass only: an identifier that was just replaced must not be replaced again.

Parameters:

  • data (Object) —

    Hash, Array, or scalar to copy

  • step_map (Hash) —

    manifest step reference => new step id

  • action_map (Hash) —

    manifest action reference => new action id

Returns:

  • (Object) —

    copy of data



1695
1696
1697
1698
1699
1700
1701
1702
1703
# File 'lib/aspera/plugins/aoc/commands.rb', line 1695

def remap_references(data, step_map, action_map)
  case data
  when Hash then data.transform_values { |v| remap_references(v, step_map, action_map) }
  when Array then data.map { |v| remap_references(v, step_map, action_map) }
  when String
    data.gsub(ACTION_OUTPUT_REFERENCE) { "step_id_#{step_map.fetch(Regexp.last_match(1), Regexp.last_match(1))}.action_id_#{action_map.fetch(Regexp.last_match(2), Regexp.last_match(2))}" }
  else data
  end
end

#resolve_dropbox_name_default_ws_id(query) ⇒ Object

Translates dropbox_name to dropbox_id and fills current workspace_id



408
409
410
411
412
413
414
415
416
417
418
# File 'lib/aspera/plugins/aoc/commands.rb', line 408

def resolve_dropbox_name_default_ws_id(query)
  if query.key?('dropbox_name')
    # convenience: specify name instead of id
    Aspera.assert(!query.key?('dropbox_id'), type: Cli::BadArgument) { 'Use field dropbox_name or dropbox_id, not both' }
    # TODO : craft a query that looks for dropbox only in current workspace
    query['dropbox_id'] = aoc_api.lookup_with_q('dropboxes', value: query.delete('dropbox_name'))['id']
  end
  workspace_id_hash(query, string: true)
  # by default show dropbox packages only for dropboxes
  query['exclude_dropbox_packages'] = !query.key?('dropbox_id') unless query.key?('exclude_dropbox_packages')
end

#resolve_sf_item(shared_folders:, shared_folder_id:) ⇒ Object Also known as: setup_admin_workspace_shared_folder_node, setup_admin_workspace_shared_folder_member

admin > workspace > shared_folder > node|member — shared_folder_id: already in ctx via arguments:(:identifier)

Raises:



1814
1815
1816
1817
1818
# File 'lib/aspera/plugins/aoc/commands.rb', line 1814

def resolve_sf_item(shared_folders:, shared_folder_id:, **)
  sf_item = shared_folders.find { |i| i['id'].eql?(shared_folder_id) }
  raise Cli::BadIdentifier.new('Shared folder', shared_folder_id) if sf_item.nil?
  {sf_item: sf_item}
end

#result_list(resource_class_path, fields: nil, base_query: {}, default_query: {}, query_component: nil, schema_path: nil) {|query| ... } ⇒ Object

List all entities, given additional, default and user's queries

Parameters:

  • resource_class_path (String) —

    path to query on API

  • fields (Array, nil) (defaults to: nil) —

    fields to display

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

    a query applied always

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

    default query unless overridden by user

  • query_component (String, nil) (defaults to: nil) —

    registry component key; when set, --query=help shows filter schema

  • schema_path (String, nil) (defaults to: nil) —

    path in the API description, when the REST path has identifiers (e.g. packages/{id}/download_counts)

Yield Parameters:

  • query (Hash) —

    The user's or default query for modification



374
375
376
377
378
379
380
381
382
383
# File 'lib/aspera/plugins/aoc/commands.rb', line 374

def result_list(resource_class_path, fields: nil, base_query: {}, default_query: {}, query_component: nil, schema_path: nil)
  Aspera.assert_type(base_query, Hash)
  Aspera.assert_type(default_query, Hash)
  qs_path = query_component ? Schema::Registry.query_params(query_component, schema_path || aoc_schema_path(resource_class_path)) : nil
  query = query_read_delete(default: default_query, schema: qs_path)
  # caller may add specific modifications or checks to query
  yield(query) if block_given?
  result = aoc_api.read_with_paging(resource_class_path, with_base_query(base_query, query).compact)
  return Cli::Result::ObjectList.new(result[:items], fields: fields, total: result[:total])
end

#setup_admin_scope ⇒ Object

admin - setup: change API scope to admin once



1392
1393
1394
1395
# File 'lib/aspera/plugins/aoc/commands.rb', line 1392

def setup_admin_scope(**)
  change_api_scope(Api::Scope::ADMIN)
  {}
end

#setup_admin_workspace_dropbox(workspace_id:) ⇒ Object

admin > workspace > dropbox — res_id: already in ctx via arguments:(:identifier)



1801
1802
1803
# File 'lib/aspera/plugins/aoc/commands.rb', line 1801

def setup_admin_workspace_dropbox(workspace_id:, **)
  {ws_res_id: workspace_id}
end

#setup_admin_workspace_shared_folder(workspace_id:) ⇒ Object

admin > workspace > shared_folder — res_id: already in ctx via arguments:(:identifier)



1806
1807
1808
1809
1810
1811
# File 'lib/aspera/plugins/aoc/commands.rb', line 1806

def setup_admin_workspace_shared_folder(workspace_id:, **)
  resource_instance_path = "#{aoc_res_path(:workspace)}/#{workspace_id}"
  query = query_read_delete(default: Api.workspace_access(workspace_id).merge({'admin' => true}))
  shared_folders = aoc_api.read_with_paging("#{resource_instance_path}/permissions", query)[:items]
  {ws_res_id: workspace_id, shared_folders: shared_folders}
end

#setup_automation_api ⇒ Object

Build automation API and store in @automation_api ivar.



1072
1073
1074
1075
1076
# File 'lib/aspera/plugins/aoc/commands.rb', line 1072

def setup_automation_api(**)
  change_api_scope(Api::Scope::ADMIN_USER)
  @automation_api = Rest::Client.new(**aoc_api.params, base_url: aoc_api.base_url.gsub('/api/', '/automation/'))
  {}
end

setup: files > short_link Resolves the target folder, sets purposes.

Returns:

  • (Hash) —

    ctx keys: shared_data, token_purpose, short_link_purpose, shared_apifid



1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
# File 'lib/aspera/plugins/aoc/commands.rb', line 1194

def setup_files_short_link(folder:, link_type:, **)
  home_node_api = aoc_api.node_api_from(
    node_id: aoc_api.home[:node_id],
    **workspace_id_hash(name: true)
  )
  shared_apifid = home_node_api.resolve_api_fid(aoc_api.home[:file_id], folder)
  shared_data = {
    node_id: shared_apifid.node_api.app_info.node_info['id'],
    file_id: shared_apifid.file_id
  }
  {
    shared_data:        shared_data,
    token_purpose:      'view_shared_file',
    short_link_purpose: SHORT_LINK_PURPOSES[link_type],
    shared_apifid:      shared_apifid
  }
end

setup: packages > shared_inboxes > short_link link_type: and dropbox_id: resolved via arguments: on the node, sets purposes.

Returns:

  • (Hash) —

    ctx keys: shared_data, token_purpose, short_link_purpose



1251
1252
1253
1254
1255
1256
1257
# File 'lib/aspera/plugins/aoc/commands.rb', line 1251

def setup_packages_short_link(link_type:, dropbox_id:, **)
  {
    shared_data:        {dropbox_id: dropbox_id, name: ''},
    token_purpose:      'send_package_to_dropbox',
    short_link_purpose: SHORT_LINK_PURPOSES[link_type]
  }
end

#setup_workspace_display ⇒ Object

Display workspace info before dispatching files/packages sub-commands. Returns {} so it does not inject anything into ctx.



1062
1063
1064
1065
1066
1067
1068
1069
# File 'lib/aspera/plugins/aoc/commands.rb', line 1062

def setup_workspace_display(**)
  formatter.display_status("Workspace: #{aoc_api.workspace_info[:name].to_s.red}#{' (default)' if aoc_api.default_workspace?}")
  if !aoc_api.private_link.nil?
    folder_name = aoc_api.node_api_from(node_id: aoc_api.home[:node_id]).read("files/#{aoc_api.home[:file_id]}")['name']
    formatter.display_status("Private Folder: #{folder_name}")
  end
  {}
end

Shared implementation for short_link > create



1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
# File 'lib/aspera/plugins/aoc/commands.rb', line 1260

def short_link_create(custom_data = {}, shared_data:, link_type:, token_purpose:, short_link_purpose:, **ctx)
  ws_shared_data = workspace_id_hash(shared_data.dup)
  create_payload = {purpose: short_link_purpose, user_selected_name: nil}
  case link_type
  when :private
    create_payload[:data] = ws_shared_data
  when :public
    create_payload[:expires_at]       = nil
    create_payload[:password_enabled] = false
    ws_shared_data[:name] = ''
    create_payload[:data] = {
      aoc:            true,
      url_token_data: {data: ws_shared_data, purpose: token_purpose}
    }
  end
  custom_data = custom_data.dup
  access_levels = custom_data.delete('access_levels')
  if (pass = custom_data.delete('password'))
    create_payload[:data][:url_token_data][:password] = pass
    create_payload[:password_enabled] = true
  end
  create_payload.deep_merge!(custom_data)
  result_create_short_link = aoc_api.create('short_links', create_payload)
  short_link_permission(:create, result_create_short_link['resource_id'], access_levels, **ctx) if link_type.eql?(:public) && ctx.key?(:shared_apifid)
  Cli::Result::SingleObject.new(result_create_short_link)
end

Shared implementation for short_link > delete



1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
# File 'lib/aspera/plugins/aoc/commands.rb', line 1298

def short_link_delete(ws_shared_data:, short_list:, link_type:, short_link_id: nil, **ctx)
  one_id = short_link_id
  if link_type.eql?(:public)
    found = short_list[:items].find { |item| item['id'].eql?(one_id) }
    raise Cli::BadIdentifier.new('Short link', one_id) if found.nil?
    short_link_permission(:delete, found['resource_id'], nil, **ctx) if ctx.key?(:shared_apifid)
  end
  # `edit_access` requires `file_id` and `node_id`: shared folder links only
  aoc_api.delete("short_links/#{one_id}", ({edit_access: true, json_query: ws_shared_data.to_json} if ctx.key?(:shared_apifid)))
  Cli::Result::Status.new('deleted')
end

Shared implementation for short_link > delete|list|show|modify: fetch the short_list



1288
1289
1290
1291
1292
1293
1294
1295
# File 'lib/aspera/plugins/aoc/commands.rb', line 1288

def short_link_fetch_list(shared_data:, **ctx)
  ws_shared_data = workspace_id_hash(shared_data.dup)
  list_params = short_link_list_params(shared_data: ws_shared_data, **ctx)
  {
    short_list:     aoc_api.read_with_paging('short_links', list_params.merge(query_read_delete(default: {}, schema: SHORT_LINK_QUERY_SCHEMA)).compact),
    ws_shared_data: ws_shared_data
  }
end

Shared implementation for short_link > list



1311
1312
1313
# File 'lib/aspera/plugins/aoc/commands.rb', line 1311

def short_link_list(short_list:, **)
  Cli::Result::ObjectList.new(short_list[:items], fields: Cli::Formatter.all_but('data'), total: short_list[:total])
end

Build the list_params hash used by delete/list/show/modify short link operations.

Returns:



537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/aspera/plugins/aoc/commands.rb', line 537

def short_link_list_params(shared_data:, link_type:, token_purpose:, short_link_purpose:, **ctx)
  query = if link_type.eql?(:private)
    shared_data
  else
    {url_token_data: {data: shared_data, purpose: token_purpose}}
  end
  # String keys: the user's `--query` overrides them
  list_params = {'json_query' => query.to_json, 'purpose' => short_link_purpose, 'sort' => '-created_at'}
  # `edit_access` requires `file_id` and `node_id`: shared folder links only
  list_params['edit_access'] = true if ctx.key?(:shared_apifid)
  list_params
end

Shared implementation for short_link > modify



1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
# File 'lib/aspera/plugins/aoc/commands.rb', line 1324

def short_link_modify(custom_data = {}, shared_data:, short_list:, link_type:, short_link_id: nil, **ctx)
  Aspera.assert_values(link_type, [:public], type: Cli::BadArgument) { 'link_type' }
  one_id = short_link_id
  # Identifies the shared resource: `node_id` and `file_id`, or `dropbox_id`
  token_data = shared_data.except(:name)
  # `edit_access` requires `file_id` and `node_id`: shared folder links only
  modify_payload = ctx.key?(:shared_apifid) ? {edit_access: true, json_query: token_data} : {}
  custom_data = custom_data.dup
  if (pass = custom_data.delete('password'))
    modify_payload[:password_enabled] = true
    modify_payload[:data] = {url_token_data: {password: pass, data: token_data}}
  else
    modify_payload[:password_enabled] = false
  end
  if (access_levels = custom_data.delete('access_levels'))
    found = short_list[:items].find { |item| item['id'].eql?(one_id) }
    raise Cli::BadIdentifier.new('Short link', one_id) if found.nil?
    short_link_permission(:update, found['resource_id'], access_levels, **ctx) if ctx.key?(:shared_apifid)
  end
  modify_payload.deep_merge!(custom_data)
  aoc_api.update("short_links/#{one_id}", modify_payload)
  Cli::Result::Status.new('modified')
end

Node permission of a public short link on the shared folder (files > short_link only)

Parameters:

  • op (Symbol) —

    :create, :update or :delete

  • id (String) —

    Short link resource id: access_id of the permission

  • access_levels (String, Array, nil) —

    Access levels for :create and :update



1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
# File 'lib/aspera/plugins/aoc/commands.rb', line 1216

def short_link_permission(op, id, access_levels, shared_apifid:, folder:, **)
  case op
  when :create
    perm_data = {
      'file_id'       => shared_apifid.file_id,
      'access_id'     => id,
      'access_type'   => 'user',
      'access_levels' => Api.expand_access_levels(access_levels),
      'tags'          => {
        'url_token'        => true,
        'folder_name'      => File.basename(folder),
        'created_by_name'  => aoc_api.['name'],
        'created_by_email' => aoc_api.['email'],
        'access_key'       => shared_apifid.node_api.app_info.node_info['access_key'],
        'node'             => shared_apifid.node_api.app_info.node_info['name'],
        **workspace_id_hash(string: true, name: true)
      }
    }
    created_data = shared_apifid.node_api.create('permissions', perm_data)
    aoc_api.permissions_send_event(event_data: created_data, app_info: shared_apifid.node_api.app_info)
  when :update
    found = shared_apifid.node_api.read('permissions', {file_id: shared_apifid.file_id, inherited: false, access_type: 'user', access_id: id}).find { |i| i['access_id'].eql?(id) }
    Aspera.assert(!found.nil?, type: Cli::Error) { "Short link not found: #{id}" }
    shared_apifid.node_api.update("permissions/#{found['id']}", {access_levels: Api.expand_access_levels(access_levels)})
  when :delete
    found = shared_apifid.node_api.read('permissions', {file_id: shared_apifid.file_id, inherited: false, access_type: 'user', access_id: id}).first
    Aspera.assert(!found.nil?, type: Cli::Error) { "Short link not found: #{id}" }
    shared_apifid.node_api.delete("permissions/#{found['id']}")
  else Aspera.error_unexpected_value(op)
  end
end

Shared implementation for short_link > show

Raises:



1316
1317
1318
1319
1320
1321
# File 'lib/aspera/plugins/aoc/commands.rb', line 1316

def short_link_show(short_list:, short_link_id: nil, **)
  one_id = short_link_id
  found = short_list[:items].find { |item| item['id'].eql?(one_id) }
  raise Cli::BadIdentifier.new('Short link', one_id) if found.nil?
  Cli::Result::SingleObject.new(found, fields: Cli::Formatter.all_but('data'))
end

#with_base_query(base_query, query) ⇒ Hash

Query of a command: the parameters that it sets (e.g. the identifier of its argument) cannot be changed by the query of the user

Parameters:

  • base_query (Hash) —

    Parameters set by the command

  • query (Hash, nil) —

    Query of the user (option query), or default query

Returns:

  • (Hash) —

    Both, with String keys: for a parameter with several values (name ending with [], e.g. embed[]), the values of the user are added

Raises:

  • (Cli::BadArgument) —

    If the query of the user gives another value to a parameter set by the command



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/aspera/plugins/aoc/commands.rb', line 390

def with_base_query(base_query, query)
  result = base_query.transform_keys(&:to_s)
  return result if query.nil?
  Aspera.assert_type(query, Hash, type: Cli::BadArgument) { 'query' }
  query.each do |key, value|
    key = key.to_s
    if !result.key?(key) || result[key].eql?(value)
      result[key] = value
    elsif key.end_with?('[]')
      result[key] = (Array(result[key]) + Array(value)).uniq
    else
      raise Cli::BadArgument, "query: parameter #{key} is set by the command (#{result[key]}): remove it from option query"
    end
  end
  result
end

#wizard(wizard, app_url) ⇒ Hash

Returns :preset_value, :test_args.

Parameters:

Returns:

  • (Hash) —

    :preset_value, :test_args



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
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
# File 'lib/aspera/plugins/aoc/commands.rb', line 192

def wizard(wizard, app_url)
  pub_link_info = Api.link_info(app_url)
  # public link case
  if pub_link_info.key?(:token)
    pub_api = Rest::Client.new(base_url: "https://#{URI.parse(pub_link_info[:url]).host}/api/v1")
    pub_info = pub_api.read('env/url_token_check', {token: pub_link_info[:token]})
    preset_value = {
      link: app_url
    }
    preset_value[:password] = options.get_option(:password, mandatory: true) if pub_info['password_protected']
    return {
      preset_ids:   [],
      preset_value: preset_value,
      test_args:    'organization'
    }
  end
  # make username mandatory for jwt, this triggers interactive input
  wiz_username = options.get_option(:username, mandatory: true)
  wizard.check_email(wiz_username)
  # Set the pub key and jwt tag in the user's profile automatically
  auto_set_pub_key = false
  auto_set_jwt = false
  # use browser authentication to bootstrap
  use_browser_authentication = false
  private_key = wizard.ask_private_key(
    user: wiz_username,
    url: app_url,
    page: [Environment.char('👤'), 'Account Settings', 'Profile', 'Public Key']
  )
  client_id = options.get_option(:client_id)
  client_secret = options.get_option(:client_secret)
  if client_id.nil? || client_secret.nil?
    use_generic_client = options.get_option(:use_generic_client)
    # Default depends on URL
    use_generic_client = Api.saas_url?(app_url) if use_generic_client.nil?
    if use_generic_client
      client_id = client_secret = nil
      formatter.display_status('Using global client_id.')
    else
      formatter.display_status('Using organization specific client_id.')
      formatter.display_status('Please login to your Aspera on Cloud instance.'.red)
      wizard.display_navigation(Environment.char('𓃑'), 'Admin', 'Integrations', 'API Clients')
      formatter.display_status('Check or create in integration:')
      formatter.display_status('- name: cli')
      formatter.display_status("- redirect uri: #{REDIRECT_LOCALHOST}")
      formatter.display_status('- origin: localhost')
      formatter.display_status('Use the generated client id and secret in the following prompts.'.red)
      Environment.instance.open_uri("#{app_url}/admin/integrations/api-clients")
      client_id = options.get_option(:client_id, mandatory: wizard.required)
      client_secret = options.get_option(:client_secret, mandatory: wizard.required)
      # use_browser_authentication = true
    end
  end
  if use_browser_authentication
    formatter.display_status('We will use web authentication to bootstrap.')
    auto_set_pub_key = true
    auto_set_jwt = true
    Aspera.error_not_implemented
    # aoc_api.oauth.grant_method = :web
    # aoc_api.oauth.scope = Api::Scope::ADMIN
    # aoc_api.oauth.specific_parameters[:redirect_uri] = REDIRECT_LOCALHOST
  end
  myself = aoc_api.read('self')
  if auto_set_pub_key
    Aspera.assert(myself['public_key'].empty?, 'Public key is already set in profile (use wizard key override=yes)', type: Cli::Error) unless option_override
    formatter.display_status('Updating profile with the public key.')
    aoc_api.update("users/#{myself['id']}", {'public_key' => pub_key_pem})
  end
  if auto_set_jwt
    formatter.display_status('Enabling JWT for client')
    aoc_api.update("clients/#{options.get_option(:client_id)}", {'jwt_grant_enabled' => true, 'explicit_authorization_required' => false})
  end
  return {
    preset_ids:   [myself['email'], client_id].compact,
    preset_value: {
      url:           app_url,
      username:      myself['email'],
      auth:          :jwt.to_s,
      private_key:   private_key,
      client_id:     client_id,
      client_secret: client_secret
    }.compact,
    test_args:    'user profile show'
  }
end

#workflow_details(workflow_id) ⇒ Object



1579
1580
1581
1582
1583
1584
1585
1586
1587
# File 'lib/aspera/plugins/aoc/commands.rb', line 1579

def workflow_details(workflow_id)
  workflow = @automation_api.read("workflows/#{workflow_id}")
  steps = Array(workflow['step_order']).map do |step_id|
    step = @automation_api.read("steps/#{step_id}")
    actions = Array(step['action_order']).map { |action_id| @automation_api.read("actions/#{action_id}") }
    step.merge('actions' => actions)
  end
  workflow.merge('steps' => steps)
end

#workflow_duplicate(workflow_id, new_name: nil) ⇒ Object

The copy is made by the server: the API does not return secrets (tokens, passwords), so an export/import would lose them.



1679
1680
1681
1682
# File 'lib/aspera/plugins/aoc/commands.rb', line 1679

def workflow_duplicate(workflow_id, new_name: nil)
  new_name ||= @automation_api.read("workflows/#{workflow_id}/default_copy_name")['default_copy_name']
  @automation_api.create("workflows/#{workflow_id}/copy", {'name' => new_name})
end

#workflow_export_data(workflow_id) ⇒ Object



1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
# File 'lib/aspera/plugins/aoc/commands.rb', line 1589

def workflow_export_data(workflow_id)
  wf = workflow_details(workflow_id)
  portable_steps = Array(wf['steps']).each_with_index.map do |step, step_idx|
    portable_actions = Array(step['actions']).each_with_index.map do |action, act_idx|
      action_data = action.dup
      orig_action_id = action_data.delete('id')
      action_data.delete('step_id')
      action_data.delete('created_at')
      action_data.delete('updated_at')
      action_data.delete('user_id')
      action_data.delete('organization_id')
      {
        'ref_id' => orig_action_id || "action_#{step_idx + 1}_#{act_idx + 1}",
        'name'   => action_data['name'],
        'type'   => action_data['type'],
        'data'   => action_data['data']
      }.compact
    end
    orig_step_id = step['id']
    {
      'ref_id'  => orig_step_id || "step_#{step_idx + 1}",
      'name'    => step['name'],
      'actions' => portable_actions
    }.compact
  end
  {
    'name'                   => wf['name'],
    'trigger_type'           => wf['trigger_type'] || 'manual',
    'allow_notifications'    => wf['allow_notifications'] || false,
    'workflow_notifications' => wf['workflow_notifications'] || {},
    'steps'                  => portable_steps
  }
end

#workflow_import_data(manifest) ⇒ Object

Raises:



1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
# File 'lib/aspera/plugins/aoc/commands.rb', line 1623

def workflow_import_data(manifest)
  raise Cli::BadArgument, 'Manifest must be a Hash' unless manifest.is_a?(Hash)
  wf_params = {
    'name'                   => manifest['name'] || 'Imported Workflow',
    'trigger_type'           => manifest['trigger_type'] || 'manual',
    'allow_notifications'    => manifest['allow_notifications'] || false,
    'workflow_notifications' => manifest['workflow_notifications'] || {}
  }
  new_wf = @automation_api.create('workflows', wf_params)
  wf_id = new_wf['id']

  step_id_map = {}
  action_id_map = {}
  created_step_ids = []

  begin
    Array(manifest['steps']).each_with_index do |step_data, s_idx|
      step_name = step_data['name'] || "Step #{s_idx + 1}"
      old_step_ref = step_data['ref_id'] || step_data['id'] || "step_#{s_idx + 1}"
      new_step = @automation_api.create('steps', {'workflow_id' => wf_id, 'name' => step_name})
      new_step_id = new_step['id']
      step_id_map[old_step_ref] = new_step_id
      created_step_ids << new_step_id
      # The API refuses an action whose step is not yet in the workflow
      @automation_api.update("workflows/#{wf_id}", {'step_order' => created_step_ids})

      created_action_ids = []
      Array(step_data['actions']).each_with_index do |action_data, a_idx|
        old_action_ref = action_data['ref_id'] || action_data['id'] || "action_#{s_idx + 1}_#{a_idx + 1}"
        action_payload = {
          'step_id' => new_step_id,
          'name'    => action_data['name'] || (s_idx.zero? && a_idx.zero? ? 'Trigger' : "Action #{a_idx + 1}"),
          'type'    => action_data['type'] || 'manual',
          'data'    => remap_references(action_data['data'] || {}, step_id_map, action_id_map)
        }
        new_act = @automation_api.create('actions', action_payload)
        new_act_id = new_act['id']
        action_id_map[old_action_ref] = new_act_id
        created_action_ids << new_act_id
      end
      @automation_api.update("steps/#{new_step_id}", {'action_order' => created_action_ids})
    end
  rescue StandardError
    # do not leave a partial workflow behind
    begin
      @automation_api.delete("workflows/#{wf_id}")
    rescue StandardError => e
      Log.log.warn { "Could not delete partial workflow #{wf_id}: #{e.message}" }
    end
    raise
  end

  workflow_details(wf_id)
end

#workflow_instance_find(instance_id) ⇒ Hash

Get one job. GET workflow_instances/<id> does not answer on the server (the job is searched without an index on instance_id), so use the list, which does. The search string q matches the UUID (instance_id) but not the numeric identifier: in this case, browse the list.

Parameters:

  • instance_id (String) —

    Numeric identifier or UUID of the job

Returns:

  • (Hash) —

    The job



1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
# File 'lib/aspera/plugins/aoc/commands.rb', line 1563

def workflow_instance_find(instance_id)
  instance_id = instance_id.to_s
  is_uuid = instance_id.include?('-')
  limit = 1000
  offset = 0
  loop do
    query = {'limit' => limit, 'offset' => offset, 'sort' => '-state_change_time'}
    query['q'] = instance_id if is_uuid
    page = @automation_api.read('workflow_instances', query)
    found = page['workflow_instances'].find { |job| job[is_uuid ? 'instance_id' : 'id'].eql?(instance_id) }
    return found unless found.nil?
    offset += limit
    raise Cli::BadIdentifier.new('Workflow instance', instance_id) if is_uuid || offset >= page['total_count'].to_i
  end
end

#workspace_id_hash(hash = nil, string: false, name: false) ⇒ Hash{Symbol, String => String}

Note:

The key type (String or Symbol) depends on the string parameter.

Generate or update Hash with workspace id and name (option), if not already set

Parameters:

  • hash (Hash, nil) (defaults to: nil) —

    Optional base Hash (modified)

  • string (Boolean) (defaults to: false) —

    true to set key as String, else as Symbol

  • name (Boolean) (defaults to: false) —

    Include name

Returns:

  • (Hash{Symbol, String => String}) —

    the modified hash containing:

    • workspace_id [String] the unique identifier.
    • workspace_name [String] (optional) the name, included if name is true.


353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/aspera/plugins/aoc/commands.rb', line 353

def workspace_id_hash(hash = nil, string: false, name: false)
  info = aoc_api.workspace_info
  hash = {} if hash.nil?
  fields = %i[id]
  fields.push(:name) if name
  fields.each do |i|
    k = "workspace_#{i}"
    k = k.to_sym unless string
    hash[k] = info[i] unless info[i].nil? || hash.key?(k)
  end
  return hash
end