Skip to content

Instantly share code, notes, and snippets.

@kminiatures
Created April 10, 2015 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kminiatures/ddf14b71829f186a0971 to your computer and use it in GitHub Desktop.
Save kminiatures/ddf14b71829f186a0971 to your computer and use it in GitHub Desktop.
Alfred Microsoft Translator Workflow
#!/usr/bin/env ruby
# -*- coding:utf-8 -*-
require 'net/http'
require 'rexml/document'
require 'json'
class Alfred
def initialize
@items = []
end
def add_item(uid, arg, title)
@items << <<-"XML"
<item uid="#{uid}" arg="#{arg}" valid="yes" autocomplete="#{title}">
<title>#{title}</title>
<subtitle>#{arg}</subtitle>
</item>
XML
end
def dump
puts <<-"XML"
<?xml version="1.0"?>
<items>
#{@items.join}
</items>
XML
end
end
# See https://datamarket.azure.com/dataset/bing/microsofttranslator
class MicrosoftTranslator
attr_accessor :error
DOMAIN = "api.datamarket.azure.com"
PATH = "/Data.ashx/Bing/MicrosoftTranslator/v1/Translate"
def initialize(app_id, text, from: 'en', to: 'ja')
@app_id = app_id
@text = URI.escape text
@from = from
@to = to
@error = ''
end
def build_query(params)
buf = []
params.each do |k,v|
buf << "#{k}='#{v}'"
end
buf.join('&')
end
def request(query)
http = Net::HTTP.new(DOMAIN, '443')
http.use_ssl = true
req = Net::HTTP::Get.new("#{PATH}?#{query}")
req.basic_auth 'APPID', @app_id
http.request(req)
end
def get
response = request build_query({
"Text" => @text,
"To" => @to,
"From" => @from
})
if response.message == 'OK'
doc = REXML::Document.new(response.body)
doc.elements['//content/m:properties/d:Text'].text
else
@error = "response Not-OK.#{response.message}"
end
end
def self.cli_params
buf = []
from = 'en'
to = 'ja'
ignore_next = false
ARGV.each_with_index do |str, i|
if ignore_next
ignore_next = false
next
end
case str
when '-f', '--from'
from = ARGV[i +1]
ignore_next = true
next
when '-t', '--to'
to = ARGV[i +1]
ignore_next = true
next
end
buf << str
end
[buf.join(" "), from, to]
end
end
app_id = File.read("MicrosoftAzureTranslatorAppId.txt").strip
text, from, to = MicrosoftTranslator.cli_params
translator = MicrosoftTranslator.new(app_id, text, from: from, to: to)
alf = Alfred.new
if r = translator.get
alf.add_item text, text, r
else
alf.add_item "Error", "Error-arg", translator.error
end
alf.dump
@kminiatures
Copy link
Author

http://i.gyazo.com/fdf09d6c21fbbc3e0db0e4eb8483c04e.gif

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment