]> git.openstreetmap.org Git - rails.git/blob - app/models/trace.rb
Limit number of directions endpoint geocoding results to 1
[rails.git] / app / models / trace.rb
1 # == Schema Information
2 #
3 # Table name: gpx_files
4 #
5 #  id          :bigint           not null, primary key
6 #  user_id     :bigint           not null
7 #  visible     :boolean          default(TRUE), not null
8 #  name        :string           default(""), not null
9 #  size        :bigint
10 #  latitude    :float
11 #  longitude   :float
12 #  timestamp   :datetime         not null
13 #  description :string           default(""), not null
14 #  inserted    :boolean          not null
15 #  visibility  :enum             default("public"), not null
16 #
17 # Indexes
18 #
19 #  gpx_files_timestamp_idx            (timestamp)
20 #  gpx_files_user_id_idx              (user_id)
21 #  gpx_files_visible_visibility_idx   (visible,visibility)
22 #  index_gpx_files_on_user_id_and_id  (user_id,id)
23 #
24 # Foreign Keys
25 #
26 #  gpx_files_user_id_fkey  (user_id => users.id)
27 #
28
29 class Trace < ApplicationRecord
30   require "open3"
31
32   self.table_name = "gpx_files"
33
34   belongs_to :user, :counter_cache => true
35   has_many :tags, :class_name => "Tracetag", :foreign_key => "gpx_id", :dependent => :delete_all, :inverse_of => :trace
36   has_many :points, :class_name => "Tracepoint", :foreign_key => "gpx_id", :dependent => :delete_all, :inverse_of => :trace
37
38   scope :visible, -> { where(:visible => true) }
39   scope :visible_to, ->(u) { visible.where(:visibility => %w[public identifiable]).or(visible.where(:user => u)) }
40   scope :visible_to_all, -> { where(:visibility => %w[public identifiable]) }
41   scope :tagged, ->(t) { joins(:tags).where(:gpx_file_tags => { :tag => t }) }
42   scope :imported, -> { where(:inserted => true) }
43
44   has_one_attached :file, :service => Settings.trace_file_storage
45   has_one_attached :image, :service => Settings.trace_image_storage
46   has_one_attached :icon, :service => Settings.trace_icon_storage
47
48   validates :user, :associated => true
49   validates :name, :presence => true, :length => 1..255, :characters => true
50   validates :description, :presence => { :on => :create }, :length => 1..255, :characters => true
51   validates :timestamp, :presence => true
52   validates :visibility, :inclusion => %w[private public trackable identifiable]
53
54   after_save :set_filename
55
56   def tagstring
57     tags.collect(&:tag).join(", ")
58   end
59
60   def tagstring=(s)
61     self.tags = if s.include? ","
62                   s.split(",").map(&:strip).reject(&:empty?).collect do |tag|
63                     tt = Tracetag.new
64                     tt.tag = tag
65                     tt
66                   end
67                 else
68                   # do as before for backwards compatibility:
69                   s.split.collect do |tag|
70                     tt = Tracetag.new
71                     tt.tag = tag
72                     tt
73                   end
74                 end
75   end
76
77   def file=(attachable)
78     case attachable
79     when ActionDispatch::Http::UploadedFile, Rack::Test::UploadedFile
80       super(:io => attachable,
81             :filename => attachable.original_filename,
82             :content_type => content_type(attachable.path),
83             :identify => false)
84     else
85       super
86     end
87   end
88
89   def public?
90     %w[public identifiable].include?(visibility)
91   end
92
93   def trackable?
94     %w[trackable identifiable].include?(visibility)
95   end
96
97   def identifiable?
98     visibility == "identifiable"
99   end
100
101   def large_picture
102     image.blob.download
103   end
104
105   def icon_picture
106     icon.blob.download
107   end
108
109   def mime_type
110     file.content_type
111   end
112
113   def extension_name
114     case mime_type
115     when "application/x-tar+gzip" then ".tar.gz"
116     when "application/x-tar+x-bzip2" then ".tar.bz2"
117     when "application/x-tar" then ".tar"
118     when "application/zip" then ".zip"
119     when "application/gzip" then ".gpx.gz"
120     when "application/x-bzip2" then ".gpx.bz2"
121     else ".gpx"
122     end
123   end
124
125   def update_from_xml(xml, create: false)
126     p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
127     doc = p.parse
128     pt = doc.find_first("//osm/gpx_file")
129
130     if pt
131       update_from_xml_node(pt, :create => create)
132     else
133       raise OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
134     end
135   rescue LibXML::XML::Error, ArgumentError => e
136     raise OSM::APIBadXMLError.new("trace", xml, e.message)
137   end
138
139   def update_from_xml_node(pt, create: false)
140     raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt["visibility"].nil?
141
142     self.visibility = pt["visibility"]
143
144     unless create
145       raise OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt["id"].nil?
146
147       id = pt["id"].to_i
148       # .to_i will return 0 if there is no number that can be parsed.
149       # We want to make sure that there is no id with zero anyway
150       raise OSM::APIBadUserInput, "ID of trace cannot be zero when updating." if id.zero?
151       raise OSM::APIBadUserInput, "The id in the url (#{self.id}) is not the same as provided in the xml (#{id})" unless self.id == id
152     end
153
154     # We don't care about the time, as it is explicitly set on create/update/delete
155     # We don't care about the visibility as it is implicit based on the action
156     # and set manually before the actual delete
157     self.visible = true
158
159     description = pt.find("description").first
160     raise OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
161
162     self.description = description.content
163
164     self.tags = pt.find("tag").collect do |tag|
165       Tracetag.new(:tag => tag.content)
166     end
167   end
168
169   def xml_file
170     gzipped = file.content_type.end_with?("gzip")
171     bzipped = file.content_type.end_with?("bzip2")
172     zipped = file.content_type.start_with?("application/zip")
173     tarred = file.content_type.start_with?("application/x-tar")
174
175     file.open do |tracefile|
176       if gzipped || bzipped || zipped || tarred
177         file = Tempfile.new("trace.#{id}")
178
179         if tarred && gzipped
180           system("tar", "-zxOf", tracefile.path, :out => file.path)
181         elsif tarred && bzipped
182           system("tar", "-jxOf", tracefile.path, :out => file.path)
183         elsif tarred
184           system("tar", "-xOf", tracefile.path, :out => file.path)
185         elsif gzipped
186           system("gunzip", "-c", tracefile.path, :out => file.path)
187         elsif bzipped
188           system("bunzip2", "-c", tracefile.path, :out => file.path)
189         elsif zipped
190           system("unzip", "-p", tracefile.path, "-x", "__MACOSX/*", :out => file.path, :err => "/dev/null")
191         end
192
193         file.unlink
194       else
195         file = File.open(tracefile.path)
196       end
197
198       file
199     end
200   end
201
202   def import
203     logger.info("GPX Import importing #{name} (#{id}) from #{user.email}")
204
205     file.open do |file|
206       gpx = GPX::File.new(file.path, :maximum_points => Settings.max_trace_size)
207
208       f_lat = 0
209       f_lon = 0
210       first = true
211
212       # If there are any existing points for this trace then delete them
213       Tracepoint.where(:trace => id).delete_all
214
215       gpx.points.each_slice(1_000) do |points|
216         # Gather the trace points together for a bulk import
217         tracepoints = []
218
219         points.each do |point|
220           if first
221             f_lat = point.latitude
222             f_lon = point.longitude
223             first = false
224           end
225
226           tp = Tracepoint.new
227           tp.lat = point.latitude
228           tp.lon = point.longitude
229           tp.altitude = point.altitude
230           tp.timestamp = point.timestamp
231           tp.gpx_id = id
232           tp.trackid = point.segment
233           tracepoints << tp
234         end
235
236         # Run the before_save and before_create callbacks, and then import them in bulk with activerecord-import
237         tracepoints.each do |tp|
238           tp.run_callbacks(:save) { false }
239           tp.run_callbacks(:create) { false }
240         end
241
242         Tracepoint.import!(tracepoints)
243       end
244
245       if gpx.actual_points.positive?
246         max_lat = Tracepoint.where(:trace => id).maximum(:latitude)
247         min_lat = Tracepoint.where(:trace => id).minimum(:latitude)
248         max_lon = Tracepoint.where(:trace => id).maximum(:longitude)
249         min_lon = Tracepoint.where(:trace => id).minimum(:longitude)
250
251         max_lat = max_lat.to_f / 10000000
252         min_lat = min_lat.to_f / 10000000
253         max_lon = max_lon.to_f / 10000000
254         min_lon = min_lon.to_f / 10000000
255
256         self.latitude = f_lat
257         self.longitude = f_lon
258         image.attach(:io => gpx.picture(min_lat, min_lon, max_lat, max_lon, gpx.actual_points), :filename => "#{id}.gif", :content_type => "image/gif")
259         icon.attach(:io => gpx.icon(min_lat, min_lon, max_lat, max_lon), :filename => "#{id}_icon.gif", :content_type => "image/gif")
260         self.size = gpx.actual_points
261         self.inserted = true
262         save!
263       end
264
265       logger.info "done trace #{id}"
266
267       gpx
268     end
269   end
270
271   def schedule_import
272     TraceImporterJob.new(self).enqueue(:priority => user.traces.where(:inserted => false).count)
273   end
274
275   def schedule_destruction
276     TraceDestroyerJob.perform_later(self)
277   end
278
279   private
280
281   def content_type(file)
282     file_type = Open3.capture2("/usr/bin/file", "-Lb", file).first.chomp
283
284     case file_type
285     when /\bcompressed data,/ then file_type = Open3.capture2("/usr/bin/file", "-Lbz", file).first.chomp
286     end
287
288     case file_type
289     when /\btar archive\b.*\bgzip\b/ then "application/x-tar+gzip"
290     when /\btar archive\b.*\bbzip2\b/ then "application/x-tar+x-bzip2"
291     when /\btar archive\b/ then "application/x-tar"
292     when /\bZip archive\b/ then "application/zip"
293     when /\bXML\b.*\bgzip\b/ then "application/gzip"
294     when /\bXML\b.*\bbzip2\b/ then "application/x-bzip2"
295     else "application/gpx+xml"
296     end
297   end
298
299   def set_filename
300     file.blob.update(:filename => "#{id}#{extension_name}") if file.attached?
301   end
302 end