2016-11-28 04:36:47 -08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class Pubsubhubbub::SubscribeService < BaseService
|
2017-05-09 11:48:30 -07:00
|
|
|
URL_PATTERN = /\A#{URI.regexp(%w(http https))}\z/
|
|
|
|
|
2017-07-14 14:01:20 -07:00
|
|
|
attr_reader :account, :callback, :secret,
|
|
|
|
:lease_seconds, :domain
|
2017-05-09 11:48:30 -07:00
|
|
|
|
2017-07-14 14:01:20 -07:00
|
|
|
def call(account, callback, secret, lease_seconds, verified_domain = nil)
|
2017-05-09 17:55:43 -07:00
|
|
|
@account = account
|
|
|
|
@callback = Addressable::URI.parse(callback).normalize.to_s
|
|
|
|
@secret = secret
|
2017-05-09 11:48:30 -07:00
|
|
|
@lease_seconds = lease_seconds
|
2017-07-14 14:01:20 -07:00
|
|
|
@domain = verified_domain
|
2017-05-09 11:48:30 -07:00
|
|
|
|
|
|
|
process_subscribe
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def process_subscribe
|
|
|
|
case subscribe_status
|
|
|
|
when :invalid_topic
|
|
|
|
['Invalid topic URL', 422]
|
|
|
|
when :invalid_callback
|
|
|
|
['Invalid callback URL', 422]
|
|
|
|
when :callback_not_allowed
|
|
|
|
['Callback URL not allowed', 403]
|
|
|
|
when :valid
|
|
|
|
confirm_subscription
|
|
|
|
['', 202]
|
|
|
|
end
|
|
|
|
end
|
2016-11-28 04:36:47 -08:00
|
|
|
|
2017-05-09 11:48:30 -07:00
|
|
|
def subscribe_status
|
|
|
|
if account.nil?
|
|
|
|
:invalid_topic
|
|
|
|
elsif !valid_callback?
|
|
|
|
:invalid_callback
|
|
|
|
elsif blocked_domain?
|
|
|
|
:callback_not_allowed
|
|
|
|
else
|
|
|
|
:valid
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def confirm_subscription
|
|
|
|
subscription = locate_subscription
|
2016-11-28 04:36:47 -08:00
|
|
|
Pubsubhubbub::ConfirmationWorker.perform_async(subscription.id, 'subscribe', secret, lease_seconds)
|
2017-05-09 11:48:30 -07:00
|
|
|
end
|
|
|
|
|
|
|
|
def valid_callback?
|
|
|
|
callback.present? && callback =~ URL_PATTERN
|
|
|
|
end
|
|
|
|
|
|
|
|
def blocked_domain?
|
2017-05-09 17:55:43 -07:00
|
|
|
DomainBlock.blocked? Addressable::URI.parse(callback).host
|
2017-05-09 11:48:30 -07:00
|
|
|
end
|
2016-11-28 04:36:47 -08:00
|
|
|
|
2017-05-09 11:48:30 -07:00
|
|
|
def locate_subscription
|
2017-07-14 14:01:20 -07:00
|
|
|
subscription = Subscription.find_by(account: account, callback_url: callback)
|
|
|
|
|
|
|
|
if subscription.nil?
|
|
|
|
subscription = Subscription.new(account: account, callback_url: callback)
|
|
|
|
end
|
|
|
|
|
|
|
|
subscription.domain = domain
|
|
|
|
subscription.save!
|
|
|
|
subscription
|
2016-11-28 04:36:47 -08:00
|
|
|
end
|
|
|
|
end
|