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_presence_of :user_id, :name, :timestamp
14 validates_presence_of :description, :on => :create
15 validates_length_of :name, :maximum => 255
16 validates_length_of :description, :maximum => 255
17 # validates_numericality_of :latitude, :longitude
18 validates_inclusion_of :inserted, :in => [true, false]
19 validates_inclusion_of :visibility, :in => %w(private public trackable identifiable)
23 FileUtils.rm_f(trace_name)
24 FileUtils.rm_f(icon_picture_name)
25 FileUtils.rm_f(large_picture_name)
29 tags.collect(&:tag).join(", ")
34 self.tags = s.split(/\s*,\s*/).select { |tag| tag !~ /^\s*$/ }.collect {|tag|
40 # do as before for backwards compatibility:
41 self.tags = s.split.collect {|tag|
50 visibility == "public" || visibility == "identifiable"
54 visibility == "trackable" || visibility == "identifiable"
58 visibility == "identifiable"
61 def large_picture=(data)
62 f = File.new(large_picture_name, "wb")
67 def icon_picture=(data)
68 f = File.new(icon_picture_name, "wb")
74 f = File.new(large_picture_name, "rb")
75 logger.info "large picture file: '#{f.path}', bytes: #{File.size(f.path)}"
76 data = f.sysread(File.size(f.path))
77 logger.info "have read data, bytes: '#{data.length}'"
83 f = File.new(icon_picture_name, "rb")
84 logger.info "icon picture file: '#{f.path}'"
85 data = f.sysread(File.size(f.path))
90 def large_picture_name
91 "#{GPX_IMAGE_DIR}/#{id}.gif"
95 "#{GPX_IMAGE_DIR}/#{id}_icon.gif"
99 "#{GPX_TRACE_DIR}/#{id}.gpx"
103 filetype = `/usr/bin/file -bz #{trace_name}`.chomp
104 gzipped = filetype =~ /gzip compressed/
105 bzipped = filetype =~ /bzip2 compressed/
106 zipped = filetype =~ /Zip archive/
109 mimetype = "application/x-gzip"
111 mimetype = "application/x-bzip2"
113 mimetype = "application/x-zip"
115 mimetype = "application/gpx+xml"
122 filetype = `/usr/bin/file -bz #{trace_name}`.chomp
123 gzipped = filetype =~ /gzip compressed/
124 bzipped = filetype =~ /bzip2 compressed/
125 zipped = filetype =~ /Zip archive/
126 tarred = filetype =~ /tar archive/
129 extension = ".tar.gz"
130 elsif tarred && bzipped
131 extension = ".tar.bz2"
135 extension = ".gpx.gz"
137 extension = ".gpx.bz2"
148 doc = OSM::API.new.get_xml_doc
149 doc.root << to_xml_node
154 el1 = XML::Node.new "gpx_file"
156 el1["name"] = name.to_s
157 el1["lat"] = latitude.to_s if inserted
158 el1["lon"] = longitude.to_s if inserted
159 el1["user"] = user.display_name
160 el1["visibility"] = visibility
161 el1["pending"] = (!inserted).to_s
162 el1["timestamp"] = timestamp.xmlschema
164 el2 = XML::Node.new "description"
169 el2 = XML::Node.new("tag")
177 # Read in xml as text and return it's Node object representation
178 def self.from_xml(xml, create = false)
179 p = XML::Parser.string(xml)
182 doc.find("//osm/gpx_file").each do |pt|
183 return Trace.from_xml_node(pt, create)
186 fail OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
187 rescue LibXML::XML::Error, ArgumentError => ex
188 raise OSM::APIBadXMLError.new("trace", xml, ex.message)
191 def self.from_xml_node(pt, create = false)
194 fail OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt["visibility"].nil?
195 trace.visibility = pt["visibility"]
198 fail OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt["id"].nil?
199 trace.id = pt["id"].to_i
200 # .to_i will return 0 if there is no number that can be parsed.
201 # We want to make sure that there is no id with zero anyway
202 fail OSM::APIBadUserInput.new("ID of trace cannot be zero when updating.") if trace.id == 0
205 # We don't care about the time, as it is explicitly set on create/update/delete
206 # We don't care about the visibility as it is implicit based on the action
207 # and set manually before the actual delete
210 description = pt.find("description").first
211 fail OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
212 trace.description = description.content
214 pt.find("tag").each do |tag|
215 trace.tags.build(:tag => tag.content)
222 # TODO: *nix specific, could do to work on windows... would be functionally inferior though - check for '.gz'
223 filetype = `/usr/bin/file -bz #{trace_name}`.chomp
224 gzipped = filetype =~ /gzip compressed/
225 bzipped = filetype =~ /bzip2 compressed/
226 zipped = filetype =~ /Zip archive/
227 tarred = filetype =~ /tar archive/
229 if gzipped || bzipped || zipped || tarred
230 tmpfile = Tempfile.new("trace.#{id}")
233 system("tar -zxOf #{trace_name} > #{tmpfile.path}")
234 elsif tarred && bzipped
235 system("tar -jxOf #{trace_name} > #{tmpfile.path}")
237 system("tar -xOf #{trace_name} > #{tmpfile.path}")
239 system("gunzip -c #{trace_name} > #{tmpfile.path}")
241 system("bunzip2 -c #{trace_name} > #{tmpfile.path}")
243 system("unzip -p #{trace_name} -x '__MACOSX/*' > #{tmpfile.path}")
250 file = File.open(trace_name)
257 logger.info("GPX Import importing #{name} (#{id}) from #{user.email}")
259 gpx = GPX::File.new(xml_file)
265 # If there are any existing points for this trace then delete
266 # them - we check for existing points first to avoid locking
267 # the table in the common case where there aren't any.
268 if Tracepoint.where(:gpx_id => id).exists?
269 Tracepoint.delete_all(:gpx_id => id)
272 gpx.points do |point|
274 f_lat = point.latitude
275 f_lon = point.longitude
280 tp.lat = point.latitude
281 tp.lon = point.longitude
282 tp.altitude = point.altitude
283 tp.timestamp = point.timestamp
285 tp.trackid = point.segment
289 if gpx.actual_points > 0
290 max_lat = Tracepoint.where(:gpx_id => id).maximum(:latitude)
291 min_lat = Tracepoint.where(:gpx_id => id).minimum(:latitude)
292 max_lon = Tracepoint.where(:gpx_id => id).maximum(:longitude)
293 min_lon = Tracepoint.where(:gpx_id => id).minimum(:longitude)
295 max_lat = max_lat.to_f / 10000000
296 min_lat = min_lat.to_f / 10000000
297 max_lon = max_lon.to_f / 10000000
298 min_lon = min_lon.to_f / 10000000
300 self.latitude = f_lat
301 self.longitude = f_lon
302 self.large_picture = gpx.picture(min_lat, min_lon, max_lat, max_lon, gpx.actual_points)
303 self.icon_picture = gpx.icon(min_lat, min_lon, max_lat, max_lon)
304 self.size = gpx.actual_points
309 logger.info "done trace #{id}"