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