]> git.openstreetmap.org Git - rails.git/blob - app/models/changeset.rb
Remove subscription methods from changeset model
[rails.git] / app / models / changeset.rb
1 # == Schema Information
2 #
3 # Table name: changesets
4 #
5 #  id          :bigint           not null, primary key
6 #  user_id     :bigint           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_many :subscriptions, :class_name => "ChangesetSubscription"
45   has_many :subscribers, :through => :subscriptions
46
47   validates :id, :uniqueness => true, :presence => { :on => :update },
48                  :numericality => { :on => :update, :only_integer => true }
49   validates :num_changes, :presence => true,
50                           :numericality => { :only_integer => 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 => { :only_integer => 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 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.utc) && (num_changes <= MAX_ELEMENTS)
77   end
78
79   def set_closed_time_now
80     self.closed_at = Time.now.utc if 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     pt = doc.find_first("//osm/changeset")
87
88     if pt
89       Changeset.from_xml_node(pt, :create => create)
90     else
91       raise OSM::APIBadXMLError.new("changeset", xml, "XML doesn't contain an osm/changeset element.")
92     end
93   rescue LibXML::XML::Error, ArgumentError => e
94     raise OSM::APIBadXMLError.new("changeset", xml, e.message)
95   end
96
97   def self.from_xml_node(pt, create: false)
98     cs = Changeset.new
99     if create
100       cs.created_at = Time.now.utc
101       # initial close time is 1h ahead, but will be increased on each
102       # modification.
103       cs.closed_at = cs.created_at + IDLE_TIMEOUT
104       # initially we have no changes in a changeset
105       cs.num_changes = 0
106     end
107
108     pt.find("tag").each do |tag|
109       raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing key") if tag["k"].nil?
110       raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing value") if tag["v"].nil?
111
112       cs.add_tag_keyval(tag["k"], tag["v"])
113     end
114
115     cs
116   end
117
118   ##
119   # returns the bounding box of the changeset. it is possible that some
120   # or all of the values will be nil, indicating that they are undefined.
121   def bbox
122     @bbox ||= BoundingBox.new(min_lon, min_lat, max_lon, max_lat)
123   end
124
125   def bbox_valid?
126     bbox.complete?
127   end
128
129   ##
130   # expand the bounding box to include the given bounding box.
131   def update_bbox!(bbox_update)
132     bbox.expand!(bbox_update)
133
134     raise OSM::APISizeLimitExceeded if bbox.linear_size > size_limit
135
136     # update active record. rails 2.1's dirty handling should take care of
137     # whether this object needs saving or not.
138     self.min_lon, self.min_lat, self.max_lon, self.max_lat = @bbox.to_a.collect(&:round) if bbox.complete?
139   end
140
141   ##
142   # the number of elements is also passed in so that we can ensure that
143   # a single changeset doesn't contain too many elements.
144   def add_changes!(elements)
145     self.num_changes += elements
146   end
147
148   def tags
149     unless @tags
150       @tags = {}
151       changeset_tags.each do |tag|
152         @tags[tag.k] = tag.v
153       end
154     end
155     @tags
156   end
157
158   attr_writer :tags
159
160   def add_tag_keyval(k, v)
161     @tags ||= {}
162
163     # duplicate tags are now forbidden, so we can't allow values
164     # in the hash to be overwritten.
165     raise OSM::APIDuplicateTagsError.new("changeset", id, k) if @tags.include? k
166
167     @tags[k] = v
168   end
169
170   def save_with_tags!
171     # do the changeset update and the changeset tags update in the
172     # same transaction to ensure consistency.
173     Changeset.transaction do
174       save!
175
176       tags = self.tags
177       ChangesetTag.where(:changeset => id).delete_all
178
179       tags.each do |k, v|
180         tag = ChangesetTag.new
181         tag.changeset_id = id
182         tag.k = k
183         tag.v = v
184         tag.save!
185       end
186     end
187   end
188
189   ##
190   # set the auto-close time to be one hour in the future unless
191   # that would make it more than 24h long, in which case clip to
192   # 24h, as this has been decided is a reasonable time limit.
193   def update_closed_at
194     if open?
195       self.closed_at = if (closed_at - created_at) > (MAX_TIME_OPEN - IDLE_TIMEOUT)
196                          created_at + MAX_TIME_OPEN
197                        else
198                          Time.now.utc + IDLE_TIMEOUT
199                        end
200     end
201   end
202
203   ##
204   # update this instance from another instance given and the user who is
205   # doing the updating. note that this method is not for updating the
206   # bounding box, only the tags of the changeset.
207   def update_from(other, user)
208     # ensure that only the user who opened the changeset may modify it.
209     raise OSM::APIUserChangesetMismatchError unless user.id == user_id
210
211     # can't change a closed changeset
212     raise OSM::APIChangesetAlreadyClosedError, self unless open?
213
214     # copy the other's tags
215     self.tags = other.tags
216
217     save_with_tags!
218   end
219
220   def size_limit
221     @size_limit ||= ActiveRecord::Base.connection.select_value(
222       "SELECT api_size_limit($1)", "api_size_limit", [user_id]
223     )
224   end
225 end