]> git.openstreetmap.org Git - rails.git/blob - app/models/changeset.rb
Made the trackpoints call return a more sensible filename.
[rails.git] / app / models / changeset.rb
1 class Changeset < ActiveRecord::Base
2   require 'xml/libxml'
3
4   belongs_to :user
5
6   has_many :changeset_tags, :foreign_key => 'id'
7
8   has_many :nodes
9   has_many :ways
10   has_many :relations
11   has_many :old_nodes
12   has_many :old_ways
13   has_many :old_relations
14
15   validates_presence_of :id, :on => :update
16   validates_presence_of :user_id, :created_at, :closed_at, :num_changes
17   validates_uniqueness_of :id
18   validates_numericality_of :id, :on => :update, :integer_only => true
19   validates_numericality_of :min_lat, :max_lat, :min_lon, :max_lat, :allow_nil => true, :integer_only => true
20   validates_numericality_of :user_id,  :integer_only => true
21   validates_numericality_of :num_changes, :integer_only => true, :greater_than_or_equal_to => 0
22   validates_associated :user
23
24   # over-expansion factor to use when updating the bounding box
25   EXPAND = 0.1
26
27   # maximum number of elements allowed in a changeset
28   MAX_ELEMENTS = 50000
29
30   # maximum time a changeset is allowed to be open for.
31   MAX_TIME_OPEN = 1.day
32
33   # idle timeout increment, one hour seems reasonable.
34   IDLE_TIMEOUT = 1.hour
35
36   # Use a method like this, so that we can easily change how we
37   # determine whether a changeset is open, without breaking code in at
38   # least 6 controllers
39   def is_open?
40     # a changeset is open (that is, it will accept further changes) when
41     # it has not yet run out of time and its capacity is small enough.
42     # note that this may not be a hard limit - due to timing changes and
43     # concurrency it is possible that some changesets may be slightly
44     # longer than strictly allowed or have slightly more changes in them.
45     return ((closed_at > Time.now.getutc) and (num_changes <= MAX_ELEMENTS))
46   end
47
48   def set_closed_time_now
49     if is_open?
50       self.closed_at = Time.now.getutc
51     end
52   end
53
54   def self.from_xml(xml, create=false)
55     begin
56       p = XML::Parser.string(xml)
57       doc = p.parse
58
59       doc.find('//osm/changeset').each do |pt|
60         return Changeset.from_xml_node(pt, create)
61       end
62       raise OSM::APIBadXMLError.new("changeset", xml, "XML doesn't contain an osm/changeset element.")
63     rescue LibXML::XML::Error, ArgumentError => ex
64       raise OSM::APIBadXMLError.new("changeset", xml, ex.message)
65     end
66   end
67
68   def self.from_xml_node(pt, create=false)
69     cs = Changeset.new
70     if create
71       cs.created_at = Time.now.getutc
72       # initial close time is 1h ahead, but will be increased on each
73       # modification.
74       cs.closed_at = cs.created_at + IDLE_TIMEOUT
75       # initially we have no changes in a changeset
76       cs.num_changes = 0
77     end
78
79     pt.find('tag').each do |tag|
80       raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing key") if tag['k'].nil?
81       raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing value") if tag['v'].nil?
82       cs.add_tag_keyval(tag['k'], tag['v'])
83     end
84
85     return cs
86   end
87
88   ##
89   # returns the bounding box of the changeset. it is possible that some
90   # or all of the values will be nil, indicating that they are undefined.
91   def bbox
92     @bbox ||= [ min_lon, min_lat, max_lon, max_lat ]
93   end
94
95   def has_valid_bbox?
96     not bbox.include? nil
97   end
98
99   ##
100   # returns area of the changset bbox as a rough comparitive quantity for use of changset displays
101   def area
102      if has_valid_bbox?
103        (max_lon - min_lon) * (max_lat - min_lat)
104      else
105        0
106      end
107   end
108
109   ##
110   # expand the bounding box to include the given bounding box. also,
111   # expand a little bit more in the direction of the expansion, so that
112   # further expansions may be unnecessary. this is an optimisation
113   # suggested on the wiki page by kleptog.
114   def update_bbox!(array)
115     # ensure that bbox is cached and has no nils in it. if there are any
116     # nils, just use the bounding box update to write over them.
117     @bbox = bbox.zip(array).collect { |a, b| a.nil? ? b : a }
118
119     # FIXME - this looks nasty and violates DRY... is there any prettier
120     # way to do this?
121     @bbox[0] = [-180 * GeoRecord::SCALE, array[0] + EXPAND * (@bbox[0] - @bbox[2])].max if array[0] < @bbox[0]
122     @bbox[1] = [ -90 * GeoRecord::SCALE, array[1] + EXPAND * (@bbox[1] - @bbox[3])].max if array[1] < @bbox[1]
123     @bbox[2] = [ 180 * GeoRecord::SCALE, array[2] + EXPAND * (@bbox[2] - @bbox[0])].min if array[2] > @bbox[2]
124     @bbox[3] = [  90 * GeoRecord::SCALE, array[3] + EXPAND * (@bbox[3] - @bbox[1])].min if array[3] > @bbox[3]
125
126     # update active record. rails 2.1's dirty handling should take care of
127     # whether this object needs saving or not.
128     self.min_lon, self.min_lat, self.max_lon, self.max_lat = @bbox
129   end
130
131   ##
132   # the number of elements is also passed in so that we can ensure that
133   # a single changeset doesn't contain too many elements. this, of course,
134   # destroys the optimisation described in the bbox method above.
135   def add_changes!(elements)
136     self.num_changes += elements
137   end
138
139   def tags_as_hash
140     return tags
141   end
142
143   def tags
144     unless @tags
145       @tags = {}
146       self.changeset_tags.each do |tag|
147         @tags[tag.k] = tag.v
148       end
149     end
150     @tags
151   end
152
153   def tags=(t)
154     @tags = t
155   end
156
157   def add_tag_keyval(k, v)
158     @tags = Hash.new unless @tags
159
160     # duplicate tags are now forbidden, so we can't allow values
161     # in the hash to be overwritten.
162     raise OSM::APIDuplicateTagsError.new("changeset", self.id, k) if @tags.include? k
163
164     @tags[k] = v
165   end
166
167   def save_with_tags!
168     # do the changeset update and the changeset tags update in the
169     # same transaction to ensure consistency.
170     Changeset.transaction do
171       self.save!
172
173       tags = self.tags
174       ChangesetTag.delete_all(['id = ?', self.id])
175
176       tags.each do |k,v|
177         tag = ChangesetTag.new
178         tag.k = k
179         tag.v = v
180         tag.id = self.id
181         tag.save!
182       end
183     end
184   end
185
186   ##
187   # set the auto-close time to be one hour in the future unless
188   # that would make it more than 24h long, in which case clip to
189   # 24h, as this has been decided is a reasonable time limit.
190   def before_save
191     if self.is_open?
192       if (closed_at - created_at) > (MAX_TIME_OPEN - IDLE_TIMEOUT)
193         self.closed_at = created_at + MAX_TIME_OPEN
194       else
195         self.closed_at = Time.now.getutc + IDLE_TIMEOUT
196       end
197     end
198   end
199
200   def to_xml
201     doc = OSM::API.new.get_xml_doc
202     doc.root << to_xml_node()
203     return doc
204   end
205
206   def to_xml_node(user_display_name_cache = nil)
207     el1 = XML::Node.new 'changeset'
208     el1['id'] = self.id.to_s
209
210     user_display_name_cache = {} if user_display_name_cache.nil?
211
212     if user_display_name_cache and user_display_name_cache.key?(self.user_id)
213       # use the cache if available
214     elsif self.user.data_public?
215       user_display_name_cache[self.user_id] = self.user.display_name
216     else
217       user_display_name_cache[self.user_id] = nil
218     end
219
220     el1['user'] = user_display_name_cache[self.user_id] unless user_display_name_cache[self.user_id].nil?
221     el1['uid'] = self.user_id.to_s if self.user.data_public?
222
223     self.tags.each do |k,v|
224       el2 = XML::Node.new('tag')
225       el2['k'] = k.to_s
226       el2['v'] = v.to_s
227       el1 << el2
228     end
229
230     el1['created_at'] = self.created_at.xmlschema
231     el1['closed_at'] = self.closed_at.xmlschema unless is_open?
232     el1['open'] = is_open?.to_s
233
234     el1['min_lon'] = (bbox[0].to_f / GeoRecord::SCALE).to_s unless bbox[0].nil?
235     el1['min_lat'] = (bbox[1].to_f / GeoRecord::SCALE).to_s unless bbox[1].nil?
236     el1['max_lon'] = (bbox[2].to_f / GeoRecord::SCALE).to_s unless bbox[2].nil?
237     el1['max_lat'] = (bbox[3].to_f / GeoRecord::SCALE).to_s unless bbox[3].nil?
238
239     # NOTE: changesets don't include the XML of the changes within them,
240     # they are just structures for tagging. to get the osmChange of a
241     # changeset, see the download method of the controller.
242
243     return el1
244   end
245
246   ##
247   # update this instance from another instance given and the user who is
248   # doing the updating. note that this method is not for updating the
249   # bounding box, only the tags of the changeset.
250   def update_from(other, user)
251     # ensure that only the user who opened the changeset may modify it.
252     unless user.id == self.user_id
253       raise OSM::APIUserChangesetMismatchError.new
254     end
255
256     # can't change a closed changeset
257     unless is_open?
258       raise OSM::APIChangesetAlreadyClosedError.new(self)
259     end
260
261     # copy the other's tags
262     self.tags = other.tags
263
264     save_with_tags!
265   end
266 end