spatial_features 3.11.2 → 3.13.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: 0d90a3143573947c3e70f74845fbd475dcddbd871df0baff29dd028d236c9833
4
- data.tar.gz: 37bf93eb6f87120a85f2e028efe77debb91772cc3cd77289f75e59deb5d5ab4e
3
+ metadata.gz: 3b36a07cd400459369dcdaedd71899954e1a4687d94db1ac1d62e987a17c9552
4
+ data.tar.gz: '02101805b5ad1fee94e726fde4c24bba09e79641cc575361ff25ff51779f0fbc'
5
5
  SHA512:
6
- metadata.gz: 0fa27a478c51fccc0a7c97ecfe5214faeea64e930b8ab0643cddc2fd4e3d2570905503308c6c2f0b1c54b5384054d774e82d48a3df6044fad135ff4688f5c9ea
7
- data.tar.gz: e07a9760f62c00fd47dbb350b4b669b067ca4a98cb8c836d7fa8d7deb0432bd6836ae1d647ee025bcf5b494d9b4dbb189174be9cfa6f90efaccbe4947e5a9cd4
6
+ metadata.gz: 3bf6e8b22a387558f09ec940d080403535ecfe89c178b8ddb3233f1d55c8107e312d6cd0f3300d43176f52d06fa41f4f490d7dc0a4c1fb3131268fdd5a3a7185
7
+ data.tar.gz: ef898f88ad2b999c4d363312ae6527e5cd05ba4e7a14ef8f43330862da8e6e9a73b48515ad21ab3539aa267d87bdded6d4817630a95edf2b7832c3b844e369b8
@@ -1,42 +1,95 @@
1
+ require 'net/http'
1
2
  require 'open-uri'
3
+ require 'openssl'
2
4
 
3
5
  module SpatialFeatures
4
6
  module Download
