2019-05-02 17:17:27 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-12-31 13:37:43 -06:00
|
|
|
class TopicRetriever
|
|
|
|
|
|
|
|
def initialize(embed_url, opts = nil)
|
|
|
|
@embed_url = embed_url
|
|
|
|
@opts = opts || {}
|
2020-04-20 13:16:34 -05:00
|
|
|
@author_username = @opts[:author_username]
|
2013-12-31 13:37:43 -06:00
|
|
|
end
|
|
|
|
|
|
|
|
def retrieve
|
2016-08-23 13:55:52 -05:00
|
|
|
perform_retrieve unless (invalid_url? || retrieved_recently?)
|
2013-12-31 13:37:43 -06:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2016-08-23 13:55:52 -05:00
|
|
|
def invalid_url?
|
2021-02-25 05:31:38 -06:00
|
|
|
!EmbeddableHost.url_allowed?(@embed_url.strip)
|
2013-12-31 13:37:43 -06:00
|
|
|
end
|
|
|
|
|
|
|
|
def retrieved_recently?
|
|
|
|
# We can disable the throttle for some users, such as staff
|
|
|
|
return false if @opts[:no_throttle]
|
|
|
|
|
|
|
|
# Throttle other users to once every 60 seconds
|
|
|
|
retrieved_key = "retrieved_topic"
|
2019-12-03 03:05:53 -06:00
|
|
|
if Discourse.redis.setnx(retrieved_key, "1")
|
|
|
|
Discourse.redis.expire(retrieved_key, 60)
|
2013-12-31 13:37:43 -06:00
|
|
|
return false
|
|
|
|
end
|
|
|
|
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
|
|
|
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?
|
|
|
|
|
|
|
|
fetch_http
|
2014-04-24 11:48:45 -05:00
|
|
|
end
|
2013-12-31 13:37:43 -06:00
|
|
|
|
2018-06-07 00:28:18 -05:00
|
|
|
def fetch_http
|
2013-12-31 13:37:43 -06:00
|
|
|
if @author_username.nil?
|
2021-03-15 09:58:53 -05:00
|
|
|
username = SiteSetting.embed_by_username.presence || SiteSetting.site_contact_username.presence || Discourse.system_user.username
|
2018-06-07 00:28:18 -05:00
|
|
|
else
|
2014-04-24 11:48:45 -05:00
|
|
|
username = @author_username
|
2013-12-31 13:37:43 -06:00
|
|
|
end
|
|
|
|
|
2014-04-24 11:48:45 -05:00
|
|
|
user = User.where(username_lower: username.downcase).first
|
2013-12-31 13:37:43 -06:00
|
|
|
return if user.blank?
|
2018-06-07 00:28:18 -05:00
|
|
|
|
2013-12-31 13:37:43 -06:00
|
|
|
TopicEmbed.import_remote(user, @embed_url)
|
2018-06-07 00:28:18 -05:00
|
|
|
end
|
|
|
|
|
2014-02-12 14:55:44 -06:00
|
|
|
end
|