Skip to content

Commit

Permalink
Implement EmbedTagFilter
Browse files Browse the repository at this point in the history
  • Loading branch information
asonas committed Oct 4, 2022
1 parent 0447d56 commit 8f6fdc4
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
65 changes: 65 additions & 0 deletions models/article.rb
@@ -1,7 +1,9 @@
require 'aws-sdk-s3'
require 'redcarpet'
require 'html/pipeline'
require 'yaml'
require 'pry'

class Article
def self.all
r = []
Expand Down Expand Up @@ -92,6 +94,7 @@ def date
def rendered_body
pipeline = HTML::Pipeline.new(
[
EmbedTagFilter,
MarkdownFilter,
BlockquotesFilter,
ImageTagFilter,
Expand Down Expand Up @@ -148,6 +151,68 @@ def call
end
end

# markdown => html
# syntax e.g. `[embed:https://example.com/foo-bar]`
class EmbedTagFilter < HTML::Pipeline::TextFilter
REGEX = %r!\[embed:(https?:\/\/[\w\/:%#\$&\?\(\)~\.=\+\-]+)\]!
BUCKET_NAME = ENV["BUCKET_NAME"]
attr_accessor :url, :response, :client

def call
@client = Aws::S3::Client.new(region: "ap-northeast-1")
@text.match REGEX
@url = $1
if @url
fetch_meta_from_cache
render
end

@text
end

def render
b = binding
erb = ERB.new <<~EOF
<div class="embed">
<a href="<%= response["url"] %>">
<img src="<%= response["images"].first %>">
<div class="body">
<header><%= response["title"] %></header>
<div>
<p><%= response["description"] %></p>
</div>
</div>
</a>
</div>
EOF
@text.gsub!(REGEX, erb.result(b))
end

def fetch_meta_from_cache
object = client.get_object(bucket: BUCKET_NAME, key: "jsonlink-io/#{cache_filename}")
@response = JSON.parse(object.body.read)
rescue Aws::S3::Errors::NoSuchKey => e
fetch_meta
save_cache
end

def fetch_meta
@response = JSON.parse(
Net::HTTP.get(
URI.parse("https://jsonlink.io/api/extract?url=#{@url}")
)
)
end

def save_cache
client.put_object(bucket: BUCKET_NAME, key: "jsonlink-io/#{cache_filename}", body: response.to_json)
end

def cache_filename
Digest::SHA256.hexdigest @url
end
end

class BlockquotesFilter < HTML::Pipeline::Filter
def call
doc.search('blockquote').each do |e|
Expand Down
27 changes: 27 additions & 0 deletions source/stylesheets/site.css.scss
Expand Up @@ -21,6 +21,33 @@ body {
margin-bottom: 10px;
}

.embed {
border: 1px solid rgba(0, 0, 0, 0.1);
background-color: rgb(255, 255, 255);
border-radius: 6px;

a {
text-decoration: none;
}

img {
margin: 0;
}

header {
font-weight: bold;
}

.body {
padding: 10px 15px;

p {
font-size: 14px;
margin: 0;
}
}
}

p {
word-wrap: break-word;
}
Expand Down

0 comments on commit 8f6fdc4

Please sign in to comment.