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, lambda { |u| visible.where("visibility IN ('public', 'identifiable') OR user_id = ?", u) }
10 scope :public, where(:visibility => ["public", "identifiable"])
12 validates_presence_of :user_id, :name, :timestamp
13 validates_presence_of :description, :on => :create
14 validates_length_of :name, :maximum => 255
15 validates_length_of :description, :maximum => 255
16 # validates_numericality_of :latitude, :longitude
17 validates_inclusion_of :inserted, :in => [ true, false ]
18 validates_inclusion_of :visibility, :in => ["private", "public", "trackable", "identifiable"]
22 FileUtils.rm_f(trace_name)
23 FileUtils.rm_f(icon_picture_name)
24 FileUtils.rm_f(large_picture_name)
28 return tags.collect {|tt| tt.tag}.join(", ")
33 self.tags = s.split(/\s*,\s*/).select {|tag| tag !~ /^\s*$/}.collect {|tag|
39 #do as before for backwards compatibility:
40 self.tags = s.split().collect {|tag|
49 visibility == "public" || visibility == "identifiable"
53 visibility == "trackable" || visibility == "identifiable"
57 visibility == "identifiable"
60 def large_picture= (data)
61 f = File.new(large_picture_name, "wb")
66 def icon_picture= (data)
67 f = File.new(icon_picture_name, "wb")
73 f = File.new(large_picture_name, "rb")
74 logger.info "large picture file: '#{f.path}', bytes: #{File.size(f.path)}"
75 data = f.sysread(File.size(f.path))
76 logger.info "have read data, bytes: '#{data.length}'"
82 f = File.new(icon_picture_name, "rb")
83 logger.info "icon picture file: '#{f.path}'"
84 data = f.sysread(File.size(f.path))
89 def large_picture_name
90 "#{GPX_IMAGE_DIR}/#{id}.gif"
94 "#{GPX_IMAGE_DIR}/#{id}_icon.gif"
98 "#{GPX_TRACE_DIR}/#{id}.gpx"
102 filetype = `/usr/bin/file -bz #{trace_name}`.chomp
103 gzipped = filetype =~ /gzip compressed/
104 bzipped = filetype =~ /bzip2 compressed/
105 zipped = filetype =~ /Zip archive/
108 mimetype = "application/x-gzip"
110 mimetype = "application/x-bzip2"
112 mimetype = "application/x-zip"
114 mimetype = "text/xml"
121 filetype = `/usr/bin/file -bz #{trace_name}`.chomp
122 gzipped = filetype =~ /gzip compressed/
123 bzipped = filetype =~ /bzip2 compressed/
124 zipped = filetype =~ /Zip archive/
125 tarred = filetype =~ /tar archive/
127 if tarred and gzipped then
128 extension = ".tar.gz"
129 elsif tarred and bzipped then
130 extension = ".tar.bz2"
134 extension = ".gpx.gz"
136 extension = ".gpx.bz2"
147 doc = OSM::API.new.get_xml_doc
148 doc.root << to_xml_node()
153 el1 = XML::Node.new 'gpx_file'
154 el1['id'] = self.id.to_s
155 el1['name'] = self.name.to_s
156 el1['lat'] = self.latitude.to_s if self.inserted
157 el1['lon'] = self.longitude.to_s if self.inserted
158 el1['user'] = self.user.display_name
159 el1['visibility'] = self.visibility
160 el1['pending'] = (!self.inserted).to_s
161 el1['timestamp'] = self.timestamp.xmlschema
163 el2 = XML::Node.new 'description'
164 el2 << self.description
167 self.tags.each do |tag|
168 el2 = XML::Node.new('tag')
176 # Read in xml as text and return it's Node object representation
177 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 raise 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)
192 def self.from_xml_node(pt, create=false)
195 raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt['visibility'].nil?
196 trace.visibility = pt['visibility']
199 raise OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt['id'].nil?
200 trace.id = pt['id'].to_i
201 # .to_i will return 0 if there is no number that can be parsed.
202 # We want to make sure that there is no id with zero anyway
203 raise OSM::APIBadUserInput.new("ID of trace cannot be zero when updating.") if trace.id == 0
206 # We don't care about the time, as it is explicitly set on create/update/delete
207 # We don't care about the visibility as it is implicit based on the action
208 # and set manually before the actual delete
211 description = pt.find('description').first
212 raise OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
213 trace.description = description.content
215 pt.find('tag').each do |tag|
216 trace.tags.build(:tag => tag.content)
223 # TODO *nix specific, could do to work on windows... would be functionally inferior though - check for '.gz'
224 filetype = `/usr/bin/file -bz #{trace_name}`.chomp
225 gzipped = filetype =~ /gzip compressed/
226 bzipped = filetype =~ /bzip2 compressed/
227 zipped = filetype =~ /Zip archive/
228 tarred = filetype =~ /tar archive/
230 if gzipped or bzipped or zipped or tarred then
231 tmpfile = Tempfile.new("trace.#{id}");
233 if tarred and gzipped then
234 system("tar -zxOf #{trace_name} > #{tmpfile.path}")
235 elsif tarred and bzipped then
236 system("tar -jxOf #{trace_name} > #{tmpfile.path}")
238 system("tar -xOf #{trace_name} > #{tmpfile.path}")
240 system("gunzip -c #{trace_name} > #{tmpfile.path}")
242 system("bunzip2 -c #{trace_name} > #{tmpfile.path}")
244 system("unzip -p #{trace_name} -x '__MACOSX/*' > #{tmpfile.path}")
251 file = File.open(trace_name)
258 logger.info("GPX Import importing #{name} (#{id}) from #{user.email}")
260 gpx = GPX::File.new(self.xml_file)
266 # If there are any existing points for this trace then delete
267 # them - we check for existing points first to avoid locking
268 # the table in the common case where there aren't any.
269 if Tracepoint.where(:gpx_id => self.id).exists?
270 Tracepoint.delete_all(:gpx_id => self.id)
273 gpx.points do |point|
275 f_lat = point.latitude
276 f_lon = point.longitude
281 tp.lat = point.latitude
282 tp.lon = point.longitude
283 tp.altitude = point.altitude
284 tp.timestamp = point.timestamp
286 tp.trackid = point.segment
290 if gpx.actual_points > 0
291 max_lat = Tracepoint.maximum('latitude', :conditions => ['gpx_id = ?', id])
292 min_lat = Tracepoint.minimum('latitude', :conditions => ['gpx_id = ?', id])
293 max_lon = Tracepoint.maximum('longitude', :conditions => ['gpx_id = ?', id])
294 min_lon = Tracepoint.minimum('longitude', :conditions => ['gpx_id = ?', id])
296 max_lat = max_lat.to_f / 10000000
297 min_lat = min_lat.to_f / 10000000
298 max_lon = max_lon.to_f / 10000000
299 min_lon = min_lon.to_f / 10000000
301 self.latitude = f_lat
302 self.longitude = f_lon
303 self.large_picture = gpx.picture(min_lat, min_lon, max_lat, max_lon, gpx.actual_points)
304 self.icon_picture = gpx.icon(min_lat, min_lon, max_lat, max_lon)
305 self.size = gpx.actual_points
310 logger.info "done trace #{id}"