1 class AmfController < ApplicationController
6 # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
8 # ====================================================================
11 # ---- talk process AMF request
14 req=StringIO.new(request.raw_post) # Get POST data as request
15 req.read(2) # Skip version indicator and client ID
16 results={} # Results of each body
21 headers=getint(req) # Read number of headers
22 for i in (1..headers) # 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 for i in (1..bodies) # 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 File.open("config/potlatch/presets.txt") do |file|
74 file.each_line {|line|
76 if (t=~/(\w+)\/(\w+)/) then
79 presetmenus[presettype].push(presetcategory)
80 presetnames[presettype][presetcategory]=["(no preset)"]
81 elsif (t=~/^(.+):\s?(.+)$/) then
83 presetnames[presettype][presetcategory].push(pre)
85 kv.split(',').each {|a|
86 if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
91 [presets,presetmenus,presetnames]
94 # ----- whichways(left,bottom,right,top)
95 # return array of ways in current bounding box
96 # at present, instead of using correct (=more complex) SQL to find
97 # corner-crossing ways, it simply enlarges the bounding box by +/- 0.01
100 waylist=WaySegment.find_by_sql("SELECT DISTINCT current_way_segments.id AS wayid"+
101 " FROM current_way_segments,current_segments,current_nodes "+
102 " WHERE segment_id=current_segments.id "+
103 " AND current_segments.visible=1 "+
104 " AND node_a=current_nodes.id "+
105 " AND (latitude BETWEEN "+(args[1].to_f-0.01).to_s+" AND "+(args[3].to_f+0.01).to_s+") "+
106 " AND (longitude BETWEEN "+(args[0].to_f-0.01).to_s+" AND "+(args[2].to_f+0.01).to_s+")")
112 pointlist=ActiveRecord::Base.connection.select_all("SELECT current_nodes.id,current_nodes.tags "+
113 " FROM current_nodes "+
114 " LEFT OUTER JOIN current_segments cs1 ON cs1.node_a=current_nodes.id "+
115 " LEFT OUTER JOIN current_segments cs2 ON cs2.node_b=current_nodes.id "+
116 " WHERE (latitude BETWEEN "+(args[1].to_f-0.01).to_s+" AND "+(args[3].to_f+0.01).to_s+") "+
117 " AND (longitude BETWEEN "+(args[0].to_f-0.01).to_s+" AND "+(args[2].to_f-0.01).to_s+") "+
118 " AND cs1.id IS NULL AND cs2.id IS NULL "+
119 " AND current_nodes.visible=1")
122 points<<[a['id'],tag2array(a['tags'])]
127 # ----- getway (objectname, way, baselong, basey, masterscale)
128 # returns objectname, array of co-ordinates, attributes,
129 # xmin,xmax,ymin,ymax
132 objname,wayid,baselong,basey,masterscale=args
136 xmin=999999; xmax=-999999
137 ymin=999999; ymax=-999999
139 readwayquery(wayid).each {|row|
140 xs1=long2coord(row['long1'].to_f,baselong,masterscale); ys1=lat2coord(row['lat1'].to_f,basey,masterscale)
141 xs2=long2coord(row['long2'].to_f,baselong,masterscale); ys2=lat2coord(row['lat2'].to_f,basey,masterscale)
142 if (row['id1'].to_i!=lastid)
143 points<<[xs1,ys1,row['id1'].to_i,0,tag2array(row['tags1']),0]
145 lastid=row['id2'].to_i
146 points<<[xs2,ys2,row['id2'].to_i,1,tag2array(row['tags2']),row['segment_id'].to_i]
147 xmin=[xmin,row['long1'].to_f,row['long2'].to_f].min
148 xmax=[xmax,row['long1'].to_f,row['long2'].to_f].max
149 ymin=[ymin,row['lat1'].to_f,row['lat2'].to_f].min
150 ymax=[ymax,row['lat1'].to_f,row['lat2'].to_f].max
154 attrlist=ActiveRecord::Base.connection.select_all "SELECT k,v FROM current_way_tags WHERE id=#{wayid}"
155 attrlist.each {|a| attributes[a['k']]=a['v'] }
157 [objname,points,attributes,xmin,xmax,ymin,ymax]
160 # ----- putway (user token, way, array of co-ordinates, array of attributes,
161 # baselong, basey, masterscale)
162 # returns current way ID, new way ID, hash of renumbered nodes,
163 # xmin,xmax,ymin,ymax
166 usertoken,originalway,points,attributes,baselong,basey,masterscale=args
167 uid=getuserid(usertoken); if !uid then return end
168 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
169 db_now='@now'+uid.to_s+originalway.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
170 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
171 originalway=originalway.to_i
173 # -- 3. read original way into memory
175 xc={}; yc={}; tagc={}; seg={}
178 readwayquery(way).each { |row|
179 id1=row['id1'].to_i; xc[id1]=row['long1'].to_f; yc[id1]=row['lat1'].to_f; tagc[id1]=row['tags1']
180 id2=row['id2'].to_i; xc[id2]=row['long2'].to_f; yc[id2]=row['lat2'].to_f; tagc[id2]=row['tags2']
181 seg[row['segment_id'].to_i]=id1.to_s+'-'+id2.to_s
184 way=ActiveRecord::Base.connection.insert("INSERT INTO current_ways (user_id,timestamp,visible) VALUES (#{uid},#{db_now},1)")
187 # -- 4. get version by inserting new row into ways
189 version=ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},1)")
191 # -- 5. compare nodes and update xmin,xmax,ymin,ymax
193 xmin=999999; xmax=-999999
194 ymin=999999; ymax=-999999
199 points.each_index do |i|
200 xs=coord2long(points[i][0],masterscale,baselong)
201 ys=coord2lat(points[i][1],masterscale,basey)
202 xmin=[xs,xmin].min; xmax=[xs,xmax].max
203 ymin=[ys,ymin].min; ymax=[ys,ymax].max
204 node=points[i][2].to_i
205 tagstr=array2tag(points[i][4])
206 tagsql="'"+sqlescape(tagstr)+"'"
211 newnode=ActiveRecord::Base.connection.insert("INSERT INTO current_nodes ( latitude,longitude,timestamp,user_id,visible,tags) VALUES ( #{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
212 ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{newnode},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
214 renumberednodes[node.to_s]=newnode.to_s
216 elsif xc.has_key?(node)
217 # old node from original way - update
218 if (xs!=xc[node] or (ys/0.0000001).round!=(yc[node]/0.0000001).round or tagstr!=tagc[node])
219 ActiveRecord::Base.connection.insert("INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible,tags) VALUES (#{node},#{ys},#{xs},#{db_now},#{uid},1,#{tagsql})")
220 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}")
222 if (nodelist!='') then nodelist+=',' end; nodelist+=node.to_s
225 # old node, created in another way and now added to this way
226 if (nodelist!='') then nodelist+=',' end; nodelist+=node.to_s
232 ActiveRecord::Base.connection.update("UPDATE current_nodes SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id IN (#{nodelist})")
235 # -- 6.i compare segments
239 for i in (0..(points.length-2))
240 if (points[i+1][3].to_i==0) then next end
241 segid=points[i+1][5].to_i
242 from =points[i ][2].to_i
243 to =points[i+1][2].to_i
244 if seg.has_key?(segid)
245 if seg[segid]=="#{from}-#{to}" then
246 if (seglist!='') then seglist+=',' end; seglist+=segid.to_s
250 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,'')")
251 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,'')")
253 numberedsegments[(i+1).to_s]=segid.to_s
255 # numberedsegments.each{|a,b| RAILS_DEFAULT_LOGGER.error("Sending back: seg no. #{a} -> id #{b}") }
258 ActiveRecord::Base.connection.update("UPDATE current_segments SET timestamp=#{db_now},user_id=#{uid},visible=1 WHERE id IN (#{seglist})")
262 # -- 6.ii insert new way segments
264 createuniquesegments(way,db_uqs)
267 # ActiveRecord::Base.connection.select_values("SELECT segment_id FROM #{db_uqs}").each {|b| a+=b+',' }
268 # RAILS_DEFAULT_LOGGER.error("Unique segments are #{a}")
269 # a=ActiveRecord::Base.connection.select_value("SELECT #{db_now}")
270 # RAILS_DEFAULT_LOGGER.error("Timestamp of this edit is #{a}")
271 # RAILS_DEFAULT_LOGGER.error("Userid of this edit is #{uid}")
273 # delete nodes from uniquesegments (and not in modified way)
276 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible)
277 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0
278 FROM current_nodes AS cn,
279 current_segments AS cs,
281 WHERE(cn.id=cs.node_a OR cn.id=cs.node_b)
282 AND cs.id=us.segment_id AND cs.visible=1
283 AND (cn.timestamp!=#{db_now} OR cn.user_id!=#{uid})
285 ActiveRecord::Base.connection.insert(sql)
288 UPDATE current_nodes AS cn,
289 current_segments AS cs,
291 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
292 WHERE (cn.id=cs.node_a OR cn.id=cs.node_b)
293 AND cs.id=us.segment_id AND cs.visible=1
294 AND (cn.timestamp!=#{db_now} OR cn.user_id!=#{uid})
296 ActiveRecord::Base.connection.update(sql)
298 # delete segments from uniquesegments (and not in modified way)
301 INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible)
302 SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0
303 FROM current_segments AS cs, #{db_uqs} AS us
304 WHERE cs.id=us.segment_id AND cs.visible=1
305 AND (cs.timestamp!=#{db_now} OR cs.user_id!=#{uid})
307 ActiveRecord::Base.connection.insert(sql)
310 UPDATE current_segments AS cs, #{db_uqs} AS us
311 SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid}
312 WHERE cs.id=us.segment_id AND cs.visible=1
313 AND (cs.timestamp!=#{db_now} OR cs.user_id!=#{uid})
315 ActiveRecord::Base.connection.update(sql)
316 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
318 # insert new version of route into way_segments
323 for i in (0..(points.length-2))
324 if (points[i+1][3].to_i==0) then next end
325 if insertsql !='' then insertsql +=',' end
326 if currentsql!='' then currentsql+=',' end
327 insertsql +="(#{way},#{points[i+1][5]},#{version})"
328 currentsql+="(#{way},#{points[i+1][5]},#{sequence})"
332 ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}");
333 ActiveRecord::Base.connection.insert("INSERT INTO way_segments (id,segment_id,version ) VALUES #{insertsql}");
334 ActiveRecord::Base.connection.insert("INSERT INTO current_way_segments (id,segment_id,sequence_id) VALUES #{currentsql}");
336 # -- 7. insert new way tags
340 attributes.each do |k,v|
341 if v=='' then next end
342 if v[0,6]=='(type ' then next end
343 if insertsql !='' then insertsql +=',' end
344 if currentsql!='' then currentsql+=',' end
345 insertsql +="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"',version)"
346 currentsql+="(#{way},'"+sqlescape(k)+"','"+sqlescape(v)+"')"
349 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
350 if (insertsql !='') then ActiveRecord::Base.connection.insert("INSERT INTO way_tags (id,k,v,version) VALUES #{insertsql}" ) end
351 if (currentsql!='') then ActiveRecord::Base.connection.insert("INSERT INTO current_way_tags (id,k,v) VALUES #{currentsql}") end
353 [originalway,way,renumberednodes,numberedsegments,xmin,xmax,ymin,ymax]
356 # ----- deleteway (user token, way)
357 # returns way ID only
361 uid=getuserid(usertoken); if !uid then return end
364 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
365 db_now='@now'+uid.to_s+way.to_i.abs.to_s+Time.new.to_i.to_s # 'now' variable name, typically 51 chars
366 ActiveRecord::Base.connection.execute("SET #{db_now}=NOW()")
367 createuniquesegments(way,db_uqs)
370 INSERT INTO nodes (id,latitude,longitude,timestamp,user_id,visible)
371 SELECT DISTINCT cn.id,cn.latitude,cn.longitude,#{db_now},#{uid},0
372 FROM current_nodes AS cn,
373 current_segments AS cs,
375 WHERE (cn.id=cs.node_a OR cn.id=cs.node_b)
376 AND cs.id=us.segment_id
378 ActiveRecord::Base.connection.insert(sql)
381 UPDATE current_nodes AS cn,
382 current_segments AS cs,
384 SET cn.timestamp=#{db_now},cn.visible=0,cn.user_id=#{uid}
385 WHERE (cn.id=cs.node_a OR cn.id=cs.node_b)
386 AND cs.id=us.segment_id
388 ActiveRecord::Base.connection.update(sql)
390 # - delete any otherwise unused segments
393 INSERT INTO segments (id,node_a,node_b,timestamp,user_id,visible)
394 SELECT DISTINCT segment_id,node_a,node_b,#{db_now},#{uid},0
395 FROM current_segments AS cs, #{db_uqs} AS us
396 WHERE cs.id=us.segment_id
398 ActiveRecord::Base.connection.insert(sql)
401 UPDATE current_segments AS cs, #{db_uqs} AS us
402 SET cs.timestamp=#{db_now},cs.visible=0,cs.user_id=#{uid}
403 WHERE cs.id=us.segment_id
405 ActiveRecord::Base.connection.update(sql)
406 ActiveRecord::Base.connection.execute("DROP TABLE #{db_uqs}")
410 ActiveRecord::Base.connection.insert("INSERT INTO ways (id,user_id,timestamp,visible) VALUES (#{way},#{uid},#{db_now},0)")
411 ActiveRecord::Base.connection.update("UPDATE current_ways SET user_id=#{uid},timestamp=#{db_now},visible=0 WHERE id=#{way}")
412 ActiveRecord::Base.connection.execute("DELETE FROM current_way_segments WHERE id=#{way}")
413 ActiveRecord::Base.connection.execute("DELETE FROM current_way_tags WHERE id=#{way}")
418 # ====================================================================
419 # Support functions for remote calls
422 ActiveRecord::Base.connection.select_all "SELECT n1.latitude AS lat1,n1.longitude AS long1,n1.id AS id1,n1.tags as tags1, "+
423 " n2.latitude AS lat2,n2.longitude AS long2,n2.id AS id2,n2.tags as tags2,segment_id "+
424 " FROM current_way_segments,current_segments,current_nodes AS n1,current_nodes AS n2 "+
425 " WHERE current_way_segments.id=#{id} "+
426 " AND segment_id=current_segments.id "+
427 " AND n1.id=node_a and n2.id=node_b "+
428 " ORDER BY sequence_id"
431 def createuniquesegments(way,uqs_name)
433 CREATE TEMPORARY TABLE #{uqs_name}
435 FROM (SELECT DISTINCT segment_id FROM current_way_segments
437 LEFT JOIN current_way_segments b
438 ON b.segment_id = a.segment_id
440 WHERE b.segment_id IS NULL
442 ActiveRecord::Base.connection.execute(sql)
447 a.gsub("'","''").gsub(92.chr,92.chr+92.chr)
452 a.gsub(';;;','#%').split(';').each do |b|
456 if k.nil? then k='' end
457 if v.nil? then v='' end
458 tags[k.gsub('#%','=')]=v.gsub('#%','=')
466 if v=='' then next end
467 if v[0,6]=='(type ' then next end
468 if str!='' then str+=';' end
469 str+=k.gsub(';',';;;').gsub('=','===')+'='+v.gsub(';',';;;').gsub('=','===')
475 token=sqlescape(token)
476 if (token=~/^(.+)\+(.+)$/) then
477 return ActiveRecord::Base.connection.select_value("SELECT id FROM users WHERE active=1 AND timeout>NOW() AND email='#{$1}' AND pass_crypt=MD5('#{$2}')")
479 return ActiveRecord::Base.connection.select_value("SELECT id FROM users WHERE active=1 AND timeout>NOW() AND token='#{token}'")
485 # ====================================================================
486 # AMF read subroutines
488 # ----- getint return two-byte integer
489 # ----- getlong return four-byte long
490 # ----- getstring return string with two-byte length
491 # ----- getdouble return eight-byte double-precision float
492 # ----- getobject return object/hash
493 # ----- getarray return numeric array
500 ((s.getc*256+s.getc)*256+s.getc)*256+s.getc
504 len=s.getc*256+s.getc
509 a=s.read(8).unpack('G') # G big-endian, E little-endian
524 while (key=getstring(s))
525 if (key=='') then break end
528 s.getc # skip the 9 'end of object' value
532 # ----- getvalue parse and get value
536 when 0; return getdouble(s) # number
537 when 1; return s.getc # boolean
538 when 2; return getstring(s) # string
539 when 3; return getobject(s) # object/hash
540 when 5; return nil # null
541 when 6; return nil # undefined
542 when 8; s.read(4) # mixedArray
543 return getobject(s) # |
544 when 10;return getarray(s) # array
545 else; return nil # error
549 # ====================================================================
550 # AMF write subroutines
552 # ----- putdata envelope data into AMF writeable form
553 # ----- encodevalue pack variables as AMF
556 d =encodestring(index+"/onResult")
557 d+=encodestring("null")
565 a=10.chr+encodelong(n.length)
573 a+=encodestring(k)+encodevalue(v)
577 2.chr+encodestring(n)
578 when 'Bignum','Fixnum','Float'
579 0.chr+encodedouble(n)
583 RAILS_DEFAULT_LOGGER.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
587 # ----- encodestring encode string with two-byte length
588 # ----- encodedouble encode number as eight-byte double precision float
589 # ----- encodelong encode number as four-byte long
592 a,b=n.size.divmod(256)
604 # ====================================================================
605 # Co-ordinate conversion
607 def lat2coord(a,basey,masterscale)
608 -(lat2y(a)-basey)*masterscale+250
611 def long2coord(a,baselong,masterscale)
612 (a-baselong)*masterscale+350
616 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
619 def coord2lat(a,masterscale,basey)
620 y2lat((a-250)/-masterscale+basey)
623 def coord2long(a,masterscale,baselong)
624 (a-350)/masterscale+baselong
628 180/Math::PI * (2*Math.atan(Math.exp(a*Math::PI/180))-Math::PI/2)