1 # amf_controller is a semi-standalone API for Flash clients, particularly
2 # Potlatch. 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 # Helper functions are in /lib/potlatch.rb
8 # Author:: editions Systeme D / Richard Fairhurst 2004-2008
9 # Licence:: public domain.
11 # == General structure
13 # Apart from the amf_read and amf_write methods (which distribute the requests
14 # from the AMF message), each method generally takes arguments in the order
15 # they were sent by the Potlatch SWF. Do not assume typing has been preserved.
16 # Methods all return an array to the SWF.
20 # Note that this requires a patched version of composite_primary_keys 1.1.0
21 # (see http://groups.google.com/group/compositekeys/t/a00e7562b677e193)
22 # if you are to run with POTLATCH_USE_SQL=false .
26 # Any method that returns a status code (0 for ok) can also send:
27 # return(-1,"message") <-- just puts up a dialogue
28 # return(-2,"message") <-- also asks the user to e-mail me
29 # return(-3,'type',id) <-- version conflict
31 # To write to the Rails log, use logger.info("message").
34 # * version conflict when POIs and ways are reverted
36 class AmfController < ApplicationController
41 # Help methods for checking boundary sanity and area size
45 before_filter :check_api_writable
46 around_filter :api_call_timeout, :only => [:amf_read]
48 # Main AMF handlers: process the raw AMF string (using AMF library) and
49 # calls each action (private method) accordingly.
50 # ** FIXME: refactor to reduce duplication of code across read/write
54 req=StringIO.new(request.raw_post+0.chr)# Get POST data as request
55 # (cf http://www.ruby-forum.com/topic/122163)
56 req.read(2) # Skip version indicator and client ID
57 results={} # Results of each body
61 headers=AMF.getint(req) # Read number of headers
63 headers.times do # Read each header
64 name=AMF.getstring(req) # |
65 req.getc # | skip boolean
66 value=AMF.getvalue(req) # |
67 header["name"]=value # |
70 bodies=AMF.getint(req) # Read number of bodies
71 bodies.times do # Read each body
72 message=AMF.getstring(req) # | get message name
73 index=AMF.getstring(req) # | get index in response sequence
74 bytes=AMF.getlong(req) # | get total size in bytes
75 args=AMF.getvalue(req) # | get response (probably an array)
76 logger.info("Executing AMF #{message}(#{args.join(',')}):#{index}")
79 when 'getpresets'; results[index]=AMF.putdata(index,getpresets())
80 when 'whichways'; results[index]=AMF.putdata(index,whichways(*args))
81 when 'whichways_deleted'; results[index]=AMF.putdata(index,whichways_deleted(*args))
82 when 'getway'; r=AMF.putdata(index,getway(args[0].to_i))
84 when 'getrelation'; results[index]=AMF.putdata(index,getrelation(args[0].to_i))
85 when 'getway_old'; results[index]=AMF.putdata(index,getway_old(args[0].to_i,args[1]))
86 when 'getway_history'; results[index]=AMF.putdata(index,getway_history(args[0].to_i))
87 when 'getnode_history'; results[index]=AMF.putdata(index,getnode_history(args[0].to_i))
88 when 'findgpx'; results[index]=AMF.putdata(index,findgpx(*args))
89 when 'findrelations'; results[index]=AMF.putdata(index,findrelations(*args))
90 when 'getpoi'; results[index]=AMF.putdata(index,getpoi(*args))
93 logger.info("Encoding AMF results")
96 render :nothing => true, :status => :method_not_allowed
102 req=StringIO.new(request.raw_post+0.chr)
105 renumberednodes={} # Shared across repeated putways
106 renumberedways={} # Shared across repeated putways
108 headers=AMF.getint(req) # Read number of headers
109 headers.times do # Read each header
110 name=AMF.getstring(req) # |
111 req.getc # | skip boolean
112 value=AMF.getvalue(req) # |
113 header["name"]=value # |
116 bodies=AMF.getint(req) # Read number of bodies
117 bodies.times do # Read each body
118 message=AMF.getstring(req) # | get message name
119 index=AMF.getstring(req) # | get index in response sequence
120 bytes=AMF.getlong(req) # | get total size in bytes
121 args=AMF.getvalue(req) # | get response (probably an array)
123 logger.info("Executing AMF #{message}:#{index}")
125 when 'putway'; r=putway(renumberednodes,*args)
127 if r[1] != r[2] then renumberedways[r[1]] = r[2] end
128 results[index]=AMF.putdata(index,r)
129 when 'putrelation'; results[index]=AMF.putdata(index,putrelation(renumberednodes, renumberedways, *args))
130 when 'deleteway'; results[index]=AMF.putdata(index,deleteway(*args))
131 when 'putpoi'; r=putpoi(*args)
132 if r[1] != r[2] then renumberednodes[r[1]] = r[2] end
133 results[index]=AMF.putdata(index,r)
134 when 'startchangeset'; results[index]=AMF.putdata(index,startchangeset(*args))
137 logger.info("Encoding AMF results")
138 sendresponse(results)
140 render :nothing => true, :status => :method_not_allowed
146 # Start new changeset
148 def startchangeset(usertoken, cstags, closeid, closecomment)
149 user = getuser(usertoken)
150 if !user then return -1,"You are not logged in, so Potlatch can't write any changes to the database." end
152 # close previous changeset and add comment
154 cs = Changeset.find(closeid)
155 cs.set_closed_time_now
156 if cs.user_id!=user.id
157 return -2,"You cannot close that changeset because you're not the person who opened it."
158 elsif closecomment.empty?
161 cs.tags['comment']=closecomment
166 # open a new changeset
170 # smsm1 doesn't like the next two lines and thinks they need to be abstracted to the model more/better
171 cs.created_at = Time.now.getutc
172 cs.closed_at = cs.created_at + Changeset::IDLE_TIMEOUT
177 # Return presets (default tags, localisation etc.):
178 # uses POTLATCH_PRESETS global, set up in OSM::Potlatch.
180 def getpresets() #:doc:
181 return POTLATCH_PRESETS
185 # Find all the ways, POI nodes (i.e. not part of ways), and relations
186 # in a given bounding box. Nodes are returned in full; ways and relations
189 # return is of the form:
191 # [[way_id, way_version], ...],
192 # [[node_id, lat, lon, [tags, ...], node_version], ...],
193 # [[rel_id, rel_version], ...]]
194 # where the ways are any visible ways which refer to any visible
195 # nodes in the bbox, nodes are any visible nodes in the bbox but not
196 # used in any way, rel is any relation which refers to either a way
197 # or node that we're returning.
198 def whichways(xmin, ymin, xmax, ymax) #:doc:
199 enlarge = [(xmax-xmin)/8,0.01].min
200 xmin -= enlarge; ymin -= enlarge
201 xmax += enlarge; ymax += enlarge
203 # check boundary is sane and area within defined
204 # see /config/application.yml
205 check_boundaries(xmin, ymin, xmax, ymax)
207 if POTLATCH_USE_SQL then
208 ways = sql_find_ways_in_area(xmin, ymin, xmax, ymax)
209 points = sql_find_pois_in_area(xmin, ymin, xmax, ymax)
210 relations = sql_find_relations_in_area_and_ways(xmin, ymin, xmax, ymax, ways.collect {|x| x[0]})
212 # find the way ids in an area
213 nodes_in_area = Node.find_by_area(ymin, xmin, ymax, xmax, :conditions => ["current_nodes.visible = ?", true], :include => :ways)
214 ways = nodes_in_area.inject([]) { |sum, node|
215 visible_ways = node.ways.select { |w| w.visible? }
216 sum + visible_ways.collect { |w| [w.id,w.version] }
220 # find the node ids in an area that aren't part of ways
221 nodes_not_used_in_area = nodes_in_area.select { |node| node.ways.empty? }
222 points = nodes_not_used_in_area.collect { |n| [n.id, n.lon, n.lat, n.tags, n.version] }.uniq
224 # find the relations used by those nodes and ways
225 relations = Relation.find_for_nodes(nodes_in_area.collect { |n| n.id }, :conditions => {:visible => true}) +
226 Relation.find_for_ways(ways.collect { |w| w[0] }, :conditions => {:visible => true})
227 relations = relations.collect { |relation| [relation.id,relation.version] }.uniq
230 [0, ways, points, relations]
232 rescue OSM::APITimeoutError => err
233 [-1,"Sorry - I can't get the map for that area. The server said: #{err}"]
234 rescue Exception => err
235 [-2,"Sorry - I can't get the map for that area. The server said: #{err}"]
238 # Find deleted ways in current bounding box (similar to whichways, but ways
239 # with a deleted node only - not POIs or relations).
241 def whichways_deleted(xmin, ymin, xmax, ymax) #:doc:
242 enlarge = [(xmax-xmin)/8,0.01].min
243 xmin -= enlarge; ymin -= enlarge
244 xmax += enlarge; ymax += enlarge
246 # check boundary is sane and area within defined
247 # see /config/application.yml
249 check_boundaries(xmin, ymin, xmax, ymax)
250 rescue Exception => err
251 return [-2,"Sorry - I can't get the map for that area. The server said: #{err}"]
254 nodes_in_area = Node.find_by_area(ymin, xmin, ymax, xmax, :conditions => ["current_ways.visible = ?", false], :include => :ways_via_history)
255 way_ids = nodes_in_area.collect { |node| node.ways_via_history_ids }.flatten.uniq
260 # Get a way including nodes and tags.
261 # Returns the way id, a Potlatch-style array of points, a hash of tags, and the version number.
263 def getway(wayid) #:doc:
264 if POTLATCH_USE_SQL then
265 points = sql_get_nodes_in_way(wayid)
266 tags = sql_get_tags_in_way(wayid)
267 version = sql_get_way_version(wayid)
269 # Ideally we would do ":include => :nodes" here but if we do that
270 # then rails only seems to return the first copy of a node when a
271 # way includes a node more than once
273 way = Way.find(wayid, :include => { :nodes => :node_tags })
274 rescue ActiveRecord::RecordNotFound
278 # check case where way has been deleted or doesn't exist
279 return [wayid,[],{}] if way.nil? or !way.visible
281 points = way.nodes.collect do |node|
283 nodetags.delete('created_by')
284 [node.lon, node.lat, node.id, nodetags, node.version]
287 version = way.version
290 [wayid, points, tags, version]
293 # Get an old version of a way, and all constituent nodes.
295 # For undelete (version<0), always uses the most recent version of each node,
296 # even if it's moved. For revert (version >= 0), uses the node in existence
297 # at the time, generating a new id if it's still visible and has been moved/
303 # 2. array of points,
306 # 5. is this the current, visible version? (boolean)
308 def getway_old(id, timestamp) #:doc:
311 old_way = OldWay.find(:first, :conditions => ['visible = ? AND id = ?', true, id], :order => 'version DESC')
312 points = old_way.get_nodes_undelete unless old_way.nil?
316 timestamp = DateTime.strptime(timestamp.to_s, "%d %b %Y, %H:%M:%S")
317 old_way = OldWay.find(:first, :conditions => ['id = ? AND timestamp <= ?', id, timestamp], :order => 'timestamp DESC')
319 points = old_way.get_nodes_revert(timestamp)
321 return [-1, "Sorry, the way was deleted at that time - please revert to a previous version."]
325 # thrown by date parsing method. leave old_way as nil for
326 # the superb error handler below.
331 # *** FIXME: shouldn't this be returning an error?
332 return [-1, id, [], {}, -1,0]
335 old_way.tags['history'] = "Retrieved from v#{old_way.version}"
336 return [0, id, points, old_way.tags, curway.version, (curway.version==old_way.version and curway.visible)]
340 # Find history of a way.
341 # Returns 'way', id, and an array of previous versions:
342 # - formerly [old_way.version, old_way.timestamp.strftime("%d %b %Y, %H:%M"), old_way.visible ? 1 : 0, user, uid]
343 # - now [timestamp,user,uid]
345 # Heuristic: Find all nodes that have ever been part of the way;
346 # get a list of their revision dates; add revision dates of the way;
347 # sort and collapse list (to within 2 seconds); trim all dates before the
348 # start date of the way.
350 def getway_history(wayid) #:doc:
353 # Find list of revision dates for way and all constituent nodes
356 Way.find(wayid).old_ways.collect do |a|
357 revdates.push(a.timestamp)
358 unless revusers.has_key?(a.timestamp.to_i) then revusers[a.timestamp.to_i]=change_user(a) end
360 Node.find(n).old_nodes.collect do |o|
361 revdates.push(o.timestamp)
362 unless revusers.has_key?(o.timestamp.to_i) then revusers[o.timestamp.to_i]=change_user(o) end
366 waycreated=revdates[0]
371 # Remove any dates (from nodes) before first revision date of way
372 revdates.delete_if { |d| d<waycreated }
373 # Remove any elements where 2 seconds doesn't elapse before next one
374 revdates.delete_if { |d| revdates.include?(d+1) or revdates.include?(d+2) }
375 # Collect all in one nested array
376 revdates.collect! {|d| [d.strftime("%d %b %Y, %H:%M:%S")] + revusers[d.to_i] }
378 return ['way',wayid,revdates]
379 rescue ActiveRecord::RecordNotFound
380 return ['way', wayid, []]
384 # Find history of a node. Returns 'node', id, and an array of previous versions as above.
386 def getnode_history(nodeid) #:doc:
388 history = Node.find(nodeid).old_nodes.reverse.collect do |old_node|
389 [old_node.timestamp.strftime("%d %b %Y, %H:%M:%S")] + change_user(old_node)
391 return ['node', nodeid, history]
392 rescue ActiveRecord::RecordNotFound
393 return ['node', nodeid, []]
398 user_object = obj.changeset.user
399 user = user_object.data_public? ? user_object.display_name : 'anonymous'
400 uid = user_object.data_public? ? user_object.id : 0
404 # Find GPS traces with specified name/id.
405 # Returns array listing GPXs, each one comprising id, name and description.
407 def findgpx(searchterm, usertoken)
408 user = getuser(usertoken)
409 if !uid then return -1,"You must be logged in to search for GPX traces." end
412 if searchterm.to_i>0 then
413 gpx = Trace.find(searchterm.to_i, :conditions => ["visible=? AND (public=? OR user_id=?)",true,true,user.id] )
415 gpxs.push([gpx.id, gpx.name, gpx.description])
418 Trace.find(:all, :limit => 21, :conditions => ["visible=? AND (public=? OR user_id=?) AND MATCH(name) AGAINST (?)",true,true,user.id,searchterm] ).each do |gpx|
419 gpxs.push([gpx.id, gpx.name, gpx.description])
425 # Get a relation with all tags and members.
429 # 2. list of members,
432 def getrelation(relid) #:doc:
434 rel = Relation.find(relid)
435 rescue ActiveRecord::RecordNotFound
436 return [relid, {}, []]
439 return [relid, {}, [], nil] if rel.nil? or !rel.visible
440 [relid, rel.tags, rel.members, rel.version]
443 # Find relations with specified name/id.
444 # Returns array of relations, each in same form as getrelation.
446 def findrelations(searchterm)
448 if searchterm.to_i>0 then
449 rel = Relation.find(searchterm.to_i)
450 if rel and rel.visible then
451 rels.push([rel.id, rel.tags, rel.members, rel.version])
454 RelationTag.find(:all, :limit => 11, :conditions => ["match(v) against (?)", searchterm] ).each do |t|
455 if t.relation.visible then
456 rels.push([t.relation.id, t.relation.tags, t.relation.members, t.relation.version])
466 # 1. original relation id (unchanged),
467 # 2. new relation id,
470 def putrelation(renumberednodes, renumberedways, usertoken, changeset_id, version, relid, tags, members, visible) #:doc:
471 user = getuser(usertoken)
472 if !user then return -1,"You are not logged in, so the relation could not be saved." end
475 visible = (visible.to_i != 0)
479 Relation.transaction do
480 # create a new relation, or find the existing one
482 relation = Relation.find(relid)
484 # We always need a new node, based on the data that has been sent to us
485 new_relation = Relation.new
487 # check the members are all positive, and correctly type
492 mid = renumberednodes[mid] if m[0] == 'Node'
493 mid = renumberedways[mid] if m[0] == 'Way'
496 typedmembers << [m[0], mid, m[2]]
500 # assign new contents
501 new_relation.members = typedmembers
502 new_relation.tags = tags
503 new_relation.visible = visible
504 new_relation.changeset_id = changeset_id
505 new_relation.version = version
508 # We're creating the relation
509 new_relation.create_with_history(user)
511 # We're updating the relation
512 new_relation.id = relid
513 relation.update_from(new_relation, user)
515 # We're deleting the relation
516 new_relation.id = relid
517 relation.delete_with_history!(new_relation, user)
522 return [0, relid, new_relation.id, new_relation.version]
524 return [0, relid, relid, relation.version]
526 rescue OSM::APIChangesetAlreadyClosedError => ex
527 return [-1, "The changeset #{ex.changeset.id} was closed at #{ex.changeset.closed_at}."]
528 rescue OSM::APIVersionMismatchError => ex
529 return [-3, "Sorry, someone else has changed this relation since you started editing. Please click the 'Edit' tab to reload the area. The server said: #{ex}"]
530 rescue OSM::APIAlreadyDeletedError => ex
531 return [-1, "The relation has already been deleted."]
532 rescue OSM::APIError => ex
533 # Some error that we don't specifically catch
534 return [-2, "An unusual error happened (in 'putrelation' #{relid}). The server said: #{ex}"]
537 # Save a way to the database, including all nodes. Any nodes in the previous
538 # version and no longer used are deleted.
541 # 0. hash of renumbered nodes (added by amf_controller)
542 # 1. current user token (for authentication)
543 # 2. current changeset
546 # 5. list of nodes in way
547 # 6. hash of way tags
548 # 7. array of nodes to change (each one is [lon,lat,id,version,tags]),
549 # 8. hash of nodes to delete (id->version).
552 # 0. '0' (code for success),
553 # 1. original way id (unchanged),
555 # 3. hash of renumbered nodes (old id=>new id),
557 # 5. hash of node versions (node=>version)
559 def putway(renumberednodes, usertoken, changeset_id, wayversion, originalway, pointlist, attributes, nodes, deletednodes) #:doc:
563 user = getuser(usertoken)
564 if !user then return -1,"You are not logged in, so the way could not be saved." end
565 if pointlist.length < 2 then return -2,"Server error - way is only #{points.length} points long." end
567 originalway = originalway.to_i
568 pointlist.collect! {|a| a.to_i }
570 way=nil # this is returned, so scope it outside the transaction
574 # -- Update each changed node
581 if id == 0 then return -2,"Server error - node with id 0 found in way #{originalway}." end
582 if lat== 90 then return -2,"Server error - node with latitude -90 found in way #{originalway}." end
583 if renumberednodes[id] then id = renumberednodes[id] end
586 node.changeset_id = changeset_id
590 node.tags.delete('created_by')
591 node.version = version
593 # We're creating the node
594 node.create_with_history(user)
595 renumberednodes[id] = node.id
596 nodeversions[node.id] = node.version
598 # We're updating an existing node
599 previous=Node.find(id)
601 previous.update_from(node, user)
602 nodeversions[previous.id] = previous.version
606 # -- Save revised way
608 pointlist.collect! {|a|
609 renumberednodes[a] ? renumberednodes[a]:a
612 new_way.tags = attributes
613 new_way.nds = pointlist
614 new_way.changeset_id = changeset_id
615 new_way.version = wayversion
617 new_way.create_with_history(user)
618 way=new_way # so we can get way.id and way.version
620 way = Way.find(originalway)
621 if way.tags!=attributes or way.nds!=pointlist or !way.visible?
622 new_way.id=originalway
623 way.update_from(new_way, user)
627 # -- Delete unwanted nodes
629 deletednodes.each do |id,v|
630 node = Node.find(id.to_i)
632 new_node.changeset_id = changeset_id
633 new_node.version = v.to_i
634 new_node.id = id.to_i
636 node.delete_with_history!(new_node, user)
637 rescue OSM::APIPreconditionFailedError => ex
638 # We don't do anything here as the node is being used elsewhere
639 # and we don't want to delete it
645 [0, originalway, way.id, renumberednodes, way.version, nodeversions, deletednodes]
646 rescue OSM::APIChangesetAlreadyClosedError => ex
647 return [-2, "Sorry, your changeset #{ex.changeset.id} has been closed (at #{ex.changeset.closed_at})."]
648 rescue OSM::APIVersionMismatchError => ex
649 return [-3, "Sorry, someone else has changed this way since you started editing. Click the 'Edit' tab to reload the area. The server said: #{ex}"]
650 rescue OSM::APITooManyWayNodesError => ex
651 return [-1, "You have tried to upload a really long way with #{ex.provided} points: only #{ex.max} are allowed."]
652 rescue OSM::APIAlreadyDeletedError => ex
653 return [-1, "The point has already been deleted."]
654 rescue OSM::APIError => ex
655 # Some error that we don't specifically catch
656 return [-2, "An unusual error happened (in 'putway' #{originalway}). The server said: #{ex}"]
659 # Save POI to the database.
660 # Refuses save if the node has since become part of a way.
661 # Returns array with:
663 # 1. original node id (unchanged),
667 def putpoi(usertoken, changeset_id, version, id, lon, lat, tags, visible) #:doc:
668 user = getuser(usertoken)
669 if !user then return -1,"You are not logged in, so the point could not be saved." end
672 visible = (visible.to_i == 1)
680 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
683 # We always need a new node, based on the data that has been sent to us
686 new_node.changeset_id = changeset_id
687 new_node.version = version
692 # We're creating the node
693 new_node.create_with_history(user)
695 # We're updating the node
697 node.update_from(new_node, user)
699 # We're deleting the node
701 node.delete_with_history!(new_node, user)
707 return [0, id, new_node.id, new_node.version]
709 return [0, id, node.id, node.version]
711 rescue OSM::APIChangesetAlreadyClosedError => ex
712 return [-1, "The changeset #{ex.changeset.id} was closed at #{ex.changeset.closed_at}"]
713 rescue OSM::APIVersionMismatchError => ex
714 return [-3, "Sorry, someone else has changed this point since you started editing. Please click the 'Edit' tab to reload the area. The server said: #{ex}"]
715 rescue OSM::APIAlreadyDeletedError => ex
716 return [-1, "The point has already been deleted"]
717 rescue OSM::APIError => ex
718 # Some error that we don't specifically catch
719 return [-2, "An unusual error happened (in 'putpoi' #{id}). The server said: #{ex}"]
722 # Read POI from database
723 # (only called on revert: POIs are usually read by whichways).
725 # Returns array of id, long, lat, hash of tags, (current) version.
727 def getpoi(id,timestamp) #:doc:
730 unless timestamp == ''
731 n = OldNode.find(id, :conditions=>['timestamp=?',DateTime.strptime(timestamp, "%d %b %Y, %H:%M:%S")])
735 return [n.id, n.lon, n.lat, n.tags, v]
737 return [nil, nil, nil, {}, nil]
741 # Delete way and all constituent nodes. Also removes from any relations.
745 # * the id of the way to change
746 # * the version of the way that was downloaded
747 # * a hash of the id and versions of all the nodes that are in the way, if any
748 # of the nodes have been changed by someone else then, there is a problem!
749 # Returns 0 (success), unchanged way id.
751 def deleteway(usertoken, changeset_id, way_id, way_version, deletednodes) #:doc:
752 user = getuser(usertoken)
753 unless user then return -1,"You are not logged in, so the way could not be deleted." end
756 # Need a transaction so that if one item fails to delete, the whole delete fails.
761 old_way = Way.find(way_id)
763 delete_way.version = way_version
764 delete_way.changeset_id = changeset_id
765 delete_way.id = way_id
766 old_way.delete_with_history!(delete_way, user)
768 # -- Delete unwanted nodes
770 deletednodes.each do |id,v|
771 node = Node.find(id.to_i)
773 new_node.changeset_id = changeset_id
774 new_node.version = v.to_i
775 new_node.id = id.to_i
777 node.delete_with_history!(new_node, user)
778 rescue OSM::APIPreconditionFailedError => ex
779 # We don't do anything with the exception as the node is in use
780 # elsewhere and we don't want to delete it
786 rescue OSM::APIChangesetAlreadyClosedError => ex
787 return [-1, "The changeset #{ex.changeset.id} was closed at #{ex.changeset.closed_at}"]
788 rescue OSM::APIVersionMismatchError => ex
789 # Really need to check to see whether this is a server load issue, and the
790 # last version was in the same changeset, or belongs to the same user, then
791 # we can return something different
792 return [-3, "Sorry, someone else has changed this way since you started editing. Please click the 'Edit' tab to reload the area."]
793 rescue OSM::APIAlreadyDeletedError => ex
794 return [-1, "The way has already been deleted."]
795 rescue OSM::APIError => ex
796 # Some error that we don't specifically catch
797 return [-2, "An unusual error happened (in 'deleteway' #{way_id}). The server said: #{ex}"]
801 # ====================================================================
805 # (can also be of form user:pass)
806 # When we are writing to the api, we need the actual user model,
807 # not just the id, hence this abstraction
809 def getuser(token) #:doc:
810 if (token =~ /^(.+)\:(.+)$/) then
811 user = User.authenticate(:username => $1, :password => $2)
813 user = User.authenticate(:token => token)
820 def sendresponse(results)
821 a,b=results.length.divmod(256)
822 render :content_type => "application/x-amf", :text => proc { |response, output|
823 # ** move amf writing loop into here -
824 # basically we read the messages in first (into an array of some sort),
825 # then iterate through that array within here, and do all the AMF writing
826 output.write 0.chr+0.chr+0.chr+0.chr+a.chr+b.chr
827 results.each do |k,v|
834 # ====================================================================
835 # Alternative SQL queries for getway/whichways
837 def sql_find_ways_in_area(xmin,ymin,xmax,ymax)
839 SELECT DISTINCT current_ways.id AS wayid,current_ways.version AS version
840 FROM current_way_nodes
841 INNER JOIN current_nodes ON current_nodes.id=current_way_nodes.node_id
842 INNER JOIN current_ways ON current_ways.id =current_way_nodes.id
843 WHERE current_nodes.visible=TRUE
844 AND current_ways.visible=TRUE
845 AND #{OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")}
847 return ActiveRecord::Base.connection.select_all(sql).collect { |a| [a['wayid'].to_i,a['version'].to_i] }
850 def sql_find_pois_in_area(xmin,ymin,xmax,ymax)
853 SELECT current_nodes.id,current_nodes.latitude*0.0000001 AS lat,current_nodes.longitude*0.0000001 AS lon,current_nodes.version
855 LEFT OUTER JOIN current_way_nodes cwn ON cwn.node_id=current_nodes.id
856 WHERE current_nodes.visible=TRUE
858 AND #{OSM.sql_for_area(ymin, xmin, ymax, xmax, "current_nodes.")}
860 ActiveRecord::Base.connection.select_all(sql).each do |row|
862 ActiveRecord::Base.connection.select_all("SELECT k,v FROM current_node_tags WHERE id=#{row['id']}").each do |n|
863 poitags[n['k']]=n['v']
865 pois << [row['id'].to_i, row['lon'].to_f, row['lat'].to_f, poitags, row['version'].to_i]
870 def sql_find_relations_in_area_and_ways(xmin,ymin,xmax,ymax,way_ids)
871 # ** It would be more Potlatchy to get relations for nodes within ways
872 # during 'getway', not here
874 SELECT DISTINCT cr.id AS relid,cr.version AS version
875 FROM current_relations cr
876 INNER JOIN current_relation_members crm ON crm.id=cr.id
877 INNER JOIN current_nodes cn ON crm.member_id=cn.id AND crm.member_type='Node'
878 WHERE #{OSM.sql_for_area(ymin, xmin, ymax, xmax, "cn.")}
880 unless way_ids.empty?
883 SELECT DISTINCT cr.id AS relid,cr.version AS version
884 FROM current_relations cr
885 INNER JOIN current_relation_members crm ON crm.id=cr.id
886 WHERE crm.member_type='Way'
887 AND crm.member_id IN (#{way_ids.join(',')})
890 ActiveRecord::Base.connection.select_all(sql).collect { |a| [a['relid'].to_i,a['version'].to_i] }
893 def sql_get_nodes_in_way(wayid)
896 SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lon,current_nodes.id,current_nodes.version
897 FROM current_way_nodes,current_nodes
898 WHERE current_way_nodes.id=#{wayid.to_i}
899 AND current_way_nodes.node_id=current_nodes.id
900 AND current_nodes.visible=TRUE
903 ActiveRecord::Base.connection.select_all(sql).each do |row|
905 ActiveRecord::Base.connection.select_all("SELECT k,v FROM current_node_tags WHERE id=#{row['id']}").each do |n|
906 nodetags[n['k']]=n['v']
908 nodetags.delete('created_by')
909 points << [row['lon'].to_f,row['lat'].to_f,row['id'].to_i,nodetags,row['version'].to_i]
914 def sql_get_tags_in_way(wayid)
916 ActiveRecord::Base.connection.select_all("SELECT k,v FROM current_way_tags WHERE id=#{wayid.to_i}").each do |row|
917 tags[row['k']]=row['v']
922 def sql_get_way_version(wayid)
923 ActiveRecord::Base.connection.select_one("SELECT version FROM current_ways WHERE id=#{wayid.to_i}")