Class: Dingtalk::Api::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/dingtalk/api/Base.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url = nil) ⇒ Base

Returns a new instance of Base.

Raises:



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/dingtalk/api/Base.rb', line 11

def initialize(url = nil)
  raise RequestException, "domain must not be empty." if url.nil?

  @__port = 80
  pathUrl = if url.start_with?('http://')
              url.gsub('http://', '')
            elsif url.start_with?('https://')
              url.gsub('https://', '')
            else
              raise RequestException, "http protocol is not validate."
  end

  index = pathUrl.index('/').to_i

  if index.positive?
    @__domain = pathUrl[0...index]
    @__path = pathUrl[index..-1]
  else
    @__domain = pathUrl
    @__path = ''
  end

  # puts "domain:#{@__domain}, path: #{@__path}, port: #{@__port}"
end

Instance Attribute Details

#__domainObject

Returns the value of attribute __domain.



9
10
11
# File 'lib/dingtalk/api/Base.rb', line 9

def __domain
  @__domain
end

#__pathObject

Returns the value of attribute __path.



9
10
11
# File 'lib/dingtalk/api/Base.rb', line 9

def __path
  @__path
end

#__portObject

Returns the value of attribute __port.



9
10
11
# File 'lib/dingtalk/api/Base.rb', line 9

def __port
  @__port
end

Instance Method Details

#computeSignature(secret, canonicalString) ⇒ Object



138
139
140
141
142
143
# File 'lib/dingtalk/api/Base.rb', line 138

def computeSignature(secret, canonicalString)
  digest = OpenSSL::HMAC.digest('sha256', secret, canonicalString)
  signature = Base64.strict_encode64(digest)
  URI.encode_www_form_component(signature)
  signature
end

#getapinameObject



48
49
50
# File 'lib/dingtalk/api/Base.rb', line 48

def getapiname
  ""
end

#getApiPathObject



52
53
54
# File 'lib/dingtalk/api/Base.rb', line 52

def getApiPath
  ""
end

#getApplicationParametersObject



145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/dingtalk/api/Base.rb', line 145

def getApplicationParameters
  application_parameter = {}
  translate_parameter = getTranslateParas
  instance_variable_names.each do |name|
    next if name.start_with?('@__')

    application_parameter[name[1..-1]] = instance_variable_get(name)
  end
  # application_parameter.each_key do |key|
  #   application_parameter[translate_parameter[key]] = application_parameter[key]
  #   application_parameter.delete(key)
  # end
  application_parameter
end

#getCanonicalStringForIsv(timestamp, suiteTicket) ⇒ Object



60
61
62
63
64
65
66
# File 'lib/dingtalk/api/Base.rb', line 60

def getCanonicalStringForIsv(timestamp, suiteTicket)
  if suiteTicket.present?
    "#{timestamp}\n#{suiteTicket}"
  else
    timestamp
  end
end

#getHttpMethodObject



44
45
46
# File 'lib/dingtalk/api/Base.rb', line 44

def getHttpMethod
  "GET"
end

#getMultipartParasObject



56
57
58
# File 'lib/dingtalk/api/Base.rb', line 56

def getMultipartParas
  []
end

#getRequestHeaderObject



36
37
38
39
40
41
42
# File 'lib/dingtalk/api/Base.rb', line 36

def getRequestHeader
  {
    'Content-type' => 'application/json;charset=UTF-8',
    "Cache-Control" => "no-cache",
    "Connection" => "Keep-Alive"
  }
end

#getResponse(authrize: '', accessKey: '', accessSecret: '', suiteTicket: '', corpId: '', timeout: 30) ⇒ Object



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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/dingtalk/api/Base.rb', line 68

def getResponse(authrize: '', accessKey: '', accessSecret: '', suiteTicket: '', corpId: '', timeout: 30)
  sys_parameters = {
    :P_PARTNER_ID => SYSTEM_GENERATE_VERSION
  }
  sys_parameters[P_ACCESS_TOKEN] = authrize if authrize.present?
  application_parameter = getApplicationParameters

  # apiname_split = self.getapiname().split(".")

  sign_parameter = sys_parameters.dup

  sign_parameter.merge!(application_parameter)

  # header = getRequestHeader

  body = application_parameter

  if accessKey.present?
    timestamp = DateTime.now.strftime('%Q')
    puts "timestamp:", timestamp
    canonicalString = getCanonicalStringForIsv(timestamp, suiteTicket)
    puts("canonicalString:" + canonicalString)
    puts("accessSecret:" + accessSecret)
    signature = computeSignature(accessSecret, canonicalString)
    puts("signature:" + signature)
    ps = {}
    ps["accessKey"] = accessKey
    ps["signature"] = signature
    ps["timestamp"] = timestamp
    ps["suiteTicket"] = suiteTicket if suiteTicket.present?
    ps["corpId"] = corpId if corpId != ''
    queryStr = ps.to_query
    fullPath = @__path.include?("?") ? "#{@__path}&#{queryStr}" : "#{@__path}?#{queryStr}"
  else
    fullPath = @__path.include?("?") ? (authrize.present? ? "#{@__path}&access_token=#{authrize}" : @__path) : (authrize.present? ? "#{@__path}?access_token=#{authrize}" : @__path)
  end

  response = if getHttpMethod == "GET"
               fullPath = fullPath.include?("?") ? "#{fullPath}&#{body.to_query}" : "#{fullPath}?#{body.to_query}"
               Faraday.get("https://#{@__domain}#{fullPath}") do |req|
                 req.headers['Content-Type'] = 'application/json'
                 req.headers['Accept'] = 'application/json'
               end
             else
               body = if getMultipartParas.present?
                        body
                      else
                        application_parameter.to_json
                      end
               Faraday.post("https://#{@__domain}#{fullPath}", body, "Content-Type" => "application/json")
             end
  unless response.success?
    raise RequestException, "invalid http status #{response.status} ,detail body: #{response.body}"
  end

  result = response.body
  # puts "result:", result
  jsonobj = JSON.parse(result)
  if jsonobj.key?(P_CODE) && (jsonobj[P_CODE] != 0)
    error = TopException.new
    error.errcode = jsonobj[P_CODE]
    error.errmsg = jsonobj[P_MSG]
    error.application_host = response.headers.fetch("Application-Host", "")
    error.service_host = response.headers.fetch("Location-Host", "")
    raise error, "TopException"
  end

  jsonobj
end

#getTranslateParasObject



160
161
162
# File 'lib/dingtalk/api/Base.rb', line 160

def getTranslateParas
  {}
end