class Gitea::ClientService < ApplicationService attr_reader :username, :secret, :token, :url, :params def initialize(options={}) @username = options[:username] @secret = options[:password] @token = options[:token] @url = options[:url] @params = options[:params] end # params # EXA: # { # token: {}, # data: {} # } def post(url, params) puts "[gitea] request params: #{params}" request_url = [api_url, url].join('').freeze auth_token = authen_params(params[:token]) response = conn(auth_token).post do |req| req.url "#{request_url}" req.body = params[:data].to_json end render_status(response) end private def conn(auth={}) username = auth[:username] || access_key_id secret = auth[:password] || access_key_secret token = auth[:token] puts "[gitea] username: #{username}" puts "[gitea] secret: #{secret}" puts "[gitea] token: #{token}" @client ||= begin Faraday.new(url: domain) do |req| req.request :url_encoded req.headers['Content-Type'] = 'application/json' req.response :logger # 显示日志 req.adapter Faraday.default_adapter if token.blank? req.basic_auth(username, secret) else req.authorization :Bearer, token req.headers['Authorization'] end end end @client end def base_url Gitea.gitea_config[:base_url] end def domain Gitea.gitea_config[:domain] end def access_key_id Gitea.gitea_config[:access_key_id] end def access_key_secret Gitea.gitea_config[:access_key_secret] end def api_url [domain, base_url].join('') end def render_status(response) mark = "[gitea] " case response.status when 201 JSON.parse(response&.body) when 401 raise Error, mark + "401" when 422 result = JSON.parse(response&.body) puts "[gitea] parse body: #{result}" # return {status: -1, message: result[0]} raise Error, result[0] else result = JSON.parse(response&.body) message = result['message'] raise Error, mark + message end end def authen_params(token) (token.is_a? String) ? {token: token} : Hash(token) end end