# frozen_string_literal: true
module Onebox
module Engine
class GfycatOnebox
include Engine
include JSON
matches_regexp(/^https?:\/\/gfycat\.com\//)
always_https
def self.priority
# This engine should have priority over AllowlistedGenericOnebox.
1
end
def to_html
<<-HTML
HTML
end
def placeholder_html
<<-HTML
#{data[:name]}
HTML
end
private
def match
@match ||= @url.match(/^https?:\/\/gfycat\.com\/(gifs\/detail\/)?(?.+)/)
end
def nokogiri_page
@nokogiri_page ||= begin
response = Onebox::Helpers.fetch_response(url, 10) rescue nil
Nokogiri::HTML(response)
end
end
def get_og_data
og_data = {}
if json_string = nokogiri_page.at_css('script[type="application/ld+json"]')&.text
og_data = Onebox::Helpers.symbolize_keys(::MultiJson.load(json_string))
end
og_data
end
def data
og_data = get_og_data
response = {
name: match[:name],
title: og_data[:headline] || 'No Title',
author: og_data[:author],
url: @url
}
keywords = og_data[:keywords]&.split(',')
if keywords
response[:keywords] = keywords.map { |t| "##{t}" }.join(' ')
end
if og_data[:video]
content_url = ::Onebox::Helpers.normalize_url_for_output(og_data[:video][:contentUrl])
video_url = Pathname.new(content_url)
response[:webmUrl] = video_url.sub_ext(".webm").to_s
response[:mp4Url] = video_url.sub_ext(".mp4").to_s
thumbnail_url = ::Onebox::Helpers.normalize_url_for_output(og_data[:video][:thumbnailUrl])
response[:posterUrl] = thumbnail_url
response[:width] = og_data[:video][:width]
response[:height] = og_data[:video][:height]
end
response
end
end
end
end