2012-04-08 04:04:37 +02:00
|
|
|
require "pp"
|
2013-01-05 00:28:01 +01:00
|
|
|
|
2012-04-07 19:15:25 +02:00
|
|
|
class Feed < ActiveRecord::Base
|
2013-01-10 21:33:21 +01:00
|
|
|
has_many :items, :dependent => :destroy
|
|
|
|
has_many :errors, :dependent => :destroy
|
2012-04-07 19:15:25 +02:00
|
|
|
|
|
|
|
validates_uniqueness_of :url
|
|
|
|
|
2012-04-08 04:04:37 +02:00
|
|
|
default_scope where(:has_errors => false)
|
|
|
|
scope :with_error, unscoped.where(:has_errors => true)
|
|
|
|
|
|
|
|
def fetch!
|
|
|
|
Feedzirra::Feed.fetch_and_parse(url,
|
|
|
|
:on_success => lambda do |url, feed|
|
2013-01-05 00:28:01 +01:00
|
|
|
begin
|
|
|
|
feed.entries.each do |entry|
|
|
|
|
unless Item.exists?(:url => entry.url)
|
|
|
|
entry.sanitize!
|
|
|
|
items << Item.create_from_feed_entry!(entry)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
by_url(url).update_attribute(:has_errors, false)
|
|
|
|
rescue Exception => e
|
2013-01-10 21:33:21 +01:00
|
|
|
Error.create!(:feed_id => self.id, :action => :fetch_and_parse,
|
|
|
|
:message => e)
|
2013-01-05 00:28:01 +01:00
|
|
|
end
|
2012-04-08 04:04:37 +02:00
|
|
|
end,
|
|
|
|
:on_failure => lambda do |url, response_code, response_header, response_body|
|
|
|
|
by_url(url).update_attribute(:has_errors, true)
|
2013-01-10 21:33:21 +01:00
|
|
|
Error.create!(:feed_id => self.id, :action => :fetch_and_parse,
|
|
|
|
:message => "
|
|
|
|
url: #{url}
|
|
|
|
response-code: #{response_code}
|
|
|
|
response-header: #{response_header}
|
|
|
|
response-body: #{response_body}
|
|
|
|
")
|
2012-04-08 04:04:37 +02:00
|
|
|
end
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.import(url, *params)
|
|
|
|
Feedzirra::Feed.fetch_and_parse(url,
|
|
|
|
:on_success => lambda do |url, feed|
|
|
|
|
Feed.create!(:url => feed.feed_url, :title => feed.title).fetch!
|
|
|
|
end,
|
|
|
|
:on_failure => lambda do |url, response_code, response_header, response_body|
|
|
|
|
if params.first.include?(:force)
|
2013-01-10 21:33:21 +01:00
|
|
|
feed = Feed.create!(:url => url, :has_errors => true)
|
|
|
|
|
|
|
|
Error.create!(:feed_id => feed.id, :action => :import,
|
|
|
|
:message => "
|
|
|
|
url: #{url}
|
|
|
|
response-code: #{response_code}
|
|
|
|
response-header: #{response_header}
|
|
|
|
response-body: #{response_body}
|
|
|
|
")
|
2012-04-08 04:04:37 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.update_all!
|
|
|
|
Feed.all.each do |feed|
|
|
|
|
feed.fetch!
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
def by_url(feed_url)
|
|
|
|
Feed.where(:url => feed_url).first
|
|
|
|
end
|
2012-04-07 19:15:25 +02:00
|
|
|
end
|