1 # frozen_string_literal: true
3 # == Schema Information
5 # Table name: gpx_files
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
14 # timestamp :datetime not null
15 # description :string default(""), not null
16 # inserted :boolean not null
17 # visibility :enum default("public"), not null
21 # gpx_files_timestamp_idx (timestamp)
22 # gpx_files_visible_visibility_idx (visible,visibility)
23 # index_gpx_files_on_user_id_and_id (user_id,id)
27 # gpx_files_user_id_fkey (user_id => users.id)
30 class Trace < ApplicationRecord
31 self.table_name = "gpx_files"
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
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) }
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
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]
53 after_save :set_filename
56 tags.collect(&:tag).join(", ")
60 self.tags = if s.include? ","
61 s.split(",").map(&:strip).reject(&:empty?).collect do |tag|
67 # do as before for backwards compatibility:
68 s.split.collect do |tag|
78 when ActionDispatch::Http::UploadedFile, Rack::Test::UploadedFile
79 super(:io => attachable,
80 :filename => attachable.original_filename,
81 :content_type => content_type(attachable.path),
89 %w[public identifiable].include?(visibility)
93 %w[trackable identifiable].include?(visibility)
97 visibility == "identifiable"
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"
124 def update_from_xml(xml, create: false)
125 p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
127 pt = doc.find_first("//osm/gpx_file")
130 update_from_xml_node(pt, :create => create)
132 raise OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
134 rescue LibXML::XML::Error, ArgumentError => e
135 raise OSM::APIBadXMLError.new("trace", xml, e.message)
138 def update_from_xml_node(pt, create: false)
139 raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt["visibility"].nil?
141 self.visibility = pt["visibility"]
144 raise OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt["id"].nil?
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
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
158 description = pt.find("description").first
159 raise OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
161 self.description = description.content
163 self.tags = pt.find("tag").collect do |tag|
164 Tracetag.new(:tag => tag.content)
169 gzipped = file.content_type.end_with?("gzip")
170 bzipped = file.content_type.end_with?("bzip2")
171 zipped = file.content_type.start_with?("application/zip")
172 tarred = file.content_type.start_with?("application/x-tar")
174 file.open do |tracefile|
175 if gzipped || bzipped || zipped || tarred
176 file = Tempfile.new("trace.#{id}")
179 system("tar", "-zxOf", tracefile.path, :out => file.path)
180 elsif tarred && bzipped
181 system("tar", "-jxOf", tracefile.path, :out => file.path)
183 system("tar", "-xOf", tracefile.path, :out => file.path)
185 system("gunzip", "-c", tracefile.path, :out => file.path)
187 system("bunzip2", "-c", tracefile.path, :out => file.path)
189 system("unzip", "-p", tracefile.path, "-x", "__MACOSX/*", :out => file.path, :err => "/dev/null")
194 file = File.open(tracefile.path)
202 logger.info("GPX Import importing #{name} (#{id}) from #{user.email}")
205 gpx = GPX::File.new(file.path, :maximum_points => Settings.max_trace_size)
211 # If there are any existing points for this trace then delete them
212 Tracepoint.where(:trace => id).delete_all
214 gpx.points.each_slice(1_000) do |points|
215 # Gather the trace points together for a bulk import
218 points.each do |point|
220 f_lat = point.latitude
221 f_lon = point.longitude
226 tp.lat = point.latitude
227 tp.lon = point.longitude
228 tp.altitude = point.altitude
229 tp.timestamp = point.timestamp
231 tp.trackid = point.segment
235 # Run the before_save and before_create callbacks, and then import them in bulk with activerecord-import
236 tracepoints.each do |tp|
237 tp.run_callbacks(:save) { false }
238 tp.run_callbacks(:create) { false }
241 Tracepoint.import!(tracepoints)
244 if gpx.actual_points.positive?
245 max_lat = Tracepoint.where(:trace => id).maximum(:latitude)
246 min_lat = Tracepoint.where(:trace => id).minimum(:latitude)
247 max_lon = Tracepoint.where(:trace => id).maximum(:longitude)
248 min_lon = Tracepoint.where(:trace => id).minimum(:longitude)
250 max_lat = max_lat.to_f / 10000000
251 min_lat = min_lat.to_f / 10000000
252 max_lon = max_lon.to_f / 10000000
253 min_lon = min_lon.to_f / 10000000
255 self.latitude = f_lat
256 self.longitude = f_lon
257 image.attach(:io => gpx.picture(min_lat, min_lon, max_lat, max_lon, gpx.actual_points), :filename => "#{id}.gif", :content_type => "image/gif")
258 icon.attach(:io => gpx.icon(min_lat, min_lon, max_lat, max_lon), :filename => "#{id}_icon.gif", :content_type => "image/gif")
259 self.size = gpx.actual_points
264 logger.info "done trace #{id}"
271 TraceImporterJob.new(self).enqueue(:priority => user.traces.where(:inserted => false).count)
274 def schedule_destruction
275 TraceDestroyerJob.perform_later(self)
280 def content_type(file)
281 file_type = Open3.capture2("/usr/bin/file", "-Lb", file).first.chomp
284 when /\bcompressed data,/ then file_type = Open3.capture2("/usr/bin/file", "-Lbz", file).first.chomp
288 when /\btar archive\b.*\bgzip\b/ then "application/x-tar+gzip"
289 when /\btar archive\b.*\bbzip2\b/ then "application/x-tar+x-bzip2"
290 when /\btar archive\b/ then "application/x-tar"
291 when /\bZip archive\b/ then "application/zip"
292 when /\bXML\b.*\bgzip\b/ then "application/gzip"
293 when /\bXML\b.*\bbzip2\b/ then "application/x-bzip2"
294 else "application/gpx+xml"
299 file.blob.update(:filename => "#{id}#{extension_name}") if file.attached?