2014-12-31 08:07:48 -05:00
|
|
|
module Gitlab
|
2015-02-02 17:26:29 -05:00
|
|
|
module GithubImport
|
2014-12-31 08:07:48 -05:00
|
|
|
class Client
|
2016-06-08 21:48:44 -04:00
|
|
|
GITHUB_SAFE_REMAINING_REQUESTS = 100
|
|
|
|
GITHUB_SAFE_SLEEP_TIME = 500
|
|
|
|
|
2015-02-05 19:57:27 -05:00
|
|
|
attr_reader :client, :api
|
2014-12-31 08:07:48 -05:00
|
|
|
|
2015-02-05 19:57:27 -05:00
|
|
|
def initialize(access_token)
|
2014-12-31 08:07:48 -05:00
|
|
|
@client = ::OAuth2::Client.new(
|
|
|
|
config.app_id,
|
|
|
|
config.app_secret,
|
2016-04-22 15:43:10 -04:00
|
|
|
github_options.merge(ssl: { verify: config['verify_ssl'] })
|
2014-12-31 08:07:48 -05:00
|
|
|
)
|
2015-02-05 19:57:27 -05:00
|
|
|
|
|
|
|
if access_token
|
2016-06-08 21:48:44 -04:00
|
|
|
::Octokit.auto_paginate = false
|
2016-04-22 15:43:10 -04:00
|
|
|
|
|
|
|
@api = ::Octokit::Client.new(
|
|
|
|
access_token: access_token,
|
|
|
|
api_endpoint: github_options[:site],
|
|
|
|
connection_options: {
|
|
|
|
ssl: { verify: config['verify_ssl'] }
|
|
|
|
}
|
|
|
|
)
|
2015-02-05 19:57:27 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def authorize_url(redirect_uri)
|
|
|
|
client.auth_code.authorize_url({
|
|
|
|
redirect_uri: redirect_uri,
|
|
|
|
scope: "repo, user, user:email"
|
|
|
|
})
|
|
|
|
end
|
|
|
|
|
|
|
|
def get_token(code)
|
|
|
|
client.auth_code.get_token(code).token
|
|
|
|
end
|
|
|
|
|
|
|
|
def method_missing(method, *args, &block)
|
|
|
|
if api.respond_to?(method)
|
2016-06-08 21:48:44 -04:00
|
|
|
request { api.send(method, *args, &block) }
|
2015-02-05 19:57:27 -05:00
|
|
|
else
|
|
|
|
super(method, *args, &block)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def respond_to?(method)
|
|
|
|
api.respond_to?(method) || super
|
2014-12-31 08:07:48 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def config
|
2016-04-22 15:43:10 -04:00
|
|
|
Gitlab.config.omniauth.providers.find { |provider| provider.name == "github" }
|
2014-12-31 08:07:48 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def github_options
|
2016-04-22 15:43:10 -04:00
|
|
|
config["args"]["client_options"].deep_symbolize_keys
|
2014-12-31 08:07:48 -05:00
|
|
|
end
|
2016-06-08 21:48:44 -04:00
|
|
|
|
|
|
|
def rate_limit
|
|
|
|
api.rate_limit!
|
|
|
|
end
|
|
|
|
|
|
|
|
def rate_limit_exceed?
|
|
|
|
rate_limit.remaining <= GITHUB_SAFE_REMAINING_REQUESTS
|
|
|
|
end
|
|
|
|
|
|
|
|
def rate_limit_sleep_time
|
|
|
|
rate_limit.resets_in + GITHUB_SAFE_SLEEP_TIME
|
|
|
|
end
|
|
|
|
|
|
|
|
def request
|
|
|
|
sleep rate_limit_sleep_time if rate_limit_exceed?
|
|
|
|
|
|
|
|
data = yield
|
|
|
|
|
|
|
|
last_response = api.last_response
|
|
|
|
|
|
|
|
while last_response.rels[:next]
|
|
|
|
sleep rate_limit_sleep_time if rate_limit_exceed?
|
|
|
|
last_response = last_response.rels[:next].get
|
|
|
|
data.concat(last_response.data) if last_response.data.is_a?(Array)
|
|
|
|
end
|
|
|
|
|
|
|
|
data
|
|
|
|
end
|
2014-12-31 08:07:48 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|