2017-07-21 15:29:04 -04:00
|
|
|
require_dependency 'retrieve_title'
|
|
|
|
|
2017-07-19 15:08:54 -04:00
|
|
|
class InlineOneboxer
|
|
|
|
|
2017-07-21 15:29:04 -04:00
|
|
|
def initialize(urls, opts=nil)
|
2017-07-19 15:08:54 -04:00
|
|
|
@urls = urls
|
2017-07-21 15:29:04 -04:00
|
|
|
@opts = opts || {}
|
2017-07-19 15:08:54 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def process
|
2017-07-21 15:29:04 -04:00
|
|
|
@urls.map {|url| InlineOneboxer.lookup(url, @opts) }.compact
|
2017-07-19 15:08:54 -04:00
|
|
|
end
|
|
|
|
|
2017-07-21 15:29:04 -04:00
|
|
|
def self.purge(url)
|
|
|
|
Rails.cache.delete(cache_key(url))
|
2017-07-19 15:08:54 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.cache_lookup(url)
|
|
|
|
Rails.cache.read(cache_key(url))
|
|
|
|
end
|
|
|
|
|
2017-07-21 15:29:04 -04:00
|
|
|
def self.lookup(url, opts=nil)
|
|
|
|
opts ||= {}
|
|
|
|
|
|
|
|
unless opts[:skip_cache]
|
|
|
|
cached = cache_lookup(url)
|
|
|
|
return cached if cached.present?
|
|
|
|
end
|
2017-07-19 15:08:54 -04:00
|
|
|
|
|
|
|
if route = Discourse.route_for(url)
|
|
|
|
if route[:controller] == "topics" &&
|
|
|
|
route[:action] == "show" &&
|
2017-07-20 16:01:16 -04:00
|
|
|
topic = (Topic.where(id: route[:topic_id].to_i).first rescue nil)
|
2017-07-19 15:08:54 -04:00
|
|
|
|
2017-07-21 15:29:04 -04:00
|
|
|
return onebox_for(url, topic.title, opts) if Guardian.new.can_see?(topic)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
if whitelist = SiteSetting.inline_onebox_domains_whitelist
|
|
|
|
uri = URI(url) rescue nil
|
|
|
|
|
|
|
|
domains = whitelist.split('|')
|
|
|
|
if uri.present? &&
|
|
|
|
uri.hostname.present? &&
|
|
|
|
domains.include?(uri.hostname) &&
|
|
|
|
title = RetrieveTitle.crawl(url)
|
|
|
|
return onebox_for(url, title, opts)
|
2017-07-19 15:08:54 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2017-07-21 15:29:04 -04:00
|
|
|
def self.onebox_for(url, title, opts)
|
|
|
|
onebox = {
|
|
|
|
url: url,
|
|
|
|
title: Emoji.gsub_emoji_to_unicode(title)
|
|
|
|
}
|
|
|
|
unless opts[:skip_cache]
|
|
|
|
Rails.cache.write(cache_key(url), onebox, expires_in: 1.day)
|
|
|
|
end
|
|
|
|
|
|
|
|
onebox
|
|
|
|
end
|
|
|
|
|
2017-07-19 15:08:54 -04:00
|
|
|
def self.cache_key(url)
|
|
|
|
"inline_onebox:#{url}"
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|