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