require 'ppc/baidu/account' require 'ppc/baidu/plan' require 'ppc/baidu/bulk' require 'ppc/baidu/report' require 'awesome_print' require 'savon' module PPC class Baidu include ::PPC def initialize(params = {}) @service = params[:service] + 'Service' @port_name = params[:service] + 'Service' @username = params[:username] @password = params[:password] @token = params[:token] @client = Savon.new("https://api.baidu.com/sem/sms/v3/#{@service}?wsdl") @debug = params[:debug] || false end def request(method,params = {}) operation = make_operation(method) operation.header = operation_header operation.body = { method+'Request' =>params } print_debug(operation.body,'operation.body') if @debug print_debug(operation.build,'operation.build') if @debug response = operation.call.hash process_response(response) print_debug(response,'response') if @debug response end def operations @client.operations(@service,@service) end protected def download(params = {}) bulk = ::PPC::Baidu::Bulk.new({ username: @username, password: @password, token: @token, debug: @debug }) params[:extended] = params[:extended] || 2 begin file_id = bulk.file_id_of_all(params) puts "file_id: #{file_id}" if @debug loop do state = bulk.state(file_id) raise "invalid file state: #{state}" unless %w(1 2 3 null).include? state break if state == '3' puts "waiting for #{file_id} to be ready. current state:#{state}" if @debug sleep 3 end puts "#{file_id} is ready" if @debug return bulk.path(file_id) rescue # @header = bulk.header # @oprs = bulk.oprs # @oprtime = bulk.oprtime # @quota = bulk.quota # @rquota = bulk.rquota # @status = bulk.status # @desc = bulk.desc # case @desc # when 'success' # when 'failure' # @code = bulk.code # @message = bulk.message # when 'system failure' # @code = bulk.code # @message = bulk.message # else # raise "unknown desc from baidu: #{@desc}" # end raise BulkException.new(file_id,bulk) end return false end private def make_operation(operation_name) @client.operation(@service,@service,operation_name) end def operation_header { :AuthHeader=> { username: @username, password: @password, token: @token } } end def example(operation,with_header=false) operation = make_operation(operation) if with_header { example_header: operation.example_header, example_body: operation.example_body } else operation.example_body end end def process_response(response) body = response[:envelope] print_debug(body,'response.envelope') if @debug @header = body[:header] res_header = header[:res_header] @oprs = res_header[:oprs] @oprtime = res_header[:oprtime] @quota = res_header[:quota] @rquota = res_header[:rquota] @status = res_header[:status] @desc = res_header[:desc] case @desc when 'success' when 'failure' failures = res_header[:failures] @code = failures[:code] @message = failures[:message] when 'system failure' failures = res_header[:failures] @code = failures[:code] @message = failures[:message] else raise "unknown desc from baidu: #{@desc}" end end end end