Created
March 9, 2011 05:29
-
-
Save namusyaka/861740 to your computer and use it in GitHub Desktop.
RSSReader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rss' | |
require 'net/http' | |
require 'uri' | |
require 'time' | |
Net::HTTP.version_1_2 | |
class RSSReader | |
@@http = Net::HTTP | |
def initialize(cachefile, target) | |
@cachefile = cachefile | |
file = File.open(@cachefile).readlines | |
@cache_time = file[0] | |
@cache = file[1..file.length] ? eval(file[1..file.length].join('')) : [] | |
@target = target | |
@time = Time.new | |
@updated = [] | |
end | |
attr_accessor :updated | |
def check | |
i = 0 | |
list = [] | |
@target.each do |a| | |
uri = URI.parse(a) | |
begin | |
body = recv(uri.host, uri.path, uri.port) | |
next if body.nil? | |
RSS::Parser.parse(body, true).items.each do |item| | |
hash = { | |
:title => item.title, | |
:description => item.description, | |
:link => item.link | |
} | |
list << hash | |
if @cache.include?(hash) | |
i += 1 | |
break | |
else | |
@updated << i | |
i += 1 | |
end | |
end | |
rescue | |
next | |
end | |
end | |
cachefile_write("#{@time}\n#{list.inspect}") | |
list | |
end | |
def cache | |
return @cache if @cache_time && Time.parse(@cache_time) + 1800 > @time | |
return nil | |
end | |
def proxy(addr, port) | |
@@http = @@http.Proxy(addr, port) | |
end | |
private | |
def cachefile_write(content) | |
loop do | |
begin | |
Dir.mkdir("rss") | |
begin | |
File.open(@cachefile, "w").write(content) | |
rescue | |
end | |
Dir.unlink("rss") | |
return | |
rescue | |
sleep 0.01 | |
end | |
end | |
end | |
def recv(domain, path, port = 80) | |
@@http.start(domain, port) { |h| return h.get(path).body} | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rss = RSSReader.new("cache.dat", File.open("list.dat").readlines) | |
list = rss.check | |
#第二引数に渡したRSSから更新のあったもののみ出力したい。 | |
rss.updated.each do |i| | |
puts list[i] | |
end | |
#キャッシュが有効か確認した後、RSSの名前のみ取り出して一覧表示。 | |
list = rss.cache || rss.check | |
list.each do |h| | |
puts h[:title] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment