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