]> git.openstreetmap.org Git - rails.git/blob - app/models/trace.rb
Don't try and store a user record in the session
[rails.git] / app / models / trace.rb
1 class Trace < ActiveRecord::Base
2   self.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   scope :public, where(:visibility => ["public", "identifiable"])
11
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"]
19
20   def destroy
21     super
22     FileUtils.rm_f(trace_name)
23     FileUtils.rm_f(icon_picture_name)
24     FileUtils.rm_f(large_picture_name)
25   end
26
27   def tagstring
28     return tags.collect {|tt| tt.tag}.join(", ")
29   end
30
31   def tagstring=(s)
32     if s.include? ','
33       self.tags = s.split(/\s*,\s*/).select {|tag| tag !~ /^\s*$/}.collect {|tag|
34         tt = Tracetag.new
35         tt.tag = tag
36         tt
37       }
38     else
39       #do as before for backwards compatibility:
40       self.tags = s.split().collect {|tag|
41         tt = Tracetag.new
42         tt.tag = tag
43         tt
44       }
45     end
46   end
47
48   def public?
49     visibility == "public" || visibility == "identifiable"
50   end
51
52   def trackable?
53     visibility == "trackable" || visibility == "identifiable"
54   end
55
56   def identifiable?
57     visibility == "identifiable"
58   end
59
60   def large_picture= (data)
61     f = File.new(large_picture_name, "wb")
62     f.syswrite(data)
63     f.close
64   end
65   
66   def icon_picture= (data)
67     f = File.new(icon_picture_name, "wb")
68     f.syswrite(data)
69     f.close
70   end
71
72   def large_picture
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}'"
77     f.close
78     data
79   end
80   
81   def icon_picture
82     f = File.new(icon_picture_name, "rb")
83     logger.info "icon picture file: '#{f.path}'"
84     data = f.sysread(File.size(f.path))
85     f.close
86     data
87   end
88   
89   def large_picture_name
90     "#{GPX_IMAGE_DIR}/#{id}.gif"
91   end
92
93   def icon_picture_name
94     "#{GPX_IMAGE_DIR}/#{id}_icon.gif"
95   end
96
97   def trace_name
98     "#{GPX_TRACE_DIR}/#{id}.gpx"
99   end
100
101   def mime_type
102     filetype = `/usr/bin/file -bz #{trace_name}`.chomp
103     gzipped = filetype =~ /gzip compressed/
104     bzipped = filetype =~ /bzip2 compressed/
105     zipped = filetype =~ /Zip archive/
106
107     if gzipped then
108       mimetype = "application/x-gzip"
109     elsif bzipped then
110       mimetype = "application/x-bzip2"
111     elsif zipped
112       mimetype = "application/x-zip"
113     else
114       mimetype = "text/xml"
115     end
116
117     return mimetype
118   end
119
120   def extension_name
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/
126
127     if tarred and gzipped then
128       extension = ".tar.gz"
129     elsif tarred and bzipped then
130       extension = ".tar.bz2"
131     elsif tarred
132       extension = ".tar"
133     elsif gzipped
134       extension = ".gpx.gz"
135     elsif bzipped
136       extension = ".gpx.bz2"
137     elsif zipped
138       extension = ".zip"
139     else
140       extension = ".gpx"
141     end
142
143     return extension
144   end
145
146   def to_xml
147     doc = OSM::API.new.get_xml_doc
148     doc.root << to_xml_node()
149     return doc
150   end
151
152   def 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
162
163     el2 = XML::Node.new 'description'
164     el2 << self.description
165     el1 << el2
166
167     self.tags.each do |tag|
168       el2 = XML::Node.new('tag')
169       el2 << tag.tag
170       el1 << el2
171     end
172
173     return el1
174   end
175
176   # Read in xml as text and return it's Node object representation
177   def self.from_xml(xml, create=false)
178     begin
179       p = XML::Parser.string(xml)
180       doc = p.parse
181
182       doc.find('//osm/gpx_file').each do |pt|
183         return Trace.from_xml_node(pt, create)
184       end
185
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)
189     end
190   end
191
192   def self.from_xml_node(pt, create=false)
193     trace = Trace.new
194     
195     raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt['visibility'].nil?
196     trace.visibility = pt['visibility']
197
198     unless create
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
204     end
205
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
209     trace.visible = true
210
211     description = pt.find('description').first
212     raise OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
213     trace.description = description.content
214
215     pt.find('tag').each do |tag|
216       trace.tags.build(:tag => tag.content)
217     end
218
219     return trace
220   end
221
222   def xml_file
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/
229
230     if gzipped or bzipped or zipped or tarred then
231       tmpfile = Tempfile.new("trace.#{id}");
232
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}")
237       elsif tarred
238         system("tar -xOf #{trace_name} > #{tmpfile.path}")
239       elsif gzipped
240         system("gunzip -c #{trace_name} > #{tmpfile.path}")
241       elsif bzipped
242         system("bunzip2 -c #{trace_name} > #{tmpfile.path}")
243       elsif zipped
244         system("unzip -p #{trace_name} -x '__MACOSX/*' > #{tmpfile.path}")
245       end
246
247       tmpfile.unlink
248
249       file = tmpfile.file
250     else
251       file = File.open(trace_name)
252     end
253
254     return file
255   end
256
257   def import
258     logger.info("GPX Import importing #{name} (#{id}) from #{user.email}")
259
260     gpx = GPX::File.new(self.xml_file)
261
262     f_lat = 0
263     f_lon = 0
264     first = true
265
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)
271     end
272
273     gpx.points do |point|
274       if first
275         f_lat = point.latitude
276         f_lon = point.longitude
277         first = false
278       end
279
280       tp = Tracepoint.new
281       tp.lat = point.latitude
282       tp.lon = point.longitude
283       tp.altitude = point.altitude
284       tp.timestamp = point.timestamp
285       tp.gpx_id = id
286       tp.trackid = point.segment
287       tp.save!
288     end
289
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])
295
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
300
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
306       self.inserted = true
307       self.save!
308     end
309
310     logger.info "done trace #{id}"
311
312     return gpx
313   end
314 end