2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2014-01-01 03:37:43 +08:00
|
|
|
class TopicRetriever
|
|
|
|
|
2017-07-28 09:20:09 +08:00
|
|
|
def initialize(embed_url, opts = nil)
|
2014-01-01 03:37:43 +08:00
|
|
|
@embed_url = embed_url
|
2014-04-25 00:48:45 +08:00
|
|
|
@author_username = opts[:author_username]
|
2014-01-01 03:37:43 +08:00
|
|
|
@opts = opts || {}
|
|
|
|
end
|
|
|
|
|
|
|
|
def retrieve
|
2016-08-24 02:55:52 +08:00
|
|
|
perform_retrieve unless (invalid_url? || retrieved_recently?)
|
2014-01-01 03:37:43 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2018-06-07 13:28:18 +08:00
|
|
|
def invalid_url?
|
|
|
|
!EmbeddableHost.url_allowed?(@embed_url)
|
|
|
|
end
|
2014-01-01 03:37:43 +08:00
|
|
|
|
2018-06-07 13:28:18 +08:00
|
|
|
def retrieved_recently?
|
|
|
|
# We can disable the throttle for some users, such as staff
|
|
|
|
return false if @opts[:no_throttle]
|
2014-01-01 03:37:43 +08:00
|
|
|
|
2018-06-07 13:28:18 +08:00
|
|
|
# Throttle other users to once every 60 seconds
|
|
|
|
retrieved_key = "retrieved_topic"
|
2019-12-03 17:05:53 +08:00
|
|
|
if Discourse.redis.setnx(retrieved_key, "1")
|
|
|
|
Discourse.redis.expire(retrieved_key, 60)
|
2018-06-07 13:28:18 +08:00
|
|
|
return false
|
2014-01-01 03:37:43 +08:00
|
|
|
end
|
|
|
|
|
2018-06-07 13:28:18 +08:00
|
|
|
true
|
|
|
|
end
|
2014-01-01 03:37:43 +08:00
|
|
|
|
2018-06-07 13:28:18 +08:00
|
|
|
def perform_retrieve
|
|
|
|
# It's possible another process or job found the embed already. So if that happened bail out.
|
|
|
|
return if TopicEmbed.where(embed_url: @embed_url).exists?
|
2014-01-01 03:37:43 +08:00
|
|
|
|
2018-06-07 13:28:18 +08:00
|
|
|
# First check RSS if that is enabled
|
|
|
|
if SiteSetting.feed_polling_enabled?
|
|
|
|
Jobs::PollFeed.new.execute({})
|
|
|
|
return if TopicEmbed.where(embed_url: @embed_url).exists?
|
2014-01-01 03:37:43 +08:00
|
|
|
end
|
|
|
|
|
2018-06-07 13:28:18 +08:00
|
|
|
fetch_http
|
|
|
|
end
|
2014-01-01 03:37:43 +08:00
|
|
|
|
2018-06-07 13:28:18 +08:00
|
|
|
def fetch_http
|
|
|
|
if @author_username.nil?
|
|
|
|
username = SiteSetting.embed_by_username.downcase
|
|
|
|
else
|
|
|
|
username = @author_username
|
2014-01-01 03:37:43 +08:00
|
|
|
end
|
|
|
|
|
2018-06-07 13:28:18 +08:00
|
|
|
user = User.where(username_lower: username.downcase).first
|
|
|
|
return if user.blank?
|
|
|
|
|
|
|
|
TopicEmbed.import_remote(user, @embed_url)
|
|
|
|
end
|
|
|
|
|
2014-02-13 04:55:44 +08:00
|
|
|
end
|