5
- # file can be a url, path, or file, any of which can return be a zipped archive
6
- def self.open(file)
7
- file = URI.open(file)
8
- file = normalize_file(file) if file.is_a?(StringIO)
9
- return file
10
- end
7
+ REMOTE_URL = %r{\Ahttps?://}i.freeze
8
+
9
+ # Seconds to wait for a remote source, applied both to establishing the connection and to
10
+ # each read. Without it a hung server holds an import worker open indefinitely.
11
+ mattr_accessor :timeout
12
+ self.timeout = 60
11
13
 
12
- # file can be a url, path, or file, any of which can return be a zipped archive
13
- def self.open_each(path_or_url, unzip: nil, **unzip_options)
14
- file = Download.open(path_or_url)
15
- files = if unzip && Unzip.is_zip?(file)
16
- find_in_zip(file, find: unzip, **unzip_options)
17
- else
18
- [file]
14
+ # Errors meaning a remote source could not be read at all, as opposed to being read and
15
+ # found unusable. `OpenURI::HTTPError` covers the 4xx and 5xx replies.
16
+ UNREACHABLE_ERRORS = [::OpenURI::HTTPError, ::SocketError, ::SystemCallError,
17
+ ::Net::OpenTimeout, ::Net::ReadTimeout, ::OpenSSL::SSL::SSLError].freeze
18
+
19
+ class << self
20
+ # Returns an open File for `file`, which may be a URL, a path, or a File. The content may
21
+ # be a zipped archive; `::open_each` unwraps one.
22
+ #
23
+ # @raise [SpatialFeatures::ImportError] when a remote source cannot be reached.
24
+ def open(file)
25
+ file = fetch(file)
26
+ file = normalize_file(file) if file.is_a?(StringIO)
27
+ return file
19
28
  end
20
29
 
21
- return files.map { |f| File.open(f) }
22
- end
30
+ # Returns the body of `path_or_url` as a String, without writing it to disk.
31
+ #
32
+ # @raise [SpatialFeatures::ImportError] when a remote source cannot be reached.
33
+ def read(path_or_url)
34
+ fetch(path_or_url).read
35
+ end
36
+
37
+ # Returns an open file for each source in `path_or_url`, unwrapping an archive when
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.
45
+ def open_each(path_or_url, unzip: nil, **unzip_options)
46
+ file = Download.open(path_or_url)
47
+ return [file] unless unzip && Unzip.is_zip?(file)
23
48
 
24
- def self.normalize_file(file)
25
- Tempfile.new.tap do |temp|
26
- temp.binmode
27
- temp.write(file.read)
28
- temp.rewind
49
+ find_in_zip(file, find: unzip, **unzip_options).map { |path| File.open(path) }
29
50
  end
30
- end
31
51
 
32
- def self.entries(file)
33
- file = Kernel.open(file)
34
- file = normalize_file(file) if file.is_a?(StringIO)
35
- Unzip.entries(file)
36
- end
52
+ def normalize_file(file)
53
+ Tempfile.new.tap do |temp|
54
+ temp.binmode
55
+ temp.write(file.read)
56
+ temp.rewind
57
+ end
58
+ end
59
+
60
+ # Returns the entries of the archive at `file` without extracting them.
61
+ def entries(file)
62
+ file = fetch(file)
63
+ file = normalize_file(file) if file.is_a?(StringIO)
64
+ Unzip.entries(file)
65
+ end
66
+
67
+ def find_in_zip(file, find:, **unzip_options)
68
+ Unzip.paths(file, find: find, **unzip_options)
69
+ end
70
+
71
+ private
37
72
 
38
- def self.find_in_zip(file, find:, **unzip_options)
39
- Unzip.paths(file, find: find, **unzip_options)
73
+ # Returns an IO for `file`: fetched over the network when it is a remote URL, opened from
74
+ # disk when it is any other String, and left to open itself otherwise.
75
+ #
76
+ # @note A local path goes to `File.open`, never `URI.open`. `URI.open` hands anything
77
+ # that is not a URL to `Kernel#open`, which runs the name as a command when it begins
78
+ # with a pipe.
79
+ # @note Timeouts and the unreachable rescue apply only to a remote URL. `URI.open`
80
+ # rejects the timeouts when handed an already open file, and `Errno::ENOENT` for a
81
+ # local path is a `SystemCallError` that callers turn into a message for the person who
82
+ # uploaded the file, without naming the path the server looked in.
83
+ def fetch(file)
84
+ return URI.open(file) unless file.is_a?(String)
85
+ return File.open(file) unless file.match?(REMOTE_URL)
86
+
87
+ begin
88
+ URI.open(file, :open_timeout => timeout, :read_timeout => timeout)
89
+ rescue *UNREACHABLE_ERRORS => e
90
+ raise SpatialFeatures::ImportError, "This source could not be reached. #{e.message}"
91
+ end
92
+ end
40
93
  end
41
94
  end
42
95
  end
@@ -0,0 +1,42 @@
1
+ require 'open3'
2
+
3
+ module SpatialFeatures
4
+ # Runs the GDAL command line tools.
5
+ #
6
+ # Every argument reaches the tool as a single argv entry, so a path or a projection taken
7
+ # from an uploaded archive arrives as one string rather than as shell syntax.
8
+ module GDAL
9
+ class << self
10
+ # Returns what `tool` wrote to standard output.
11
+ #
12
+ # @param tool [String] the executable name, such as `ogr2ogr`.
13
+ # @param args [Array<String>] one argv entry each.
14
+ # @return [String] the output, empty when the tool wrote nothing.
15
+ # @raise [Errno::ENOENT] when the tool is not installed.
16
+ def capture(tool, *args)
17
+ Open3.capture2(*argv(tool, args)).first
18
+ end
19
+
20
+ # Runs `tool` for its exit status rather than its output.
21
+ #
22
+ # @param tool [String] the executable name, such as `ogr2ogr`.
23
+ # @param args [Array<String>] one argv entry each.
24
+ # @return [Boolean] true when the tool exited successfully.
25
+ # @raise [Errno::ENOENT] when the tool is not installed.
26
+ def run(tool, *args)
27
+ system(*argv(tool, args))
28
+ end
29
+
30
+ private
31
+
32
+ # Returns the argv to spawn `tool` with.
33
+ #
34
+ # @note The command is a two element array so that Ruby spawns the executable directly.
35
+ # Both `system` and `Open3` fall back to a shell when handed a lone string, which
36
+ # would put every argument here back in reach of shell parsing.
37
+ def argv(tool, args)
38
+ [[tool.to_s, tool.to_s], *args.map(&:to_s)]
39
+ end
40
+ end
41
+ end
42
+ end
@@ -1,10 +1,18 @@
1
1
  require 'digest/md5'
2
- require 'open3'
2
+ require 'json'
3
+ require 'tempfile'
3
4
  require 'spatial_features/importers/geo_json'
4
5
 
5
6
  module SpatialFeatures
6
7
  module Importers
7
8
  class ESRIGeoJSON < GeoJSON
9
+ # How many pages to walk before concluding the endpoint is ignoring `resultOffset` and
10
+ # serving the same features over and over. A service capped at the usual 1000 or 2000
11
+ # features per page would have to hold half a million features to reach this
12
+ # legitimately. Raise it for a layer that genuinely holds more.
13
+ class_attribute :max_pages
14
+ self.max_pages = 500
15
+
8
16
  def parsed_geojson
9
17
  @parsed_geojson ||= JSON.parse(geojson)
10
18
  end
@@ -15,10 +23,115 @@ module SpatialFeatures
15
23
 
16
24
  private
17
25
 
18
- def esri_json_to_geojson(url)
19
- args = ['ogr2ogr', '-t_srs', 'EPSG:4326', '-f', 'GeoJSON', '/dev/stdout', url]
20
- args << 'OGRGeoJSON' unless URI.parse(url).relative? # A relative URL is a local file path
21
- Open3.capture2(*args).first
26
+ # Returns the layer as GeoJSON. A relative path is read from disk; anything else is
27
+ # downloaded first, so OGR is always given a local file.
28
+ #
29
+ # @param path_or_url [String] a local file path, or the URL of an ArcGIS query endpoint.
30
+ # @return [String] a GeoJSON FeatureCollection in EPSG:4326.
31
+ # @note Downloading rather than passing the URL to OGR is what makes an endpoint offering
32
+ # only HTTPS 1.1 readable. GDAL's curl client gets an empty reply from those servers,
33
+ # which surfaces as `ERROR 1: Empty reply from server`.
34
+ def esri_json_to_geojson(path_or_url)
35
+ return ogr2ogr_to_geojson(path_or_url) if URI.parse(path_or_url).relative?
36
+
37
+ with_downloaded_file(path_or_url) do |path|
38
+ ogr2ogr_to_geojson(path)
39
+ end
40
+ end
41
+
42
+ # Returns the GeoJSON OGR reads out of the file at `path`, reprojected to EPSG:4326.
43
+ # OGR selects its driver by inspecting the content, so the file may hold either GeoJSON
44
+ # or ESRI JSON.
45
+ #
46
+ # @note No layer name is passed. OGR names a local file's layer after its basename, and
47
+ # naming a layer that does not exist fails the read.
48
+ def ogr2ogr_to_geojson(path)
49
+ GDAL.capture('ogr2ogr', '-t_srs', 'EPSG:4326', '-f', 'GeoJSON', '/dev/stdout', path)
50
+ end
51
+
52
+ # Downloads the query into a tempfile and yields its path, removing it afterwards.
53
+ def with_downloaded_file(url)
54
+ Tempfile.create(['esri_geojson', '.json']) do |tempfile|
55
+ tempfile.binmode
56
+ download_paginated(url, tempfile)
57
+ tempfile.close
58
+ return yield(tempfile.path)
59
+ end
60
+ end
61
+
62
+ # Walks the query's pages with `resultOffset` and writes them to `io` as one collection.
63
+ # ArcGIS endpoints cap each response at the service's `maxRecordCount`, commonly 1000 or
64
+ # 2000 features, and set `exceededTransferLimit` while more results are waiting.
65
+ #
66
+ # @note Raises `SpatialFeatures::ImportError` once `max_pages` requests have been made
67
+ # and the endpoint still reports more, since a server that ignores `resultOffset`
68
+ # otherwise repeats its first page until the process runs out of memory.
69
+ def download_paginated(url, io)
70
+ combined = nil
71
+ offset = 0
72
+ pages = 0
73
+
74
+ loop do
75
+ page = fetch_page(paginated_url(url, offset))
76
+ page_features = page['features'] || []
77
+
78
+ if combined.nil?
79
+ combined = page
80
+ else
81
+ combined['features'].concat(page_features)
82
+ end
83
+
84
+ break if page_features.empty? || !exceeded_transfer_limit?(page)
85
+
86
+ pages += 1
87
+ if pages >= max_pages
88
+ raise SpatialFeatures::ImportError,
89
+ "This layer was still reporting more features after #{max_pages} requests. " \
90
+ "The server may be ignoring the `resultOffset` parameter."
91
+ end
92
+
93
+ offset += page_features.length
94
+ end
95
+
96
+ if combined
97
+ combined.delete('exceededTransferLimit')
98
+ combined['properties']&.delete('exceededTransferLimit')
99
+ io.write(JSON.dump(combined))
100
+ end
101
+ end
102
+
103
+ # Returns one page of the query.
104
+ #
105
+ # @return [Hash] the parsed response body.
106
+ # @raise [SpatialFeatures::ImportError] when the endpoint cannot be reached, or answers
107
+ # with a body that is not JSON. An endpoint that rejects a query replies with HTML or
108
+ # an error document, which the parse failure alone does not convey.
109
+ def fetch_page(url)
110
+ body = Download.read(url)
111
+ JSON.parse(body)
112
+ rescue JSON::ParserError
113
+ raise SpatialFeatures::ImportError,
114
+ "This layer did not return map data. The server replied with #{body.to_s[0, 100].inspect}."
115
+ end
116
+
117
+ # Returns true while the service reports that more features are waiting. Services set the
118
+ # flag at the top level or under `properties` depending on the response format.
119
+ def exceeded_transfer_limit?(page)
120
+ page['exceededTransferLimit'] || page.dig('properties', 'exceededTransferLimit')
121
+ end
122
+
123
+ # Returns `url` with `resultOffset` set to `offset`, replacing any the caller supplied.
124
+ # Returns it unchanged for the first page, so a service that does not paginate is asked
125
+ # exactly what the caller asked for.
126
+ def paginated_url(url, offset)
127
+ return url if offset.zero?
128
+
129
+ uri = URI.parse(url)
130
+ params = URI.decode_www_form(uri.query || '')
131
+ params.reject! { |key, _| key == 'resultOffset' }
132
+ params << ['resultOffset', offset.to_s]
133
+ uri.query = URI.encode_www_form(params)
134
+ uri.to_s
22
135
  end
23
136
  end
24
137
  end
@@ -0,0 +1,62 @@
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
+ Download.open_each(data, unzip: JPEG_PATTERN, tmpdir: options[:tmpdir]).map do |file|
13
+ new(file.path, **options)
14
+ end
15
+ rescue Unzip::PathNotFound
16
+ raise ImportError, NO_PHOTOS
17
+ end
18
+
19
+ def initialize(data, **options)
20
+ options[:source_identifier] ||= ::File.basename(data.to_s)
21
+ super(data, **options)
22
+ end
23
+
24
+ def cache_key
25
+ @cache_key ||= Digest::MD5.file(@data).hexdigest
26
+ end
27
+
28
+ private
29
+
30
+ def each_record
31
+ photo = EXIFR::JPEG.new(@data)
32
+ gps = photo.gps
33
+ unless usable_gps?(gps)
34
+ @warnings << 'No usable GPS coordinates were found in this photo.'
35
+ return
36
+ end
37
+
38
+ yield OpenStruct.new(
39
+ name: ::File.basename(@data),
40
+ geog: "POINT(#{gps.longitude} #{gps.latitude})",
41
+ metadata: metadata_from(photo, gps),
42
+ importable_image_paths: [@data]
43
+ )
44
+ rescue EXIFR::MalformedImage
45
+ raise ImportError, UNREADABLE_PHOTO
46
+ end
47
+
48
+ def usable_gps?(gps)
49
+ gps && gps.latitude.is_a?(Numeric) && gps.longitude.is_a?(Numeric) &&
50
+ (-90..90).cover?(gps.latitude) && (-180..180).cover?(gps.longitude)
51
+ end
52
+
53
+ def metadata_from(photo, gps)
54
+ {
55
+ 'capture_time' => photo.date_time_original&.strftime('%Y-%m-%d %H:%M:%S'),
56
+ 'altitude' => gps.altitude&.to_s,
57
+ 'camera_model' => photo.model.presence
58
+ }.compact
59
+ end
60
+ end
61
+ end
62
+ end
@@ -1,6 +1,5 @@
1
1
  require 'ostruct'
2
2
  require 'digest/md5'
3
- require 'open3'
4
3
 
5
4
  module SpatialFeatures
6
5
  module Importers
@@ -101,7 +100,7 @@ module SpatialFeatures
101
100
  def project_to_4326(file_path)
102
101
  output_path = Tempfile.create([::File.basename(file_path, '.shp') + '_epsg_4326_', '.shp']) { |file| file.path }
103
102
  return unless (proj4 = proj4_from_file(file_path))
104
- return unless system('ogr2ogr', '-s_srs', proj4, '-t_srs', 'EPSG:4326', output_path, file_path)
103
+ return unless GDAL.run('ogr2ogr', '-s_srs', proj4, '-t_srs', 'EPSG:4326', output_path, file_path)
105
104
  return ::File.open(output_path)
106
105
  end
107
106
 
@@ -112,7 +111,7 @@ module SpatialFeatures
112
111
  # Sanitize: "'+proj=utm +zone=11 +datum=NAD83 +units=m +no_defs '\n" and lately
113
112
  # "+proj=utm +zone=11 +datum=NAD83 +units=m +no_defs \n" to
114
113
  # "+proj=utm +zone=11 +datum=NAD83 +units=m +no_defs"
115
- Open3.capture2('gdalsrsinfo', file_path, '-o', 'proj4').first.strip.remove(/^'|'$/).presence
114
+ GDAL.capture('gdalsrsinfo', file_path, '-o', 'proj4').strip.remove(/^'|'$/).presence
116
115
  rescue Errno::ENOENT
117
116
  nil
118
117
  end
@@ -1,3 +1,3 @@
1
1
  module SpatialFeatures
2
- VERSION = "3.11.2"
2
+ VERSION = "3.13.0"
3
3
  end
@@ -10,6 +10,7 @@ require 'spatial_features/caching'
10
10
  require 'spatial_features/uncached_result'
11
11
  require 'spatial_features/venn_polygons'
12
12
  require 'spatial_features/controller_helpers/spatial_extensions'
13
+ require 'spatial_features/gdal'
13
14
  require 'spatial_features/download'
14
15
  require 'spatial_features/unzip'
15
16
  require 'spatial_features/utils'
@@ -20,6 +21,7 @@ require 'spatial_features/has_spatial_features/queued_spatial_processing'
20
21
  require 'spatial_features/has_spatial_features/feature_import'
21
22
 
22
23
  require 'spatial_features/importers/base'
24
+ require 'spatial_features/importers/exif_photo'
23
25
  require 'spatial_features/importers/file'
24
26
  require 'spatial_features/importers/geo_json'
25
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.11.2
4
+ version: 3.13.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
@@ -198,11 +212,13 @@ files:
198
212
  - lib/spatial_features/controller_helpers/spatial_extensions.rb
199
213
  - lib/spatial_features/download.rb
200
214
  - lib/spatial_features/engine.rb
215
+ - lib/spatial_features/gdal.rb
201
216
  - lib/spatial_features/has_spatial_features.rb
202
217
  - lib/spatial_features/has_spatial_features/feature_import.rb
203
218
  - lib/spatial_features/has_spatial_features/queued_spatial_processing.rb
204
219
  - lib/spatial_features/importers/base.rb
205
220
  - lib/spatial_features/importers/esri_geo_json.rb
221
+ - lib/spatial_features/importers/exif_photo.rb
206
222
  - lib/spatial_features/importers/file.rb
207
223
  - lib/spatial_features/importers/geo_json.rb
208
224
  - lib/spatial_features/importers/geomark.rb
@@ -236,7 +252,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
236
252
  - !ruby/object:Gem::Version
237
253
  version: '0'
238
254
  requirements: []
239
- rubygems_version: 4.0.5
255
+ rubygems_version: 3.7.2
240
256
  specification_version: 4
241
257
  summary: Adds spatial methods to a model.
242
258
  test_files: []