2021-06-17 20:54:30 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class WebhookService
|
|
|
|
class InactiveWebhookSendException < StandardError; end
|
|
|
|
|
2021-07-22 19:43:36 +08:00
|
|
|
class RequestFailureException < StandardError; end
|
2021-06-17 20:54:30 +08:00
|
|
|
|
|
|
|
def initialize(webhook, payload)
|
|
|
|
@webhook = webhook
|
|
|
|
@payload = payload
|
|
|
|
end
|
|
|
|
|
|
|
|
def send_webhook
|
|
|
|
unless @webhook.active?
|
|
|
|
raise(
|
2021-07-22 19:43:36 +08:00
|
|
|
InactiveWebhookSendException,
|
2021-06-30 19:15:08 +08:00
|
|
|
'Refused to send inactive webhook.'
|
2021-06-17 20:54:30 +08:00
|
|
|
)
|
|
|
|
end
|
|
|
|
|
2021-11-03 22:04:13 +08:00
|
|
|
headers = { 'Content-Type' => 'application/json' }
|
|
|
|
headers['Webhook-Secret-Key'] = @webhook.secret_key if @webhook.secret_key.present?
|
|
|
|
|
2021-06-18 04:00:13 +08:00
|
|
|
response = HTTParty.public_send(
|
2021-06-17 20:54:30 +08:00
|
|
|
@webhook.http_method,
|
|
|
|
@webhook.url,
|
|
|
|
{
|
2021-11-03 22:04:13 +08:00
|
|
|
headers: headers,
|
2021-08-06 19:43:30 +08:00
|
|
|
body: @payload.to_json
|
2021-06-17 20:54:30 +08:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2021-07-22 19:43:36 +08:00
|
|
|
unless response.success?
|
|
|
|
error_description = "#{response.code}: #{response.message}"
|
|
|
|
log_error!(error_description)
|
|
|
|
|
|
|
|
raise(
|
|
|
|
RequestFailureException,
|
|
|
|
error_description
|
|
|
|
)
|
|
|
|
end
|
2021-06-17 20:54:30 +08:00
|
|
|
|
|
|
|
response
|
2021-06-18 04:00:13 +08:00
|
|
|
rescue Net::ReadTimeout, Net::OpenTimeout, SocketError => e
|
|
|
|
log_error!(e)
|
|
|
|
raise e
|
2021-06-17 20:54:30 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def log_error!(message)
|
2021-07-22 16:51:03 +08:00
|
|
|
@webhook.update!(
|
2021-06-17 20:54:30 +08:00
|
|
|
last_error: message
|
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|