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(", ")
32 self.tags = s.split(/\s*,\s*/).select { |tag| tag !~ /^\s*$/ }.collect {|tag|
38 # do as before for backwards compatibility:
39 self.tags = s.split.collect {|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 logger.info "large picture file: '#{f.path}', bytes: #{File.size(f.path)}"
74 data = f.sysread(File.size(f.path))
75 logger.info "have read data, bytes: '#{data.length}'"
81 f = File.new(icon_picture_name, "rb")
82 logger.info "icon picture file: '#{f.path}'"
83 data = f.sysread(File.size(f.path))
88 def large_picture_name
89 "#{GPX_IMAGE_DIR}/#{id}.gif"
93 "#{GPX_IMAGE_DIR}/#{id}_icon.gif"
97 "#{GPX_TRACE_DIR}/#{id}.gpx"
101 filetype = `/usr/bin/file -bz #{trace_name}`.chomp
102 gzipped = filetype =~ /gzip compressed/
103 bzipped = filetype =~ /bzip2 compressed/
104 zipped = filetype =~ /Zip archive/
105 tarred = filetype =~ /tar archive/
108 mimetype = "application/x-gzip"
110 mimetype = "application/x-bzip2"
112 mimetype = "application/x-zip"
114 mimetype = "application/x-tar"
116 mimetype = "application/gpx+xml"
123 filetype = `/usr/bin/file -bz #{trace_name}`.chomp
124 gzipped = filetype =~ /gzip compressed/
125 bzipped = filetype =~ /bzip2 compressed/
126 zipped = filetype =~ /Zip archive/
127 tarred = filetype =~ /tar archive/
130 extension = ".tar.gz"
131 elsif tarred && bzipped
132 extension = ".tar.bz2"
136 extension = ".gpx.gz"
138 extension = ".gpx.bz2"
149 doc = OSM::API.new.get_xml_doc
150 doc.root << to_xml_node
155 el1 = XML::Node.new "gpx_file"
157 el1["name"] = name.to_s
158 el1["lat"] = latitude.to_s if inserted
159 el1["lon"] = longitude.to_s if inserted
160 el1["user"] = user.display_name
161 el1["visibility"] = visibility
162 el1["pending"] = (!inserted).to_s
163 el1["timestamp"] = timestamp.xmlschema
165 el2 = XML::Node.new "description"
170 el2 = XML::Node.new("tag")
178 # Read in xml as text and return it's Node object representation
179 def self.from_xml(xml, create = false)
180 p = XML::Parser.string(xml)
183 doc.find("//osm/gpx_file").each do |pt|
184 return Trace.from_xml_node(pt, create)
187 fail OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
188 rescue LibXML::XML::Error, ArgumentError => ex
189 raise OSM::APIBadXMLError.new("trace", xml, ex.message)
192 def self.from_xml_node(pt, create = false)
195 fail OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt["visibility"].nil?
196 trace.visibility = pt["visibility"]
199 fail 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 fail 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 fail 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 || bzipped || zipped || tarred
231 tmpfile = Tempfile.new("trace.#{id}")
234 system("tar -zxOf #{trace_name} > #{tmpfile.path}")
235 elsif tarred && bzipped
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} 2> /dev/null")
251 file = File.open(trace_name)
258 logger.info("GPX Import importing #{name} (#{id}) from #{user.email}")
260 gpx = GPX::File.new(xml_file)
266 # If there are any existing points for this trace then delete them
267 Tracepoint.delete_all(:gpx_id => id)
269 gpx.points do |point|
271 f_lat = point.latitude
272 f_lon = point.longitude
277 tp.lat = point.latitude
278 tp.lon = point.longitude
279 tp.altitude = point.altitude
280 tp.timestamp = point.timestamp
282 tp.trackid = point.segment
286 if gpx.actual_points > 0
287 max_lat = Tracepoint.where(:gpx_id => id).maximum(:latitude)
288 min_lat = Tracepoint.where(:gpx_id => id).minimum(:latitude)
289 max_lon = Tracepoint.where(:gpx_id => id).maximum(:longitude)
290 min_lon = Tracepoint.where(:gpx_id => id).minimum(:longitude)
292 max_lat = max_lat.to_f / 10000000
293 min_lat = min_lat.to_f / 10000000
294 max_lon = max_lon.to_f / 10000000
295 min_lon = min_lon.to_f / 10000000
297 self.latitude = f_lat
298 self.longitude = f_lon
299 self.large_picture = gpx.picture(min_lat, min_lon, max_lat, max_lon, gpx.actual_points)
300 self.icon_picture = gpx.icon(min_lat, min_lon, max_lat, max_lon)
301 self.size = gpx.actual_points
306 logger.info "done trace #{id}"