- 1. リンク先を取得
1. リンク先を取得
リンク先を実際に通信して結果を判断するクラスが長くなったので、リンク先を編集する処理と実際に取得する処理にわけました。。
こちらは実際に取得する処理です。
=begin
外部リンク・ドメイン内リンク・イメージファイルは open してみる
=end
require('pry')
require('uri')
require('open-uri')
require('searchName')
require('exceptlog')
require('openuri')
class Fetch
def initialize()
end
def execute(sharp, uri, check)
begin
str = String(uri);
begin
puri = URI.parse(str)
rescue URI::InvalidURIError => error
return "InvalidURIError[#{error.message}]", check
rescue => error
exeptlog = ExceptLog.new
binding.pry
exeptlog.execute(self, error)
exit 1
end
#puts("puri.host[#{puri.host}]")
#binding.pry
if (puri.host == nil)
return "InvalidURIError", check
end
if ((str[-4, 4] == '.png') || # イメージなので存在の有無のみ
(str[-4, 4] == '.gif'))
html = open(uri).read
else
openuri = Openuri.new
html = openuri.execute(uri)
end
html.sub!(/^<!DOCTYPE html(.*)$/, '<!DOCTYPE html>')
doc = Nokogiri::HTML(html)
# 本サイトで不明なリンクは「検索」にたどり着く
if (doc.title == 'FreeBSDあれこれ - 検索')
# ただし、もともとのリンク先が /search/ の場合は、正常なのだ
if (str[-8,8] != '/search/')
return 'link error', check
end
end
if (sharp) # # つきのものはドキュメント内の id まで検索
search = SearchName.new
response = search.execute(uri, doc, '#'+sharp)
return response, check
end
rescue OpenURI::HTTPError => error
return "HTTPError[#{error.message}]", check
rescue SocketError => error
return "#{error.message}", check
rescue RuntimeError => error
if (error.message.include?('redirection forbidden'))
return 'redirection forbidden', check
elsif ("#{error.class}" == 'Net::OpenTimeout')
return 'Net::OpenTimeout', check
elsif ("#{error.class}" == 'Net::ReadTimeout')
return 'Net::ReadTimeout', check
else
exeptlog = ExceptLog.new
binding.pry
exeptlog.execute(self, error)
exit 1
end
rescue TypeError => error
if (error.message.include?('no implicit conversion'))
return 'no implicit conversion', check
elsif (error.message.include?('Net::OpenTimeout'))
return 'Net::OpenTimeout', check
else
exeptlog = ExceptLog.new
binding.pry
exeptlog.execute(self, error)
exit 1
end
rescue Net::ReadTimeout => error
return "#{error.message}", check
rescue OpenSSL::SSL::SSLError => error
return "#{error.message}", check
rescue EOFError => error
return 'end of file reached', check
rescue Errno::ECONNRESET => error
return 'Connection reset by peer', check
rescue Errno::ENOENT => error # No such file or directory
return 'No such file or directory', check
rescue Errno::EHOSTUNREACH => error
return 'Failed to open TCP connection', check
rescue Errno::ECONNREFUSED => error
return 'Connection refused', check
rescue Zlib::DataError => error
return 'Zlib::DataError', check
rescue => error
exeptlog = ExceptLog.new
binding.pry
exeptlog.execute(self, error)
exit 1
end
return 'OK', check
end
end
|