Skip to content

Instantly share code, notes, and snippets.

@codeout
Created July 13, 2012 18:59
Show Gist options
  • Save codeout/3106699 to your computer and use it in GitHub Desktop.
Save codeout/3106699 to your computer and use it in GitHub Desktop.
email notifier via im.kayac.com
#!/usr/bin/env ruby
#
# Read standard input or a file specified by the argument and notify devices
# via im.kayac.com.
#
# Usage:
#
# echo 'something' | $0 -u user_name -s secret
# $0 -u user_name -p password text_file
#
# Copyright 2012 by Shintaro Kojima. Released under an MIT license.
#
Version = '1.0'
require 'digest/sha1'
require 'json'
require 'mail'
require 'net/http'
require 'optparse'
#
# Class which generates and send messages to im.kayac.com via http API.
# (see also: im.kayac.com)
#
# == Usage
#
# Im.Kayac.new(:user => 'username', :secret => 'string',
# :message => 'something').send
# Im.Kayac.new(:user => 'username', :secret => 'string').send('other')
# Im.Kayac.send('something', :to => 'username', :secret => 'string')
#
module Im
module Kayac
URL = 'http://im.kayac.com/api/post/%s'
class Message
attr_accessor :options
def initialize(options={})
raise ArgumentError.new("username for the API is not specified") unless options[:user]
@data = { message: options.delete(:message) }
@options = options
end
def send(string=nil)
@data[:message] = string if string
compose
post
end
def self.send(message, options={})
options[:message] = message
options[:user] = options.delete(:to)
message = new(options).send
end
private
def compose
add_digest
add_password
@data
end
def add_digest
if @options[:secret]
@data[:sig] = Digest::SHA1.hexdigest(@data[:message].to_s + @options[:secret].to_s)
end
@data
end
def add_password
if @options[:password] and @data[:sig].nil?
@data[:password] = @options[:password]
end
@data
end
def post
response = Net::HTTP.post_form( URI(URL % @options[:user]), @data )
case response
when Net::HTTPSuccess, Net::HTTPRedirection
result = JSON.parse(response.body)
raise RuntimeError.new(result['error']) unless result['result'] == 'posted'
else
response.value
end
end
end
end
end
def init
parser = OptionParser.new
options = {}
parser.on('-q', '--quiet', 'do not write anything to standard output'){|v| options[:quiet] = true }
parser.on('-u', '--user==VAL', 'user name for HTTP API') {|v| options[:to] = v }
parser.on('-p', '--password==VAL', 'password for HTTP API') {|v| options[:password] = v }
parser.on('-s', '--secret==VAL', 'secret key string for SHA1 hash') {|v| options[:secret] = v }
begin
parser.parse! ARGV
rescue
abort parser.help
end
options
end
#
# main
#
options = init
begin
src = Mail.read_from_string($<.read)
Im::Kayac::Message.send "From: #{src.from && src.from.join(', ')}\n\n#{src.subject}",
options.select{|key, value| [:to, :password, :secret].include? key }
rescue
raise $! unless options[:quiet]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment