]> git.openstreetmap.org Git - rails.git/blob - app/models/node.rb
Use relative translations for changeset comments
[rails.git] / app / models / node.rb
1 # == Schema Information
2 #
3 # Table name: current_nodes
4 #
5 #  id           :integer          not null, primary key
6 #  latitude     :integer          not null
7 #  longitude    :integer          not null
8 #  changeset_id :integer          not null
9 #  visible      :boolean          not null
10 #  timestamp    :datetime         not null
11 #  tile         :integer          not null
12 #  version      :integer          not null
13 #
14 # Indexes
15 #
16 #  current_nodes_tile_idx       (tile)
17 #  current_nodes_timestamp_idx  (timestamp)
18 #
19 # Foreign Keys
20 #
21 #  current_nodes_changeset_id_fkey  (changeset_id => changesets.id)
22 #
23
24 class Node < ActiveRecord::Base
25   require "xml/libxml"
26
27   include GeoRecord
28   include ConsistencyValidations
29   include NotRedactable
30   include ObjectMetadata
31
32   self.table_name = "current_nodes"
33
34   belongs_to :changeset
35
36   has_many :old_nodes, -> { order(:version) }
37
38   has_many :way_nodes
39   has_many :ways, :through => :way_nodes
40
41   has_many :node_tags
42
43   has_many :old_way_nodes
44   has_many :ways_via_history, :class_name => "Way", :through => :old_way_nodes, :source => :way
45
46   has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
47   has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
48
49   validates :id, :uniqueness => true, :presence => { :on => :update },
50                  :numericality => { :on => :update, :integer_only => true }
51   validates :version, :presence => true,
52                       :numericality => { :integer_only => true }
53   validates :changeset_id, :presence => true,
54                            :numericality => { :integer_only => true }
55   validates :latitude, :presence => true,
56                        :numericality => { :integer_only => true }
57   validates :longitude, :presence => true,
58                         :numericality => { :integer_only => true }
59   validates :timestamp, :presence => true
60   validates :changeset, :associated => true
61   validates :visible, :inclusion => [true, false]
62
63   validate :validate_position
64
65   scope :visible, -> { where(:visible => true) }
66   scope :invisible, -> { where(:visible => false) }
67
68   # Sanity check the latitude and longitude and add an error if it's broken
69   def validate_position
70     errors.add(:base, "Node is not in the world") unless in_world?
71   end
72
73   # Read in xml as text and return it's Node object representation
74   def self.from_xml(xml, create = false)
75     p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
76     doc = p.parse
77
78     doc.find("//osm/node").each do |pt|
79       return Node.from_xml_node(pt, create)
80     end
81     raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
82   rescue LibXML::XML::Error, ArgumentError => ex
83     raise OSM::APIBadXMLError.new("node", xml, ex.message)
84   end
85
86   def self.from_xml_node(pt, create = false)
87     node = Node.new
88
89     raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt["lat"].nil?
90     raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt["lon"].nil?
91
92     node.lat = OSM.parse_float(pt["lat"], OSM::APIBadXMLError, "node", pt, "lat not a number")
93     node.lon = OSM.parse_float(pt["lon"], OSM::APIBadXMLError, "node", pt, "lon not a number")
94     raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt["changeset"].nil?
95
96     node.changeset_id = pt["changeset"].to_i
97
98     raise OSM::APIBadUserInput, "The node is outside this world" unless node.in_world?
99
100     # version must be present unless creating
101     raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create || !pt["version"].nil?
102
103     node.version = create ? 0 : pt["version"].to_i
104
105     unless create
106       raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt["id"].nil?
107
108       node.id = pt["id"].to_i
109       # .to_i will return 0 if there is no number that can be parsed.
110       # We want to make sure that there is no id with zero anyway
111       raise OSM::APIBadUserInput, "ID of node cannot be zero when updating." if node.id.zero?
112     end
113
114     # We don't care about the time, as it is explicitly set on create/update/delete
115     # We don't care about the visibility as it is implicit based on the action
116     # and set manually before the actual delete
117     node.visible = true
118
119     # Start with no tags
120     node.tags = {}
121
122     # Add in any tags from the XML
123     pt.find("tag").each do |tag|
124       raise OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag["k"].nil?
125       raise OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag["v"].nil?
126
127       node.add_tag_key_val(tag["k"], tag["v"])
128     end
129
130     node
131   end
132
133   ##
134   # the bounding box around a node, which is used for determining the changeset's
135   # bounding box
136   def bbox
137     BoundingBox.new(longitude, latitude, longitude, latitude)
138   end
139
140   # Should probably be renamed delete_from to come in line with update
141   def delete_with_history!(new_node, user)
142     raise OSM::APIAlreadyDeletedError.new("node", new_node.id) unless visible
143
144     # need to start the transaction here, so that the database can
145     # provide repeatable reads for the used-by checks. this means it
146     # shouldn't be possible to get race conditions.
147     Node.transaction do
148       lock!
149       check_consistency(self, new_node, user)
150       ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
151       raise OSM::APIPreconditionFailedError, "Node #{id} is still used by ways #{ways.collect(&:id).join(',')}." unless ways.empty?
152
153       rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
154       raise OSM::APIPreconditionFailedError, "Node #{id} is still used by relations #{rels.collect(&:id).join(',')}." unless rels.empty?
155
156       self.changeset_id = new_node.changeset_id
157       self.tags = {}
158       self.visible = false
159
160       # update the changeset with the deleted position
161       changeset.update_bbox!(bbox)
162
163       save_with_history!
164     end
165   end
166
167   def update_from(new_node, user)
168     Node.transaction do
169       lock!
170       check_consistency(self, new_node, user)
171
172       # update changeset first
173       self.changeset_id = new_node.changeset_id
174       self.changeset = new_node.changeset
175
176       # update changeset bbox with *old* position first
177       changeset.update_bbox!(bbox)
178
179       # FIXME: logic needs to be double checked
180       self.latitude = new_node.latitude
181       self.longitude = new_node.longitude
182       self.tags = new_node.tags
183       self.visible = true
184
185       # update changeset bbox with *new* position
186       changeset.update_bbox!(bbox)
187
188       save_with_history!
189     end
190   end
191
192   def create_with_history(user)
193     check_create_consistency(self, user)
194     self.version = 0
195     self.visible = true
196
197     # update the changeset to include the new location
198     changeset.update_bbox!(bbox)
199
200     save_with_history!
201   end
202
203   def to_xml
204     doc = OSM::API.new.get_xml_doc
205     doc.root << to_xml_node
206     doc
207   end
208
209   def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
210     el = XML::Node.new "node"
211     el["id"] = id.to_s
212
213     add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
214
215     if visible?
216       el["lat"] = lat.to_s
217       el["lon"] = lon.to_s
218     end
219
220     add_tags_to_xml_node(el, node_tags)
221
222     el
223   end
224
225   def tags_as_hash
226     tags
227   end
228
229   def tags
230     @tags ||= Hash[node_tags.collect { |t| [t.k, t.v] }]
231   end
232
233   attr_writer :tags
234
235   def add_tag_key_val(k, v)
236     @tags ||= {}
237
238     # duplicate tags are now forbidden, so we can't allow values
239     # in the hash to be overwritten.
240     raise OSM::APIDuplicateTagsError.new("node", id, k) if @tags.include? k
241
242     @tags[k] = v
243   end
244
245   ##
246   # are the preconditions OK? this is mainly here to keep the duck
247   # typing interface the same between nodes, ways and relations.
248   def preconditions_ok?
249     in_world?
250   end
251
252   ##
253   # dummy method to make the interfaces of node, way and relation
254   # more consistent.
255   def fix_placeholders!(_id_map, _placeholder_id = nil)
256     # nodes don't refer to anything, so there is nothing to do here
257   end
258
259   private
260
261   def save_with_history!
262     t = Time.now.getutc
263
264     self.version += 1
265     self.timestamp = t
266
267     Node.transaction do
268       # clone the object before saving it so that the original is
269       # still marked as dirty if we retry the transaction
270       clone.save!
271
272       # Create a NodeTag
273       tags = self.tags
274       NodeTag.where(:node_id => id).delete_all
275       tags.each do |k, v|
276         tag = NodeTag.new
277         tag.node_id = id
278         tag.k = k
279         tag.v = v
280         tag.save!
281       end
282
283       # Create an OldNode
284       old_node = OldNode.from_node(self)
285       old_node.timestamp = t
286       old_node.save_with_dependencies!
287
288       # tell the changeset we updated one element only
289       changeset.add_changes! 1
290
291       # save the changeset in case of bounding box updates
292       changeset.save!
293     end
294   end
295 end