Created
November 12, 2010 21:44
-
-
Save jberkel/674741 to your computer and use it in GitHub Desktop.
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
| #!/usr/bin/env ruby | |
| #twitter-translate - demoapp for droidcon | |
| $LOAD_PATH << '/sdcard/lib' | |
| require 'net/http' | |
| require 'json/pure' | |
| require 'cgi' | |
| SEARCH = "#droidcon" unless defined?(SEARCH) | |
| LANGUAGE = 'fr' unless defined?(LANGUAGE) | |
| class Twitter | |
| #http://apiwiki.twitter.com/Twitter-Search-API-Method:-search | |
| def self.search(what) | |
| JSON.parse( | |
| Net::HTTP.get( | |
| URI.parse("http://search.twitter.com/search.json?q=#{CGI.escape(what)}")) | |
| ) | |
| end | |
| end | |
| class Translator | |
| @headers = { | |
| 'user-agent' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) ' + | |
| 'AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.11', | |
| 'referer' => 'http://translate.google.com/' | |
| } | |
| def self.translate(text, tl) | |
| url = "http://translate.google.com/translate_a/t?client=t&text=#{CGI.escape(text)}&hl=en&sl=auto&tl=#{tl}" | |
| uri = URI.parse(url) | |
| http = Net::HTTP.new(uri.host, uri.port) | |
| request = Net::HTTP::Get.new(uri.request_uri) | |
| @headers.each { |h,v| request[h] = v } | |
| result = http.request(request).body | |
| if result =~ /\[\[\["([^"]+)"/ | |
| $1 | |
| else | |
| nil | |
| end | |
| end | |
| end | |
| def search_and_translate(what, tl) | |
| if results = Twitter.search(what)['results'] | |
| results.each do |r| | |
| original = "#{r['from_user']}: #{r['text']}" | |
| yield original, Translator.translate(original, tl) if block_given? | |
| end | |
| end | |
| nil | |
| end | |
| # executed on commandline? | |
| if __FILE__ == $0 | |
| search_and_translate(SEARCH, LANGUAGE) do |original, translated| | |
| puts original | |
| puts translated | |
| puts "-" * 80 | |
| end | |
| # executed on android? | |
| elsif defined?($activity) | |
| require "ruboto.rb" | |
| confirm_ruboto_version(4) | |
| ruboto_import_widgets :LinearLayout, :ScrollView | |
| $activity.start_ruboto_activity "$tl" do | |
| setTitle "TwittterTranslate #{SEARCH} => #{LANGUAGE}" | |
| @translations = {} | |
| setup_content do | |
| scroll_view do | |
| linear_layout(:orientation => LinearLayout::VERTICAL) do | |
| search_and_translate(SEARCH, LANGUAGE) do |original, translated| | |
| @translations[translated] = original | |
| button :text => translated | |
| end | |
| end | |
| end | |
| end | |
| handle_click do |view| | |
| toast @translations[view.getText] | |
| end | |
| end | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment