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