Class: Top4R::Client

Inherits:
Object
  • Object
show all
Includes:
ClassUtilMixin
Defined in:
lib/top4r/config.rb,
lib/top4r/client.rb,
lib/top4r/console.rb,
lib/top4r/client/base.rb,
lib/top4r/client/item.rb,
lib/top4r/client/shop.rb,
lib/top4r/client/user.rb,
lib/top4r/client/suite.rb,
lib/top4r/client/trade.rb,
lib/top4r/client/itemcat.rb,
lib/top4r/client/shipping.rb,
lib/top4r/client/taobaokeitem.rb

Overview

Config class

Constant Summary collapse

@@no_login_required_methods =
{
  :user => {
    :info => 'taobao.user.get',
    :multi_info => 'taobao.users.get'
  },
  :trade => {},
  :area => {
    :list => 'taobao.areas.get'
  },
  :logistic_company => {
    :list => 'taobao.logistics.companies.get'
  },
  :shop => {
    :cats_list => 'taobao.sellercats.list.get', 
    :shop_info => 'taobao.shop.get'      
  },
  :item => {
    :item_info => 'taobao.item.get', 
    :items_info => 'taobao.items.list.get', 
    :item_skus => 'taobao.item.skus.get', 
    :search => 'taobao.items.get'
  },
  :taobaoke_item => {
    :taobaoke_items_get => 'taobao.taobaoke.items.get', 
    :taobaoke_items_detail_get => 'taobao.taobaoke.items.detail.get', 
    :taobaoke_items_convert => 'taobao.taobaoke.items.convert', 
    :taobaoke_shops_convert => 'taobao.taobaoke.shops.convert'
  },
  :item_cat => {
    :cats_info => 'taobao.itemcats.get'
  }
}
@@defaults =
{
  :env => :test,
  :host => 'gw.api.taobao.com',
  :rest_uri => '/router/rest',
  :port => 80,
  :protocol => :http,
  :test_host => 'gw.api.tbsandbox.com',
  :test_rest_uri => '/router/rest',
  :test_port => 80,
  :test_protocol => :http,
  :proxy_host => nil,
  :proxy_port => nil,
  :format => :json,
  :application_name => 'Top4R',
  :application_key => '12000224',
  :application_secret => '2f26cb1a99570aa72daee12a1db88e63',
  :application_version => Top4R::Version.to_version,
  :application_url => 'http://top4r.labs.nowa.me',
  :user_agent => 'default',
  :source => 'top4r',
  :logger => nil,
  :trace => false
}
@@config =
Top4R::Config.new(@@defaults)
@@logger =
Top4R::Logger.new(@@config.logger)
@@ITEM_METHODS =
{
  :inventory_list => 'taobao.items.inventory.get',
  :onsale_list => 'taobao.items.onsale.get', 
  :item_info => 'taobao.item.get', 
  :items_info => 'taobao.items.list.get', 
  :item_skus => 'taobao.item.skus.get', 
  :search => 'taobao.items.get'
}
@@SHOP_METHODS =
{
  :cats_list => 'taobao.sellercats.list.get',
  :shop_info => 'taobao.shop.get'
}
@@USER_METHODS =
{
  :info => 'taobao.user.get',
  :multi_info => 'taobao.users.get'
}
@@SUITE_METHODS =
{
  :list => 'taobao.suites.get',
}
@@TRADE_METHODS =
{
  :bought_list => 'taobao.trades.bought.get',
  :sold_list => 'taobao.trades.sold.get',
  :increments_list => 'taobao.trades.sold.increment.get',
  :info => 'taobao.trade.get',
  :fullinfo => 'taobao.trade.fullinfo.get',
  :close => 'taobao.trade.close',
  :add_memo => 'taobao.trade.memo.add',
  :update_memo => 'taobao.trade.memo.update',
  :confirmfee => 'taobao.trade.confirmfee.get'
}
@@ITEMCAT_METHODS =
{
  :cats_info => 'taobao.itemcats.get',
}
@@AREA_METHODS =
{
  :list => 'taobao.areas.get'
}
@@LOGISTIC_COMPANY_METHODS =
{
  :list => 'taobao.logistics.companies.get'
}
@@DELIVERY_METHODS =
{
  :send => 'taobao.delivery.send'
}
@@TAOBAOKEITEM_METHODS =
{
  :taobaoke_items_get => 'taobao.taobaoke.items.get', 
  :taobaoke_items_detail_get => 'taobao.taobaoke.items.detail.get', 
  :taobaoke_items_convert => 'taobao.taobaoke.items.convert', 
  :taobaoke_shops_convert => 'taobao.taobaoke.shops.convert'
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ClassUtilMixin

included

Instance Attribute Details

#loginObject (readonly)

Returns the value of attribute login.



5
6
7
# File 'lib/top4r/client/base.rb', line 5

def 
  @login
end

#parametersObject

Returns the value of attribute parameters.



4
5
6
# File 'lib/top4r/client/base.rb', line 4

def parameters
  @parameters
end

#sessionObject

Returns the value of attribute session.



4
5
6
# File 'lib/top4r/client/base.rb', line 4

def session
  @session
end

#total_resultsObject

Returns the value of attribute total_results.



4
5
6
# File 'lib/top4r/client/base.rb', line 4

def total_results
  @total_results
end

Class Method Details

.configure {|@@config| ... } ⇒ Object

Yields to given block to configure the Twitter4R API.

Yields:

  • (@@config)

Raises:

  • (ArgumentError)


78
79
80
81
# File 'lib/top4r/config.rb', line 78

def configure(&block)
  raise ArgumentError, "Block must be provided to configure" unless block_given?
  yield @@config
end

.from_config(config_file, env = 'test') ⇒ Object

Helper method mostly for irb shell prototyping.

Reads in app_key/app_secret from YAML file found at the location given by config_file that has the following format: envname: app_key: application key app_secret: application secret

Where envname is the name of the environment like ‘test’, ‘dev’ or ‘prod’. The env argument defaults to ‘test’.

To use this in the shell you would do something like the following examples: top = Top4R::Client.from_config(‘config/top.yml’, ‘dev’) top = Top4R::Client.from_config(‘config/top.yml’)



24
25
26
27
# File 'lib/top4r/console.rb', line 24

def from_config(config_file, env = 'test')
  yaml_hash = YAML.load(File.read(config_file))
  self.new yaml_hash[env]
end

Instance Method Details

#areas(method = :list, options = {}, &block) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/top4r/client/shipping.rb', line 15

def areas(method = :list, options = {}, &block)
  valid_method(method, @@AREA_METHODS, :area)
  params = {:fields => Top4R::Area.fields}.merge(options)
  response = http_connect {|conn| create_http_get_request(@@AREA_METHODS[method], params)}
  result = JSON.parse(response.body)[rsp(@@AREA_METHODS[method])]
  if result.is_a?(Hash) and result["areas"]
    areas = Top4R::Area.unmarshal(result["areas"]["area"])
    areas.each {|area| bless_model(area); yield area if block_given?}
  else
    areas = []
  end
  areas
end

#deliver_trade(t, method = :send, options = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/top4r/client/shipping.rb', line 43

def deliver_trade(t, method = :send, options = {})
  valid_method(method, @@DELIVERY_METHODS, :delivery)
  params = {}
  if t.is_a?(Top4R::Delivery)
    params = t.to_hash
  else
    t = t.tid if t.is_a?(Top4R::Trade)
    params = options.merge(:tid => t)
  end
  response = http_connect {|conn| create_http_get_request(@@DELIVERY_METHODS[method], params)}
  json = JSON.parse(response.body)
  json.is_a?(Hash) ? json[rsp(@@DELIVERY_METHODS[method])]["shipping"]["is_success"] : false
end

#initObject



12
13
14
15
16
17
18
19
# File 'lib/top4r/client/base.rb', line 12

def init
  total_results = 0
  @@logger = Top4R::Logger.new(@@config.logger, @@config.trace)
  if @parameters and @session
    @parameters = Base64.decode64(@parameters).split('&').inject({}) do |hsh, i| kv = i.split('='); hsh[kv[0]] = kv[1]; hsh end
    @login = user(@parameters['visitor_nick'])
  end
end

#inspectObject



7
8
9
10
# File 'lib/top4r/client/base.rb', line 7

def inspect
  s = old_inspect
  s.gsub!(/@app_secret=".*?"/, '@app_secret="******"')
end

#item_info(iid = nil, options = {}, &block) ⇒ Object Also known as: item



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/top4r/client/item.rb', line 48

def item_info(iid = nil, options = {}, &block)
  method = :item_info
  valid_method(method, @@ITEM_METHODS, :item)
  options = {:num_iid => iid}.merge(options) if iid
  params = {:fields => Top4R::Item.fields}.merge(options)
  response = http_connect {|conn| create_http_get_request(@@ITEM_METHODS[method], params)}
  result = JSON.parse(response.body)[rsp(@@ITEM_METHODS[method])]
  if result.is_a?(Hash) and result['item']
    item = Top4R::Item.unmarshal(result["item"])
    item = bless_model(item)
  else
    item = nil
  end
  item
end

#itemcats(cids, options = {}, &block) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/top4r/client/itemcat.rb', line 7

def itemcats(cids, options = {}, &block)
  method = :cats_info
  valid_method(method, @@ITEMCAT_METHODS, :item_cat)
  cids = [cids] if !cids.is_a?(Array)
  params = {:cids => cids.join(',')}.merge(options)
  response = http_connect {|conn| create_http_get_request(@@ITEMCAT_METHODS[method], params)}
  result = JSON.parse(response.body)[rsp(@@ITEMCAT_METHODS[method])]
  if result.is_a?(Hash) and result["item_cats"]
    item_cats = Top4R::ItemCat.unmarshal(result["item_cats"]["item_cat"])
    item_cats.each {|cat| bless_model(cat); yield cat if block_given?}
  else
    item_cats = []
  end
  # puts "\nsuites: #{suites.inspect}"
  item_cats
end

#items_info(iid = nil, options = {}, &block) ⇒ Object Also known as: items_list



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/top4r/client/item.rb', line 64

def items_info(iid = nil, options = {}, &block)
  method = :items_info
  valid_method(method, @@ITEM_METHODS, :item)
  # 为了兼容老的items_list接口,先split,后面再join
  iid = iid.split(',') if !iid.is_a?(Array)
  options = {:num_iids => iid.join(',')}.merge(options) if iid
  params = {:fields => Top4R::Item.fields}.merge(options)
  response = http_connect {|conn| create_http_get_request(@@ITEM_METHODS[method], params)}
  result = JSON.parse(response.body)[rsp(@@ITEM_METHODS[method])]
  if result.is_a?(Hash) and result['items']
    items = Top4R::Item.unmarshal(result["items"]["item"])
    items.each {|item| bless_model(item); yield item if block_given?}
    @total_results = items.size
  else
    @total_results = 0
    items = []
  end
  items
end

#items_inventory(q = nil, options = {}, &block) ⇒ Object

得到当前会话用户库存中的商品列表



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/top4r/client/item.rb', line 30

def items_inventory(q = nil, options = {}, &block)
  method = :inventory_list
  valid_method(method, @@ITEM_METHODS, :item)
  options = {:q => q}.merge(options) if q
  params = {:fields => Top4R::Item.fields}.merge(options)
  response = http_connect {|conn| create_http_get_request(@@ITEM_METHODS[method], params)}
  result = JSON.parse(response.body)[rsp(@@ITEM_METHODS[method])]
  if result.is_a?(Hash) and result['items']
    items = Top4R::Item.unmarshal(result["items"]["item"])
    items.each {|item| bless_model(item); yield item if block_given?}
    @total_results = result["total_results"].to_i
  else
    @total_results = 0
    items = []
  end
  items
end

#items_onsale(q = nil, method = :onsale_list, options = {}, &block) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/top4r/client/item.rb', line 12

def items_onsale(q = nil, method = :onsale_list, options = {}, &block)
  valid_method(method, @@ITEM_METHODS, :item)
  options = {:q => q}.merge(options) if q
  params = {:fields => Top4R::Item.fields}.merge(options)
  response = http_connect {|conn| create_http_get_request(@@ITEM_METHODS[method], params)}
  result = JSON.parse(response.body)[rsp(@@ITEM_METHODS[method])]
  if result.is_a?(Hash) and result['items']
    items = Top4R::Item.unmarshal(result["items"]["item"])
    items.each {|item| bless_model(item); yield item if block_given?}
    @total_results = result["total_results"].to_i
  else
    @total_results = 0
    items = []
  end
  items
end

#logged_in?Boolean

Returns:

  • (Boolean)


8
9
10
# File 'lib/top4r/client/user.rb', line 8

def logged_in?
  @login.is_a?(Top4R::User) ? true : false
end

#logistic_companies(method = :list, options = {}, &block) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/top4r/client/shipping.rb', line 29

def logistic_companies(method = :list, options = {}, &block)
  valid_method(method, @@LOGISTIC_COMPANY_METHODS, :logistic_company)
  params = {:fields => Top4R::LogisticCompany.fields}.merge(options)
  response = http_connect {|conn| create_http_get_request(@@LOGISTIC_COMPANY_METHODS[method], params)}
  result = JSON.parse(response.body)[rsp(@@LOGISTIC_COMPANY_METHODS[method])]
  if result.is_a?(Hash) and result["logistics_companies"]
    logistic_companies = Top4R::LogisticCompany.unmarshal(result["logistics_companies"]["logistics_company"])
    logistic_companies.each {|logistic_company| bless_model(logistic_company); yield logistic_company if block_given?}
  else
    logistic_companies = []
  end
  logistic_companies
end

#my(method, options = {}) ⇒ Object



19
20
21
22
23
# File 'lib/top4r/client/user.rb', line 19

def my(method, options = {})
  valid_method(method, @@USER_METHODS, :user, true)
  users = user_request(@login.nick, method, options)
  method == :info ? bless_model(users.first) : bless_models(users)
end

#old_inspectObject



3
# File 'lib/top4r/client/base.rb', line 3

alias :old_inspect :inspect

#seller_cats(u, method = :cats_list, options = {}, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/top4r/client/shop.rb', line 8

def seller_cats(u, method = :cats_list, options = {}, &block)
  valid_method(method, @@SHOP_METHODS, :shop)
  u = u.nick if u.is_a?(Top4R::User)
  params = options.merge(:nick => u)
  response = http_connect {|conn| create_http_get_request(@@SHOP_METHODS[method], params)}
  result = JSON.parse(response.body)[rsp(@@SHOP_METHODS[method])]
  if result.is_a?(Hash) and result["seller_cats"]
    seller_cats = Top4R::SellerCat.unmarshal(result["seller_cats"]["seller_cat"])
    seller_cats.each {|cat| bless_model(cat); yield cat if block_given?}
  else
    seller_cats = []
  end
  # puts "\nsuites: #{suites.inspect}"
  seller_cats
end

#shop(u, method = :shop_info, options = {}, &block) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/top4r/client/shop.rb', line 24

def shop(u, method = :shop_info, options = {}, &block)
  valid_method(method, @@SHOP_METHODS, :shop)
  u = u.nick if u.is_a?(Top4R::User)
  params = {:fields => Top4R::Shop.fields}.merge(options).merge(:nick => u)
  response = http_connect {|conn| create_http_get_request(@@SHOP_METHODS[method], params)}
  shop = Top4R::Shop.unmarshal(JSON.parse(response.body)[rsp(@@SHOP_METHODS[method])]["shop"])
  bless_model(shop)
end

#suites(u, service_code, method = :list, options = {}, &block) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/top4r/client/suite.rb', line 7

def suites(u, service_code, method = :list, options = {}, &block)
  valid_method(method, @@SUITE_METHODS, :suite)
  u = u.nick if u.is_a?(Top4R::User)
  params = {:service_code => service_code}.merge(options).merge(:nick => u)
  response = http_connect {|conn| create_http_get_request(@@SUITE_METHODS[method], params)}
  if response.body == "{\"suites_get_response\":{}}"
    raise Top4R::SuiteNotOrderedError.new(:code => 630,
                                  :message => "没有#{service_code}的订购记录",
                                  :error => "{}",
                                  :uri => @@SUITE_METHODS[method])
  end
  result = JSON.parse(response.body)[rsp(@@SUITE_METHODS[method])]
  if result.is_a?(Hash) and result["suites"]
    suites = Top4R::Suite.unmarshal(result["suites"]["suite"])
    suites.each {|suite| bless_model(suite); yield suite if block_given?}
    @total_results = result["total_results"].to_i
  else
    @total_results = 0
    suites = []
  end
  suites
end

#taobaoke_items(q = nil, method = :taobaoke_items_get, options = {}, &block) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/top4r/client/taobaokeitem.rb', line 10

def taobaoke_items(q = nil, method = :taobaoke_items_get, options = {}, &block)
  valid_method(method, @@TAOBAOKEITEM_METHODS, :taobaoke_item)
  options = {:keyword => q}.merge(options) if q
  params = {:fields => Top4R::TaobaokeItem.fields, :v => "2.0"}.merge(options)
  response = http_connect {|conn| create_http_get_request(@@TAOBAOKEITEM_METHODS[method], params)}
  result = JSON.parse(response.body)[rsp(@@TAOBAOKEITEM_METHODS[method])]
  if result.is_a?(Hash) and result["taobaoke_items"]
    items = Top4R::TaobaokeItem.unmarshal(result["taobaoke_items"]["taobaoke_item"])
    items.each {|item| bless_model(item); yield item if block_given?}
    @total_results = result["total_results"].to_i
  else
    @total_results = 0
    items = []
  end
  items
end

#taobaoke_items_detail(num_iids, options = {}, &block) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/top4r/client/taobaokeitem.rb', line 27

def taobaoke_items_detail(num_iids, options = {}, &block)
  method = :taobaoke_items_detail_get
  valid_method(method, @@TAOBAOKEITEM_METHODS, :taobaoke_item)
  options = {:num_iids => num_iids.join(',')}.merge(options) if num_iids
  params = {:fields => Top4R::TaobaokeItemDetail.fields, :v => "2.0"}.merge(options)
  response = http_connect {|conn| create_http_get_request(@@TAOBAOKEITEM_METHODS[method], params)}
  result = JSON.parse(response.body)[rsp(@@TAOBAOKEITEM_METHODS[method])]
  if result.is_a?(Hash) and result["taobaoke_item_details"]
    items = Top4R::TaobaokeItemDetail.unmarshal(result["taobaoke_item_details"]["taobaoke_item_detail"])
    items.each {|item| bless_model(item); yield item if block_given?}
    @total_results = result["total_results"].to_i
  else
    @total_results = 0
    items = []
  end
  items
end

#taobaoke_shops(method = :taobaoke_shops_convert, options = {}, &block) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/top4r/client/taobaokeitem.rb', line 45

def taobaoke_shops(method = :taobaoke_shops_convert, options = {}, &block)
  valid_method(method, @@TAOBAOKEITEM_METHODS, :taobaoke_item)
  params = {:fields => Top4R::TaobaokeItem.fields, :v => "2.0"}.merge(options)
  response = http_connect {|conn| create_http_get_request(@@TAOBAOKEITEM_METHODS[method], params)}
  result = JSON.parse(response.body)[rsp(@@TAOBAOKEITEM_METHODS[method])]
  if result.is_a?(Hash) and result["taobaoke_shops"]
    items = Top4R::TaobaokeShop.unmarshal(result["taobaoke_shops"]["taobaoke_shop"])
    items.each {|item| bless_model(item); yield item if block_given?}
    @total_results = result["total_results"].to_i
  else
    @total_results = 0
    items = []
  end
  items
end

#trade(t, method = :info, options = {}) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/top4r/client/trade.rb', line 35

def trade(t, method = :info, options = {})
  valid_method(method, @@TRADE_METHODS, :trade)
  t = t.tid if t.is_a?(Top4R::Trade)
  params = {:fields => Top4R::Trade.fields}.merge(options).merge(:tid => t)
  response = http_connect {|conn| create_http_get_request(@@TRADE_METHODS[method], params)}
  parsed_body = JSON.parse(response.body)
  
  if [:info, :fullinfo].member?(method)
    trades = Top4R::Trade.unmarshal(parsed_body[rsp(@@TRADE_METHODS[method])]["trade"])
    bless_model(trades.first)
  elsif method == :confirmfee
    confirmfees = Top4R::TradeConfirmFee.unmarshal(parsed_body[rsp(@@TRADE_METHODS[method])]["trade_confirm_fee"])
    bless_models(confirmfees)
  elsif [:close, :update_memo].member?(method)
    parsed_body[rsp(@@TRADE_METHODS[method])]["trade"]["modified"]
  elsif method == :add_memo
    parsed_body[rsp(@@TRADE_METHODS[method])]["trade"]["created"]
  end
end

#trades_for(method = :bought_list, options = {}, &block) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/top4r/client/trade.rb', line 15

def trades_for(method = :bought_list, options = {}, &block)
  valid_method(method, @@TRADE_METHODS, :trade)
  params = {:fields => Top4R::Trade.fields}.merge(options)
  if method == :increments_list
    now = Time.now
    params = {:start_modified => (now - 24.hours).strftime("%Y-%m-%d %H:%M:%S"), :end_modified => now.strftime("%Y-%m-%d %H:%M:%S")}.merge(params)
  end
  response = http_connect {|conn| create_http_get_request(@@TRADE_METHODS[method], params)}
  result = JSON.parse(response.body)[rsp(@@TRADE_METHODS[method])]
  if result.is_a?(Hash) and result["trades"]
    trades = Top4R::Trade.unmarshal(result["trades"]["trade"])
    trades.each {|trade| bless_model(trade); yield trade if block_given?}
    @total_results = result["total_results"].to_i
  else
    @total_results = 0
    trades = []
  end
  trades
end

#user(u, method = :info, options = {}) ⇒ Object



12
13
14
15
16
17
# File 'lib/top4r/client/user.rb', line 12

def user(u, method = :info, options = {})
  valid_method(method, @@USER_METHODS, :user)
  u = u.nick if u.is_a?(Top4R::User)
  users = user_request(u, method, options)
  method == :info ? bless_model(users.first) : bless_models(users)
end