Skip to content

Instantly share code, notes, and snippets.

@jacter
Forked from siuying/gist:199009
Created December 4, 2009 05:41
Show Gist options
  • Save jacter/248852 to your computer and use it in GitHub Desktop.
Save jacter/248852 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'open-uri'
require 'sinatra'
require 'json'
require 'digest/sha1'
configure do
set :developer_key, ENV['LAYAR_DEVELOPER_KEY'] || ""
set :user_agent, ENV['USER_AGENT'] || "Layar (hsbchk) / 1.0"
end
get "/hsbc" do
layerName = "hsbc"
locale = "zh"
base = "http://www.hsbc.com.hk/1/PA_1_1_1RD/ABSLFCServlet"
userId = params[:userId]
developerId = params[:developerId]
lat = params[:lat].to_f
lng = params[:lon].to_f
radius = (params[:radius] || "2500").to_f
puts "user: #{userId}, pos: #{lat},#{lng}"
if !validate_hash(params[:timestamp], params[:developerHash])
halt 403, "no permission"
end
begin
data = open("#{base}?event=cmd_ajax&location_type=show-all-results&address=&cLat=#{lat}&cLng=#{lng}&LOCALE=#{locale}&rand=#{rand()}",
"User-Agent" => options.user_agent,
"Referer" => "http://www.hsbc.com.hk/1/2/hk/branchnetwork").read
results = JSON.parse(data)["results"]
hotspots = adapt_hsbc(results).select(){|r| r[:distance] <= radius}
result = {:nextPageKey => "#{lat},#{lng}", :morePages => false, :layer => layerName,
:errorCode => 0, :errorString => "ok", :hotspots => hotspots}
result.to_json
rescue StandardError => e # simplistic error handling
result = {:nextPageKey => "#{lat},#{lng}", :morePages => false, :layer => layerName,
:errorCode => 1, :errorString => "Unexpected Error: #{e.message}", :hotspots => []}
halt 500, result.to_json
end
end
helpers do
def adapt_hsbc(results)
results.collect do |r|
name = r["location"]["name"]
facilities = r["location"]["facilities"].join(" / ") rescue ""
locationId = r["location"]["locationId"]
contacts = r["location"]["contacts"].join(", ") rescue ""
address = r["location"]["address"]["postalAddress"]
lng = r["location"]["address"]["lng"].to_f
lat = r["location"]["address"]["lat"].to_f
dist = r["location"]["distance"].to_f
{
:actions => [],
:distance => dist * 1000,
:attribution => "data from www.hsbc.com.hk",
:id => "#{locationId}",
:imageURL => nil,
:lat => (lat * 1000000).to_i,
:lon => (lng * 1000000).to_i,
:title => name,
:line2 => address,
:line3 => contacts,
:line4 => facilities,
:type => 0
}
end
end
def validate_hash(timestamp, developerHash)
developerHashCorrect = Digest::SHA1.hexdigest(options.developer_key + timestamp)
return developerHash == developerHashCorrect
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment