1 class AmfController < ApplicationController
5 # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
7 # ====================================================================
10 # ---- talk process AMF request
13 req=StringIO.new(request.raw_post) # Get POST data as request
14 req.read(2) # Skip version indicator and client ID
15 results={} # Results of each body
20 headers=getint(req) # Read number of headers
22 headers.times do # Read each header
23 name=getstring(req) # |
24 req.getc # | skip boolean
25 value=getvalue(req) # |
26 header["name"]=value # |
29 bodies=getint(req) # Read number of bodies
30 bodies.times do # Read each body
31 message=getstring(req) # | get message name
32 index=getstring(req) # | get index in response sequence
33 bytes=getlong(req) # | get total size in bytes
34 args=getvalue(req) # | get response (probably an array)
37 when 'getpresets'; results[index]=putdata(index,getpresets)
38 when 'whichways'; results[index]=putdata(index,whichways(args))
39 when 'getway'; results[index]=putdata(index,getway(args))
40 when 'putway'; results[index]=putdata(index,putway(args))
41 when 'deleteway'; results[index]=putdata(index,deleteway(args))
48 response.headers["Content-Type"]="application/x-amf"
49 a,b=results.length.divmod(256)
50 ans=0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
60 # ====================================================================
64 # return presets,presetmenus and presetnames arrays
68 presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]
69 presetnames={}; presetnames['point']={}; presetnames['way']={}
73 ActiveRecord::Base.logger.info(" Message: getpresets")
75 # File.open("config/potlatch/presets.txt") do |file|
77 # Temporary patch to get around filepath problem
78 # To remove this patch and make the code nice again:
79 # 1. uncomment above line
80 # 2. fix the path in the above line
81 # 3. delete this here document, and the following line (StringIO....)
85 motorway: highway=motorway,ref=(type road number)
86 trunk road: highway=trunk,ref=(type road number),name=(type road name)
87 primary road: highway=primary,ref=(type road number),name=(type road name)
88 secondary road: highway=secondary,ref=(type road number),name=(type road name)
89 residential road: highway=residential,name=(type road name)
90 unclassified road: highway=unclassified,name=(type road name)
93 footpath: highway=footway,foot=yes
94 bridleway: highway=bridleway,foot=yes,horse=yes,bicycle=yes
95 byway: highway=byway,foot=yes,horse=yes,bicycle=yes,motorcar=yes
96 permissive path: highway=footway,foot=permissive
99 cycle lane: highway=cycleway,cycleway=lane,ncn_ref=
100 cycle track: highway=cycleway,cycleway=track,ncn_ref=
101 cycle lane (NCN): highway=cycleway,cycleway=lane,name=(type name here),ncn_ref=(type route number)
102 cycle track (NCN): highway=cycleway,cycleway=track,name=(type name here),ncn_ref=(type route number)
105 canal: waterway=canal,name=(type name here)
106 navigable river: waterway=river,boat=yes,name=(type name here)
107 navigable drain: waterway=drain,boat=yes,name=(type name here)
108 derelict canal: waterway=derelict_canal,name=(type name here)
109 unnavigable river: waterway=river,boat=no,name=(type name here)
110 unnavigable drain: waterway=drain,boat=no,name=(type name here)
113 railway: railway=rail
114 tramway: railway=tram
115 light railway: railway=light_rail
116 preserved railway: railway=preserved
117 disused railway tracks: railway=disused
118 course of old railway: railway=abandoned
121 mini roundabout: highway=mini_roundabout
122 traffic lights: highway=traffic_signals
125 bridge: highway=bridge
128 cattle grid: highway=cattle_grid
134 lock gate: waterway=lock_gate
136 aqueduct: waterway=aqueduct
137 winding hole: waterway=turning_point
138 mooring: waterway=mooring
141 station: railway=station
142 viaduct: railway=viaduct
143 level crossing: railway=crossing
146 StringIO.open(txt) do |file|
147 file.each_line {|line|
149 if (t=~/(\w+)\/(\w+)/) then
152 presetmenus[presettype].push(presetcategory)
153 presetnames[presettype][presetcategory]=["(no preset)"]
154 elsif (t=~/^(.+):\s?(.+)$/) then
156 presetnames[presettype][presetcategory].push(pre)
158 kv.split(',').each {|a|
159 if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
164 return [presets,presetmenus,presetnames]
167 # ----- whichways(left,bottom,right,top)
168 # return array of ways in current bounding box
169 # at present, instead of using correct (=more complex) SQL to find
170 # corner-crossing ways, it simply enlarges the bounding box by +/- 0.01
173 xmin = args[0].to_f-0.01
174 ymin = args[1].to_f-0.01
175 xmax = args[2].to_f+0.01
176 ymax = args[3].to_f+0.01
178 ActiveRecord::Base.logger.info(" Message: whichways, bbox=#{xmin},#{ymin},#{xmax},#{ymax}")
180 waylist=WaySegment.find_by_sql("SELECT DISTINCT current_way_segments.id AS wayid"+
181 " FROM current_way_segments,current_segments,current_nodes,current_ways "+
182 " WHERE segment_id=current_segments.id "+
183 " AND current_segments.visible=1 "+
184 " AND node_a=current_nodes.id "+
185 " AND current_ways.id=current_way_segments.id "+
186 " AND current_ways.visible=1 "+
187 " AND (latitude BETWEEN "+ymin.to_s+" AND "+ymax.to_s+") "+
188 " AND (longitude BETWEEN "+xmin.to_s+" AND "+xmax.to_s+")")
190 ways = waylist.collect {|a| a.wayid.to_i } # get an array of way id's
192 pointlist =ActiveRecord::Base.connection.select_all("SELECT current_nodes.id,current_nodes.tags "+
193 " FROM current_nodes "+
194 " LEFT OUTER JOIN current_segments cs1 ON cs1.node_a=current_nodes.id "+
195 " LEFT OUTER JOIN current_segments cs2 ON cs2.node_b=current_nodes.id "+
196 " WHERE (latitude BETWEEN "+ymin.to_s+" AND "+ymax.to_s+") "+
197 " AND (longitude BETWEEN "+xmin.to_s+" AND "+xmax.to_s+") "+
198 " AND cs1.id IS NULL AND cs2.id IS NULL "+
199 " AND current_nodes.visible=1")
201 points = pointlist.collect {|a| [a['id'],tag2array(a['tags'])] } # get a list of node ids and their tags
206 # ----- getway (objectname, way, baselong, basey, masterscale)
207 # returns objectname, array of co-ordinates, attributes,
208 # xmin,xmax,ymin,ymax
211 objname,wayid,baselong,basey,masterscale=args
216 xmax = ymax = -999999
218 ActiveRecord::Base.logger.info(" Message: getway, id=#{wayid}")
220 readwayquery(wayid).each {|row|
221 xs1=long2coord(row['long1'].to_f,baselong,masterscale); ys1=lat2coord(row['lat1'].to_f,basey,masterscale)
222 xs2=long2coord(row['long2'].to_f,baselong,masterscale); ys2=lat2coord(row['lat2'].to_f,basey,masterscale)
223 points << [xs1,ys1,row['id1'].to_i,0,tag2array(row['tags1']),0] if (row['id1'].to_i!=lastid)
224 lastid = row['id2'].to_i
225 points << [xs2,ys2,row['id2'].to_i,1,tag2array(row['tags2']),row['segment_id'].to_i]
226 xmin = [xmin,row['long1'].to_f,row['long2'].to_f].min
227 xmax = [xmax,row['long1'].to_f,row['long2'].to_f].max
228 ymin = [ymin,row['lat1'].to_f,row['lat2'].to_f].min
229 ymax = [ymax,row['lat1'].to_f,row['lat2'].to_f].max
233 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM current_way_tags WHERE id=#{wayid}"
234 attrlist.each {|a| attributes[a['k']]=a['v'] }
236 [objname,points,attributes,xmin,xmax,ymin,ymax]
239 # ----- putway (user token, way, array of co-ordinates, array of attributes,
240 # baselong, basey, masterscale)
241 # returns current way ID, new way ID, hash of renumbered nodes,
242 # xmin,xmax,ymin,ymax
245 usertoken,originalway,points,attributes,baselong,basey,masterscale=args
246 uid=getuserid(usertoken)
248 db_uqs='uniq'+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # temp uniquesegments table name, typically 51 chars
249 db_uqn='unin'+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # temp uniquenodes table name, typically 51 chars
250 db_now='@now'+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
251 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
252 originalway=originalway.to_i
254 ActiveRecord::Base.logger.info(" Message: putway, id=#{way}")
256 # -- 3. read original way into memory
258 xc={}; yc={}; tagc={}; seg={}
261 readwayquery(way).each { |row|
262 id1=row['id1'].to_i; xc[id1]=row['long1'].to_f; yc[id1]=row['lat1'].to_f; tagc[id1]=row['tags1']
263 id2=row['id2'].to_i; xc[id2]=row['long2'].to_f; yc[id2]=row['lat2'].to_f; tagc[id2]=row['tags2']
264 seg[row['segment_id'].to_i]=id1.to_s+'-'+id2.to_s
266 ActiveRecord::Base.connection.update("UPDATE current_ways SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id=#{way}")
268 way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
271 # -- 4. get version by inserting new row into ways
273 version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
275 # -- 5. compare nodes and update xmin,xmax,ymin,ymax
278 xmax = ymax = -999999
282 points.each_index do |i|
283 xs=coord2long(points[i][0],masterscale,baselong)
284 ys=coord2lat(points[i][1],masterscale,basey)
285 xmin=[xs,xmin].min; xmax=[xs,xmax].max
286 ymin=[ys,ymin].min; ymax=[ys,ymax].max
287 node=points[i][2].to_i
288 tagstr=array2tag(points[i][4])
289 tagsql="'"+sqlescape(tagstr)+"'"
294 newnode=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes ( latitude,longitude,timestamp,user_id,visible,tags) VALUES ( #{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
295 ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{newnode},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
297 renumberednodes[node.to_s]=newnode.to_s
299 elsif xc.has_key?(node)
300 # old node from original way - update
301 if (xs!=xc[node] or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node])
302 ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{node},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
303 ActiveRecord::Base.connection.update("UPDATE current_nodes SET latitude=#{ys},longitude=#{xs},timestamp=#{db_now},user_id=#{uid},tags=#{tagsql},visible=1 WHERE id=#{node}")
306 # old node, created in another way and now added to this way
312 # -- 6.i compare segments
315 seglist='' # list of existing segments that we want to keep
316 for i in (0..(points.length-2))
317 if (points[i+1][3].to_i==0) then next end
318 segid=points[i+1][5].to_i
319 from =points[i ][2].to_i
320 to =points[i+1][2].to_i
321 if seg.has_key?(segid)
322 if seg[segid]=="#{from}-#{to}" then
323 if (seglist!='') then seglist+=',' end; seglist+=segid.to_s
327 segid=ActiveRecord::Base.connection.insert("INSERT INTO current_segments ( node_a,node_b,timestamp,user_id,visible,tags) VALUES ( #{from},#{to},#{db_now},#{uid},1,'')")
328 ActiveRecord::Base.connection.insert("INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible,tags) VALUES (#{segid},#{from},#{to},#{db_now},#{uid},1,'')")
330 numberedsegments[(i+1).to_s]=segid.to_s
332 # numberedsegments.each{|a,b| RAILS_DEFAULT_LOGGER.error("Sending back: seg no. #{a} -> id #{b}") }
335 # -- 6.ii insert new way segments
337 createuniquesegments(way,db_uqs,seglist) # segments which appear in this way but no other
339 # delete segments from uniquesegments (and not in modified way)
342 INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible)
343 SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0
344 FROM current_segments AS cs, #{db_uqs} AS us
345 WHERE cs.id=us.segment_id AND cs.visible=1
347 ActiveRecord::Base.connection.insert(sql)
350 UPDATE current_segments AS cs, #{db_uqs} AS us
351 SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid}
352 WHERE cs.id=us.segment_id AND cs.visible=1
354 ActiveRecord::Base.connection.update(sql)
356 # delete nodes not in modified way or any other segments
358 createuniquenodes(db_uqs,db_uqn) # nodes which appear in this way but no other
361 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible)
362 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0
363 FROM current_nodes AS cn,#{db_uqn}
366 ActiveRecord::Base.connection.insert(sql)
369 UPDATE current_nodes AS cn, #{db_uqn}
370 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
373 ActiveRecord::Base.connection.update(sql)
375 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
376 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
378 # insert new version of route into way_segments
383 for i in (0..(points.length-2))
384 if (points[i+1][3].to_i==0) then next end
385 if insertsql !='' then insertsql +=',' end
386 if currentsql!='' then currentsql+=',' end
387 insertsql +="(#{way},#{points[i+1][5]},#{version})"
388 currentsql+="(#{way},#{points[i+1][5]},#{sequence})"
392 ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}");
393 ActiveRecord::Base.connection.insert("INSERT INTO way_segments (id,segment_id,version ) VALUES #{insertsql}");
394 ActiveRecord::Base.connection.insert("INSERT INTO current_way_segments (id,segment_id,sequence_id) VALUES #{currentsql}");
396 # -- 7. insert new way tags
400 attributes.each do |k,v|
401 if v=='' then next end
402 if v[0,6]=='(type ' then next end
403 if insertsql !='' then insertsql +=',' end
404 if currentsql!='' then currentsql+=',' end
405 insertsql +="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"',#{version})"
406 currentsql+="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"')"
409 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
410 if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
411 if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
413 [originalway,way,renumberednodes,numberedsegments,xmin,xmax,ymin,ymax]
416 # ----- deleteway (user token, way)
417 # returns way ID only
422 ActiveRecord::Base.logger.info(" Message: deleteway, id=#{way}")
424 uid=getuserid(usertoken); if !uid then return end
427 db_uqs='uniq'+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s # temp uniquesegments table name, typically 51 chars
428 db_uqn='unin'+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s # temp uniquenodes table name, typically 51 chars
429 db_now='@now'+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
430 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
431 createuniquesegments(way,db_uqs,'')
433 # - delete any otherwise unused segments
436 INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible)
437 SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0
438 FROM current_segments AS cs, #{db_uqs} AS us
439 WHERE cs.id=us.segment_id
441 ActiveRecord::Base.connection.insert(sql)
444 UPDATE current_segments AS cs, #{db_uqs} AS us
445 SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid}
446 WHERE cs.id=us.segment_id
448 ActiveRecord::Base.connection.update(sql)
450 # - delete any unused nodes
452 createuniquenodes(db_uqs,db_uqn)
455 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible)
456 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0
457 FROM current_nodes AS cn,#{db_uqn}
460 ActiveRecord::Base.connection.insert(sql)
463 UPDATE current_nodes AS cn, #{db_uqn}
464 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
467 ActiveRecord::Base.connection.update(sql)
469 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
470 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqn}")
474 ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
475 ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
476 ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}")
477 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
482 # ====================================================================
483 # Support functions for remote calls
486 ActiveRecord::Base.connection.select_all "SELECT n1.latitude AS lat1,n1.longitude AS long1,n1.id AS id1,n1.tags as tags1, "+
487 " n2.latitude AS lat2,n2.longitude AS long2,n2.id AS id2,n2.tags as tags2,segment_id "+
488 " FROM current_way_segments,current_segments,current_nodes AS n1,current_nodes AS n2 "+
489 " WHERE current_way_segments.id=#{id} "+
490 " AND segment_id=current_segments.id "+
491 " AND current_segments.visible=1 "+
492 " AND n1.id=node_a and n2.id=node_b "+
493 " AND n1.visible=1 AND n2.visible=1 "+
494 " ORDER BY sequence_id"
497 def createuniquesegments(way,uqs_name,seglist)
498 # Finds segments which appear in (previous version of) this way and no other
500 CREATE TEMPORARY TABLE #{uqs_name}
502 FROM (SELECT DISTINCT segment_id FROM current_way_segments
504 LEFT JOIN current_way_segments b
505 ON b.segment_id = a.segment_id
507 WHERE b.segment_id IS NULL
509 if (seglist!='') then sql+=" AND a.segment_id NOT IN (#{seglist})" end
510 ActiveRecord::Base.connection.execute(sql)
513 def createuniquenodes(uqs_name,uqn_name)
514 # Finds nodes which appear in uniquesegments but no other segments
516 CREATE TEMPORARY TABLE #{uqn_name}
517 SELECT DISTINCT node_id
518 FROM (SELECT cn.id AS node_id
519 FROM current_nodes AS cn,
520 current_segments AS cs,
522 WHERE cs.id=us.segment_id
523 AND (cn.id=cs.node_a OR cn.id=cs.node_b)) AS n
524 LEFT JOIN current_segments AS cs2 ON node_id=cs2.node_a AND cs2.visible=1
525 LEFT JOIN current_segments AS cs3 ON node_id=cs3.node_b AND cs3.visible=1
526 WHERE cs2.node_a IS NULL
527 AND cs3.node_b IS NULL
529 ActiveRecord::Base.connection.execute(sql)
533 a.gsub("'","''").gsub(92.chr,92.chr+92.chr)
538 a.gsub(';;;','#%').split(';').each do |b|
542 if k.nil? then k='' end
543 if v.nil? then v='' end
544 tags[k.gsub('#%','=')]=v.gsub('#%','=')
552 if v=='' then next end
553 if v[0,6]=='(type ' then next end
554 if str!='' then str+=';' end
555 str+=k.gsub(';',';;;').gsub('=','===')+'='+v.gsub(';',';;;').gsub('=','===')
561 token=sqlescape(token)
562 if (token=~/^(.+)\+(.+)$/) then
563 return ActiveRecord::Base.connection.select_value("SELECT id FROM users WHERE active=1 AND email='#{$1}' AND pass_crypt=MD5('#{$2}')")
565 return ActiveRecord::Base.connection.select_value("SELECT id FROM users WHERE active=1 AND token='#{token}'")
571 # ====================================================================
572 # AMF read subroutines
574 # ----- getint return two-byte integer
575 # ----- getlong return four-byte long
576 # ----- getstring return string with two-byte length
577 # ----- getdouble return eight-byte double-precision float
578 # ----- getobject return object/hash
579 # ----- getarray return numeric array
586 ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
590 len=s.getc*256+s.getc
595 a=s.read(8).unpack('G') # G big-endian, E little-endian
610 while (key=getstring(s))
611 if (key=='') then break end
614 s.getc # skip the 9 'end of object' value
618 # ----- getvalue parse and get value
622 when 0; return getdouble(s) # number
623 when 1; return s.getc # boolean
624 when 2; return getstring(s) # string
625 when 3; return getobject(s) # object/hash
626 when 5; return nil # null
627 when 6; return nil # undefined
628 when 8; s.read(4) # mixedArray
629 return getobject(s) # |
630 when 10;return getarray(s) # array
631 else; return nil # error
635 # ====================================================================
636 # AMF write subroutines
638 # ----- putdata envelope data into AMF writeable form
639 # ----- encodevalue pack variables as AMF
642 d =encodestring(index+"/onResult")
643 d+=encodestring("null")
651 a=10.chr+encodelong(n.length)
659 a+=encodestring(k)+encodevalue(v)
663 2.chr+encodestring(n)
664 when 'Bignum','Fixnum','Float'
665 0.chr+encodedouble(n)
669 RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
673 # ----- encodestring encode string with two-byte length
674 # ----- encodedouble encode number as eight-byte double precision float
675 # ----- encodelong encode number as four-byte long
678 a,b=n.size.divmod(256)
690 # ====================================================================
691 # Co-ordinate conversion
693 def lat2coord(a,basey,masterscale)
694 -(lat2y(a)-basey)*masterscale+250
697 def long2coord(a,baselong,masterscale)
698 (a-baselong)*masterscale+350
702 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
705 def coord2lat(a,masterscale,basey)
706 y2lat((a-250)/-masterscale+basey)
709 def coord2long(a,masterscale,baselong)
710 (a-350)/masterscale+baselong
714 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)