1 # == Schema Information
3 # Table name: gpx_files
5 # id :integer not null, primary key
6 # user_id :integer 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 < ActiveRecord::Base
29 self.table_name = "gpx_files"
31 belongs_to :user, :counter_cache => true
32 has_many :tags, :class_name => "Tracetag", :foreign_key => "gpx_id", :dependent => :delete_all
33 has_many :points, :class_name => "Tracepoint", :foreign_key => "gpx_id", :dependent => :delete_all
35 scope :visible, -> { where(:visible => true) }
36 scope :visible_to, ->(u) { visible.where("visibility IN ('public', 'identifiable') OR user_id = ?", u) }
37 scope :visible_to_all, -> { where(:visibility => %w[public identifiable]) }
38 scope :tagged, ->(t) { joins(:tags).where(:gpx_file_tags => { :tag => t }) }
40 validates :user, :presence => true, :associated => true
41 validates :name, :presence => true, :length => 1..255
42 validates :description, :presence => { :on => :create }, :length => 1..255
43 validates :timestamp, :presence => true
44 validates :visibility, :inclusion => %w[private public trackable identifiable]
48 FileUtils.rm_f(trace_name)
49 FileUtils.rm_f(icon_picture_name)
50 FileUtils.rm_f(large_picture_name)
54 tags.collect(&:tag).join(", ")
58 self.tags = if s.include? ","
59 s.split(/\s*,\s*/).reject { |tag| tag =~ /^\s*$/ }.collect do |tag|
65 # do as before for backwards compatibility:
66 s.split.collect do |tag|
75 visibility == "public" || visibility == "identifiable"
79 visibility == "trackable" || visibility == "identifiable"
83 visibility == "identifiable"
86 def large_picture=(data)
87 f = File.new(large_picture_name, "wb")
92 def icon_picture=(data)
93 f = File.new(icon_picture_name, "wb")
99 f = File.new(large_picture_name, "rb")
100 data = f.sysread(File.size(f.path))
106 f = File.new(icon_picture_name, "rb")
107 data = f.sysread(File.size(f.path))
112 def large_picture_name
113 "#{GPX_IMAGE_DIR}/#{id}.gif"
116 def icon_picture_name
117 "#{GPX_IMAGE_DIR}/#{id}_icon.gif"
121 "#{GPX_TRACE_DIR}/#{id}.gpx"
125 filetype = `/usr/bin/file -Lbz #{trace_name}`.chomp
126 gzipped = filetype =~ /gzip compressed/
127 bzipped = filetype =~ /bzip2 compressed/
128 zipped = filetype =~ /Zip archive/
129 tarred = filetype =~ /tar archive/
131 mimetype = if gzipped
134 "application/x-bzip2"
140 "application/gpx+xml"
147 filetype = `/usr/bin/file -Lbz #{trace_name}`.chomp
148 gzipped = filetype =~ /gzip compressed/
149 bzipped = filetype =~ /bzip2 compressed/
150 zipped = filetype =~ /Zip archive/
151 tarred = filetype =~ /tar archive/
153 extension = if tarred && gzipped
155 elsif tarred && bzipped
173 doc = OSM::API.new.get_xml_doc
174 doc.root << to_xml_node
179 el1 = XML::Node.new "gpx_file"
181 el1["name"] = name.to_s
182 el1["lat"] = latitude.to_s if inserted
183 el1["lon"] = longitude.to_s if inserted
184 el1["user"] = user.display_name
185 el1["visibility"] = visibility
186 el1["pending"] = inserted ? "false" : "true"
187 el1["timestamp"] = timestamp.xmlschema
189 el2 = XML::Node.new "description"
194 el2 = XML::Node.new("tag")
202 def update_from_xml(xml, create = false)
203 p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
206 doc.find("//osm/gpx_file").each do |pt|
207 return update_from_xml_node(pt, create)
210 raise OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
211 rescue LibXML::XML::Error, ArgumentError => ex
212 raise OSM::APIBadXMLError.new("trace", xml, ex.message)
215 def update_from_xml_node(pt, create = false)
216 raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt["visibility"].nil?
218 self.visibility = pt["visibility"]
221 raise OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt["id"].nil?
224 # .to_i will return 0 if there is no number that can be parsed.
225 # We want to make sure that there is no id with zero anyway
226 raise OSM::APIBadUserInput, "ID of trace cannot be zero when updating." if id.zero?
227 raise OSM::APIBadUserInput, "The id in the url (#{self.id}) is not the same as provided in the xml (#{id})" unless self.id == id
230 # We don't care about the time, as it is explicitly set on create/update/delete
231 # We don't care about the visibility as it is implicit based on the action
232 # and set manually before the actual delete
235 description = pt.find("description").first
236 raise OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
238 self.description = description.content
240 self.tags = pt.find("tag").collect do |tag|
241 Tracetag.new(:tag => tag.content)
246 # TODO: *nix specific, could do to work on windows... would be functionally inferior though - check for '.gz'
247 filetype = `/usr/bin/file -Lbz #{trace_name}`.chomp
248 gzipped = filetype =~ /gzip compressed/
249 bzipped = filetype =~ /bzip2 compressed/
250 zipped = filetype =~ /Zip archive/
251 tarred = filetype =~ /tar archive/
253 if gzipped || bzipped || zipped || tarred
254 tmpfile = Tempfile.new("trace.#{id}")
257 system("tar -zxOf #{trace_name} > #{tmpfile.path}")
258 elsif tarred && bzipped
259 system("tar -jxOf #{trace_name} > #{tmpfile.path}")
261 system("tar -xOf #{trace_name} > #{tmpfile.path}")
263 system("gunzip -c #{trace_name} > #{tmpfile.path}")
265 system("bunzip2 -c #{trace_name} > #{tmpfile.path}")
267 system("unzip -p #{trace_name} -x '__MACOSX/*' > #{tmpfile.path} 2> /dev/null")
274 file = File.open(trace_name)
281 logger.info("GPX Import importing #{name} (#{id}) from #{user.email}")
283 gpx = GPX::File.new(xml_file)
289 # If there are any existing points for this trace then delete them
290 Tracepoint.where(:gpx_id => id).delete_all
292 gpx.points do |point|
294 f_lat = point.latitude
295 f_lon = point.longitude
300 tp.lat = point.latitude
301 tp.lon = point.longitude
302 tp.altitude = point.altitude
303 tp.timestamp = point.timestamp
305 tp.trackid = point.segment
309 if gpx.actual_points.positive?
310 max_lat = Tracepoint.where(:gpx_id => id).maximum(:latitude)
311 min_lat = Tracepoint.where(:gpx_id => id).minimum(:latitude)
312 max_lon = Tracepoint.where(:gpx_id => id).maximum(:longitude)
313 min_lon = Tracepoint.where(:gpx_id => id).minimum(:longitude)
315 max_lat = max_lat.to_f / 10000000
316 min_lat = min_lat.to_f / 10000000
317 max_lon = max_lon.to_f / 10000000
318 min_lon = min_lon.to_f / 10000000
320 self.latitude = f_lat
321 self.longitude = f_lon
322 self.large_picture = gpx.picture(min_lat, min_lon, max_lat, max_lon, gpx.actual_points)
323 self.icon_picture = gpx.icon(min_lat, min_lon, max_lat, max_lon)
324 self.size = gpx.actual_points
329 logger.info "done trace #{id}"