]> git.openstreetmap.org Git - rails.git/blob - app/models/trace.rb
45abdf474ded2175ca9b5cab15d519e9a00ed46f
[rails.git] / app / models / trace.rb
1 class Trace < ActiveRecord::Base
2   set_table_name 'gpx_files'
3
4   belongs_to :user
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
7
8   scope :visible, where(:visible => true)
9   scope :visible_to, lambda { |u| visible.where("visibility IN ('public', 'identifiable') OR user_id = ?", u) }
10
11   validates_presence_of :user_id, :name, :timestamp
12   validates_presence_of :description, :on => :create
13   validates_length_of :name, :maximum => 255
14   validates_length_of :description, :maximum => 255
15 #  validates_numericality_of :latitude, :longitude
16   validates_inclusion_of :inserted, :in => [ true, false ]
17   validates_inclusion_of :visibility, :in => ["private", "public", "trackable", "identifiable"]
18
19   def destroy
20     super
21     FileUtils.rm_f(trace_name)
22     FileUtils.rm_f(icon_picture_name)
23     FileUtils.rm_f(large_picture_name)
24   end
25
26   def tagstring
27     return tags.collect {|tt| tt.tag}.join(", ")
28   end
29
30   def tagstring=(s)
31     if s.include? ','
32       self.tags = s.split(/\s*,\s*/).select {|tag| tag !~ /^\s*$/}.collect {|tag|
33         tt = Tracetag.new
34         tt.tag = tag
35         tt
36       }
37     else
38       #do as before for backwards compatibility:
39       self.tags = s.split().collect {|tag|
40         tt = Tracetag.new
41         tt.tag = tag
42         tt
43       }
44     end
45   end
46
47   def public?
48     visibility == "public" || visibility == "identifiable"
49   end
50
51   def trackable?
52     visibility == "trackable" || visibility == "identifiable"
53   end
54
55   def identifiable?
56     visibility == "identifiable"
57   end
58
59   def large_picture= (data)
60     f = File.new(large_picture_name, "wb")
61     f.syswrite(data)
62     f.close
63   end
64   
65   def icon_picture= (data)
66     f = File.new(icon_picture_name, "wb")
67     f.syswrite(data)
68     f.close
69   end
70
71   def large_picture
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}'"
76     f.close
77     data
78   end
79   
80   def icon_picture
81     f = File.new(icon_picture_name, "rb")
82     logger.info "icon picture file: '#{f.path}'"
83     data = f.sysread(File.size(f.path))
84     f.close
85     data
86   end
87   
88   def large_picture_name
89     "#{GPX_IMAGE_DIR}/#{id}.gif"
90   end
91
92   def icon_picture_name
93     "#{GPX_IMAGE_DIR}/#{id}_icon.gif"
94   end
95
96   def trace_name
97     "#{GPX_TRACE_DIR}/#{id}.gpx"
98   end
99
100   def mime_type
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
106     if gzipped then
107       mimetype = "application/x-gzip"
108     elsif bzipped then
109       mimetype = "application/x-bzip2"
110     elsif zipped
111       mimetype = "application/x-zip"
112     else
113       mimetype = "text/xml"
114     end
115
116     return mimetype
117   end
118
119   def extension_name
120     filetype = `/usr/bin/file -bz #{trace_name}`.chomp
121     gzipped = filetype =~ /gzip compressed/
122     bzipped = filetype =~ /bzip2 compressed/
123     zipped = filetype =~ /Zip archive/
124     tarred = filetype =~ /tar archive/
125
126     if tarred and gzipped then
127       extension = ".tar.gz"
128     elsif tarred and bzipped then
129       extension = ".tar.bz2"
130     elsif tarred
131       extension = ".tar"
132     elsif gzipped
133       extension = ".gpx.gz"
134     elsif bzipped
135       extension = ".gpx.bz2"
136     elsif zipped
137       extension = ".zip"
138     else
139       extension = ".gpx"
140     end
141
142     return extension
143   end
144
145   def to_xml
146     doc = OSM::API.new.get_xml_doc
147     doc.root << to_xml_node()
148     return doc
149   end
150
151   def to_xml_node
152     el1 = XML::Node.new 'gpx_file'
153     el1['id'] = self.id.to_s
154     el1['name'] = self.name.to_s
155     el1['lat'] = self.latitude.to_s if self.inserted
156     el1['lon'] = self.longitude.to_s if self.inserted
157     el1['user'] = self.user.display_name
158     el1['visibility'] = self.visibility
159     el1['pending'] = (!self.inserted).to_s
160     el1['timestamp'] = self.timestamp.xmlschema
161
162     el2 = XML::Node.new 'description'
163     el2 << self.description
164     el1 << el2
165
166     self.tags.each do |tag|
167       el2 = XML::Node.new('tag')
168       el2 << tag.tag
169       el1 << el2
170     end
171
172     return el1
173   end
174
175   # Read in xml as text and return it's Node object representation
176   def self.from_xml(xml, create=false)
177     begin
178       p = XML::Parser.string(xml)
179       doc = p.parse
180
181       doc.find('//osm/gpx_file').each do |pt|
182         return Trace.from_xml_node(pt, create)
183       end
184
185       raise OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
186     rescue LibXML::XML::Error, ArgumentError => ex
187       raise OSM::APIBadXMLError.new("trace", xml, ex.message)
188     end
189   end
190
191   def self.from_xml_node(pt, create=false)
192     trace = Trace.new
193     
194     raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt['visibility'].nil?
195     trace.visibility = pt['visibility']
196
197     unless create
198       raise 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       raise OSM::APIBadUserInput.new("ID of trace cannot be zero when updating.") if trace.id == 0
203     end
204
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
208     trace.visible = true
209
210     description = pt.find('description').first
211     raise OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
212     trace.description = description.content
213
214     pt.find('tag').each do |tag|
215       trace.tags.build(:tag => tag.content)
216     end
217
218     return trace
219   end
220
221   def xml_file
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/
228
229     if gzipped or bzipped or zipped or tarred then
230       tmpfile = Tempfile.new("trace.#{id}");
231
232       if tarred and gzipped then
233         system("tar -zxOf #{trace_name} > #{tmpfile.path}")
234       elsif tarred and bzipped then
235         system("tar -jxOf #{trace_name} > #{tmpfile.path}")
236       elsif tarred
237         system("tar -xOf #{trace_name} > #{tmpfile.path}")
238       elsif gzipped
239         system("gunzip -c #{trace_name} > #{tmpfile.path}")
240       elsif bzipped
241         system("bunzip2 -c #{trace_name} > #{tmpfile.path}")
242       elsif zipped
243         system("unzip -p #{trace_name} -x '__MACOSX/*' > #{tmpfile.path}")
244       end
245
246       tmpfile.unlink
247
248       file = tmpfile.file
249     else
250       file = File.open(trace_name)
251     end
252
253     return file
254   end
255
256   def import
257     logger.info("GPX Import importing #{name} (#{id}) from #{user.email}")
258
259     gpx = GPX::File.new(self.xml_file)
260
261     f_lat = 0
262     f_lon = 0
263     first = true
264
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 => self.id).exists?
269       Tracepoint.delete_all(:gpx_id => self.id)
270     end
271
272     gpx.points do |point|
273       if first
274         f_lat = point.latitude
275         f_lon = point.longitude
276         first = false
277       end
278
279       tp = Tracepoint.new
280       tp.lat = point.latitude
281       tp.lon = point.longitude
282       tp.altitude = point.altitude
283       tp.timestamp = point.timestamp
284       tp.gpx_id = id
285       tp.trackid = point.segment
286       tp.save!
287     end
288
289     if gpx.actual_points > 0
290       max_lat = Tracepoint.maximum('latitude', :conditions => ['gpx_id = ?', id])
291       min_lat = Tracepoint.minimum('latitude', :conditions => ['gpx_id = ?', id])
292       max_lon = Tracepoint.maximum('longitude', :conditions => ['gpx_id = ?', id])
293       min_lon = Tracepoint.minimum('longitude', :conditions => ['gpx_id = ?', id])
294
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
299
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
305       self.inserted = true
306       self.save!
307     end
308
309     logger.info "done trace #{id}"
310
311     return gpx
312   end
313 end