mirror of
https://github.com/discourse/discourse.git
synced 2024-11-25 08:43:25 +08:00
51 lines
1.2 KiB
Ruby
51 lines
1.2 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
module Onebox
|
|
module Engine
|
|
class HackernewsOnebox
|
|
include Engine
|
|
include LayoutSupport
|
|
include JSON
|
|
|
|
REGEX = %r{^https?://news\.ycombinator\.com/item\?id=(?<item_id>\d+)}
|
|
|
|
matches_regexp(REGEX)
|
|
|
|
# This is their official API: https://blog.ycombinator.com/hacker-news-api/
|
|
def url
|
|
"https://hacker-news.firebaseio.com/v0/item/#{match[:item_id]}.json"
|
|
end
|
|
|
|
private
|
|
|
|
def match
|
|
@match ||= @url.match(REGEX)
|
|
end
|
|
|
|
def data
|
|
return nil if %w[story comment].exclude?(raw["type"])
|
|
|
|
html_entities = HTMLEntities.new
|
|
data = {
|
|
link: @url,
|
|
title: Onebox::Helpers.truncate(raw["title"], 80),
|
|
favicon: "https://news.ycombinator.com/y18.gif",
|
|
timestamp: Time.at(raw["time"]).strftime("%-l:%M %p - %-d %b %Y"),
|
|
author: raw["by"],
|
|
}
|
|
|
|
data["description"] = html_entities.decode(
|
|
Onebox::Helpers.truncate(raw["text"], 400),
|
|
) if raw["text"]
|
|
|
|
if raw["type"] == "story"
|
|
data["data_1"] = raw["score"]
|
|
data["data_2"] = raw["descendants"]
|
|
end
|
|
|
|
data
|
|
end
|
|
end
|
|
end
|
|
end
|