-
-
Save taylor/2716769 to your computer and use it in GitHub Desktop.
Wolfram CAPTCHA Sinatra App
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'sinatra' | |
require 'nokogiri' | |
require 'digest' | |
require 'net/http' | |
require 'cgi' | |
configure do | |
set :config, YAML.load_file(File.join(File.dirname(__FILE__), 'config.yml')) | |
set :api_key, settings.config['api_key'] | |
set :api_base, "http://api.wolframalpha.com/v2/query" | |
set :captcha_length, 6 | |
end | |
get '/' do | |
"hello world" | |
end | |
get '/captcha/:secret' do | |
# Calculate our CAPTCHA and request it from Wolfram's API. Then parse the response. | |
captcha = CGI::escape(Digest::MD5.hexdigest(params[:secret])[0, settings.captcha_length]) | |
key = CGI::escape(settings.api_key) | |
url = URI.parse(settings.api_base + "?input=captcha+#{captcha}&appid=#{key}") | |
resp = Net::HTTP.get_response(url) | |
xml = Nokogiri::XML(resp.body) | |
# need to remove the other attributes, because it contains the plaintext as an alt attribute | |
@img = xml.search('pod#Result > subpod[primary="true"] > img').first.attr('src') | |
content_type 'text/html' | |
"<img src='#{@img}' />" | |
end | |
# vim: set ft=ruby sw=2 ts=2 : |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment