spatial_features 3.12.0 → 3.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 992823b144d43f8a6c13f32ce0fbd71bb6bea5bafb1aadb7840767f18d2a8d9f
4
- data.tar.gz: 45397ed799db69896d94a48e8c3958ab7026420587e9dd1a4755fe57a650132f
3
+ metadata.gz: 913e169e0e0111010984baffd6b6c71abf1ff3e69c2c4ac53bc22b7ade73de53
4
+ data.tar.gz: 8d820f9647554da9ffb9375791b8af06bb34161a899c174384b20fa0689503d7
5
5
  SHA512:
6
- metadata.gz: 9a9c533b9af654d339344dee13b62f14becf6e2c20fdd57868bfe5c185a5bede4657d130a6c9049d0557b274c1ed2a4a7cd70a8b826c3548824ed4b7bf7df76c
7
- data.tar.gz: 7a9d9ecdd4f65b01e2cc3c0558ca3699205ecf783617e2adcd4958ca2639dd8240a99b883f1567199ce34ca5a3aad4d5bee4804902c9dddc3cf7e38690015fa5
6
+ metadata.gz: d6f00c46d859fdb79152cea1093f879839ac904881a3185f1b7e92224f85a96c70c3ac97f1669d9ba88b542f9234d4d68c29ac5ad6a8550f82a6717eae2710dc
7
+ data.tar.gz: e86855a339d86efe32f0d2daa10a432d781b730bc1bce57f4da4aaf4851993f0f15b4d2d90a8f692718f6f34fd1722c48db628a3b4b6cddfaf2722e37859c96d
@@ -6,22 +6,68 @@ class AggregateFeature < AbstractFeature
6
6
  # Aggregate the features for the spatial model into a single feature
7
7
  before_validation :set_geog, on: :create, unless: :geog?
8
8
 
9
- private
9
+ # Replaces the spatial model's aggregate with a new one built from its features. The database
10
+ # builds and stores the new geometry, so neither the old aggregate nor the new one is sent to
11
+ # Ruby, however large it is. The new aggregate has a new id, so its cache key changes.
12
+ #
13
+ # @param spatial_model_type [String] the type the model's features are stored under
14
+ # @param spatial_model_id [Integer]
15
+ # @return [Integer] the id of the new aggregate. Its geometry is an empty `MULTIPOLYGON` when
16
+ # the model has no features.
17
+ # @raise [ActiveRecord::RecordInvalid] when the new geometry is not valid. The old aggregate
18
+ # is kept.
19
+ def self.refresh(spatial_model_type, spatial_model_id)
20
+ transaction(requires_new: true) do
21
+ unscoped.where(spatial_model_type: spatial_model_type, spatial_model_id: spatial_model_id).delete_all
10
22
 
11
- def set_geog
12
- feature_array_sql = <<~SQL
13
- ARRAY[
14
- (#{features.select('ST_UNION(ST_CollectionExtract(geog::geometry, 1))').to_sql}),
15
- (#{features.select('ST_UNION(ST_CollectionExtract(geog::geometry, 2))').to_sql}),
16
- (#{features.select('ST_UNION(ST_CollectionExtract(geog::geometry, 3))').to_sql})
17
- ]
18
- SQL
23
+ id = connection.select_value(sanitize_sql_array([<<~SQL, sti_name, spatial_model_type, spatial_model_id]))
24
+ INSERT INTO #{quoted_table_name} (type, spatial_model_type, spatial_model_id, geog)
25
+ SELECT ?, ?, ?, #{union_sql(spatial_model_type, spatial_model_id)}
26
+ RETURNING id
27
+ SQL
19
28
 
20
- # Remove empty features so ST_COLLECT doesn't choke. This seems to be a difference between PostGIS 2.x and 3.x
21
- self.geog = SpatialFeatures::Utils.select_db_value <<~SQL
22
- SELECT COALESCE(ST_Collect(unnest)::geography, ST_GeogFromText('MULTIPOLYGON EMPTY'))
23
- FROM (SELECT unnest(#{feature_array_sql})) AS features
24
- WHERE NOT ST_IsEmpty(unnest)
29
+ validate_stored_geometry!(id)
30
+ unscoped.where(id: id).cache_derivatives if automatically_cache_derivatives?
31
+ id
32
+ end
33
+ end
34
+
35
+ # Returns a SQL expression for the union of the spatial model's features: the points, lines
36
+ # and polygons each unioned, then collected as a 2D geography. A geometry several features
37
+ # share is unioned once. The union's cost grows with the square of the copies of a line, so
38
+ # a few hundred identical lines can take gigabytes of memory to union and one takes none.
39
+ #
40
+ # @param spatial_model_type [String] the type the model's features are stored under
41
+ # @param spatial_model_id [Integer]
42
+ # @return [String] an expression evaluating to an empty `MULTIPOLYGON` when the model has no
43
+ # features.
44
+ def self.union_sql(spatial_model_type, spatial_model_id)
45
+ features = Feature.unscoped.where(spatial_model_type: spatial_model_type, spatial_model_id: spatial_model_id)
46
+ parts = [1, 2, 3].map {|type| "(#{features.select("ST_Union(DISTINCT ST_CollectionExtract(geog::geometry, #{type}))").to_sql})" }
47
+
48
+ # Remove empty parts so ST_Collect doesn't choke. This seems to be a difference between PostGIS 2.x and 3.x
49
+ <<~SQL
50
+ (SELECT COALESCE(ST_Force2D(ST_Collect(part))::geography, ST_GeogFromText('MULTIPOLYGON EMPTY'))
51
+ FROM unnest(ARRAY[#{parts.join(', ')}]) AS part
52
+ WHERE NOT ST_IsEmpty(part))
25
53
  SQL
26
54
  end
55
+ private_class_method :union_sql
56
+
57
+ # Raises when the stored aggregate's geometry is not valid, as saving an invalid one would.
58
+ def self.validate_stored_geometry!(id)
59
+ reason = unscoped.where(id: id).where.not('ST_IsValid(geog::geometry)').pick(Arel.sql('ST_IsValidReason(geog::geometry)'))
60
+ return unless reason
61
+
62
+ record = new
63
+ record.errors.add(:geog, reason)
64
+ raise ActiveRecord::RecordInvalid, record
65
+ end
66
+ private_class_method :validate_stored_geometry!
67
+
68
+ private
69
+
70
+ def set_geog
71
+ self.geog = SpatialFeatures::Utils.select_db_value("SELECT #{self.class.send(:union_sql, spatial_model_type, spatial_model_id)}")
72
+ end
27
73
  end
@@ -46,8 +46,10 @@ class Feature < AbstractFeature
46
46
  end
47
47
 
48
48
  def refresh_aggregate
49
- aggregate_feature&.destroy # Destroy the existing aggregate feature to ensure its cache key changes when it is refreshed
50
- create_aggregate_feature!
49
+ # Neither aggregate is read, because one can be larger than PostgreSQL will send to a client.
50
+ # The association is reset, so the new aggregate is loaded only when it is next asked for.
51
+ AggregateFeature.refresh(spatial_model_type, spatial_model_id)
52
+ association(:aggregate_feature).reset
51
53
  end
52
54
 
53
55
  def automatically_refresh_aggregate?
@@ -34,17 +34,19 @@ module SpatialFeatures
34
34
  fetch(path_or_url).read
35
35
  end
36
36
 
37
- # Returns an open File for each source in `path_or_url`, unwrapping an archive when
37
+ # Returns an open file for each source in `path_or_url`, unwrapping an archive when
38
38
  # `unzip` is given a pattern its entries can match.
39
+ #
40
+ # @note A remote or IO-backed source is held in a `Tempfile`, which unlinks its path
41
+ # when it is garbage collected. The `Tempfile` itself is returned, rather than a fresh
42
+ # `File` opened on its path, so the path stays valid for as long as the caller holds
43
+ # the result. Entries extracted from an archive are ordinary files on disk and are
44
+ # opened by path.
39
45
  def open_each(path_or_url, unzip: nil, **unzip_options)
40
46
  file = Download.open(path_or_url)
41
- files = if unzip && Unzip.is_zip?(file)
42
- find_in_zip(file, find: unzip, **unzip_options)
43
- else
44
- [file]
45
- end
47
+ return [file] unless unzip && Unzip.is_zip?(file)
46
48
 
47
- return files.map { |f| File.open(f) }
49
+ find_in_zip(file, find: unzip, **unzip_options).map { |path| File.open(path) }
48
50
  end
49
51
 
50
52
  def normalize_file(file)
@@ -10,6 +10,9 @@ module SpatialFeatures
10
10
  # method failed. Any per-file reasons are appended after it.
11
11
  EMPTY_IMPORT_MESSAGE = "No mapped areas could be imported.".freeze
12
12
 
13
+ # For a source whose records were all read but none could be saved.
14
+ NOTHING_IMPORTABLE_MESSAGE = "None of the mapped areas in this file could be imported.".freeze
15
+
13
16
  included do
14
17
  extend ActiveModel::Callbacks
15
18
  define_model_callbacks :update_features
@@ -28,14 +31,33 @@ module SpatialFeatures
28
31
  options = options.reverse_merge(spatial_features_options)
29
32
  tmpdir = options.fetch(:tmpdir) { Dir.mktmpdir("ruby_spatial_features") }
30
33
 
31
- ActiveRecord::Base.transaction do
34
+ # A transaction of its own, so a failed import rolls back its own deletes even when
35
+ # the caller's transaction rescues the failure and goes on to commit. Joined to the
36
+ # caller's transaction instead, those deletes would commit with it.
37
+ ActiveRecord::Base.transaction(requires_new: true) do
32
38
  imports = spatial_feature_imports(options[:import], options[:make_valid], tmpdir)
33
39
  cache_key = Digest::MD5.hexdigest(imports.collect(&:cache_key).join)
34
40
 
35
41
  return if !force && features_cache_key_matches?(cache_key)
36
42
 
37
43
  run_callbacks :update_features do
38
- features = import_features(imports, skip_invalid)
44
+ new_features = imports.flat_map {|import| features_from(import) }
45
+
46
+ # Attribute each warning to the file it came from (e.g. `archive.zip/layer.kml`)
47
+ # so a multi-file or multi-source import makes clear which file was affected.
48
+ import_warnings = imports.flat_map do |import|
49
+ import.warnings.map {|warning| [import.source_identifier.presence, warning].compact.join(': ') }
50
+ end
51
+
52
+ # Decided before anything is deleted or assigned, so the record is left as it was,
53
+ # in the database and in memory. `allow_blank` accepts a source that was read and
54
+ # holds no features; a source that could not be read says nothing about what it
55
+ # holds, so the record keeps its features and its cache key until it can be read.
56
+ if imports.present? && new_features.empty? && imports.any?(&:unreadable?)
57
+ raise ImportError, [EMPTY_IMPORT_MESSAGE, *import_warnings].join(' ')
58
+ end
59
+
60
+ features = import_features(new_features, imports, skip_invalid)
39
61
  update_features_cache_key(cache_key)
40
62
  update_features_area
41
63
 
@@ -45,11 +67,6 @@ module SpatialFeatures
45
67
  update_spatial_cache(options.slice(:spatial_cache))
46
68
  end
47
69
 
48
- # Attribute each warning to the file it came from (e.g. `archive.zip/layer.kml`)
49
- # so a multi-file or multi-source import makes clear which file was affected.
50
- import_warnings = imports.flat_map do |import|
51
- import.warnings.map {|warning| [import.source_identifier.presence, warning].compact.join(': ') }
52
- end
53
70
  store_feature_update_warnings(import_warnings)
54
71
 
55
72
  if imports.present? && features.compact_blank.empty? && !allow_blank
@@ -149,11 +166,13 @@ module SpatialFeatures
149
166
  handler_name.to_s.constantize
150
167
  end
151
168
 
152
- def import_features(imports, skip_invalid)
169
+ # Replaces the record's features with `new_features`, the unsaved features read from
170
+ # `imports`. Returns the ones that saved.
171
+ def import_features(new_features, imports, skip_invalid)
153
172
  features.delete_all
154
173
  valid, invalid = Feature.defer_aggregate_refresh do
155
174
  Feature.without_caching_derivatives do
156
- imports.flat_map {|import| features_from(import) }.partition do |feature|
175
+ new_features.partition do |feature|
157
176
  feature.spatial_model = self
158
177
  if feature.save
159
178
  handle_images(feature)
@@ -191,9 +210,19 @@ module SpatialFeatures
191
210
  # shapefile archive missing its `.shx`), so they need the same containment as a file
192
211
  # that couldn't be opened at all: record the reason against that source and keep going.
193
212
  def features_from(import)
194
- import.features
213
+ features = import.features
214
+ # A source that yielded nothing has to say so, or the file disappears from an otherwise
215
+ # successful import. Importers that know why (a KML holding only an empty folder) have
216
+ # already said something more specific. A source whose every record errored fails the
217
+ # import unless `skip_invalid` is set, in which case the errors are only logged, so it
218
+ # is named here too.
219
+ if features.compact_blank.empty? && import.warnings.empty?
220
+ import.warnings << (import.errors.any? ? NOTHING_IMPORTABLE_MESSAGE : Importers::File::INVALID_ARCHIVE)
221
+ end
222
+ features
195
223
  rescue ImportError => e
196
224
  import.warnings << e.message
225
+ import.unreadable!
197
226
  []
198
227
  end
199
228
 
@@ -11,7 +11,10 @@ module SpatialFeatures
11
11
  include FeatureImport
12
12
 
13
13
  has_many :features, lambda { extending FeaturesAssociationExtensions }, as: :spatial_model, dependent: :delete_all
14
- has_one :aggregate_feature, lambda { extending FeaturesAssociationExtensions }, as: :spatial_model, dependent: :delete
14
+ has_one :aggregate_feature, lambda { extending FeaturesAssociationExtensions }, as: :spatial_model
15
+
16
+ # Avoid loading large geometry just to delete the aggregate.
17
+ before_destroy { aggregate_features.delete_all }
15
18
 
16
19
  scope :with_features, lambda { joins(:features).distinct }
17
20
  scope :without_features, lambda { joins("LEFT OUTER JOIN features ON features.spatial_model_type = '#{Utils.base_class(name)}' AND features.spatial_model_id = #{table_name}.id").where("features.id IS NULL") }
@@ -30,6 +30,17 @@ module SpatialFeatures
30
30
  @cache_key ||= Digest::MD5.hexdigest(@data)
31
31
  end
32
32
 
33
+ # True when the source could not be read at all, as distinct from read and found to
34
+ # hold no features. `FeatureImport#update_features!` never treats an import whose
35
+ # source is unreadable as legitimately empty.
36
+ def unreadable?
37
+ @unreadable == true
38
+ end
39
+
40
+ def unreadable!
41
+ @unreadable = true
42
+ end
43
+
33
44
  # factory method that should always be used instead of `new` when creating importers
34
45
  # returns an array of Importer::* objects
35
46
  def self.create_all(data, **options)
@@ -75,4 +86,6 @@ module SpatialFeatures
75
86
  class ImportError < StandardError; end
76
87
  class ImportEncodingError < ImportError; end
77
88
  class EmptyImportError < ImportError; end
89
+ # Raised by `Validation.validate_spatial_data!` for an upload that holds nothing to import.
90
+ class EmptyFileError < ImportError; end
78
91
  end
@@ -0,0 +1,69 @@
1
+ require 'exifr/jpeg'
2
+ require 'ostruct'
3
+
4
+ module SpatialFeatures
5
+ module Importers
6
+ class ExifPhoto < Base
7
+ JPEG_PATTERN = /\.jpe?g\z/i.freeze
8
+ NO_PHOTOS = "This archive doesn't contain any JPEG photos.".freeze
9
+ UNREADABLE_PHOTO = "This photo couldn't be read. It may be damaged, or saved in a JPEG format we don't support.".freeze
10
+
11
+ def self.create_all(data, **options)
12
+ file = Download.open(data)
13
+ if Unzip.is_zip?(file)
14
+ paths = Download.find_in_zip(file, find: JPEG_PATTERN, tmpdir: options[:tmpdir])
15
+ else
16
+ paths = [file.path]
17
+ end
18
+
19
+ paths.map do |path|
20
+ new(path, **options)
21
+ end
22
+ rescue Unzip::PathNotFound
23
+ raise ImportError, NO_PHOTOS
24
+ end
25
+
26
+ def initialize(data, **options)
27
+ options[:source_identifier] ||= ::File.basename(data.to_s)
28
+ super(data, **options)
29
+ end
30
+
31
+ def cache_key
32
+ @cache_key ||= Digest::MD5.file(@data).hexdigest
33
+ end
34
+
35
+ private
36
+
37
+ def each_record
38
+ photo = EXIFR::JPEG.new(@data)
39
+ gps = photo.gps
40
+ unless usable_gps?(gps)
41
+ @warnings << 'No usable GPS coordinates were found in this photo.'
42
+ return
43
+ end
44
+
45
+ yield OpenStruct.new(
46
+ name: ::File.basename(@data),
47
+ geog: "POINT(#{gps.longitude} #{gps.latitude})",
48
+ metadata: metadata_from(photo, gps),
49
+ importable_image_paths: [@data]
50
+ )
51
+ rescue EXIFR::MalformedImage
52
+ raise ImportError, UNREADABLE_PHOTO
53
+ end
54
+
55
+ def usable_gps?(gps)
56
+ gps && gps.latitude.is_a?(Numeric) && gps.longitude.is_a?(Numeric) &&
57
+ (-90..90).cover?(gps.latitude) && (-180..180).cover?(gps.longitude)
58
+ end
59
+
60
+ def metadata_from(photo, gps)
61
+ {
62
+ 'capture_time' => photo.date_time_original&.strftime('%Y-%m-%d %H:%M:%S'),
63
+ 'altitude' => gps.altitude&.to_s,
64
+ 'camera_model' => photo.model.presence
65
+ }.compact
66
+ end
67
+ end
68
+ end
69
+ end
@@ -19,8 +19,18 @@ module SpatialFeatures
19
19
 
20
20
  private
21
21
 
22
+ # The geometry elements we import, each with the word a warning uses for it.
23
+ GEOMETRY_ELEMENTS = {'Polygon' => 'polygon', 'LineString' => 'line', 'Point' => 'point'}.freeze
24
+
25
+ # How many placemark names a warning lists before summarising the rest.
26
+ NAMED_LIMIT = 5
27
+
22
28
  def each_record(&block)
23
- {'Polygon' => 'POLYGON', 'LineString' => 'LINE', 'Point' => 'POINT'}.each do |kml_type, sql_type|
29
+ found = false
30
+ blank = []
31
+ unreadable = []
32
+
33
+ GEOMETRY_ELEMENTS.each do |kml_type, noun|
24
34
  kml_document.css(kml_type).each do |feature|
25
35
  if (placemark = feature.ancestors('Placemark').first)
26
36
  metadata = extract_metadata(placemark)
@@ -29,16 +39,74 @@ module SpatialFeatures
29
39
  metadata = {}
30
40
  end
31
41
 
32
- next if blank_feature?(feature)
42
+ label = name.presence || "an unnamed #{noun}"
43
+
44
+ if blank_feature?(feature)
45
+ blank << label
46
+ next
47
+ end
33
48
 
34
49
  geog = geom_from_kml(feature)
35
- next if geog.blank?
50
+ if geog.blank?
51
+ unreadable << label
52
+ next
53
+ end
36
54
 
37
55
  importable_image_paths = images_from_metadata(metadata)
38
56
 
57
+ found = true
39
58
  yield OpenStruct.new(geog: geog, name: name, metadata: metadata, importable_image_paths: importable_image_paths)
40
59
  end
41
60
  end
61
+
62
+ report_skipped(blank, 'with no coordinates')
63
+ report_skipped(unreadable, 'whose coordinates could not be read as a shape')
64
+ report_nothing_to_import unless found || @warnings.any?
65
+ end
66
+
67
+ # One warning per kind of skipped placemark, however many there were, naming the first
68
+ # few. An export of thousands of empty placemarks is one line, not thousands.
69
+ def report_skipped(labels, reason)
70
+ return if labels.empty?
71
+
72
+ @warnings << "Skipped #{labels.size} #{'placemark'.pluralize(labels.size)} #{reason}: #{listed(labels)}."
73
+ end
74
+
75
+ # A file with no geometry at all is not a parse failure, so nothing above has said
76
+ # why it imported nothing. Say what the file does hold, the way an archive with no map
77
+ # data names the files it did contain. Google Earth writes an untouched "Temporary
78
+ # Places" folder this way.
79
+ def report_nothing_to_import
80
+ placemarks = kml_document.search('Placemark')
81
+ folders = kml_document.search('Folder')
82
+
83
+ contents =
84
+ if placemarks.any?
85
+ "Its #{placemarks.one? ? 'placemark' : "#{placemarks.size} placemarks"}#{named(placemarks)} #{placemarks.one? ? 'has' : 'have'} no polygon, line or point to import."
86
+ elsif folders.any?
87
+ "It contains only #{count_of(folders.size, 'empty folder')}#{named(folders)}."
88
+ else
89
+ "It contains no placemarks."
90
+ end
91
+
92
+ @warnings << "#{File::INVALID_ARCHIVE} #{contents}"
93
+ end
94
+
95
+ # "a placemark", "an empty folder", "3 placemarks".
96
+ def count_of(count, noun)
97
+ count == 1 ? "#{noun.match?(/\A[aeiou]/i) ? 'an' : 'a'} #{noun}" : "#{count} #{noun.pluralize}"
98
+ end
99
+
100
+ # " named A, B and C", from each node's own name element, not one nested further down.
101
+ def named(nodes)
102
+ names = nodes.map {|node| node.at_xpath('name')&.text.presence }.compact.uniq
103
+ names.any? ? " named #{listed(names)}" : ''
104
+ end
105
+
106
+ def listed(names)
107
+ return names.to_sentence if names.size <= NAMED_LIMIT
108
+
109
+ "#{names.first(NAMED_LIMIT).join(', ')} and #{names.size - NAMED_LIMIT} more"
42
110
  end
43
111
 
44
112
  def kml_document
@@ -95,6 +163,8 @@ module SpatialFeatures
95
163
  feature.css('coordinates').text.blank?
96
164
  end
97
165
 
166
+ # Returns the geometry for `kml`, or nil when PostGIS would not read it. The caller
167
+ # reports the placemark as skipped; the file is otherwise imported.
98
168
  def geom_from_kml(kml)
99
169
  strip_altitude(kml)
100
170
 
@@ -8,8 +8,8 @@ module SpatialFeatures
8
8
  # uploaded beside it still import and the user is told which file was skipped and why.
9
9
  #
10
10
  # When every source is unreadable the import ends up empty and `update_features!`
11
- # raises `EmptyImportError` with these warnings as the reason, the same way a file
12
- # containing only NetworkLinks does.
11
+ # raises `ImportError` with these warnings as the reason, whether or not the caller
12
+ # allows a blank import, so the record keeps the features it had.
13
13
  class UnreadableFile < Base
14
14
  # Fallbacks for failures that didn't come from an importer, whose own messages would
15
15
  # mean nothing to the person who uploaded the file — and in the missing-file case
@@ -23,6 +23,10 @@ module SpatialFeatures
23
23
  @warnings << reason_for(error)
24
24
  end
25
25
 
26
+ def unreadable?
27
+ true
28
+ end
29
+
26
30
  # Include the reason so that fixing an importer (or the user re-uploading) produces a
27
31
  # different key and the record re-imports rather than matching its cached hash.
28
32
  def cache_key
@@ -76,6 +76,9 @@ module SpatialFeatures
76
76
  basename = File.basename(path)
77
77
 
78
78
  FileUtils.mkdir_p(directory)
79
+ # An archive can store a directory as read-only, and the entries inside it still
80
+ # have to be written.
81
+ entry.restore_permissions = false
79
82
  entry.extract(basename, destination_directory: directory)
80
83
 
81
84
  paths << path
@@ -51,6 +51,93 @@ module SpatialFeatures
51
51
  raise ::SpatialFeatures::Importers::IncompleteShapefileArchive, "This archive has no shapefile (.shp) in it." \
52
52
  unless allow_generic_zip_files
53
53
  end
54
+
55
+ # Raises `EmptyFileError` when nothing in the upload at `path` could ever import: a KML
56
+ # with no geometry, a shapefile with no records, a GeoJSON with no features, or an
57
+ # archive holding none of those. An archive holding several files passes when any one
58
+ # of them has something to import; the import reports the rest.
59
+ #
60
+ # Cheap enough to run while a form is being saved. Each file is scanned for coordinate
61
+ # text rather than parsed, and only a KML without any is parsed, to say what it does
62
+ # hold. Anything with coordinates passes, however malformed, as does a file the
63
+ # importer cannot read at all, and both are left for the import to explain: a
64
+ # save-time check that guesses wrong blocks an application with no way past it.
65
+ #
66
+ # @return [true]
67
+ # @raise [EmptyFileError] naming what each file holds instead of map data, or the file
68
+ # types an archive held instead of a map file.
69
+ # @raise [ImportError] when a remote `path` cannot be reached.
70
+ def validate_spatial_data!(path)
71
+ Dir.mktmpdir('spatial_features_validation') do |tmpdir|
72
+ files = Download.open_each(path, unzip: Importers::File::FILE_PATTERNS, downcase: true, tmpdir: tmpdir)
73
+ reasons = files.map {|file| empty_file_reason(file) }
74
+ return true if reasons.any?(&:nil?)
75
+
76
+ # An archive's files are named so the reader knows which is which; a lone file is
77
+ # already named by whoever shows the error.
78
+ reasons = files.zip(reasons).map {|file, reason| "#{::File.basename(file.path)}: #{reason}" } if files.many?
79
+ raise EmptyFileError, reasons.uniq.join(' ')
80
+ ensure
81
+ files&.each(&:close)
82
+ end
83
+ rescue Unzip::PathNotFound => e
84
+ raise EmptyFileError, Importers::File.invalid_archive_message(e)
85
+ end
86
+
87
+ private
88
+
89
+ # Returns why `file` has nothing to import, or nil when it has something.
90
+ def empty_file_reason(file)
91
+ case ::File.extname(file.path).downcase
92
+ when '.kml' then empty_kml_reason(file)
93
+ when '.shp' then empty_shapefile_reason(file)
94
+ when '.json', '.geojson' then empty_json_reason(file)
95
+ end
96
+ end
97
+
98
+ # A KML without coordinate text is handed to the importer, which says what it found
99
+ # instead. The scan can miss coordinates the importer still reads, in a CDATA block for
100
+ # one, so the importer's own count decides, and a KML it cannot read at all is passed
101
+ # through for the import to report.
102
+ def empty_kml_reason(file)
103
+ data = file.read
104
+ return if data.b.match?(KML_COORDINATES)
105
+
106
+ importer = Importers::KML.new(data)
107
+ return if importer.features.any?
108
+
109
+ reason = importer.warnings.join(' ')
110
+ reason.start_with?(Importers::File::INVALID_ARCHIVE) ? reason : "#{Importers::File::INVALID_ARCHIVE} #{reason}".strip
111
+ rescue ImportError
112
+ nil
113
+ end
114
+
115
+ def empty_shapefile_reason(file)
116
+ header = file.read(SHAPEFILE_HEADER_BYTES).to_s
117
+ words = header.byteslice(SHAPEFILE_LENGTH_OFFSET, 4)&.unpack1('N')
118
+ return unless words && words * 2 <= SHAPEFILE_HEADER_BYTES
119
+
120
+ "#{Importers::File::INVALID_ARCHIVE} Its shapefile has no shapes in it."
121
+ end
122
+
123
+ def empty_json_reason(file)
124
+ return if file.read.b.match?(JSON_COORDINATES)
125
+
126
+ "#{Importers::File::INVALID_ARCHIVE} It has no features with coordinates in it."
127
+ end
54
128
  end
129
+
130
+ # Coordinate text in a KML: a `<coordinates>` element, or a `<gx:coord>` in a track, with
131
+ # a digit in it. The prefix is optional because a document may qualify its elements.
132
+ KML_COORDINATES = /<(?:\w+:)?coord(?:inates)?\b[^>]*>[^<]*\d/.freeze
133
+
134
+ # Coordinate text in GeoJSON or ESRI JSON: an array of positions, rings or paths that
135
+ # opens with a number or a nested array, or an ESRI point's `x`.
136
+ JSON_COORDINATES = /"(?:coordinates|rings|paths|points)"\s*:\s*\[\s*[\[\-\d]|"x"\s*:\s*-?\d/.freeze
137
+
138
+ # A shapefile's header is 100 bytes, and bytes 24-27 hold the file's length in 16-bit
139
+ # words, so a file whose length is the header's is one with no records.
140
+ SHAPEFILE_HEADER_BYTES = 100
141
+ SHAPEFILE_LENGTH_OFFSET = 24
55
142
  end
56
143
  end
@@ -1,3 +1,3 @@
1
1
  module SpatialFeatures
2
- VERSION = "3.12.0"
2
+ VERSION = "3.14.0"
3
3
  end
@@ -21,6 +21,7 @@ require 'spatial_features/has_spatial_features/queued_spatial_processing'
21
21
  require 'spatial_features/has_spatial_features/feature_import'
22
22
 
23
23
  require 'spatial_features/importers/base'
24
+ require 'spatial_features/importers/exif_photo'
24
25
  require 'spatial_features/importers/file'
25
26
  require 'spatial_features/importers/geo_json'
26
27
  require 'spatial_features/importers/esri_geo_json'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: spatial_features
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.12.0
4
+ version: 3.14.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ryan Wallace
@@ -114,6 +114,20 @@ dependencies:
114
114
  - - ">="
115
115
  - !ruby/object:Gem::Version
116
116
  version: '0'
117
+ - !ruby/object:Gem::Dependency
118
+ name: exifr
119
+ requirement: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - ">="
122
+ - !ruby/object:Gem::Version
123
+ version: '0'
124
+ type: :runtime
125
+ prerelease: false
126
+ version_requirements: !ruby/object:Gem::Requirement
127
+ requirements:
128
+ - - ">="
129
+ - !ruby/object:Gem::Version
130
+ version: '0'
117
131
  - !ruby/object:Gem::Dependency
118
132
  name: rails
119
133
  requirement: !ruby/object:Gem::Requirement
@@ -204,6 +218,7 @@ files:
204
218
  - lib/spatial_features/has_spatial_features/queued_spatial_processing.rb
205
219
  - lib/spatial_features/importers/base.rb
206
220
  - lib/spatial_features/importers/esri_geo_json.rb
221
+ - lib/spatial_features/importers/exif_photo.rb
207
222
  - lib/spatial_features/importers/file.rb
208
223
  - lib/spatial_features/importers/geo_json.rb
209
224
  - lib/spatial_features/importers/geomark.rb