forgeplus/app/services/api/v1/projects/webhooks/create_service.rb

63 lines
1.9 KiB
Ruby

class Api::V1::Projects::Webhooks::CreateService < ApplicationService
include ActiveModel::Model
attr_reader :project, :token, :owner, :repo, :active, :branch_filter, :content_type, :url, :http_method, :secret, :events, :type
attr_accessor :gitea_data
validates :url, format: { with: URI::regexp(%w[http https]), message: "请输入正确的地址" }
validates :active, inclusion: {in: [true, false]}
validates :http_method, inclusion: { in: %w(POST GET), message: "请输入正确的请求方式"}
validates :content_type, inclusion: { in: %w(json form), message: "请输入正确的Content Type"}
validates :type, inclusion: {in: %w(gitea slack discord dingtalk telegram msteams feishu matrix jianmu), message: "请输入正确的Webhook Type"}
def initialize(project, params, token=nil)
@project = project
@owner = project&.owner.login
@repo = project&.identifier
@active = params[:active]
@branch_filter = params[:branch_filter]
@content_type = params[:content_type]
@url = params[:url]
@http_method = params[:http_method]
@secret = params[:secret]
@events = params[:events]
@type = params[:type] || "gitea"
@token = token
end
def call
raise Error, errors.full_messages.join(",") unless valid?
begin
excute_data_to_gitea
gitea_data
rescue
raise Error, "服务器错误,请联系系统管理员!"
end
end
private
def request_params
{
access_token: token
}
end
def request_body
{
active: active,
branch_filter: branch_filter,
config: {
content_type: content_type,
url: url,
http_method: http_method,
secret: secret
},
events: events || [],
type: type,
}
end
def excute_data_to_gitea
@gitea_data = $gitea_client.post_repos_hooks_by_owner_repo(owner, repo, {body: request_body.to_json, query: request_params}) rescue nil
end
end