]> git.openstreetmap.org Git - rails.git/blob - app/models/changeset.rb
Merge remote-tracking branch 'upstream/pull/4753'
[rails.git] / app / models / changeset.rb
1 # == Schema Information
2 #
3 # Table name: changesets
4 #
5 #  id          :bigint(8)        not null, primary key
6 #  user_id     :bigint(8)        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) USING gist
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 #  index_changesets_on_user_id_and_closed_at  (user_id,closed_at)
23 #
24 # Foreign Keys
25 #
26 #  changesets_user_id_fkey  (user_id => users.id)
27 #
28
29 class Changeset < ApplicationRecord
30   require "xml/libxml"
31
32   belongs_to :user, :counter_cache => true
33
34   has_many :changeset_tags
35
36   has_many :nodes
37   has_many :ways
38   has_many :relations
39   has_many :old_nodes
40   has_many :old_ways
41   has_many :old_relations
42
43   has_many :comments, -> { where(:visible => true).order(:created_at) }, :class_name => "ChangesetComment"
44   has_and_belongs_to_many :subscribers, :class_name => "User", :join_table => "changesets_subscribers", :association_foreign_key => "subscriber_id"
45
46   validates :id, :uniqueness => true, :presence => { :on => :update },
47                  :numericality => { :on => :update, :only_integer => true }
48   validates :num_changes, :presence => true,
49                           :numericality => { :only_integer => true,
50                                              :greater_than_or_equal_to => 0 }
51   validates :created_at, :closed_at, :presence => true
52   validates :min_lat, :max_lat, :min_lon, :max_lat, :allow_nil => true,
53                                                     :numericality => { :only_integer => true }
54
55   before_save :update_closed_at
56
57   # maximum number of elements allowed in a changeset
58   MAX_ELEMENTS = 10000
59
60   # maximum time a changeset is allowed to be open for.
61   MAX_TIME_OPEN = 1.day
62
63   # idle timeout increment, one hour seems reasonable.
64   IDLE_TIMEOUT = 1.hour
65
66   # Use a method like this, so that we can easily change how we
67   # determine whether a changeset is open, without breaking code in at
68   # least 6 controllers
69   def open?
70     # a changeset is open (that is, it will accept further changes) when
71     # it has not yet run out of time and its capacity is small enough.
72     # note that this may not be a hard limit - due to timing changes and
73     # concurrency it is possible that some changesets may be slightly
74     # longer than strictly allowed or have slightly more changes in them.
75     (closed_at > Time.now.utc) && (num_changes <= MAX_ELEMENTS)
76   end
77
78   def set_closed_time_now
79     self.closed_at = Time.now.utc if open?
80   end
81
82   def self.from_xml(xml, create: false)
83     p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
84     doc = p.parse
85     pt = doc.find_first("//osm/changeset")
86
87     if pt
88       Changeset.from_xml_node(pt, :create => create)
89     else
90       raise OSM::APIBadXMLError.new("changeset", xml, "XML doesn't contain an osm/changeset element.")
91     end
92   rescue LibXML::XML::Error, ArgumentError => e
93     raise OSM::APIBadXMLError.new("changeset", xml, e.message)
94   end
95
96   def self.from_xml_node(pt, create: false)
97     cs = Changeset.new
98     if create
99       cs.created_at = Time.now.utc
100       # initial close time is 1h ahead, but will be increased on each
101       # modification.
102       cs.closed_at = cs.created_at + IDLE_TIMEOUT
103       # initially we have no changes in a changeset
104       cs.num_changes = 0
105     end
106
107     pt.find("tag").each do |tag|
108       raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing key") if tag["k"].nil?
109       raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing value") if tag["v"].nil?
110
111       cs.add_tag_keyval(tag["k"], tag["v"])
112     end
113
114     cs
115   end
116
117   ##
118   # returns the bounding box of the changeset. it is possible that some
119   # or all of the values will be nil, indicating that they are undefined.
120   def bbox
121     @bbox ||= BoundingBox.new(min_lon, min_lat, max_lon, max_lat)
122   end
123
124   def bbox_valid?
125     bbox.complete?
126   end
127
128   ##
129   # expand the bounding box to include the given bounding box.
130   def update_bbox!(bbox_update)
131     bbox.expand!(bbox_update)
132
133     # update active record. rails 2.1's dirty handling should take care of
134     # whether this object needs saving or not.
135     self.min_lon, self.min_lat, self.max_lon, self.max_lat = @bbox.to_a.collect(&:round) if bbox.complete?
136   end
137
138   ##
139   # the number of elements is also passed in so that we can ensure that
140   # a single changeset doesn't contain too many elements.
141   def add_changes!(elements)
142     self.num_changes += elements
143   end
144
145   def tags
146     unless @tags
147       @tags = {}
148       changeset_tags.each do |tag|
149         @tags[tag.k] = tag.v
150       end
151     end
152     @tags
153   end
154
155   attr_writer :tags
156
157   def add_tag_keyval(k, v)
158     @tags ||= {}
159
160     # duplicate tags are now forbidden, so we can't allow values
161     # in the hash to be overwritten.
162     raise OSM::APIDuplicateTagsError.new("changeset", id, k) if @tags.include? k
163
164     @tags[k] = v
165   end
166
167   def save_with_tags!
168     # do the changeset update and the changeset tags update in the
169     # same transaction to ensure consistency.
170     Changeset.transaction do
171       save!
172
173       tags = self.tags
174       ChangesetTag.where(:changeset => id).delete_all
175
176       tags.each do |k, v|
177         tag = ChangesetTag.new
178         tag.changeset_id = id
179         tag.k = k
180         tag.v = v
181         tag.save!
182       end
183     end
184   end
185
186   ##
187   # set the auto-close time to be one hour in the future unless
188   # that would make it more than 24h long, in which case clip to
189   # 24h, as this has been decided is a reasonable time limit.
190   def update_closed_at
191     if open?
192       self.closed_at = if (closed_at - created_at) > (MAX_TIME_OPEN - IDLE_TIMEOUT)
193                          created_at + MAX_TIME_OPEN
194                        else
195                          Time.now.utc + IDLE_TIMEOUT
196                        end
197     end
198   end
199
200   ##
201   # update this instance from another instance given and the user who is
202   # doing the updating. note that this method is not for updating the
203   # bounding box, only the tags of the changeset.
204   def update_from(other, user)
205     # ensure that only the user who opened the changeset may modify it.
206     raise OSM::APIUserChangesetMismatchError unless user.id == user_id
207
208     # can't change a closed changeset
209     raise OSM::APIChangesetAlreadyClosedError, self unless open?
210
211     # copy the other's tags
212     self.tags = other.tags
213
214     save_with_tags!
215   end
216
217   def subscribe(user)
218     subscribers << user
219   end
220
221   def unsubscribe(user)
222     subscribers.delete(user)
223   end
224
225   def subscribed?(user)
226     subscribers.exists?(user.id)
227   end
228 end