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