Skip to content

Instantly share code, notes, and snippets.

@rubiii
Created April 5, 2011 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rubiii/903374 to your computer and use it in GitHub Desktop.
Save rubiii/903374 to your computer and use it in GitHub Desktop.
Savon InterFAX example: Chunked upload to fax
# more examples at:
# https://gist.github.com/903337
require "rubygems"
require "base64"
require "date"
# $ gem install savon (works with v0.9.1 and higher)
require "savon"
# convert hash key symbols to camelcase
Gyoku.convert_symbols_to(:camelcase)
module ChunkedFax
extend self
CREDENTIALS = { :username => "your username", :password => "your password" }
# uploads a given +file+ in chunks and faxes it using the given
# hash of +options+.
#
# === options
#
# <tt>:chunk_size</tt> - the chunk size to use, defaults to 250k
# <tt>:fax_numbers</tt> - comma separated list of fax numbers
# <tt>:contacts</tt> - comma separated list of recipients
# ...
def send(file, options = {})
chunk_size = options.delete(:chunk_size) || 250
session_id = start_file_upload
each_chunk(file, chunk_size) do |chunk, is_last|
upload_chunk(chunk, session_id, is_last)
end
send_fax(file, session_id, options)
end
private
# starts a file upload and returns the +session_id+.
def start_file_upload
response = client.request(:int, :start_file_upload, :body => CREDENTIALS)
response[:start_file_upload_response][:session_id]
end
# reads the given +file+ in chunks set though +chunk_size+ and yields
# the current chunk and whether it's the last chunk to iterate over.
def each_chunk(file, chunk_size)
File.open(file, "rb") { |f| yield(f.read(chunk_size), f.eof?) until f.eof? }
end
# uploads a given +chunk+ under the given +session_id+.
# +is_last+ indicates whether the chunk is the last chunk to upload.
def upload_chunk(chunk, session_id, is_last)
client.request(:int, :upload_file_chunk, :body => {
:chunk => Base64.encode64(chunk), :session_ID => session_id, :is_last => is_last
})
end
# sends a fax for a given +session_id+.
def send_fax(file, session_id, options)
params = options.merge(CREDENTIALS).merge(
:file_types => File.extname(file)[1..4].upcase,
:file_sizes => "#{File.size(file)}/sessionID=#{session_id}"
)
response = client.request(:int, :sendfax_ex_2, :body => params)
response[:sendfax_ex_2_response][:sendfax_ex_2_result]
end
# returns a client using the InterFAX WSDL.
def client
@client ||= Savon::Client.new("http://ws.interfax.net/dfs.asmx?wsdl")
end
end
# fax a file with chunked upload
result = ChunkedFax.send("/Users/username/Desktop/some.png", :fax_numbers => "+18667743015", :contacts => "Mac")
# print the result. returns for example: "56778" (the Transaction ID)
p result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment