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
|
# File 'lib/link_thumbnail.rb', line 9
def thumbnail_url(url)
source = open(url).read
doc = Nokogiri.parse(source)
if element = doc.xpath('//meta[@property="og:image" and @content]').first
return element.attributes['content'].value
elsif element = doc.xpath('//link[@type="application/json+oembed" and @href]').first
oembed_json_response = fetch(element.attributes['href'].value)
json = JSON.parse(oembed_json_response)
if src = json['thumbnail_url']
return src
elsif json['type'] == 'photo'
return json['url']
end
elsif element = doc.xpath('//link[@type="text/xml+oembed" and @href]').first
oembed_xml_response = fetch(element.attributes['href'].value)
response = Nokogiri.parse(oembed_xml_response)
if thumbnail = response.xpath('/oembed/thumbnail_url').first
return thumbnail.content
elsif response.xpath('/oembed[type="photo" and url]').first
return response.xpath('/oembed/url').first.content
end
elsif element = doc.xpath('//img[@class="photo" and @src]').first
return element.attributes['src'].value
elsif readability_doc = Readability::Document.new(source)
if element = readability_doc.get_best_candidate
if img = element.xpath('//img[@src]').first
return img.attributes['src'].value
end
end
end
end
|