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