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