|
Revision 12584, 1.3 kB
(checked in by iskwrsk, 5 years ago)
|
|
ホスト名の定数化。
concatを+=から<<に変更。
query_stringのセパレータを&から&に変更。
|
| Line | |
|---|
| 1 | # |
|---|
| 2 | # IM::Kayac |
|---|
| 3 | # License: Ruby |
|---|
| 4 | # See also: http://im.kayac.com/ |
|---|
| 5 | # Usage: |
|---|
| 6 | # |
|---|
| 7 | # im = IM::Kayac.new('to', :id => 'from', :sig => 'sigunature') |
|---|
| 8 | # res = im.notify('message') #ret Net::HTTPResponse |
|---|
| 9 | # require 'json' |
|---|
| 10 | # JSON.parse(res.body).each do |k, v| |
|---|
| 11 | # printf "%s: %s\n", k, v |
|---|
| 12 | # end |
|---|
| 13 | # |
|---|
| 14 | |
|---|
| 15 | |
|---|
| 16 | require 'digest/sha1' |
|---|
| 17 | require 'net/http' |
|---|
| 18 | |
|---|
| 19 | module IM |
|---|
| 20 | class Kayac |
|---|
| 21 | HOST = 'im.kayac.com' |
|---|
| 22 | def initialize(to, params={}) |
|---|
| 23 | if to.nil? |
|---|
| 24 | raise ArgumentError |
|---|
| 25 | else |
|---|
| 26 | @to = to |
|---|
| 27 | end |
|---|
| 28 | @id = params[:id] |
|---|
| 29 | @pwd = params[:password] |
|---|
| 30 | @sig = params[:sig] |
|---|
| 31 | end |
|---|
| 32 | |
|---|
| 33 | def notify(msg) |
|---|
| 34 | if !@sig.nil? |
|---|
| 35 | sig = Digest::SHA1.hexdigest(msg + @sig) |
|---|
| 36 | data = 'message=%s&sig=%s' % [u(msg), sig] |
|---|
| 37 | elsif !@pwd.nil? |
|---|
| 38 | data = 'message=%s&password=%s' % [u(msg), u(@pwd)] |
|---|
| 39 | else |
|---|
| 40 | data = 'message=%s' % [u(msg)] |
|---|
| 41 | end |
|---|
| 42 | data << '&id=%s' % [u(@id)] unless @id.nil? |
|---|
| 43 | header = { |
|---|
| 44 | 'Host' => HOST, |
|---|
| 45 | 'Content-Type' => 'application/x-www-form-urlencoded', |
|---|
| 46 | 'Content-length' => data.size.to_s, |
|---|
| 47 | } |
|---|
| 48 | |
|---|
| 49 | path = '/api/post/%s' % [@to] |
|---|
| 50 | Net::HTTP.version_1_2 |
|---|
| 51 | Net::HTTP.start(HOST, 80) do |http| |
|---|
| 52 | http.post(path, data, header) |
|---|
| 53 | end |
|---|
| 54 | end |
|---|
| 55 | |
|---|
| 56 | private |
|---|
| 57 | def u(str) |
|---|
| 58 | str.to_s.gsub(/[^a-zA-Z0-9_\-.]/n) do |
|---|
| 59 | '%%%02X' % $&.unpack("C").first |
|---|
| 60 | end |
|---|
| 61 | end |
|---|
| 62 | |
|---|
| 63 | end |
|---|
| 64 | end |
|---|