BigW Consortium Gitlab

web_hook.rb 1.65 KB
Newer Older
1 2 3 4
# == Schema Information
#
# Table name: web_hooks
#
5 6 7
#  id                    :integer          not null, primary key
#  url                   :string(255)
#  project_id            :integer
Dmitriy Zaporozhets committed
8 9
#  created_at            :datetime
#  updated_at            :datetime
10 11 12 13 14
#  type                  :string(255)      default("ProjectHook")
#  service_id            :integer
#  push_events           :boolean          default(TRUE), not null
#  issues_events         :boolean          default(FALSE), not null
#  merge_requests_events :boolean          default(FALSE), not null
Dmitriy Zaporozhets committed
15
#  tag_push_events       :boolean          default(FALSE)
16 17
#

18 19 20
class WebHook < ActiveRecord::Base
  include HTTParty

21 22 23 24
  default_value_for :push_events, true
  default_value_for :issues_events, false
  default_value_for :merge_requests_events, false

25 26 27
  # HTTParty timeout
  default_timeout 10

28
  validates :url, presence: true,
Andrey Kumanyaev committed
29
                  format: { with: URI::regexp(%w(http https)), message: "should be a valid url" }
30 31

  def execute(data)
32 33
    parsed_url = URI.parse(url)
    if parsed_url.userinfo.blank?
34
      WebHook.post(url, body: data.to_json, headers: { "Content-Type" => "application/json" }, verify: false)
35
    else
36
      post_url = url.gsub("#{parsed_url.userinfo}@", "")
37 38 39 40
      auth = {
        username: URI.decode(parsed_url.user),
        password: URI.decode(parsed_url.password),
      }
41 42
      WebHook.post(post_url,
                   body: data.to_json,
43
                   headers: {"Content-Type" => "application/json"},
44
                   verify: false,
45
                   basic_auth: auth)
46
    end
47
  end
48 49 50 51

  def async_execute(data)
    Sidekiq::Client.enqueue(ProjectWebHookWorker, id, data)
  end
52
end