-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatters.rb
63 lines (51 loc) · 2.06 KB
/
formatters.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def shorten(string, max = 60)
return string if string.length < max
return string.slice(0, max) + "…"
end
# Matches og['site_name'].downcase for the default matcher
blacklist_description = [ :imgur, :voat ]
whitelist_image = [ :imgur ]
# All formatters receive the following arguments
# (... , plain response body, formatter descriptor, original url)
# With ... depending on the rewriter type:
# html (default): ... = OpenGraph data, HTML title, Nokogiri parser
# json: ... = parsed JSON data
# text: ... = <nothing>
{
# Default matcher for HTML
"" => Proc.new do |og, title|
unless og.nil?
site = og['site_name'].downcase.to_sym unless og['site_name'].nil?
title = og['title']
title << " [#{shorten og['description']}]" if og['description'] && !blacklist_description.include?(site)
title << " -> #{og['image']}" if og['image'] && whitelist_image.include?(site)
end
title
end,
# Note: "foo.bar.baz" will search for the matchers "foo.bar.baz", "bar.baz", "baz", "" (in this order)
"youtube.com" => Proc.new{|og| og['title'] },
"twitter.com" => Proc.new{|og| "#{og['title'].gsub(/ auf Twitter$/, '')}: #{og['description']}" },
"reddit.com" => Proc.new do |og|
description = ''
if og['description']
stripped = og['description'].gsub(/(?:\*\*|''|__)/, '').gsub(/\[([^\]]+)\]\([^)]*\)/, '\1')
description = " [#{shorten stripped}]"
end
"#{og['title']}#{description}"
end,
# JSON formatters
"4chan" => Proc.new do |json, response, descriptor, url|
uri = URI(url)
frag = uri.fragment
board = uri.path.match(/^\/([^\/]+)\//)[1]
post = json['posts'].first
if !frag.nil? && !frag.empty? && frag.start_with?('p')
no = frag[1..-1].to_i
post = json['posts'].find(post){ |post| post['no'] == no }
end
suffix = ''
suffix = " -> https://i.4cdn.org/#{board}/#{post['tim']}#{post['ext']}" if post['tim']
content = HTMLEntities.new.decode post['com'].gsub('<br>', ' ').gsub(/<[^>]*>/, '')
"“#{shorten(content, 120)}”#{suffix}"
end
}