class Wechat::Qcloud::Token

Attributes

access_token[R]
client[R]
qcloud_env[R]
qcloud_token[R]
qcloud_token_expired_time[R]
qcloud_token_file[R]
qcloud_token_lifespan[R]

Public Class Methods

new(client, access_token, qcloud_setting) click to toggle source
# File lib/wechat/qcloud/token.rb, line 13
def initialize(client, access_token, qcloud_setting)
  @client = client
  @access_token = access_token
  @qcloud_env = qcloud_setting.qcloud_env
  @qcloud_token_file = qcloud_setting.qcloud_token
  @qcloud_token_lifespan = qcloud_setting.qcloud_token_lifespan
  @random_generator = Random.new
end

Public Instance Methods

refresh() click to toggle source
# File lib/wechat/qcloud/token.rb, line 32
def refresh
  data = client.post('getqcloudtoken', JSON.generate(lifespan: qcloud_token_lifespan), base: ::Wechat::ApiBase::TCB_BASE, params: { access_token: access_token.token })
  write_qcloud_token_to_store(data)
  read_qcloud_token_from_store
end
token(tries = 2) click to toggle source
# File lib/wechat/qcloud/token.rb, line 22
def token(tries = 2)
  # Possible two worker running, one worker refresh ticket, other unaware, so must read every time
  read_qcloud_token_from_store
  refresh if remain_life_seconds < @random_generator.rand(30..(3 * 60))
  qcloud_token
rescue AccessTokenExpiredError
  access_token.refresh
  retry unless (tries -= 1).zero?
end

Protected Instance Methods

read_qcloud_token() click to toggle source
# File lib/wechat/qcloud/token.rb, line 53
def read_qcloud_token
  JSON.parse(File.read(qcloud_token_file))
end
read_qcloud_token_from_store() click to toggle source
# File lib/wechat/qcloud/token.rb, line 40
def read_qcloud_token_from_store
  td = read_qcloud_token
  @qcloud_token_expired_time = td.fetch('qcloud_token_expired_time').to_i
  @qcloud_token = td.fetch('token') # return qcloud_token same time
rescue JSON::ParserError, Errno::ENOENT, KeyError, TypeError
  refresh
end
remain_life_seconds() click to toggle source
# File lib/wechat/qcloud/token.rb, line 61
def remain_life_seconds
  qcloud_token_expired_time - Time.now.to_i
end
write_qcloud_token(qcloud_token_hash) click to toggle source
# File lib/wechat/qcloud/token.rb, line 57
def write_qcloud_token(qcloud_token_hash)
  File.write(qcloud_token_file, qcloud_token_hash.to_json)
end
write_qcloud_token_to_store(qcloud_token_hash) click to toggle source
# File lib/wechat/qcloud/token.rb, line 48
def write_qcloud_token_to_store(qcloud_token_hash)
  qcloud_token_hash['qcloud_token_expired_time'] = qcloud_token_hash.delete('expired_time')
  write_qcloud_token(qcloud_token_hash)
end