1 class Trace < ActiveRecord::Base
2 self.table_name = "gpx_files"
4 belongs_to :user, :counter_cache => true
5 has_many :tags, :class_name => "Tracetag", :foreign_key => "gpx_id", :dependent => :delete_all
6 has_many :points, :class_name => "Tracepoint", :foreign_key => "gpx_id", :dependent => :delete_all
8 scope :visible, -> { where(:visible => true) }
9 scope :visible_to, ->(u) { visible.where("visibility IN ('public', 'identifiable') OR user_id = ?", u) }
10 scope :visible_to_all, -> { where(:visibility => %w[public identifiable]) }
11 scope :tagged, ->(t) { joins(:tags).where(:gpx_file_tags => { :tag => t }) }
13 validates :user, :presence => true, :associated => true
14 validates :name, :presence => true, :length => 1..255
15 validates :description, :presence => { :on => :create }, :length => 1..255
16 validates :timestamp, :presence => true
17 validates :visibility, :inclusion => %w[private public trackable identifiable]
21 FileUtils.rm_f(trace_name)
22 FileUtils.rm_f(icon_picture_name)
23 FileUtils.rm_f(large_picture_name)
27 tags.collect(&:tag).join(", ")
31 self.tags = if s.include? ","
32 s.split(/\s*,\s*/).reject { |tag| tag =~ /^\s*$/ }.collect do |tag|
38 # do as before for backwards compatibility:
39 s.split.collect do |tag|
48 visibility == "public" || visibility == "identifiable"
52 visibility == "trackable" || visibility == "identifiable"
56 visibility == "identifiable"
59 def large_picture=(data)
60 f = File.new(large_picture_name, "wb")
65 def icon_picture=(data)
66 f = File.new(icon_picture_name, "wb")
72 f = File.new(large_picture_name, "rb")
73 data = f.sysread(File.size(f.path))
79 f = File.new(icon_picture_name, "rb")
80 data = f.sysread(File.size(f.path))
85 def large_picture_name
86 "#{GPX_IMAGE_DIR}/#{id}.gif"
90 "#{GPX_IMAGE_DIR}/#{id}_icon.gif"
94 "#{GPX_TRACE_DIR}/#{id}.gpx"
98 filetype = `/usr/bin/file -Lbz #{trace_name}`.chomp
99 gzipped = filetype =~ /gzip compressed/
100 bzipped = filetype =~ /bzip2 compressed/
101 zipped = filetype =~ /Zip archive/
102 tarred = filetype =~ /tar archive/
104 mimetype = if gzipped
107 "application/x-bzip2"
113 "application/gpx+xml"
120 filetype = `/usr/bin/file -Lbz #{trace_name}`.chomp
121 gzipped = filetype =~ /gzip compressed/
122 bzipped = filetype =~ /bzip2 compressed/
123 zipped = filetype =~ /Zip archive/
124 tarred = filetype =~ /tar archive/
126 extension = if tarred && gzipped
128 elsif tarred && bzipped
146 doc = OSM::API.new.get_xml_doc
147 doc.root << to_xml_node
152 el1 = XML::Node.new "gpx_file"
154 el1["name"] = name.to_s
155 el1["lat"] = latitude.to_s if inserted
156 el1["lon"] = longitude.to_s if inserted
157 el1["user"] = user.display_name
158 el1["visibility"] = visibility
159 el1["pending"] = inserted ? "false" : "true"
160 el1["timestamp"] = timestamp.xmlschema
162 el2 = XML::Node.new "description"
167 el2 = XML::Node.new("tag")
175 def update_from_xml(xml, create = false)
176 p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
179 doc.find("//osm/gpx_file").each do |pt|
180 return update_from_xml_node(pt, create)
183 raise OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
184 rescue LibXML::XML::Error, ArgumentError => ex
185 raise OSM::APIBadXMLError.new("trace", xml, ex.message)
188 def update_from_xml_node(pt, create = false)
189 raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt["visibility"].nil?
190 self.visibility = pt["visibility"]
193 raise OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt["id"].nil?
195 # .to_i will return 0 if there is no number that can be parsed.
196 # We want to make sure that there is no id with zero anyway
197 raise OSM::APIBadUserInput.new("ID of trace cannot be zero when updating.") if id.zero?
198 raise OSM::APIBadUserInput.new("The id in the url (#{self.id}) is not the same as provided in the xml (#{id})") unless self.id == id
201 # We don't care about the time, as it is explicitly set on create/update/delete
202 # We don't care about the visibility as it is implicit based on the action
203 # and set manually before the actual delete
206 description = pt.find("description").first
207 raise OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
208 self.description = description.content
210 self.tags = pt.find("tag").collect do |tag|
211 Tracetag.new(:tag => tag.content)
216 # TODO: *nix specific, could do to work on windows... would be functionally inferior though - check for '.gz'
217 filetype = `/usr/bin/file -Lbz #{trace_name}`.chomp
218 gzipped = filetype =~ /gzip compressed/
219 bzipped = filetype =~ /bzip2 compressed/
220 zipped = filetype =~ /Zip archive/
221 tarred = filetype =~ /tar archive/
223 if gzipped || bzipped || zipped || tarred
224 tmpfile = Tempfile.new("trace.#{id}")
227 system("tar -zxOf #{trace_name} > #{tmpfile.path}")
228 elsif tarred && bzipped
229 system("tar -jxOf #{trace_name} > #{tmpfile.path}")
231 system("tar -xOf #{trace_name} > #{tmpfile.path}")
233 system("gunzip -c #{trace_name} > #{tmpfile.path}")
235 system("bunzip2 -c #{trace_name} > #{tmpfile.path}")
237 system("unzip -p #{trace_name} -x '__MACOSX/*' > #{tmpfile.path} 2> /dev/null")
244 file = File.open(trace_name)
251 logger.info("GPX Import importing #{name} (#{id}) from #{user.email}")
253 gpx = GPX::File.new(xml_file)
259 # If there are any existing points for this trace then delete them
260 Tracepoint.where(:gpx_id => id).delete_all
262 gpx.points do |point|
264 f_lat = point.latitude
265 f_lon = point.longitude
270 tp.lat = point.latitude
271 tp.lon = point.longitude
272 tp.altitude = point.altitude
273 tp.timestamp = point.timestamp
275 tp.trackid = point.segment
279 if gpx.actual_points > 0
280 max_lat = Tracepoint.where(:gpx_id => id).maximum(:latitude)
281 min_lat = Tracepoint.where(:gpx_id => id).minimum(:latitude)
282 max_lon = Tracepoint.where(:gpx_id => id).maximum(:longitude)
283 min_lon = Tracepoint.where(:gpx_id => id).minimum(:longitude)
285 max_lat = max_lat.to_f / 10000000
286 min_lat = min_lat.to_f / 10000000
287 max_lon = max_lon.to_f / 10000000
288 min_lon = min_lon.to_f / 10000000
290 self.latitude = f_lat
291 self.longitude = f_lon
292 self.large_picture = gpx.picture(min_lat, min_lon, max_lat, max_lon, gpx.actual_points)
293 self.icon_picture = gpx.icon(min_lat, min_lon, max_lat, max_lon)
294 self.size = gpx.actual_points
299 logger.info "done trace #{id}"