Method: OpenC3::TargetModel.download

Defined in:
lib/openc3/models/target_model.rb

.download(target_name, scope:) ⇒ Object



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
# File 'lib/openc3/models/target_model.rb', line 162

def self.download(target_name, scope:)
  tmp_dir = Dir.mktmpdir
  zip_filename = File.join(tmp_dir, "#{target_name}.zip")
  Zip.continue_on_exists_proc = true
  zip = Zip::File.open(zip_filename, Zip::File::CREATE)

  if ENV['OPENC3_LOCAL_MODE']
    OpenC3::LocalMode.zip_target(target_name, zip, scope: scope)
  else
    bucket = Bucket.getClient()
    # The trailing slash is important!
    prefix = "#{scope}/targets_modified/#{target_name}/"
    resp = bucket.list_objects(
      bucket: ENV['OPENC3_CONFIG_BUCKET'],
      prefix: prefix,
    )
    resp.each do |item|
      # item.key looks like DEFAULT/targets_modified/INST/screens/blah.txt
      base_path = item.key.sub(prefix, '') # remove prefix
      local_path = File.join(tmp_dir, base_path)
      # Ensure dir structure exists, get_object fails if not
      FileUtils.mkdir_p(File.dirname(local_path))
      bucket.get_object(bucket: ENV['OPENC3_CONFIG_BUCKET'], key: item.key, path: local_path)
      zip.add(base_path, local_path)
    end
  end
  zip.close

  result = OpenStruct.new
  result.filename = File.basename(zip_filename)
  result.contents = File.read(zip_filename, mode: 'rb')
  return result
end