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