Added a bunch more tests on the API 0.6. Fixed node/way/relation from_xml code to...
[rails.git] / app / models / relation.rb
1 class Relation < ActiveRecord::Base
2   require 'xml/libxml'
3   
4   include ConsistencyValidations
5   
6   set_table_name 'current_relations'
7
8   belongs_to :changeset
9
10   has_many :old_relations, :foreign_key => 'id', :order => 'version'
11
12   has_many :relation_members, :foreign_key => 'id'
13   has_many :relation_tags, :foreign_key => 'id'
14
15   has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
16   has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
17
18   def self.from_xml(xml, create=false)
19     begin
20       p = XML::Parser.new
21       p.string = xml
22       doc = p.parse
23
24       doc.find('//osm/relation').each do |pt|
25         return Relation.from_xml_node(pt, create)
26       end
27     rescue
28       return nil
29     end
30   end
31
32   def self.from_xml_node(pt, create=false)
33     relation = Relation.new
34
35     if !create and pt['id'] != '0'
36       relation.id = pt['id'].to_i
37     end
38
39     relation.version = pt['version']
40     relation.changeset_id = pt['changeset']
41
42     if create
43       relation.timestamp = Time.now
44       relation.visible = true
45     else
46       if pt['timestamp']
47         relation.timestamp = Time.parse(pt['timestamp'])
48       end
49     end
50
51     pt.find('tag').each do |tag|
52       relation.add_tag_keyval(tag['k'], tag['v'])
53     end
54
55     pt.find('member').each do |member|
56       relation.add_member(member['type'], member['ref'], member['role'])
57     end
58
59     return relation
60   end
61
62   def to_xml
63     doc = OSM::API.new.get_xml_doc
64     doc.root << to_xml_node()
65     return doc
66   end
67
68   def to_xml_node(user_display_name_cache = nil)
69     el1 = XML::Node.new 'relation'
70     el1['id'] = self.id.to_s
71     el1['visible'] = self.visible.to_s
72     el1['timestamp'] = self.timestamp.xmlschema
73     el1['version'] = self.version.to_s
74     el1['changeset'] = self.changeset_id.to_s
75
76     user_display_name_cache = {} if user_display_name_cache.nil?
77     
78     if user_display_name_cache and user_display_name_cache.key?(self.changeset.user_id)
79       # use the cache if available
80     elsif self.changeset.user.data_public?
81       user_display_name_cache[self.changeset.user_id] = self.changeset.user.display_name
82     else
83       user_display_name_cache[self.changeset.user_id] = nil
84     end
85
86     el1['user'] = user_display_name_cache[self.changeset.user_id] unless user_display_name_cache[self.changeset.user_id].nil?
87
88     self.relation_members.each do |member|
89       p=0
90       #if visible_members
91       #  # if there is a list of visible members then use that to weed out deleted segments
92       #  if visible_members[member.member_type][member.member_id]
93       #    p=1
94       #  end
95       #else
96         # otherwise, manually go to the db to check things
97         if member.member.visible?
98           p=1
99         end
100       #end
101       if p
102         e = XML::Node.new 'member'
103         e['type'] = member.member_type
104         e['ref'] = member.member_id.to_s 
105         e['role'] = member.member_role
106         el1 << e
107        end
108     end
109
110     self.relation_tags.each do |tag|
111       e = XML::Node.new 'tag'
112       e['k'] = tag.k
113       e['v'] = tag.v
114       el1 << e
115     end
116     return el1
117   end 
118
119   def self.find_for_nodes(ids, options = {})
120     if ids.empty?
121       return []
122     else
123       self.with_scope(:find => { :joins => "INNER JOIN current_relation_members ON current_relation_members.id = current_relations.id", :conditions => "current_relation_members.member_type = 'node' AND current_relation_members.member_id IN (#{ids.join(',')})" }) do
124         return self.find(:all, options)
125       end
126     end
127   end
128
129   def self.find_for_ways(ids, options = {})
130     if ids.empty?
131       return []
132     else
133       self.with_scope(:find => { :joins => "INNER JOIN current_relation_members ON current_relation_members.id = current_relations.id", :conditions => "current_relation_members.member_type = 'way' AND current_relation_members.member_id IN (#{ids.join(',')})" }) do
134         return self.find(:all, options)
135       end
136     end
137   end
138
139   def self.find_for_relations(ids, options = {})
140     if ids.empty?
141       return []
142     else
143       self.with_scope(:find => { :joins => "INNER JOIN current_relation_members ON current_relation_members.id = current_relations.id", :conditions => "current_relation_members.member_type = 'relation' AND current_relation_members.member_id IN (#{ids.join(',')})" }) do
144         return self.find(:all, options)
145       end
146     end
147   end
148
149   # FIXME is this really needed?
150   def members
151     unless @members
152       @members = Array.new
153       self.relation_members.each do |member|
154         @members += [[member.member_type,member.member_id,member.member_role]]
155       end
156     end
157     @members
158   end
159
160   def tags
161     unless @tags
162       @tags = Hash.new
163       self.relation_tags.each do |tag|
164         @tags[tag.k] = tag.v
165       end
166     end
167     @tags
168   end
169
170   def members=(m)
171     @members = m
172   end
173
174   def tags=(t)
175     @tags = t
176   end
177
178   def add_member(type,id,role)
179     @members = Array.new unless @members
180     @members += [[type,id,role]]
181   end
182
183   def add_tag_keyval(k, v)
184     @tags = Hash.new unless @tags
185
186     # duplicate tags are now forbidden, so we can't allow values
187     # in the hash to be overwritten.
188     raise OSM::APIDuplicateTagsError.new if @tags.include? k
189
190     @tags[k] = v
191   end
192
193   def save_with_history!
194     Relation.transaction do
195       t = Time.now
196       self.version += 1
197       self.timestamp = t
198       self.save!
199
200       tags = self.tags
201       RelationTag.delete_all(['id = ?', self.id])
202       tags.each do |k,v|
203         tag = RelationTag.new
204         tag.k = k
205         tag.v = v
206         tag.id = self.id
207         tag.save!
208       end
209
210       members = self.members
211       RelationMember.delete_all(['id = ?', self.id])
212       members.each do |n|
213         mem = RelationMember.new
214         mem.id = self.id
215         mem.member_type = n[0];
216         mem.member_id = n[1];
217         mem.member_role = n[2];
218         mem.save!
219       end
220
221       old_relation = OldRelation.from_relation(self)
222       old_relation.timestamp = t
223       old_relation.save_with_dependencies!
224     end
225   end
226
227   def delete_with_history(new_relation, user)
228     if self.visible
229       check_consistency(self, new_relation, user)
230       if RelationMember.find(:first, :joins => "INNER JOIN current_relations ON current_relations.id=current_relation_members.id", :conditions => [ "visible = 1 AND member_type='relation' and member_id=?", self.id ])
231         raise OSM::APIPreconditionFailedError.new
232       else
233         #self.user_id = user.id
234         # FIXME we need to deal with changeset here, which is probably already dealt with
235         self.changeset_id = new_relation.changeset_id
236         self.tags = []
237         self.members = []
238         self.visible = false
239         save_with_history!
240       end
241     else
242       raise OSM::APIAlreadyDeletedError.new
243     end
244   end
245
246   def update_from(new_relation, user)
247     check_consistency(self, new_relation, user)
248     if !new_relation.preconditions_ok?
249       raise OSM::APIPreconditionFailedError.new
250     end
251     # FIXME need to deal with changeset etc
252     #self.user_id = user.id
253     self.changeset_id = new_relation.changeset_id
254     self.tags = new_relation.tags
255     self.members = new_relation.members
256     self.visible = true
257     save_with_history!
258   end
259   
260   def create_with_history(user)
261     check_create_consistency(self, user)
262     if !self.preconditions_ok?
263       raise OSM::APIPreconditionFailedError.new
264     end
265     self.version = 0
266     self.visible = true
267     save_with_history!
268   end
269
270   def preconditions_ok?
271     # These are hastables that store an id in the index of all 
272     # the nodes/way/relations that have already been added.
273     # Once we know the id of the node/way/relation exists
274     # we check to see if it is already existing in the hashtable
275     # if it does, then we return false. Otherwise
276     # we add it to the relevant hash table, with the value true..
277     # Thus if you have nodes with the ids of 50 and 1 already in the
278     # relation, then the hash table nodes would contain:
279     # => {50=>true, 1=>true}
280     nodes = Hash.new
281     ways = Hash.new
282     relations = Hash.new
283     self.members.each do |m|
284       if (m[0] == "node")
285         n = Node.find(:first, :conditions => ["id = ?", m[1]])
286         unless n and n.visible 
287           return false
288         end
289         if nodes[m[1]]
290           return false
291         else
292           nodes[m[1]] = true
293         end
294       elsif (m[0] == "way")
295         w = Way.find(:first, :conditions => ["id = ?", m[1]])
296         unless w and w.visible and w.preconditions_ok?
297           return false
298         end
299         if ways[m[1]]
300           return false
301         else
302           ways[m[1]] = true
303         end
304       elsif (m[0] == "relation")
305         e = Relation.find(:first, :conditions => ["id = ?", m[1]])
306         unless e and e.visible and e.preconditions_ok?
307           return false
308         end
309         if relations[m[1]]
310           return false
311         else
312           relations[m[1]] = true
313         end
314       else
315         return false
316       end
317     end
318     return true
319   rescue
320     return false
321   end
322
323   # Temporary method to match interface to nodes
324   def tags_as_hash
325     return self.tags
326   end
327 end