]> git.openstreetmap.org Git - rails.git/blob - app/models/node.rb
Refactor generation of object metadata in API calls
[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, :extend => ObjectFinder
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     begin
46       p = XML::Parser.string(xml)
47       doc = p.parse
48
49       doc.find('//osm/node').each do |pt|
50         return Node.from_xml_node(pt, create)
51       end
52       raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
53     rescue LibXML::XML::Error, ArgumentError => ex
54       raise OSM::APIBadXMLError.new("node", xml, ex.message)
55     end
56   end
57
58   def self.from_xml_node(pt, create=false)
59     node = Node.new
60     
61     raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt['lat'].nil?
62     raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt['lon'].nil?
63     node.lat = OSM.parse_float(pt['lat'], OSM::APIBadXMLError, "node", pt, "lat not a number")
64     node.lon = OSM.parse_float(pt['lon'], OSM::APIBadXMLError, "node", pt, "lon not a number")
65     raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt['changeset'].nil?
66     node.changeset_id = pt['changeset'].to_i
67
68     raise OSM::APIBadUserInput.new("The node is outside this world") unless node.in_world?
69
70     # version must be present unless creating
71     raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create or not pt['version'].nil?
72     node.version = create ? 0 : pt['version'].to_i
73
74     unless create
75       raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt['id'].nil?
76       node.id = pt['id'].to_i
77       # .to_i will return 0 if there is no number that can be parsed. 
78       # We want to make sure that there is no id with zero anyway
79       raise OSM::APIBadUserInput.new("ID of node cannot be zero when updating.") if node.id == 0
80     end
81
82     # We don't care about the time, as it is explicitly set on create/update/delete
83     # We don't care about the visibility as it is implicit based on the action
84     # and set manually before the actual delete
85     node.visible = true
86
87     # Start with no tags
88     node.tags = Hash.new
89
90     # Add in any tags from the XML
91     pt.find('tag').each do |tag|
92       raise OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag['k'].nil?
93       raise OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag['v'].nil?
94       node.add_tag_key_val(tag['k'],tag['v'])
95     end
96
97     return node
98   end
99
100   ##
101   # the bounding box around a node, which is used for determining the changeset's
102   # bounding box
103   def bbox
104     BoundingBox.new(longitude, latitude, longitude, latitude)
105   end
106
107   # Should probably be renamed delete_from to come in line with update
108   def delete_with_history!(new_node, user)
109     unless self.visible
110       raise OSM::APIAlreadyDeletedError.new("node", new_node.id)
111     end
112
113     # need to start the transaction here, so that the database can 
114     # provide repeatable reads for the used-by checks. this means it
115     # shouldn't be possible to get race conditions.
116     Node.transaction do
117       self.lock!
118       check_consistency(self, new_node, user)
119       ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
120       raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by ways #{ways.collect { |w| w.id }.join(",")}.") unless ways.empty?
121       
122       rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
123       raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by relations #{rels.collect { |r| r.id }.join(",")}.") unless rels.empty?
124
125       self.changeset_id = new_node.changeset_id
126       self.tags = {}
127       self.visible = false
128       
129       # update the changeset with the deleted position
130       changeset.update_bbox!(bbox)
131       
132       save_with_history!
133     end
134   end
135
136   def update_from(new_node, user)
137     Node.transaction do
138       self.lock!
139       check_consistency(self, new_node, user)
140       
141       # update changeset first
142       self.changeset_id = new_node.changeset_id
143       self.changeset = new_node.changeset
144       
145       # update changeset bbox with *old* position first
146       changeset.update_bbox!(bbox);
147       
148       # FIXME logic needs to be double checked
149       self.latitude = new_node.latitude 
150       self.longitude = new_node.longitude
151       self.tags = new_node.tags
152       self.visible = true
153       
154       # update changeset bbox with *new* position
155       changeset.update_bbox!(bbox);
156       
157       save_with_history!
158     end
159   end
160   
161   def create_with_history(user)
162     check_create_consistency(self, user)
163     self.version = 0
164     self.visible = true
165
166     # update the changeset to include the new location
167     changeset.update_bbox!(bbox)
168
169     save_with_history!
170   end
171
172   def to_xml
173     doc = OSM::API.new.get_xml_doc
174     doc.root << to_xml_node()
175     return doc
176   end
177
178   def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
179     el1 = XML::Node.new 'node'
180     el1['id'] = self.id.to_s
181     add_metadata_to_xml_node(el1, self, changeset_cache, user_display_name_cache)
182
183     if self.visible?
184       el1['lat'] = self.lat.to_s
185       el1['lon'] = self.lon.to_s
186     end
187
188     self.tags.each do |k,v|
189       el2 = XML::Node.new('tag')
190       el2['k'] = k.to_s
191       el2['v'] = v.to_s
192       el1 << el2
193     end
194
195     return el1
196   end
197
198   def tags_as_hash
199     return tags
200   end
201
202   def tags
203     unless @tags
204       @tags = {}
205       self.node_tags.each do |tag|
206         @tags[tag.k] = tag.v
207       end
208     end
209     @tags
210   end
211
212   def tags=(t)
213     @tags = t 
214   end 
215
216   def add_tag_key_val(k,v)
217     @tags = Hash.new unless @tags
218
219     # duplicate tags are now forbidden, so we can't allow values
220     # in the hash to be overwritten.
221     raise OSM::APIDuplicateTagsError.new("node", self.id, k) if @tags.include? k
222
223     @tags[k] = v
224   end
225
226   ##
227   # are the preconditions OK? this is mainly here to keep the duck
228   # typing interface the same between nodes, ways and relations.
229   def preconditions_ok?
230     in_world?
231   end
232
233   ##
234   # dummy method to make the interfaces of node, way and relation
235   # more consistent.
236   def fix_placeholders!(id_map, placeholder_id = nil)
237     # nodes don't refer to anything, so there is nothing to do here
238   end
239   
240   private
241
242   def save_with_history!
243     t = Time.now.getutc
244     Node.transaction do
245       self.version += 1
246       self.timestamp = t
247       self.save!
248
249       # Create a NodeTag
250       tags = self.tags
251       NodeTag.delete_all(:node_id => self.id)
252       tags.each do |k,v|
253         tag = NodeTag.new
254         tag.node_id = self.id
255         tag.k = k 
256         tag.v = v 
257         tag.save!
258       end 
259
260       # Create an OldNode
261       old_node = OldNode.from_node(self)
262       old_node.timestamp = t
263       old_node.save_with_dependencies!
264
265       # tell the changeset we updated one element only
266       changeset.add_changes! 1
267
268       # save the changeset in case of bounding box updates
269       changeset.save!
270     end
271   end
272   
273 end