]> git.openstreetmap.org Git - rails.git/blob - app/models/changeset.rb
Merge remote-tracking branch 'upstream/pull/2167'
[rails.git] / app / models / changeset.rb
1 # == Schema Information
2 #
3 # Table name: changesets
4 #
5 #  id          :integer          not null, primary key
6 #  user_id     :integer          not null
7 #  created_at  :datetime         not null
8 #  min_lat     :integer
9 #  max_lat     :integer
10 #  min_lon     :integer
11 #  max_lon     :integer
12 #  closed_at   :datetime         not null
13 #  num_changes :integer          default(0), not null
14 #
15 # Indexes
16 #
17 #  changesets_bbox_idx                (min_lat,max_lat,min_lon,max_lon)
18 #  changesets_closed_at_idx           (closed_at)
19 #  changesets_created_at_idx          (created_at)
20 #  changesets_user_id_created_at_idx  (user_id,created_at)
21 #  changesets_user_id_id_idx          (user_id,id)
22 #
23 # Foreign Keys
24 #
25 #  changesets_user_id_fkey  (user_id => users.id)
26 #
27
28 class Changeset < ActiveRecord::Base
29   require "xml/libxml"
30
31   belongs_to :user, :counter_cache => true
32
33   has_many :changeset_tags
34
35   has_many :nodes
36   has_many :ways
37   has_many :relations
38   has_many :old_nodes
39   has_many :old_ways
40   has_many :old_relations
41
42   has_many :comments, -> { where(:visible => true).order(:created_at) }, :class_name => "ChangesetComment"
43   has_and_belongs_to_many :subscribers, :class_name => "User", :join_table => "changesets_subscribers", :association_foreign_key => "subscriber_id"
44
45   validates :id, :uniqueness => true, :presence => { :on => :update },
46                  :numericality => { :on => :update, :integer_only => true }
47   validates :user_id, :presence => true,
48                       :numericality => { :integer_only => true }
49   validates :num_changes, :presence => true,
50                           :numericality => { :integer_only => true,
51                                              :greater_than_or_equal_to => 0 }
52   validates :created_at, :closed_at, :presence => true
53   validates :min_lat, :max_lat, :min_lon, :max_lat, :allow_nil => true,
54                                                     :numericality => { :integer_only => true }
55
56   before_save :update_closed_at
57
58   # maximum number of elements allowed in a changeset
59   MAX_ELEMENTS = 10000
60
61   # maximum time a changeset is allowed to be open for.
62   MAX_TIME_OPEN = 1.day
63
64   # idle timeout increment, one hour seems reasonable.
65   IDLE_TIMEOUT = 1.hour
66
67   # Use a method like this, so that we can easily change how we
68   # determine whether a changeset is open, without breaking code in at
69   # least 6 controllers
70   def is_open?
71     # a changeset is open (that is, it will accept further changes) when
72     # it has not yet run out of time and its capacity is small enough.
73     # note that this may not be a hard limit - due to timing changes and
74     # concurrency it is possible that some changesets may be slightly
75     # longer than strictly allowed or have slightly more changes in them.
76     ((closed_at > Time.now.getutc) && (num_changes <= MAX_ELEMENTS))
77   end
78
79   def set_closed_time_now
80     self.closed_at = Time.now.getutc if is_open?
81   end
82
83   def self.from_xml(xml, create = false)
84     p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
85     doc = p.parse
86
87     doc.find("//osm/changeset").each do |pt|
88       return Changeset.from_xml_node(pt, create)
89     end
90     raise OSM::APIBadXMLError.new("changeset", xml, "XML doesn't contain an osm/changeset element.")
91   rescue LibXML::XML::Error, ArgumentError => ex
92     raise OSM::APIBadXMLError.new("changeset", xml, ex.message)
93   end
94
95   def self.from_xml_node(pt, create = false)
96     cs = Changeset.new
97     if create
98       cs.created_at = Time.now.getutc
99       # initial close time is 1h ahead, but will be increased on each
100       # modification.
101       cs.closed_at = cs.created_at + IDLE_TIMEOUT
102       # initially we have no changes in a changeset
103       cs.num_changes = 0
104     end
105
106     pt.find("tag").each do |tag|
107       raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing key") if tag["k"].nil?
108       raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing value") if tag["v"].nil?
109
110       cs.add_tag_keyval(tag["k"], tag["v"])
111     end
112
113     cs
114   end
115
116   ##
117   # returns the bounding box of the changeset. it is possible that some
118   # or all of the values will be nil, indicating that they are undefined.
119   def bbox
120     @bbox ||= BoundingBox.new(min_lon, min_lat, max_lon, max_lat)
121   end
122
123   def has_valid_bbox?
124     bbox.complete?
125   end
126
127   ##
128   # expand the bounding box to include the given bounding box.
129   def update_bbox!(bbox_update)
130     bbox.expand!(bbox_update)
131
132     # update active record. rails 2.1's dirty handling should take care of
133     # whether this object needs saving or not.
134     self.min_lon, self.min_lat, self.max_lon, self.max_lat = @bbox.to_a if bbox.complete?
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.
140   def add_changes!(elements)
141     self.num_changes += elements
142   end
143
144   def tags
145     unless @tags
146       @tags = {}
147       changeset_tags.each do |tag|
148         @tags[tag.k] = tag.v
149       end
150     end
151     @tags
152   end
153
154   attr_writer :tags
155
156   def add_tag_keyval(k, v)
157     @tags ||= {}
158
159     # duplicate tags are now forbidden, so we can't allow values
160     # in the hash to be overwritten.
161     raise OSM::APIDuplicateTagsError.new("changeset", id, k) if @tags.include? k
162
163     @tags[k] = v
164   end
165
166   def save_with_tags!
167     # do the changeset update and the changeset tags update in the
168     # same transaction to ensure consistency.
169     Changeset.transaction do
170       save!
171
172       tags = self.tags
173       ChangesetTag.where(:changeset_id => id).delete_all
174
175       tags.each do |k, v|
176         tag = ChangesetTag.new
177         tag.changeset_id = id
178         tag.k = k
179         tag.v = v
180         tag.save!
181       end
182     end
183   end
184
185   ##
186   # set the auto-close time to be one hour in the future unless
187   # that would make it more than 24h long, in which case clip to
188   # 24h, as this has been decided is a reasonable time limit.
189   def update_closed_at
190     if is_open?
191       self.closed_at = if (closed_at - created_at) > (MAX_TIME_OPEN - IDLE_TIMEOUT)
192                          created_at + MAX_TIME_OPEN
193                        else
194                          Time.now.getutc + IDLE_TIMEOUT
195                        end
196     end
197   end
198
199   def to_xml(include_discussion = false)
200     doc = OSM::API.new.get_xml_doc
201     doc.root << to_xml_node(nil, include_discussion)
202     doc
203   end
204
205   def to_xml_node(user_display_name_cache = nil, include_discussion = false)
206     el1 = XML::Node.new "changeset"
207     el1["id"] = id.to_s
208
209     user_display_name_cache = {} if user_display_name_cache.nil?
210
211     if user_display_name_cache&.key?(user_id)
212       # use the cache if available
213     elsif user.data_public?
214       user_display_name_cache[user_id] = user.display_name
215     else
216       user_display_name_cache[user_id] = nil
217     end
218
219     el1["user"] = user_display_name_cache[user_id] unless user_display_name_cache[user_id].nil?
220     el1["uid"] = user_id.to_s if user.data_public?
221
222     tags.each do |k, v|
223       el2 = XML::Node.new("tag")
224       el2["k"] = k.to_s
225       el2["v"] = v.to_s
226       el1 << el2
227     end
228
229     el1["created_at"] = created_at.xmlschema
230     el1["closed_at"] = closed_at.xmlschema unless is_open?
231     el1["open"] = is_open?.to_s
232
233     bbox.to_unscaled.add_bounds_to(el1, "_") if bbox.complete?
234
235     el1["comments_count"] = comments.length.to_s
236     el1["changes_count"] = num_changes.to_s
237
238     if include_discussion
239       el2 = XML::Node.new("discussion")
240       comments.includes(:author).each do |comment|
241         el3 = XML::Node.new("comment")
242         el3["date"] = comment.created_at.xmlschema
243         el3["uid"] = comment.author.id.to_s if comment.author.data_public?
244         el3["user"] = comment.author.display_name.to_s if comment.author.data_public?
245         el4 = XML::Node.new("text")
246         el4.content = comment.body.to_s
247         el3 << el4
248         el2 << el3
249       end
250       el1 << el2
251     end
252
253     # NOTE: changesets don't include the XML of the changes within them,
254     # they are just structures for tagging. to get the osmChange of a
255     # changeset, see the download method of the controller.
256
257     el1
258   end
259
260   ##
261   # update this instance from another instance given and the user who is
262   # doing the updating. note that this method is not for updating the
263   # bounding box, only the tags of the changeset.
264   def update_from(other, user)
265     # ensure that only the user who opened the changeset may modify it.
266     raise OSM::APIUserChangesetMismatchError unless user.id == user_id
267
268     # can't change a closed changeset
269     raise OSM::APIChangesetAlreadyClosedError, self unless is_open?
270
271     # copy the other's tags
272     self.tags = other.tags
273
274     save_with_tags!
275   end
276 end