Method: WikiBot::Bot#query_api

Defined in:
lib/wikibot/core/bot.rb

#query_api(method, raw_data = {}) ⇒ Object



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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/wikibot/core/bot.rb', line 52

def query_api(method, raw_data = {})
  # Send a query to the API and handle the response
  url = @config.api
  raw_data = raw_data.to_openhash

  raw_data[:format] = :xml if raw_data.format.nil?

  # Setup cookie headers for the request
  @curl.headers["Cookie"] = @cookies.inject([]) do |memo, pair|
    key, val = pair
    memo.push(CGI::escape(key) + "=" + CGI::escape(val))
  end.join("; ") unless @cookies.nil?

  response_xml = {}

  while true
    if method == :post
      data = raw_data.to_post_fields
    elsif method == :get
      url = url.chomp("?") + "?" + raw_data.to_querystring
      data = nil
    end

    @curl.url = url
    @curl.headers["Expect"] = nil # MediaWiki will give a 417 error if Expect is set

    @curl.on_debug { |type, data| p data } if @debug
    
    @gzip = false
    @curl.on_header do |data|
      header, text = data.split(":").map(&:strip)
      if header == "Set-Cookie"
        # If Set-Cookie headers are given in the response, set the cookies
        parts = text.split(";")
        cookie_name, cookie_value = parts[0].split("=")
        @cookies[cookie_name] = cookie_value
      elsif header == "Content-Encoding"
        # If the respons is gzip encoded we'll have to decode it before use
        @gzip = true if text == "gzip"
      end
      data.length
    end

    params = ["http_#{method}".to_sym]
    params.push(*data) unless data.nil? or (data.is_a? Array and data.empty?)
    @curl.send(*params)
    @api_hits += 1

    raise CurbError.new(@curl) unless @curl.response_code == 200
    
    body = @gzip ? Zlib::GzipReader.new(StringIO.new(@curl.body_str)).read : @curl.body_str 

    xml = XmlSimple.xml_in(body, {'ForceArray' => false})
    raise APIError.new(xml['error']['code'], xml['error']['info']) if xml['error']

    response_xml.deep_merge! xml
    break unless xml['query-continue']
    raw_data.merge! xml['query-continue'][xml['query-continue'].keys.first]
  end

  response_xml.to_openhash
end