fblee-feedzirra 0.0.17

Sign up to get free protection for your applications and to get access to all the features.
data/README.textile ADDED
@@ -0,0 +1,196 @@
1
+ h1. Feedzirra
2
+
3
+ "http://github.com/pauldix/feedzirra/tree/master":http://github.com/pauldix/feedzirra/tree/master
4
+
5
+ I'd like feedback on the api and any bugs encountered on feeds in the wild. I've set up a "google group here":http://groups.google.com/group/feedzirra.
6
+
7
+ h2. Summary
8
+
9
+ A feed fetching and parsing library that treats the internet like Godzilla treats Japan: it dominates and eats all.
10
+
11
+ h2. Description
12
+
13
+ Feedzirra is a feed library that is designed to get and update many feeds as quickly as possible. This includes using libcurl-multi through the "taf2-curb":http://github.com/taf2/curb/tree/master gem for faster http gets, and libxml through "nokogiri":http://github.com/tenderlove/nokogiri/tree/master and "sax-machine":http://github.com/pauldix/sax-machine/tree/master for faster parsing.
14
+
15
+ Once you have fetched feeds using Feedzirra, they can be updated using the feed objects. Feedzirra automatically inserts etag and last-modified information from the http response headers to lower bandwidth usage, eliminate unnecessary parsing, and make things speedier in general.
16
+
17
+ Another feature present in Feedzirra is the ability to create callback functions that get called "on success" and "on failure" when getting a feed. This makes it easy to do things like log errors or update data stores.
18
+
19
+ The fetching and parsing logic have been decoupled so that either of them can be used in isolation if you'd prefer not to use everything that Feedzirra offers. However, the code examples below use helper methods in the Feed class that put everything together to make things as simple as possible.
20
+
21
+ The final feature of Feedzirra is the ability to define custom parsing classes. In truth, Feedzirra could be used to parse much more than feeds. Microformats, page scraping, and almost anything else are fair game.
22
+
23
+ h2. Installation
24
+
25
+ For now Feedzirra exists only on github. It also has a few gem requirements that are only on github. Before you start you need to have "libcurl":http://curl.haxx.se/ and "libxml":http://xmlsoft.org/ installed. If you're on Leopard you have both. Otherwise, you'll need to grab them. Once you've got those libraries, these are the gems that get used: nokogiri, pauldix-sax-machine, taf2-curb (note that this is a fork that lives on github and not the Ruby Forge version of curb), and pauldix-feedzirra. The feedzirra gemspec has all the dependencies so you should be able to get up and running with the standard github gem install routine:
26
+
27
+ <pre>
28
+ gem sources -a http://gems.github.com # if you haven't already
29
+ gem install pauldix-feedzirra
30
+ </pre>
31
+
32
+ <b>NOTE:</b>Some people have been reporting a few issues related to installation. First, the Ruby Forge version of curb is not what you want. It will not work. Nor will the curl-multi gem that lives on Ruby Forge. You have to get the "taf2-curb":http://github.com/taf2/curb/tree/master fork installed.
33
+
34
+ If you see this error when doing a require:
35
+ <pre>
36
+ /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- curb_core (LoadError)
37
+ </pre>
38
+ It means that the taf2-curb gem didn't build correctly. To resolve this you can do a git clone git://github.com/taf2/curb.git then run rake gem in the curb directory, then sudo gem install pkg/curb-0.2.4.0.gem. After that you should be good.
39
+
40
+ If you see something like this when trying to run it:
41
+ <pre>
42
+ NoMethodError: undefined method `on_success' for #<Curl::Easy:0x1182724>
43
+ from ./lib/feedzirra/feed.rb:88:in `add_url_to_multi'
44
+ </pre>
45
+ This means that you are requiring curl-multi or the Ruby Forge version of Curb somewhere. You can't use those and need to get the taf2 version up and running.
46
+
47
+ If you're on Debian or Ubuntu and getting errors while trying to install the taf2-curb gem, it could be because you don't have the latest version of libcurl installed. Do this to fix:
48
+ <pre>
49
+ sudo apt-get install libcurl4-gnutls-dev
50
+ </pre>
51
+
52
+ Another problem could be if you are running Mac Ports and you have libcurl installed through there. You need to uninstall it for curb to work! The version in Mac Ports is old and doesn't play nice with curb. If you're running Leopard, you can just uninstall and you should be golden. If you're on an older version of OS X, you'll then need to "download curl":http://curl.haxx.se/download.html and build from source. Then you'll have to install the taf2-curb gem again. You might have to perform the step above.
53
+
54
+ If you're still having issues, please let me know on the mailing list. Also, "Todd Fisher (taf2)":http://github.com/taf2 is working on fixing the gem install. Please send him a full error report.
55
+
56
+ h2. Usage
57
+
58
+ "A gist of the following code":http://gist.github.com/57285
59
+ <pre>
60
+ require 'feedzirra'
61
+
62
+ # fetching a single feed
63
+ feed = Feedzirra::Feed.fetch_and_parse("http://feeds.feedburner.com/PaulDixExplainsNothing")
64
+
65
+ # feed and entries accessors
66
+ feed.title # => "Paul Dix Explains Nothing"
67
+ feed.url # => "http://www.pauldix.net"
68
+ feed.feed_url # => "http://feeds.feedburner.com/PaulDixExplainsNothing"
69
+ feed.etag # => "GunxqnEP4NeYhrqq9TyVKTuDnh0"
70
+ feed.last_modified # => Sat Jan 31 17:58:16 -0500 2009 # it's a Time object
71
+
72
+ entry = feed.entries.first
73
+ entry.title # => "Ruby Http Client Library Performance"
74
+ entry.url # => "http://www.pauldix.net/2009/01/ruby-http-client-library-performance.html"
75
+ entry.author # => "Paul Dix"
76
+ entry.summary # => "..."
77
+ entry.content # => "..."
78
+ entry.published # => Thu Jan 29 17:00:19 UTC 2009 # it's a Time object
79
+ entry.categories # => ["...", "..."]
80
+
81
+ # sanitizing an entry's content
82
+ entry.title.sanitize # => returns the title with harmful stuff escaped
83
+ entry.author.sanitize # => returns the author with harmful stuff escaped
84
+ entry.content.sanitize # => returns the content with harmful stuff escaped
85
+ entry.content.sanitize! # => returns content with harmful stuff escaped and replaces original (also exists for author and title)
86
+ entry.sanitize! # => sanitizes the entry's title, author, and content in place (as in, it changes the value to clean versions)
87
+ feed.sanitize_entries! # => sanitizes all entries in place
88
+
89
+ # updating a single feed
90
+ updated_feed = Feedzirra::Feed.update(feed)
91
+
92
+ # an updated feed has the following extra accessors
93
+ updated_feed.updated? # returns true if any of the feed attributes have been modified. will return false if only new entries
94
+ updated_feed.new_entries # a collection of the entry objects that are newer than the latest in the feed before update
95
+
96
+ # fetching multiple feeds
97
+ feed_urls = ["http://feeds.feedburner.com/PaulDixExplainsNothing", "http://feeds.feedburner.com/trottercashion"]
98
+ feeds = Feedzirra::Feed.fetch_and_parse(feed_urls)
99
+
100
+ # feeds is now a hash with the feed_urls as keys and the parsed feed objects as values. If an error was thrown
101
+ # there will be a Fixnum of the http response code instead of a feed object
102
+
103
+ # updating multiple feeds. it expects a collection of feed objects
104
+ updated_feeds = Feedzirra::Feed.update(feeds.values)
105
+
106
+ # defining custom behavior on failure or success. note that a return status of 304 (not updated) will call the on_success handler
107
+ feed = Feedzirra::Feed.fetch_and_parse("http://feeds.feedburner.com/PaulDixExplainsNothing",
108
+ :on_success => lambda {|feed| puts feed.title },
109
+ :on_failure => lambda {|url, response_code, response_header, response_body| puts response_body })
110
+ # if a collection was passed into fetch_and_parse, the handlers will be called for each one
111
+
112
+ # the behavior for the handlers when using Feedzirra::Feed.update is slightly different. The feed passed into on_success will be
113
+ # the updated feed with the standard updated accessors. on failure it will be the original feed object passed into update
114
+
115
+ # You can add custom parsing to the feed entry classes. Say you want the wfw:comments fields in an entry
116
+ Feedzirra::Feed.add_common_feed_entry_element("wfw:commentRss", :as => :comment_rss)
117
+ # The arguments are the same as the SAXMachine arguments for the element method. For more example usage look at the RSSEntry and
118
+ # AtomEntry classes. Now you can access those in an atom feed:
119
+ Feedzirra::Feed.parse(some_atom_xml).entries.first.comment_rss_ # => wfw:commentRss is now parsed!
120
+
121
+
122
+ # You can also define your own parsers and add them to the ones Feedzirra knows about. Here's an example that adds
123
+ # ITunesRSS parsing. It's included in the library, but not part of Feedzirra by default because some of the field names
124
+ # differ from other classes, thus breaking normalization.
125
+ Feedzirra::Feed.add_feed_class(ITunesRSS) # now all feeds will be checked to see if they match ITunesRSS before others
126
+
127
+ # You can also access http basic auth feeds. Unfortunately, you can't get to these inside of a bulk get of a bunch of feeds.
128
+ # You'll have to do it on its own like so:
129
+ Feedzirra::Feed.fetch_and_parse(some_url, :http_authentication => ["myusername", "mypassword"])
130
+
131
+ # Defining custom parsers
132
+ # TODO: the functionality is here, just write some good examples that show how to do this
133
+ </pre>
134
+
135
+ h2. Benchmarks
136
+
137
+ One of the goals of Feedzirra is speed. This includes not only parsing, but fetching multiple feeds as quickly as possible. I ran a benchmark getting 20 feeds 10 times using Feedzirra, rFeedParser, and FeedNormalizer. For more details the "benchmark code can be found in the project in spec/benchmarks/feedzirra_benchmarks.rb":http://github.com/pauldix/feedzirra/blob/7fb5634c5c16e9c6ec971767b462c6518cd55f5d/spec/benchmarks/feedzirra_benchmarks.rb
138
+ <pre>
139
+ feedzirra 5.170000 1.290000 6.460000 ( 18.917796)
140
+ rfeedparser 104.260000 12.220000 116.480000 (244.799063)
141
+ feed-normalizer 66.250000 4.010000 70.260000 (191.589862)
142
+ </pre>
143
+ The result of that benchmark is a bit sketchy because of the network variability. Running 10 times against the same 20 feeds was meant to smooth some of that out. However, there is also a "benchmark comparing parsing speed in spec/benchmarks/parsing_benchmark.rb":http://github.com/pauldix/feedzirra/blob/7fb5634c5c16e9c6ec971767b462c6518cd55f5d/spec/benchmarks/parsing_benchmark.rb on an atom feed.
144
+ <pre>
145
+ feedzirra 0.500000 0.030000 0.530000 ( 0.658744)
146
+ rfeedparser 8.400000 1.110000 9.510000 ( 11.839827)
147
+ feed-normalizer 5.980000 0.160000 6.140000 ( 7.576140)
148
+ </pre>
149
+ There's also a "benchmark that shows the results of using Feedzirra to perform updates on feeds":http://github.com/pauldix/feedzirra/blob/45d64319544c61a4c9eb9f7f825c73b9f9030cb3/spec/benchmarks/updating_benchmarks.rb you've already pulled in. I tested against 179 feeds. The first is the initial pull and the second is an update 65 seconds later. I'm not sure how many of them support etag and last-modified, so performance may be better or worse depending on what feeds you're requesting.
150
+ <pre>
151
+ feedzirra fetch and parse 4.010000 0.710000 4.720000 ( 15.110101)
152
+ feedzirra update 0.660000 0.280000 0.940000 ( 5.152709)
153
+ </pre>
154
+
155
+ h2. Next Steps
156
+
157
+ This thing needs to hammer on many different feeds in the wild. I'm sure there will be bugs. I want to find them and crush them. I didn't bother using the test suite for feedparser. i wanted to start fresh.
158
+
159
+ Here are some more specific TODOs.
160
+ * Fix the iTunes parser so things are normalized again
161
+ * Fix the Zlib deflate error
162
+ * Fix this error: http://github.com/inbox/70508
163
+ * Convert to use Typhoeus instead of taf2-curb
164
+ * Make the entries parse all link fields
165
+ * Make a feedzirra-rails gem to integrate feedzirra seamlessly with Rails and ActiveRecord.
166
+ * Create a super sweet DSL for defining new parsers.
167
+ * Test against Ruby 1.9.1 and fix any bugs.
168
+ * Clean up the fetching code inside feed.rb so it doesn't suck so hard.
169
+ * Readdress how feeds determine if they can parse a document. Maybe I should use namespaces instead?
170
+
171
+ h2. LICENSE
172
+
173
+ (The MIT License)
174
+
175
+ Copyright (c) 2009:
176
+
177
+ "Paul Dix":http://pauldix.net
178
+
179
+ Permission is hereby granted, free of charge, to any person obtaining
180
+ a copy of this software and associated documentation files (the
181
+ 'Software'), to deal in the Software without restriction, including
182
+ without limitation the rights to use, copy, modify, merge, publish,
183
+ distribute, sublicense, and/or sell copies of the Software, and to
184
+ permit persons to whom the Software is furnished to do so, subject to
185
+ the following conditions:
186
+
187
+ The above copyright notice and this permission notice shall be
188
+ included in all copies or substantial portions of the Software.
189
+
190
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
191
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
192
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
193
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
194
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
195
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
196
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,56 @@
1
+ require "spec"
2
+ require "spec/rake/spectask"
3
+ require 'rake/rdoctask'
4
+ require 'lib/feedzirra.rb'
5
+
6
+ # Grab recently touched specs
7
+ def recent_specs(touched_since)
8
+ recent_specs = FileList['app/**/*'].map do |path|
9
+
10
+ if File.mtime(path) > touched_since
11
+ spec = File.join('spec', File.dirname(path).split("/")[1..-1].join('/'),
12
+ "#{File.basename(path, ".*")}_spec.rb")
13
+ spec if File.exists?(spec)
14
+ end
15
+ end.compact
16
+
17
+ recent_specs += FileList['spec/**/*_spec.rb'].select do |path|
18
+ File.mtime(path) > touched_since
19
+ end
20
+ recent_specs.uniq
21
+ end
22
+
23
+ desc "Run all the tests"
24
+ task :default => :spec
25
+
26
+ # Tasks
27
+ Spec::Rake::SpecTask.new do |t|
28
+ t.spec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""]
29
+ t.spec_files = FileList['spec/**/*_spec.rb']
30
+ end
31
+
32
+ desc 'Run recent specs'
33
+ Spec::Rake::SpecTask.new("spec:recent") do |t|
34
+ t.spec_opts = ["--format","specdoc","--color"]
35
+ t.spec_files = recent_specs(Time.now - 600) # 10 min.
36
+ end
37
+
38
+ Spec::Rake::SpecTask.new('spec:rcov') do |t|
39
+ t.spec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""]
40
+ t.spec_files = FileList['spec/**/*_spec.rb']
41
+ t.rcov = true
42
+ t.rcov_opts = ['--exclude', 'spec,/usr/lib/ruby,/usr/local,/var/lib,/Library', '--text-report']
43
+ end
44
+
45
+ Rake::RDocTask.new do |rd|
46
+ rd.title = 'Feedzirra'
47
+ rd.rdoc_dir = 'rdoc'
48
+ rd.rdoc_files.include('README.rdoc', 'lib/feedzirra.rb', 'lib/feedzirra/**/*.rb')
49
+ rd.options = ["--quiet", "--opname", "index.html", "--line-numbers", "--inline-source", '--main', 'README.rdoc']
50
+ end
51
+
52
+ task :install do
53
+ rm_rf "*.gem"
54
+ puts `gem build feedzirra.gemspec`
55
+ puts `sudo gem install feedzirra-#{Feedzirra::VERSION}.gem`
56
+ end
@@ -0,0 +1,21 @@
1
+ # Date code pulled from:
2
+ # Ruby Cookbook by Lucas Carlson and Leonard Richardson
3
+ # Published by O'Reilly
4
+ # ISBN: 0-596-52369-6
5
+ class Date
6
+ def feed_utils_to_gm_time
7
+ feed_utils_to_time(new_offset, :gm)
8
+ end
9
+
10
+ def feed_utils_to_local_time
11
+ feed_utils_to_time(new_offset(DateTime.now.offset-offset), :local)
12
+ end
13
+
14
+ private
15
+ def feed_utils_to_time(dest, method)
16
+ #Convert a fraction of a day to a number of microseconds
17
+ usec = (dest.sec_fraction * 60 * 60 * 24 * (10**6)).to_i
18
+ Time.send(method, dest.year, dest.month, dest.day, dest.hour, dest.min,
19
+ dest.sec, usec)
20
+ end
21
+ end
@@ -0,0 +1,9 @@
1
+ class String
2
+ def sanitize!
3
+ self.replace(sanitize)
4
+ end
5
+
6
+ def sanitize
7
+ Dryopteris.sanitize(self)
8
+ end
9
+ end
@@ -0,0 +1,357 @@
1
+ require 'uri'
2
+
3
+ module Feedzirra
4
+ class NoParserAvailable < StandardError; end
5
+
6
+ class Feed
7
+ USER_AGENT = "feedzirra http://github.com/pauldix/feedzirra/tree/master"
8
+
9
+ # Takes a raw XML feed and attempts to parse it. If no parser is available a Feedzirra::NoParserAvailable exception is raised.
10
+ #
11
+ # === Parameters
12
+ # [xml<String>] The XML that you would like parsed.
13
+ # === Returns
14
+ # An instance of the determined feed type. By default a Feedzirra::Atom, Feedzirra::AtomFeedBurner, Feedzirra::RDF, or Feedzirra::RSS object.
15
+ # === Raises
16
+ # Feedzirra::NoParserAvailable : If no valid parser classes could be found for the feed.
17
+ def self.parse(xml)
18
+ if parser = determine_feed_parser_for_xml(xml)
19
+ parser.parse(xml)
20
+ else
21
+ raise NoParserAvailable.new("No valid parser for XML.")
22
+ end
23
+ end
24
+
25
+ # Determines the correct parser class to use for parsing the feed.
26
+ #
27
+ # === Parameters
28
+ # [xml<String>] The XML that you would like determine the parser for.
29
+ # === Returns
30
+ # The class name of the parser that can handle the XML.
31
+ def self.determine_feed_parser_for_xml(xml)
32
+ start_of_doc = xml.slice(0, 2000)
33
+ feed_classes.detect {|klass| klass.able_to_parse?(start_of_doc)}
34
+ end
35
+
36
+ # Adds a new feed parsing class that will be used for parsing.
37
+ #
38
+ # === Parameters
39
+ # [klass<Constant>] The class/constant that you want to register.
40
+ # === Returns
41
+ # A updated array of feed parser class names.
42
+ def self.add_feed_class(klass)
43
+ feed_classes.unshift klass
44
+ end
45
+
46
+ # Provides a list of registered feed parsing classes.
47
+ #
48
+ # === Returns
49
+ # A array of class names.
50
+ def self.feed_classes
51
+ @feed_classes ||= [Feedzirra::Parser::RSS, Feedzirra::Parser::AtomFeedBurner, Feedzirra::Parser::Atom]
52
+ end
53
+
54
+ # Makes all entry types look for the passed in element to parse. This is actually just a call to
55
+ # element (a SAXMachine call) in the class
56
+ #
57
+ # === Parameters
58
+ # [element_tag<String>]
59
+ # [options<Hash>] Valid keys are same as with SAXMachine
60
+ def self.add_common_feed_entry_element(element_tag, options = {})
61
+ # need to think of a better way to do this. will break for people who want this behavior
62
+ # across their added classes
63
+ feed_classes.map{|k| eval("#{k}Entry") }.each do |klass|
64
+ klass.send(:element, element_tag, options)
65
+ end
66
+ end
67
+
68
+ # Fetches and returns the raw XML for each URL provided.
69
+ #
70
+ # === Parameters
71
+ # [urls<String> or <Array>] A single feed URL, or an array of feed URLs.
72
+ # [options<Hash>] Valid keys for this argument as as followed:
73
+ # :user_agent - String that overrides the default user agent.
74
+ # :if_modified_since - Time object representing when the feed was last updated.
75
+ # :if_none_match - String that's normally an etag for the request that was stored previously.
76
+ # :on_success - Block that gets executed after a successful request.
77
+ # :on_failure - Block that gets executed after a failed request.
78
+ # === Returns
79
+ # A String of XML if a single URL is passed.
80
+ #
81
+ # A Hash if multiple URL's are passed. The key will be the URL, and the value the XML.
82
+ def self.fetch_raw(urls, options = {})
83
+ url_queue = [*urls]
84
+ multi = Curl::Multi.new
85
+ responses = {}
86
+ url_queue.each do |url|
87
+ easy = Curl::Easy.new(url) do |curl|
88
+ curl.headers["User-Agent"] = (options[:user_agent] || USER_AGENT)
89
+ curl.headers["If-Modified-Since"] = options[:if_modified_since].httpdate if options.has_key?(:if_modified_since)
90
+ curl.headers["If-None-Match"] = options[:if_none_match] if options.has_key?(:if_none_match)
91
+ curl.headers["Accept-encoding"] = 'gzip, deflate' if options.has_key?(:compress)
92
+ curl.follow_location = true
93
+ curl.userpwd = options[:http_authentication].join(':') if options.has_key?(:http_authentication)
94
+
95
+ curl.max_redirects = options[:max_redirects] if options[:max_redirects]
96
+ curl.timeout = options[:timeout] if options[:timeout]
97
+
98
+ curl.on_success do |c|
99
+ responses[url] = decode_content(c)
100
+ end
101
+ curl.on_failure do |c, err|
102
+ responses[url] = c.response_code
103
+ end
104
+ end
105
+ multi.add(easy)
106
+ end
107
+
108
+ multi.perform
109
+ urls.is_a?(String) ? responses.values.first : responses
110
+ end
111
+
112
+ # Fetches and returns the parsed XML for each URL provided.
113
+ #
114
+ # === Parameters
115
+ # [urls<String> or <Array>] A single feed URL, or an array of feed URLs.
116
+ # [options<Hash>] Valid keys for this argument as as followed:
117
+ # * :user_agent - String that overrides the default user agent.
118
+ # * :if_modified_since - Time object representing when the feed was last updated.
119
+ # * :if_none_match - String, an etag for the request that was stored previously.
120
+ # * :on_success - Block that gets executed after a successful request.
121
+ # * :on_failure - Block that gets executed after a failed request.
122
+ # === Returns
123
+ # A Feed object if a single URL is passed.
124
+ #
125
+ # A Hash if multiple URL's are passed. The key will be the URL, and the value the Feed object.
126
+ def self.fetch_and_parse(urls, options = {})
127
+ url_queue = [*urls]
128
+ multi = Curl::Multi.new
129
+ responses = {}
130
+
131
+ # I broke these down so I would only try to do 30 simultaneously because
132
+ # I was getting weird errors when doing a lot. As one finishes it pops another off the queue.
133
+ url_queue.slice!(0, 30).each do |url|
134
+ add_url_to_multi(multi, url, url_queue, responses, options)
135
+ end
136
+
137
+ multi.perform
138
+ return urls.is_a?(String) ? responses.values.first : responses
139
+ end
140
+
141
+ # Decodes the XML document if it was compressed.
142
+ #
143
+ # === Parameters
144
+ # [curl_request<Curl::Easy>] The Curl::Easy response object from the request.
145
+ # === Returns
146
+ # A decoded string of XML.
147
+ def self.decode_content(c)
148
+ if c.header_str.match(/Content-Encoding: gzip/)
149
+ begin
150
+ gz = Zlib::GzipReader.new(StringIO.new(c.body_str))
151
+ xml = gz.read
152
+ gz.close
153
+ rescue Zlib::GzipFile::Error
154
+ # Maybe this is not gzipped?
155
+ xml = c.body_str
156
+ end
157
+ elsif c.header_str.match(/Content-Encoding: deflate/)
158
+ xml = Zlib::Inflate.inflate(c.body_str)
159
+ else
160
+ xml = c.body_str
161
+ end
162
+
163
+ # if we retrieved a web page, rather than RSS, look for a linked RSS feed
164
+ if c.header_str.match(/Content-Type: text\/html/)
165
+ html = c.body_str
166
+ # parse the web page for the URL of an embedded RSS feed
167
+ parsed_page = WebPage.parse(html)
168
+
169
+ if !parsed_page.nil? && !parsed_page.feed_url.nil?
170
+
171
+ # If the extracted URL is relative to the web page URL, create an absolute
172
+ # URL we can use
173
+ unless parsed_page.feed_url =~ /:\/\//
174
+ # parse the URL of the web page that was retrieved
175
+ uri = URI.parse(c.last_effective_url)
176
+ # reconstruct a feed URL
177
+ parsed_page.feed_url = uri.scheme + '://' + uri.host + parsed_page.feed_url
178
+ end
179
+
180
+ # re-use the same curl instance that generated this response, so that
181
+ # any calling context can pick up on things like last_effective_url from it
182
+ c.url = parsed_page.feed_url
183
+ c.perform
184
+ end
185
+ xml = c.body_str
186
+ end
187
+
188
+ xml
189
+ end
190
+
191
+ # Updates each feed for each Feed object provided.
192
+ #
193
+ # === Parameters
194
+ # [feeds<Feed> or <Array>] A single feed object, or an array of feed objects.
195
+ # [options<Hash>] Valid keys for this argument as as followed:
196
+ # * :user_agent - String that overrides the default user agent.
197
+ # * :on_success - Block that gets executed after a successful request.
198
+ # * :on_failure - Block that gets executed after a failed request.
199
+ # === Returns
200
+ # A updated Feed object if a single URL is passed.
201
+ #
202
+ # A Hash if multiple Feeds are passed. The key will be the URL, and the value the updated Feed object.
203
+ def self.update(feeds, options = {})
204
+ feed_queue = [*feeds]
205
+ multi = Curl::Multi.new
206
+ responses = {}
207
+
208
+ feed_queue.slice!(0, 30).each do |feed|
209
+ add_feed_to_multi(multi, feed, feed_queue, responses, options)
210
+ end
211
+
212
+ multi.perform
213
+ responses.size == 1 ? responses.values.first : responses.values
214
+ end
215
+
216
+ # An abstraction for adding a feed by URL to the passed Curb::multi stack.
217
+ #
218
+ # === Parameters
219
+ # [multi<Curl::Multi>] The Curl::Multi object that the request should be added too.
220
+ # [url<String>] The URL of the feed that you would like to be fetched.
221
+ # [url_queue<Array>] An array of URLs that are queued for request.
222
+ # [responses<Hash>] Existing responses that you want the response from the request added to.
223
+ # [feeds<String> or <Array>] A single feed object, or an array of feed objects.
224
+ # [options<Hash>] Valid keys for this argument as as followed:
225
+ # * :user_agent - String that overrides the default user agent.
226
+ # * :on_success - Block that gets executed after a successful request.
227
+ # * :on_failure - Block that gets executed after a failed request.
228
+ # === Returns
229
+ # The updated Curl::Multi object with the request details added to it's stack.
230
+ def self.add_url_to_multi(multi, url, url_queue, responses, options)
231
+ easy = Curl::Easy.new(url) do |curl|
232
+ curl.headers["User-Agent"] = (options[:user_agent] || USER_AGENT)
233
+ curl.headers["If-Modified-Since"] = options[:if_modified_since].httpdate if options.has_key?(:if_modified_since)
234
+ curl.headers["If-None-Match"] = options[:if_none_match] if options.has_key?(:if_none_match)
235
+ curl.headers["Accept-encoding"] = 'gzip, deflate' if options.has_key?(:compress)
236
+ curl.follow_location = true
237
+ curl.userpwd = options[:http_authentication].join(':') if options.has_key?(:http_authentication)
238
+
239
+ curl.max_redirects = options[:max_redirects] if options[:max_redirects]
240
+ curl.timeout = options[:timeout] if options[:timeout]
241
+
242
+ curl.on_success do |c|
243
+ add_url_to_multi(multi, url_queue.shift, url_queue, responses, options) unless url_queue.empty?
244
+ xml = decode_content(c)
245
+ klass = determine_feed_parser_for_xml(xml)
246
+
247
+ if klass
248
+ begin
249
+ feed = klass.parse(xml)
250
+ feed.feed_url = c.last_effective_url
251
+ feed.etag = etag_from_header(c.header_str)
252
+ feed.last_modified = last_modified_from_header(c.header_str)
253
+ responses[url] = feed
254
+ options[:on_success].call(url, feed) if options.has_key?(:on_success)
255
+ rescue Exception => e
256
+ options[:on_failure].call(url, c.response_code, c.header_str, c.body_str) if options.has_key?(:on_failure)
257
+ end
258
+ else
259
+ # puts "Error determining parser for #{url} - #{c.last_effective_url}"
260
+ if options.has_key?(:on_failure)
261
+ options[:on_failure].call(url, c.response_code, c.header_str, c.body_str)
262
+ else
263
+ # this will unfortunately fail the whole 'multi', so it's not really useable
264
+ url_message = url
265
+ url_message += "- #{c.last_effective_url}" unless url == c.last_effective_url
266
+ raise NoParserAvailable.new("No valid parser for #{url_message}")
267
+ end
268
+ end
269
+ end
270
+
271
+ curl.on_failure do |c, err|
272
+ add_url_to_multi(multi, url_queue.shift, url_queue, responses, options) unless url_queue.empty?
273
+ responses[url] = c.response_code
274
+ options[:on_failure].call(url, c.response_code, c.header_str, c.body_str) if options.has_key?(:on_failure)
275
+ end
276
+ end
277
+ multi.add(easy)
278
+ end
279
+
280
+ # An abstraction for adding a feed by a Feed object to the passed Curb::multi stack.
281
+ #
282
+ # === Parameters
283
+ # [multi<Curl::Multi>] The Curl::Multi object that the request should be added too.
284
+ # [feed<Feed>] A feed object that you would like to be fetched.
285
+ # [url_queue<Array>] An array of feed objects that are queued for request.
286
+ # [responses<Hash>] Existing responses that you want the response from the request added to.
287
+ # [feeds<String>] or <Array> A single feed object, or an array of feed objects.
288
+ # [options<Hash>] Valid keys for this argument as as followed:
289
+ # * :user_agent - String that overrides the default user agent.
290
+ # * :on_success - Block that gets executed after a successful request.
291
+ # * :on_failure - Block that gets executed after a failed request.
292
+ # === Returns
293
+ # The updated Curl::Multi object with the request details added to it's stack.
294
+ def self.add_feed_to_multi(multi, feed, feed_queue, responses, options)
295
+ easy = Curl::Easy.new(feed.feed_url) do |curl|
296
+ curl.headers["User-Agent"] = (options[:user_agent] || USER_AGENT)
297
+ curl.headers["If-Modified-Since"] = feed.last_modified.httpdate if feed.last_modified
298
+ curl.headers["If-None-Match"] = feed.etag if feed.etag
299
+ curl.userpwd = options[:http_authentication].join(':') if options.has_key?(:http_authentication)
300
+ curl.follow_location = true
301
+
302
+ curl.max_redirects = options[:max_redirects] if options[:max_redirects]
303
+ curl.timeout = options[:timeout] if options[:timeout]
304
+
305
+ curl.on_success do |c|
306
+ begin
307
+ add_feed_to_multi(multi, feed_queue.shift, feed_queue, responses, options) unless feed_queue.empty?
308
+ updated_feed = Feed.parse(c.body_str)
309
+ updated_feed.feed_url = c.last_effective_url
310
+ updated_feed.etag = etag_from_header(c.header_str)
311
+ updated_feed.last_modified = last_modified_from_header(c.header_str)
312
+ feed.update_from_feed(updated_feed)
313
+ responses[feed.feed_url] = feed
314
+ options[:on_success].call(feed) if options.has_key?(:on_success)
315
+ rescue Exception => e
316
+ options[:on_failure].call(feed, c.response_code, c.header_str, c.body_str) if options.has_key?(:on_failure)
317
+ end
318
+ end
319
+
320
+ curl.on_failure do |c, err|
321
+ add_feed_to_multi(multi, feed_queue.shift, feed_queue, responses, options) unless feed_queue.empty?
322
+ response_code = c.response_code
323
+ if response_code == 304 # it's not modified. this isn't an error condition
324
+ responses[feed.feed_url] = feed
325
+ options[:on_success].call(feed) if options.has_key?(:on_success)
326
+ else
327
+ responses[feed.url] = c.response_code
328
+ options[:on_failure].call(feed, c.response_code, c.header_str, c.body_str) if options.has_key?(:on_failure)
329
+ end
330
+ end
331
+ end
332
+ multi.add(easy)
333
+ end
334
+
335
+ # Determines the etag from the request headers.
336
+ #
337
+ # === Parameters
338
+ # [header<String>] Raw request header returned from the request
339
+ # === Returns
340
+ # A string of the etag or nil if it cannot be found in the headers.
341
+ def self.etag_from_header(header)
342
+ header =~ /.*ETag:\s(.*)\r/
343
+ $1
344
+ end
345
+
346
+ # Determines the last modified date from the request headers.
347
+ #
348
+ # === Parameters
349
+ # [header<String>] Raw request header returned from the request
350
+ # === Returns
351
+ # A Time object of the last modified date or nil if it cannot be found in the headers.
352
+ def self.last_modified_from_header(header)
353
+ header =~ /.*Last-Modified:\s(.*)\r/
354
+ Time.parse($1) if $1
355
+ end
356
+ end
357
+ end