client.rb 2.0 KB
Newer Older
V
Valery Sizov 已提交
1 2 3 4 5 6 7 8 9 10 11
module Gitlab
  module GitlabImport
    class Client
      attr_reader :client, :api

      PER_PAGE = 100

      def initialize(access_token)
        @client = ::OAuth2::Client.new(
          config.app_id,
          config.app_secret,
D
Douwe Maan 已提交
12
          gitlab_options
V
Valery Sizov 已提交
13 14 15
        )

        if access_token
16
          @api = OAuth2::AccessToken.from_hash(@client, access_token: access_token)
V
Valery Sizov 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
        end
      end

      def authorize_url(redirect_uri)
        client.auth_code.authorize_url({
          redirect_uri: redirect_uri,
          scope: "api"
        })
      end

      def get_token(code, redirect_uri)
        client.auth_code.get_token(code, redirect_uri: redirect_uri).token
      end

      def issues(project_identifier)
        lazy_page_iterator(PER_PAGE) do |page|
          api.get("/api/v3/projects/#{project_identifier}/issues?per_page=#{PER_PAGE}&page=#{page}").parsed
        end
      end

      def issue_comments(project_identifier, issue_id)
        lazy_page_iterator(PER_PAGE) do |page|
          api.get("/api/v3/projects/#{project_identifier}/issues/#{issue_id}/notes?per_page=#{PER_PAGE}&page=#{page}").parsed
        end
      end

      def project(id)
        api.get("/api/v3/projects/#{id}").parsed
      end

      def projects
        lazy_page_iterator(PER_PAGE) do |page|
          api.get("/api/v3/projects?per_page=#{PER_PAGE}&page=#{page}").parsed
        end
      end

      private

      def lazy_page_iterator(per_page)
        Enumerator.new do |y|
          page = 1
          loop do
            items = yield(page)
            items.each do |item|
              y << item
            end
            break if items.empty? || items.size < per_page
            page += 1
          end
        end
      end

      def config
70
        Gitlab.config.omniauth.providers.find{|provider| provider.name == "gitlab"}
V
Valery Sizov 已提交
71 72
      end

D
Douwe Maan 已提交
73
      def gitlab_options
74
        OmniAuth::Strategies::GitLab.default_options[:client_options].symbolize_keys
V
Valery Sizov 已提交
75 76 77 78
      end
    end
  end
end