1 # == Schema Information
3 # Table name: gpx_files
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
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)
25 # gpx_files_user_id_fkey (user_id => users.id)
28 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 }) }
42 has_one_attached :file, :service => Settings.trace_file_storage
43 has_one_attached :image, :service => Settings.trace_image_storage
44 has_one_attached :icon, :service => Settings.trace_icon_storage
46 validates :user, :associated => true
47 validates :name, :presence => true, :length => 1..255, :characters => true
48 validates :description, :presence => { :on => :create }, :length => 1..255, :characters => true
49 validates :timestamp, :presence => true
50 validates :visibility, :inclusion => %w[private public trackable identifiable]
52 after_save :set_filename
55 tags.collect(&:tag).join(", ")
59 self.tags = if s.include? ","
60 s.split(",").map(&:strip).reject(&:empty?).collect do |tag|
66 # do as before for backwards compatibility:
67 s.split.collect do |tag|
77 when ActionDispatch::Http::UploadedFile, Rack::Test::UploadedFile
78 super(:io => attachable,
79 :filename => attachable.original_filename,
80 :content_type => content_type(attachable.path),
88 visibility == "public" || visibility == "identifiable"
92 visibility == "trackable" || visibility == "identifiable"
96 visibility == "identifiable"
113 when "application/x-tar+gzip" then ".tar.gz"
114 when "application/x-tar+x-bzip2" then ".tar.bz2"
115 when "application/x-tar" then ".tar"
116 when "application/zip" then ".zip"
117 when "application/gzip" then ".gpx.gz"
118 when "application/x-bzip2" then ".gpx.bz2"
123 def update_from_xml(xml, create: false)
124 p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
126 pt = doc.find_first("//osm/gpx_file")
129 update_from_xml_node(pt, :create => create)
131 raise OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
133 rescue LibXML::XML::Error, ArgumentError => e
134 raise OSM::APIBadXMLError.new("trace", xml, e.message)
137 def update_from_xml_node(pt, create: false)
138 raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt["visibility"].nil?
140 self.visibility = pt["visibility"]
143 raise OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt["id"].nil?
146 # .to_i will return 0 if there is no number that can be parsed.
147 # We want to make sure that there is no id with zero anyway
148 raise OSM::APIBadUserInput, "ID of trace cannot be zero when updating." if id.zero?
149 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 # We don't care about the time, as it is explicitly set on create/update/delete
153 # We don't care about the visibility as it is implicit based on the action
154 # and set manually before the actual delete
157 description = pt.find("description").first
158 raise OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
160 self.description = description.content
162 self.tags = pt.find("tag").collect do |tag|
163 Tracetag.new(:tag => tag.content)
168 file.open do |tracefile|
169 filetype = Open3.capture2("/usr/bin/file", "-Lbz", tracefile.path).first.chomp
170 gzipped = filetype.include?("gzip compressed")
171 bzipped = filetype.include?("bzip2 compressed")
172 zipped = filetype.include?("Zip archive")
173 tarred = filetype.include?("tar archive")
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)
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}"
272 def content_type(file)
273 case Open3.capture2("/usr/bin/file", "-Lbz", file).first.chomp
274 when /.*\btar archive\b.*\bgzip\b/ then "application/x-tar+gzip"
275 when /.*\btar archive\b.*\bbzip2\b/ then "application/x-tar+x-bzip2"
276 when /.*\btar archive\b/ then "application/x-tar"
277 when /.*\bZip archive\b/ then "application/zip"
278 when /.*\bXML\b.*\bgzip\b/ then "application/gzip"
279 when /.*\bXML\b.*\bbzip2\b/ then "application/x-bzip2"
280 else "application/gpx+xml"
285 file.blob.update(:filename => "#{id}#{extension_name}") if file.attached?