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