]> git.openstreetmap.org Git - rails.git/blob - app/models/trace.rb
Merge remote-tracking branch 'upstream/pull/4826'
[rails.git] / app / models / trace.rb
1 # == Schema Information
2 #
3 # Table name: gpx_files
4 #
5 #  id          :bigint(8)        not null, primary key
6 #  user_id     :bigint(8)        not null
7 #  visible     :boolean          default(TRUE), not null
8 #  name        :string           default(""), not null
9 #  size        :bigint(8)
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 #
23 # Foreign Keys
24 #
25 #  gpx_files_user_id_fkey  (user_id => users.id)
26 #
27
28 class Trace < ApplicationRecord
29   require "open3"
30
31   self.table_name = "gpx_files"
32
33   belongs_to :user, :counter_cache => true
34   has_many :tags, :class_name => "Tracetag", :foreign_key => "gpx_id", :dependent => :delete_all, :inverse_of => :trace
35   has_many :points, :class_name => "Tracepoint", :foreign_key => "gpx_id", :dependent => :delete_all, :inverse_of => :trace
36
37   scope :visible, -> { where(:visible => true) }
38   scope :visible_to, ->(u) { visible.where(:visibility => %w[public identifiable]).or(visible.where(:user => u)) }
39   scope :visible_to_all, -> { where(:visibility => %w[public identifiable]) }
40   scope :tagged, ->(t) { joins(:tags).where(:gpx_file_tags => { :tag => t }) }
41   scope :imported, -> { where(:inserted => true) }
42
43   has_one_attached :file, :service => Settings.trace_file_storage
44   has_one_attached :image, :service => Settings.trace_image_storage
45   has_one_attached :icon, :service => Settings.trace_icon_storage
46
47   validates :user, :associated => true
48   validates :name, :presence => true, :length => 1..255, :characters => true
49   validates :description, :presence => { :on => :create }, :length => 1..255, :characters => true
50   validates :timestamp, :presence => true
51   validates :visibility, :inclusion => %w[private public trackable identifiable]
52
53   after_save :set_filename
54
55   def tagstring
56     tags.collect(&:tag).join(", ")
57   end
58
59   def tagstring=(s)
60     self.tags = if s.include? ","
61                   s.split(",").map(&:strip).reject(&:empty?).collect do |tag|
62                     tt = Tracetag.new
63                     tt.tag = tag
64                     tt
65                   end
66                 else
67                   # do as before for backwards compatibility:
68                   s.split.collect do |tag|
69                     tt = Tracetag.new
70                     tt.tag = tag
71                     tt
72                   end
73                 end
74   end
75
76   def file=(attachable)
77     case attachable
78     when ActionDispatch::Http::UploadedFile, Rack::Test::UploadedFile
79       super(:io => attachable,
80             :filename => attachable.original_filename,
81             :content_type => content_type(attachable.path),
82             :identify => false)
83     else
84       super(attachable)
85     end
86   end
87
88   def public?
89     visibility == "public" || visibility == "identifiable"
90   end
91
92   def trackable?
93     visibility == "trackable" || visibility == "identifiable"
94   end
95
96   def identifiable?
97     visibility == "identifiable"
98   end
99
100   def large_picture
101     image.blob.download
102   end
103
104   def icon_picture
105     icon.blob.download
106   end
107
108   def mime_type
109     file.content_type
110   end
111
112   def extension_name
113     case mime_type
114     when "application/x-tar+gzip" then ".tar.gz"
115     when "application/x-tar+x-bzip2" then ".tar.bz2"
116     when "application/x-tar" then ".tar"
117     when "application/zip" then ".zip"
118     when "application/gzip" then ".gpx.gz"
119     when "application/x-bzip2" then ".gpx.bz2"
120     else ".gpx"
121     end
122   end
123
124   def update_from_xml(xml, create: false)
125     p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
126     doc = p.parse
127     pt = doc.find_first("//osm/gpx_file")
128
129     if pt
130       update_from_xml_node(pt, :create => create)
131     else
132       raise OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
133     end
134   rescue LibXML::XML::Error, ArgumentError => e
135     raise OSM::APIBadXMLError.new("trace", xml, e.message)
136   end
137
138   def update_from_xml_node(pt, create: false)
139     raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt["visibility"].nil?
140
141     self.visibility = pt["visibility"]
142
143     unless create
144       raise OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt["id"].nil?
145
146       id = pt["id"].to_i
147       # .to_i will return 0 if there is no number that can be parsed.
148       # We want to make sure that there is no id with zero anyway
149       raise OSM::APIBadUserInput, "ID of trace cannot be zero when updating." if id.zero?
150       raise OSM::APIBadUserInput, "The id in the url (#{self.id}) is not the same as provided in the xml (#{id})" unless self.id == id
151     end
152
153     # We don't care about the time, as it is explicitly set on create/update/delete
154     # We don't care about the visibility as it is implicit based on the action
155     # and set manually before the actual delete
156     self.visible = true
157
158     description = pt.find("description").first
159     raise OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
160
161     self.description = description.content
162
163     self.tags = pt.find("tag").collect do |tag|
164       Tracetag.new(:tag => tag.content)
165     end
166   end
167
168   def xml_file
169     file.open do |tracefile|
170       filetype = Open3.capture2("/usr/bin/file", "-Lbz", tracefile.path).first.chomp
171       gzipped = filetype.include?("gzip compressed")
172       bzipped = filetype.include?("bzip2 compressed")
173       zipped = filetype.include?("Zip archive")
174       tarred = filetype.include?("tar archive")
175
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     case Open3.capture2("/usr/bin/file", "-Lbz", file).first.chomp
283     when /.*\btar archive\b.*\bgzip\b/ then "application/x-tar+gzip"
284     when /.*\btar archive\b.*\bbzip2\b/ then "application/x-tar+x-bzip2"
285     when /.*\btar archive\b/ then "application/x-tar"
286     when /.*\bZip archive\b/ then "application/zip"
287     when /.*\bXML\b.*\bgzip\b/ then "application/gzip"
288     when /.*\bXML\b.*\bbzip2\b/ then "application/x-bzip2"
289     else "application/gpx+xml"
290     end
291   end
292
293   def set_filename
294     file.blob.update(:filename => "#{id}#{extension_name}") if file.attached?
295   end
296 end