public
Last active

Savon InterFAX example: Chunked upload to fax

  • Download Gist
interfax_example05.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
# 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.