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 IN ('public', 'identifiable') OR user_id = ?", 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, :presence => true, :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_destroy :remove_files
53 after_save :set_filename
56 tags.collect(&:tag).join(", ")
60 self.tags = if s.include? ","
61 s.split(/\s*,\s*/).grep_v(/^\s*$/).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 visibility == "public" || visibility == "identifiable"
93 visibility == "trackable" || visibility == "identifiable"
97 visibility == "identifiable"
102 data = image.blob.download
104 f = File.new(large_picture_name, "rb")
105 data = f.sysread(File.size(f.path))
114 data = icon.blob.download
116 f = File.new(icon_picture_name, "rb")
117 data = f.sysread(File.size(f.path))
124 def large_picture_name
125 "#{Settings.gpx_image_dir}/#{id}.gif"
128 def icon_picture_name
129 "#{Settings.gpx_image_dir}/#{id}_icon.gif"
133 "#{Settings.gpx_trace_dir}/#{id}.gpx"
140 content_type(trace_name)
146 when "application/x-tar+gzip" then ".tar.gz"
147 when "application/x-tar+x-bzip2" then ".tar.bz2"
148 when "application/x-tar" then ".tar"
149 when "application/zip" then ".zip"
150 when "application/gzip" then ".gpx.gz"
151 when "application/x-bzip2" then ".gpx.bz2"
156 def update_from_xml(xml, create: false)
157 p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
159 pt = doc.find_first("//osm/gpx_file")
162 update_from_xml_node(pt, :create => create)
164 raise OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
166 rescue LibXML::XML::Error, ArgumentError => e
167 raise OSM::APIBadXMLError.new("trace", xml, e.message)
170 def update_from_xml_node(pt, create: false)
171 raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt["visibility"].nil?
173 self.visibility = pt["visibility"]
176 raise OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt["id"].nil?
179 # .to_i will return 0 if there is no number that can be parsed.
180 # We want to make sure that there is no id with zero anyway
181 raise OSM::APIBadUserInput, "ID of trace cannot be zero when updating." if id.zero?
182 raise OSM::APIBadUserInput, "The id in the url (#{self.id}) is not the same as provided in the xml (#{id})" unless self.id == id
185 # We don't care about the time, as it is explicitly set on create/update/delete
186 # We don't care about the visibility as it is implicit based on the action
187 # and set manually before the actual delete
190 description = pt.find("description").first
191 raise OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
193 self.description = description.content
195 self.tags = pt.find("tag").collect do |tag|
196 Tracetag.new(:tag => tag.content)
201 with_trace_file do |trace_name|
202 filetype = Open3.capture2("/usr/bin/file", "-Lbz", trace_name).first.chomp
203 gzipped = filetype.include?("gzip compressed")
204 bzipped = filetype.include?("bzip2 compressed")
205 zipped = filetype.include?("Zip archive")
206 tarred = filetype.include?("tar archive")
208 if gzipped || bzipped || zipped || tarred
209 file = Tempfile.new("trace.#{id}")
212 system("tar", "-zxOf", trace_name, :out => file.path)
213 elsif tarred && bzipped
214 system("tar", "-jxOf", trace_name, :out => file.path)
216 system("tar", "-xOf", trace_name, :out => file.path)
218 system("gunzip", "-c", trace_name, :out => file.path)
220 system("bunzip2", "-c", trace_name, :out => file.path)
222 system("unzip", "-p", trace_name, "-x", "__MACOSX/*", :out => file.path, :err => "/dev/null")
227 file = File.open(trace_name)
235 logger.info("GPX Import importing #{name} (#{id}) from #{user.email}")
237 with_trace_file do |trace_name|
238 gpx = GPX::File.new(trace_name)
244 # If there are any existing points for this trace then delete them
245 Tracepoint.where(:gpx_id => id).delete_all
247 gpx.points.each_slice(1_000) do |points|
248 # Gather the trace points together for a bulk import
251 points.each do |point|
253 f_lat = point.latitude
254 f_lon = point.longitude
259 tp.lat = point.latitude
260 tp.lon = point.longitude
261 tp.altitude = point.altitude
262 tp.timestamp = point.timestamp
264 tp.trackid = point.segment
268 # Run the before_save and before_create callbacks, and then import them in bulk with activerecord-import
269 tracepoints.each do |tp|
270 tp.run_callbacks(:save) { false }
271 tp.run_callbacks(:create) { false }
274 Tracepoint.import!(tracepoints)
277 if gpx.actual_points.positive?
278 max_lat = Tracepoint.where(:gpx_id => id).maximum(:latitude)
279 min_lat = Tracepoint.where(:gpx_id => id).minimum(:latitude)
280 max_lon = Tracepoint.where(:gpx_id => id).maximum(:longitude)
281 min_lon = Tracepoint.where(:gpx_id => id).minimum(:longitude)
283 max_lat = max_lat.to_f / 10000000
284 min_lat = min_lat.to_f / 10000000
285 max_lon = max_lon.to_f / 10000000
286 min_lon = min_lon.to_f / 10000000
288 self.latitude = f_lat
289 self.longitude = f_lon
290 image.attach(:io => gpx.picture(min_lat, min_lon, max_lat, max_lon, gpx.actual_points), :filename => "#{id}.gif", :content_type => "image/gif")
291 icon.attach(:io => gpx.icon(min_lat, min_lon, max_lat, max_lon), :filename => "#{id}_icon.gif", :content_type => "image/gif")
292 self.size = gpx.actual_points
297 logger.info "done trace #{id}"
303 def migrate_to_storage!
304 file.attach(:io => File.open(trace_name),
306 :content_type => content_type(trace_name),
310 image.attach(:io => File.open(large_picture_name),
311 :filename => "#{id}.gif",
312 :content_type => "image/gif")
313 icon.attach(:io => File.open(icon_picture_name),
314 :filename => "#{id}_icon.gif",
315 :content_type => "image/gif")
325 def content_type(file)
326 case Open3.capture2("/usr/bin/file", "-Lbz", file).first.chomp
327 when /.*\btar archive\b.*\bgzip\b/ then "application/x-tar+gzip"
328 when /.*\btar archive\b.*\bbzip2\b/ then "application/x-tar+x-bzip2"
329 when /.*\btar archive\b/ then "application/x-tar"
330 when /.*\bZip archive\b/ then "application/zip"
331 when /.*\bXML\b.*\bgzip\b/ then "application/gzip"
332 when /.*\bXML\b.*\bbzip2\b/ then "application/x-bzip2"
333 else "application/gpx+xml"
348 file.blob.update(:filename => "#{id}#{extension_name}") if file.attached?
352 FileUtils.rm_f(trace_name)
353 FileUtils.rm_f(icon_picture_name)
354 FileUtils.rm_f(large_picture_name)