Skip to content

Commit

Permalink
Ignore low-confidence CharlockHolmes guesses when parsing link cards (
Browse files Browse the repository at this point in the history
…mastodon#9510)

* Add failing test for windows-1251 link cards

* Ignore low-confidence CharlockHolmes guesses

Fixes mastodon#9466

* Fix no method error when charlock holmes cannot detect charset
  • Loading branch information
ClearlyClaire authored and hiyuki2578 committed Oct 2, 2019
1 parent 9cf0120 commit 0486c21
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
3 changes: 2 additions & 1 deletion app/services/fetch_link_card_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,8 @@ def attempt_opengraph
detector.strip_tags = true

guess = detector.detect(@html, @html_charset)
page = Nokogiri::HTML(@html, nil, guess&.fetch(:encoding, nil))
encoding = guess&.fetch(:confidence, 0).to_i > 60 ? guess&.fetch(:encoding, nil) : nil
page = Nokogiri::HTML(@html, nil, encoding)
player_url = meta_property(page, 'twitter:player')

if player_url && !bad_url?(Addressable::URI.parse(player_url))
Expand Down
17 changes: 17 additions & 0 deletions spec/fixtures/requests/windows-1251.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
HTTP/1.1 200 OK
server: nginx
date: Wed, 12 Dec 2018 13:14:03 GMT
content-type: text/html
content-length: 190
accept-ranges: bytes

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />
<title>����� �����</title>
</head>
<body>
<p>����� �����</p>
</body>
</html>
11 changes: 11 additions & 0 deletions spec/services/fetch_link_card_service_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
stub_request(:head, 'https://github.com/qbi/WannaCry').to_return(status: 404)
stub_request(:head, 'http://example.com/test-').to_return(status: 200, headers: { 'Content-Type' => 'text/html' })
stub_request(:get, 'http://example.com/test-').to_return(request_fixture('idn.txt'))
stub_request(:head, 'http://example.com/windows-1251').to_return(status: 200, headers: { 'Content-Type' => 'text/html' })
stub_request(:get, 'http://example.com/windows-1251').to_return(request_fixture('windows-1251.txt'))

subject.call(status)
end
Expand Down Expand Up @@ -57,6 +59,15 @@
end
end

context do
let(:status) { Fabricate(:status, text: 'Check out http://example.com/windows-1251') }

it 'works with windows-1251' do
expect(a_request(:get, 'http://example.com/windows-1251')).to have_been_made.at_least_once
expect(status.preview_cards.first.title).to eq('сэмпл текст')
end
end

context do
let(:status) { Fabricate(:status, text: 'テストhttp://example.com/日本語') }

Expand Down

0 comments on commit 0486c21

Please sign in to comment.