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