diff --git a/app/services/aircraft_archive/importer.rb b/app/services/aircraft_archive/importer.rb index 9a4ee83..7ca6a9c 100644 --- a/app/services/aircraft_archive/importer.rb +++ b/app/services/aircraft_archive/importer.rb @@ -28,13 +28,31 @@ module AircraftArchive counts: RECORD_SECTIONS.to_h { [ _1, Array(manifest[_1]).size ] }) end - def self.with_zip(path) + # Opens the archive. A records package (Access & Sharing) carries the + # .sam.zip inside it, so that inner archive is opened instead. + def self.with_zip(path, &) Zip.validate_entry_sizes = true # a lying size header raises instead of inflating forever - Zip::File.open(path) { |zip| yield zip } + Zip::File.open(path) do |zip| + inner = nested_archive(zip) + next yield(zip) unless inner + raise Error, "The archive inside the records package is too large." if inner.size > ARCHIVE_MAX_BYTES + Tempfile.create([ "sam-inner", ".zip" ], binmode: true) do |tmp| + inner.get_input_stream { |io| IO.copy_stream(io, tmp) } + tmp.flush + Zip::File.open(tmp.path, &) + end + end rescue Zip::Error => e raise Error, "Not a valid .sam.zip archive (#{e.message})" end + # The single *.sam.zip entry of a records package (no manifest of its own). + def self.nested_archive(zip) + return if zip.find_entry("manifest.json") || root_prefix(zip).present? + candidates = zip.entries.reject { _1.name.start_with?("__MACOSX/") }.select { _1.name.match?(%r{\A([^/]+/)?[^/]+\.sam\.zip\z}) } + candidates.first if candidates.one? + end + # "" normally; "folder/" when everything sits in one folder, as when a # browser unzipped the download and the folder was zipped again (Finder's # Compress adds that folder, and a __MACOSX folder that's ignored). diff --git a/test/integration/aircraft_archive_flow_test.rb b/test/integration/aircraft_archive_flow_test.rb index 2287559..a53d9e1 100644 --- a/test/integration/aircraft_archive_flow_test.rb +++ b/test/integration/aircraft_archive_flow_test.rb @@ -41,6 +41,14 @@ class AircraftArchiveFlowTest < ActionDispatch::IntegrationTest assert_equal "Aircraft exported (.sam.zip)", @a.events.last.event_name end + test "a records package imports from the .sam.zip inside it" do + package = File.join(Dir.mktmpdir, "n12345-records.zip") + RecordsPackage.new(@a, source: "test").write_to(package) + assert_equal "N12345", AircraftArchive::Importer.check(package).tail_number + copy = AircraftArchive::Importer.new(package, owner: @owner, tail_number: "N54321").run[:aircraft] + assert_equal @a.logbook_entries.count, copy.logbook_entries.count + end + test "an archive re-zipped from an unzipped folder still imports" do sign_in @owner path = download_export