1 # AMF Controller is a semi-standalone API for Flash clients, particularly Potlatch.
2 # All interaction between Potlatch (as a .SWF application) and the
3 # OSM database takes place using this controller. Messages are
4 # encoded in the Actionscript Message Format (AMF).
6 # See Also Potlatch::Potlatch and Potlatch::AMF
9 # editions Systeme D / Richard Fairhurst 2004-2008
11 # All in/out parameters are floats unless explicitly stated.
13 # to trap errors (getway_old,putway,putpoi,deleteway only):
14 # return(-1,"message") <-- just puts up a dialogue
15 # return(-2,"message") <-- also asks the user to e-mail me
17 # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
18 class AmfController < ApplicationController
24 before_filter :check_write_availability
26 # Main AMF handler. Tha talk method takes in AMF, figures out what to do and dispatched to the appropriate private method
28 req=StringIO.new(request.raw_post+0.chr) # Get POST data as request
29 # (cf http://www.ruby-forum.com/topic/122163)
30 req.read(2) # Skip version indicator and client ID
31 results={} # Results of each body
32 renumberednodes={} # Shared across repeated putways
33 renumberedways={} # Shared across repeated putways
38 headers=AMF.getint(req) # Read number of headers
40 headers.times do # Read each header
41 name=AMF.getstring(req) # |
42 req.getc # | skip boolean
43 value=AMF.getvalue(req) # |
44 header["name"]=value # |
47 bodies=AMF.getint(req) # Read number of bodies
48 bodies.times do # Read each body
49 message=AMF.getstring(req) # | get message name
50 index=AMF.getstring(req) # | get index in response sequence
51 bytes=AMF.getlong(req) # | get total size in bytes
52 args=AMF.getvalue(req) # | get response (probably an array)
55 when 'getpresets'; results[index]=AMF.putdata(index,getpresets)
56 when 'whichways'; results[index]=AMF.putdata(index,whichways(args))
57 when 'whichways_deleted'; results[index]=AMF.putdata(index,whichways_deleted(args))
58 when 'getway'; results[index]=AMF.putdata(index,getway(args))
59 when 'getrelation'; results[index]=AMF.putdata(index,getrelation(args))
60 when 'getway_old'; results[index]=AMF.putdata(index,getway_old(args))
61 when 'getway_history'; results[index]=AMF.putdata(index,getway_history(args))
62 when 'putway'; r=putway(args,renumberednodes)
65 renumberedways[r[1]] = r[2]
67 results[index]=AMF.putdata(index,r)
68 when 'putrelation'; results[index]=AMF.putdata(index,putrelation(args, renumberednodes, renumberedways))
69 when 'deleteway'; results[index]=AMF.putdata(index,deleteway(args))
70 when 'putpoi'; results[index]=AMF.putdata(index,putpoi(args))
71 when 'getpoi'; results[index]=AMF.putdata(index,getpoi(args))
78 RAILS_DEFAULT_LOGGER.info(" Response: start")
79 a,b=results.length.divmod(256)
80 render :content_type => "application/x-amf", :text => proc { |response, output|
81 output.write 0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
86 RAILS_DEFAULT_LOGGER.info(" Response: end")
91 # Return presets (default tags and crap) to potlatch.
92 # Uses POTLATCH_PRESETS global, set up in OSM::Potlatch
94 return POTLATCH_PRESETS
98 # Find all the way ids and nodes (including tags and projected lat/lng) which aren't part of those ways in an are
100 # The argument is an array containing the following, in order:
101 # 0. minimum longitude
102 # 1. minimum latitude
103 # 2. maximum longitude
104 # 3. maximum latitude
105 # 4. baselong, 5. basey, 6. masterscale as above
106 def whichways(args) #:doc:
107 xmin = args[0].to_f-0.01
108 ymin = args[1].to_f-0.01
109 xmax = args[2].to_f+0.01
110 ymax = args[3].to_f+0.01
113 masterscale = args[6]
115 def whichways(xmin, ymin, xmax, ymax) #:doc:
116 xmin -= 0.01; ymin -= 0.01
117 xmax += 0.01; ymax += 0.01
119 if POTLATCH_USE_SQL then
120 way_ids = sql_find_way_ids_in_area(xmin, ymin, xmax, ymax)
121 points = sql_find_pois_in_area(xmin, ymin, xmax, ymax)
122 relation_ids = sql_find_relations_in_area_and_ways(xmin, ymin, xmax, ymax, way_ids)
124 # find the way ids in an area
125 nodes_in_area = Node.find_by_area(ymin, xmin, ymax, xmax, :conditions => "current_nodes.visible = 1", :include => :ways)
126 way_ids = nodes_in_area.collect { |node| node.way_ids }.flatten.uniq
128 # find the node ids in an area that aren't part of ways
129 nodes_not_used_in_area = nodes_in_area.select { |node| node.ways.empty? }
130 points = nodes_not_used_in_area.collect { |n| [n.id, n.lon_potlatch(baselong,masterscale), n.lat_potlatch(basey,masterscale), n.tags_as_hash] }
132 # find the relations used by those nodes and ways
133 relations = Relation.find_for_nodes(nodes_in_area.collect { |n| n.id }, :conditions => "visible = 1") +
134 Relation.find_for_ways(way_ids, :conditions => "visible = 1")
135 relation_ids = relations.collect { |relation| relation.id }.uniq
138 [way_ids, points, relation_ids]
141 # ----- whichways_deleted
142 # return array of deleted ways in current bounding box
144 # does: finds all deleted ways with a deleted node in bounding box
145 # out: [0] array of way ids
146 def whichways_deleted(args) #:doc:
147 xmin = args[0].to_f-0.01
148 ymin = args[1].to_f-0.01
149 xmax = args[2].to_f+0.01
150 ymax = args[3].to_f+0.01
153 masterscale = args[6]
155 def whichways_deleted(xmin, ymin, xmax, ymax) #:doc:
156 xmin -= 0.01; ymin -= 0.01
157 xmax += 0.01; ymax += 0.01
159 nodes_in_area = Node.find_by_area(ymin, xmin, ymax, xmax, :conditions => "current_nodes.visible = 0 AND current_ways.visible = 0", :include => :ways_via_history)
160 way_ids = nodes_in_area.collect { |node| node.ways_via_history_ids }.flatten.uniq
166 # Get a way with all of it's nodes and tags
167 # The input is an array with the following components, in order:
168 # 0. wayid - the ID of the way to get
169 # 1. baselong - origin of SWF map (longitude)
170 # 2. basey - origin of SWF map (latitude)
171 # 3. masterscale - SWF map scale
173 # The output is an array which contains all the nodes (with projected
174 # latitude and longitude) and tags for a way (and all the nodes tags).
175 # It also has the way's unprojected (WGS84) bbox.
177 # FIXME: The server really shouldn't be figuring out a ways bounding box and doing projection for potlatch
178 # FIXME: the argument splitting should be done in the 'talk' method, not here
179 def getway(args) #:doc:
180 wayid,baselong,basey,masterscale = args
183 def getway(wayid) #:doc:
184 if POTLATCH_USE_SQL then
185 points = sql_get_nodes_in_way(wayid)
186 tags = sql_get_tags_in_way(wayid)
188 # Ideally we would do ":include => :nodes" here but if we do that
189 # then rails only seems to return the first copy of a node when a
190 # way includes a node more than once
191 way = Way.find(wayid)
192 points = way.nodes.collect do |node|
193 [node.lon, node.lat, node.id, nil, node.tags_as_hash]
198 [wayid, points, tags]
202 # returns old version of way
204 # [1] way version to get (or -1 for "last deleted version")
205 # [2] baselong, [3] basey, [4] masterscale
206 # does: gets old version of way and all constituent nodes
207 # for undelete, always uses the most recent version of each node
208 # (even if it's moved)
209 # for revert, uses the historic version of each node, but if that node is
210 # still visible and has been changed since, generates a new node id
211 # out: [0] 0 (code for success), [1] SWF object name,
212 # [2] array of points (as getway _except_ [3] is node.visible?, 0 or 1),
213 # [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox),
215 def getway_old(args) #:doc:
216 RAILS_DEFAULT_LOGGER.info(" Message: getway_old (server is #{SERVER_URL})")
217 # if SERVER_URL=="www.openstreetmap.org" then return -1,"Revert is not currently enabled on the OpenStreetMap server." end
219 def getway_old(id, version) #:doc:
221 old_way = OldWay.find(:first, :conditions => ['visible = 1 AND id = ?', id], :order => 'version DESC')
222 points = old_way.get_nodes_undelete
224 old_way = OldWay.find(:first, :conditions => ['id = ? AND version = ?', id, version])
225 points = old_way.get_nodes_revert
228 old_way.tags['history'] = "Retrieved from v#{old_way.version}"
230 [0, id, points, old_way.tags, old_way.version]
233 def getway_history(wayid) #:doc:
234 history = Way.find(wayid).old_ways.collect do |old_way|
235 user = old_way.user.data_public? ? old_way.user.display_name : 'anonymous'
236 [old_way.version, old_way.timestamp.strftime("%d %b %Y, %H:%M"), old_way.visible ? 1 : 0, user]
242 # Get a relation with all tags and members.
246 # 2. list of members.
248 def getrelation(relid) #:doc:
249 rel = Relation.find(relid)
251 [relid, rel.tags, rel.members]
255 # save relation to the database
256 # in: [0] user token (string),
257 # [1] original relation id (may be negative),
258 # [2] hash of tags, [3] list of members,
260 # out: [0] 0 (success), [1] original relation id (unchanged),
261 # [2] new relation id
262 def putrelation(args, renumberednodes, renumberedways) #:doc:
263 usertoken,relid,tags,members,visible=args
264 uid=getuserid(usertoken)
265 if !uid then return -1,"You are not logged in, so the point could not be saved." end
267 def putrelation(renumberednodes, renumberedways, usertoken, relid, tags, members, visible) #:doc:
268 uid = getuserid(usertoken)
269 if !uid then return -1,"You are not logged in, so the relation could not be saved." end
272 visible = visible.to_i
274 # create a new relation, or find the existing one
278 rel = Relation.find(relid)
281 # check the members are all positive, and correctly type
286 mid = renumberednodes[mid] if m[0] == 'node'
287 mid = renumberedways[mid] if m[0] == 'way'
289 return -2, "Negative ID unresolved"
292 typedmembers << [m[0], mid, m[2]]
295 # assign new contents
296 rel.members = typedmembers
298 rel.visible = visible
301 # check it then save it
302 # BUG: the following is commented out because it always fails on my
303 # install. I think it's a Rails bug.
305 #if !rel.preconditions_ok?
306 # return -2, "Relation preconditions failed"
308 rel.save_with_history!
315 # saves a way to the database
316 # in: [0] user token (string),
317 # [1] original way id (may be negative),
318 # [2] array of points (as getway/getway_old),
319 # [3] hash of way tags,
320 # [4] original way version (0 if not a reverted/undeleted way),
321 # [5] baselong, [6] basey, [7] masterscale
322 # does: saves way to the database
323 # all constituent nodes are created/updated as necessary
324 # (or deleted if they were in the old version and are otherwise unused)
325 # out: [0] 0 (code for success), [1] original way id (unchanged),
326 # [2] new way id, [3] hash of renumbered nodes (old id=>new id),
327 # [4] xmin, [5] xmax, [6] ymin, [7] ymax (unprojected bbox)
328 def putway(args,renumberednodes) #:doc:
329 RAILS_DEFAULT_LOGGER.info(" putway started")
330 usertoken,originalway,points,attributes,oldversion,baselong,basey,masterscale=args
331 uid=getuserid(usertoken)
332 if !uid then return -1,"You are not logged in, so the way could not be saved." end
334 def putway(renumberednodes, usertoken, originalway, points, attributes) #:doc:
336 # -- Initialise and carry out checks
338 uid = getuserid(usertoken)
339 if !uid then return -1,"You are not logged in, so the way could not be saved." end
341 originalway = originalway.to_i
344 if a[2] == 0 or a[2].nil? then return -2,"Server error - node with id 0 found in way #{originalway}." end
345 if a[1] == 90 then return -2,"Server error - node with lat -90 found in way #{originalway}." end
348 if points.length < 2 then return -2,"Server error - way is only #{points.length} points long." end
350 # -- 3. read original way into memory
356 way = Way.find(originalway)
357 uniques = way.unshared_node_ids
360 # -- 4. get version by inserting new row into ways
370 if renumberednodes[id]
371 id = renumberednodes[id]
378 if !fpcomp(lat, node.lat) or !fpcomp(lon, node.lon) or
379 Tags.join(n[4]) != node.tags or !node.visible?
388 node.tags = Tags.join(n[4])
390 node.save_with_history!
393 renumberednodes[id] = node.id
398 uniques = uniques - [id]
402 # -- Delete any unique nodes
405 deleteitemrelations(n, 'node')
410 node.save_with_history!
413 points.each_index do |i|
414 xs=coord2long(points[i][0],masterscale,baselong)
415 ys=coord2lat(points[i][1],masterscale,basey)
416 xmin=[xs,xmin].min; xmax=[xs,xmax].max
417 ymin=[ys,ymin].min; ymax=[ys,ymax].max
418 node=points[i][2].to_i
419 tagstr=array2tag(points[i][4])
420 tagsql="'"+sqlescape(tagstr)+"'"
421 lat=(ys * 10000000).round
422 long=(xs * 10000000).round
423 tile=QuadTile.tile_for_point(ys, xs)
425 way.tags = attributes
429 way.save_with_history!
431 [0, originalway, way.id, renumberednodes]
435 # save POI to the database
436 # in: [0] user token (string),
437 # [1] original node id (may be negative),
438 # [2] projected longitude, [3] projected latitude,
439 # [4] hash of tags, [5] visible (0 to delete, 1 otherwise),
440 # [6] baselong, [7] basey, [8] masterscale
441 # does: saves POI node to the database
442 # refuses save if the node has since become part of a way
443 # out: [0] 0 (success), [1] original node id (unchanged),
445 def putpoi(args) #:doc:
446 usertoken,id,x,y,tags,visible,baselong,basey,masterscale=args
447 uid=getuserid(usertoken)
448 if !uid then return -1,"You are not logged in, so the point could not be saved." end
450 def putpoi(usertoken, id, lon, lat, tags, visible) #:doc:
451 uid = getuserid(usertoken)
452 if !uid then return -1,"You are not logged in, so the point could not be saved." end
455 visible = (visible.to_i == 1)
461 unless node.ways.empty? then return -1,"The point has since become part of a way, so you cannot save it as a POI." end
462 deleteitemrelations(id, 'node')
471 node.tags = Tags.join(tags)
472 node.visible = visible
473 node.save_with_history!
479 # read POI from database
480 # (only called on revert: POIs are usually read by whichways)
481 # in: [0] node id, [1] baselong, [2] basey, [3] masterscale
483 # out: [0] id (unchanged), [1] projected long, [2] projected lat,
485 def getpoi(args) #:doc:
486 id,baselong,basey,masterscale = args
488 n = Node.find(id.to_i)
490 return [n.id, n.lon_potlatch(baselong,masterscale), n.lat_potlatch(basey,masterscale), n.tags_as_hash]
492 return [nil,nil,nil,'']
496 def getpoi(id) #:doc:
500 return [n.id, n.lon, n.lat, n.tags_as_hash]
502 return [nil, nil, nil, '']
507 def deleteway(usertoken, way_id) #:doc:
508 uid = getuserid(usertoken)
509 if !uid then return -1,"You are not logged in, so the way could not be deleted." end
511 # FIXME: would be good not to make two history entries when removing
512 # two nodes from the same relation
513 user = User.find(uid)
514 way = Way.find(way_id)
515 way.unshared_node_ids.each do |n|
516 deleteitemrelations(n, 'node')
519 way.delete_with_relations_and_nodes_and_history(user)
524 def createuniquenodes(way,uqn_name,nodelist) #:doc:
525 # Find nodes which appear in this way but no others
527 CREATE TEMPORARY TABLE #{uqn_name}
529 FROM (SELECT DISTINCT node_id FROM current_way_nodes
531 LEFT JOIN current_way_nodes b
532 ON b.node_id=a.node_id
534 WHERE b.node_id IS NULL
536 unless nodelist.empty? then
537 sql+="AND a.node_id NOT IN ("+nodelist.join(',')+")"
539 ActiveRecord::Base.connection.execute(sql)
544 # ====================================================================
546 # deleteuniquenoderelations(uqn_name,uid,db_now)
547 # deleteitemrelations(way|node,'way'|'node',uid,db_now)
549 def deleteuniquenoderelations(uqn_name,uid,db_now) #:doc:
551 SELECT node_id,cr.id FROM #{uqn_name},current_relation_members crm,current_relations cr
552 WHERE crm.member_id=node_id
553 AND crm.member_type='node'
558 def deleteitemrelations(objid, type) #:doc:
559 relations = RelationMember.find(:all,
560 :conditions => ['member_type = ? and member_id = ?', type, objid],
561 :include => :relation).collect { |rm| rm.relation }.uniq
563 relations.each do |rel|
564 rel.members.delete_if { |x| x[0] == type and x[1] == objid }
565 rel.save_with_history!
569 def deleteitemrelations(objid,type,uid,db_now) #:doc:
571 SELECT cr.id FROM current_relation_members crm,current_relations cr
572 WHERE crm.member_id=#{objid}
573 AND crm.member_type='#{type}'
578 relways=ActiveRecord::Base.connection.select_all(sql)
580 removefromrelation(objid,type,a['id'],uid,db_now)
584 def removefromrelation(objid,type,relation,uid,db_now) #:doc:
585 rver=ActiveRecord::Base.connection.insert("INSERT INTO relations (id,user_id,timestamp,visible) VALUES (#{relation},#{uid},#{db_now},1)")
588 INSERT INTO relation_tags (id,k,v,version)
589 SELECT id,k,v,#{rver} FROM current_relation_tags
592 ActiveRecord::Base.connection.insert(tagsql)
595 INSERT INTO relation_members (id,member_type,member_id,member_role,version)
596 SELECT id,member_type,member_id,member_role,#{rver} FROM current_relation_members
598 AND (member_id!=#{objid} OR member_type!='#{type}')
600 ActiveRecord::Base.connection.insert(membersql)
602 ActiveRecord::Base.connection.update("UPDATE current_relations SET user_id=#{uid},timestamp=#{db_now} WHERE id=#{relation}")
603 ActiveRecord::Base.connection.execute("DELETE FROM current_relation_members WHERE id=#{relation} AND member_type='#{type}' AND member_id=#{objid}")
606 def sqlescape(a) #:doc:
607 a.gsub(/[\000-\037]/,"").gsub("'","''").gsub(92.chr) {92.chr+92.chr}
610 def tag2array(a) #:doc:
612 Tags.split(a) do |k, v|
613 tags[k.gsub(':','|')]=v
618 def array2tag(a) #:doc:
621 if v=='' then next end
622 if v[0,6]=='(type ' then next end
623 tags << [k.gsub('|',':'), v]
625 return Tags.join(tags)
628 def getuserid(token) #:doc:
629 if (token =~ /^(.+)\+(.+)$/) then
630 user = User.authenticate(:username => $1, :password => $2)
632 user = User.authenticate(:token => token)
635 return user ? user.id : nil;
638 # ====================================================================
639 # Co-ordinate conversion
641 def lat2coord(a,basey,masterscale) #:doc:
642 -(lat2y(a)-basey)*masterscale
645 def long2coord(a,baselong,masterscale) #:doc:
646 (a-baselong)*masterscale
650 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
653 def coord2lat(a,masterscale,basey) #:doc:
654 y2lat(a/-masterscale+basey)
657 def coord2long(a,masterscale,baselong) #:doc:
658 a/masterscale+baselong
662 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)
668 # indent-tabs-mode: t