1 # == Schema Information
3 # Table name: gpx_files
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
12 # timestamp :datetime not null
13 # description :string default(""), not null
14 # inserted :boolean not null
15 # visibility :enum default("public"), not null
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)
26 # gpx_files_user_id_fkey (user_id => users.id)
29 class Trace < ApplicationRecord
32 self.table_name = "gpx_files"
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
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) }
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
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]
54 after_save :set_filename
57 tags.collect(&:tag).join(", ")
61 self.tags = if s.include? ","
62 s.split(",").map(&:strip).reject(&:empty?).collect do |tag|
68 # do as before for backwards compatibility:
69 s.split.collect do |tag|
79 when ActionDispatch::Http::UploadedFile, Rack::Test::UploadedFile
80 super(:io => attachable,
81 :filename => attachable.original_filename,
82 :content_type => content_type(attachable.path),
90 %w[public identifiable].include?(visibility)
94 %w[trackable identifiable].include?(visibility)
98 visibility == "identifiable"
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"
125 def update_from_xml(xml, create: false)
126 p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
128 pt = doc.find_first("//osm/gpx_file")
131 update_from_xml_node(pt, :create => create)
133 raise OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
135 rescue LibXML::XML::Error, ArgumentError => e
136 raise OSM::APIBadXMLError.new("trace", xml, e.message)
139 def update_from_xml_node(pt, create: false)
140 raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt["visibility"].nil?
142 self.visibility = pt["visibility"]
145 raise OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt["id"].nil?
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
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
159 description = pt.find("description").first
160 raise OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
162 self.description = description.content
164 self.tags = pt.find("tag").collect do |tag|
165 Tracetag.new(:tag => tag.content)
170 file.open do |tracefile|
171 filetype = Open3.capture2("/usr/bin/file", "-Lbz", tracefile.path).first.chomp
172 gzipped = filetype.include?("gzip compressed")
173 bzipped = filetype.include?("bzip2 compressed")
174 zipped = filetype.include?("Zip archive")
175 tarred = filetype.include?("tar archive")
177 if gzipped || bzipped || zipped || tarred
178 file = Tempfile.new("trace.#{id}")
181 system("tar", "-zxOf", tracefile.path, :out => file.path)
182 elsif tarred && bzipped
183 system("tar", "-jxOf", tracefile.path, :out => file.path)
185 system("tar", "-xOf", tracefile.path, :out => file.path)
187 system("gunzip", "-c", tracefile.path, :out => file.path)
189 system("bunzip2", "-c", tracefile.path, :out => file.path)
191 system("unzip", "-p", tracefile.path, "-x", "__MACOSX/*", :out => file.path, :err => "/dev/null")
196 file = File.open(tracefile.path)
204 logger.info("GPX Import importing #{name} (#{id}) from #{user.email}")
207 gpx = GPX::File.new(file.path, :maximum_points => Settings.max_trace_size)
213 # If there are any existing points for this trace then delete them
214 Tracepoint.where(:trace => id).delete_all
216 gpx.points.each_slice(1_000) do |points|
217 # Gather the trace points together for a bulk import
220 points.each do |point|
222 f_lat = point.latitude
223 f_lon = point.longitude
228 tp.lat = point.latitude
229 tp.lon = point.longitude
230 tp.altitude = point.altitude
231 tp.timestamp = point.timestamp
233 tp.trackid = point.segment
237 # Run the before_save and before_create callbacks, and then import them in bulk with activerecord-import
238 tracepoints.each do |tp|
239 tp.run_callbacks(:save) { false }
240 tp.run_callbacks(:create) { false }
243 Tracepoint.import!(tracepoints)
246 if gpx.actual_points.positive?
247 max_lat = Tracepoint.where(:trace => id).maximum(:latitude)
248 min_lat = Tracepoint.where(:trace => id).minimum(:latitude)
249 max_lon = Tracepoint.where(:trace => id).maximum(:longitude)
250 min_lon = Tracepoint.where(:trace => id).minimum(:longitude)
252 max_lat = max_lat.to_f / 10000000
253 min_lat = min_lat.to_f / 10000000
254 max_lon = max_lon.to_f / 10000000
255 min_lon = min_lon.to_f / 10000000
257 self.latitude = f_lat
258 self.longitude = f_lon
259 image.attach(:io => gpx.picture(min_lat, min_lon, max_lat, max_lon, gpx.actual_points), :filename => "#{id}.gif", :content_type => "image/gif")
260 icon.attach(:io => gpx.icon(min_lat, min_lon, max_lat, max_lon), :filename => "#{id}_icon.gif", :content_type => "image/gif")
261 self.size = gpx.actual_points
266 logger.info "done trace #{id}"
273 TraceImporterJob.new(self).enqueue(:priority => user.traces.where(:inserted => false).count)
276 def schedule_destruction
277 TraceDestroyerJob.perform_later(self)
282 def content_type(file)
283 case Open3.capture2("/usr/bin/file", "-Lbz", file).first.chomp
284 when /.*\btar archive\b.*\bgzip\b/ then "application/x-tar+gzip"
285 when /.*\btar archive\b.*\bbzip2\b/ then "application/x-tar+x-bzip2"
286 when /.*\btar archive\b/ then "application/x-tar"
287 when /.*\bZip archive\b/ then "application/zip"
288 when /.*\bXML\b.*\bgzip\b/ then "application/gzip"
289 when /.*\bXML\b.*\bbzip2\b/ then "application/x-bzip2"
290 else "application/gpx+xml"
295 file.blob.update(:filename => "#{id}#{extension_name}") if file.attached?