Class: Pluto::Fetcher

Inherits:
Object
  • Object
show all
Includes:
LogUtils::Logging, Models
Defined in:
lib/pluto/fetcher.rb

Constant Summary

Constants included from Models

Models::Activity

Instance Method Summary collapse

Constructor Details

#initialize ⇒ Fetcher

Returns a new instance of Fetcher.



10
11
12
# File 'lib/pluto/fetcher.rb', line 10

def initialize
  @worker  = ::Fetcher::Worker.new
end

Instance Method Details

#debug=(value) ⇒ Object



14
# File 'lib/pluto/fetcher.rb', line 14

def debug=(value)  @debug = value;   end

#debug? ⇒ Boolean

Returns:

  • (Boolean)


15
# File 'lib/pluto/fetcher.rb', line 15

def debug?()       @debug || false;  end

#feed_by_rec(feed_rec) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/pluto/fetcher.rb', line 50

def feed_by_rec( feed_rec )
  # simple feed fetcher; use for debugging (only/mostly)
  #  -- will NOT change db records in any way

  feed_url = feed_rec.feed_url
  feed_key = feed_rec.key

  feed_xml = fetch_feed( feed_url )

  logger.debug "feed_xml:"
  logger.debug feed_xml[ 0..500 ] # get first 500 chars

  #  if opts.verbose?  # also write a copy to disk
  if debug?
    logger.debug "saving feed to >./#{feed_key}.xml<..."
    File.open( "./#{feed_key}.xml", 'w' ) do |f|
      f.write( feed_xml )
    end
  end
    
  puts "Before parsing feed >#{feed_key}<..."

  ## fix/todo: check for feed.nil?   -> error parsing!!!
  #    or throw exception
  feed = FeedUtils::Parser.parse( feed_xml )
end

#feed_by_rec_if_modified(feed_rec) ⇒ Object

try smart http update; will update db records



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/pluto/fetcher.rb', line 78

def feed_by_rec_if_modified( feed_rec )   # try smart http update; will update db records
  feed_url = feed_rec.feed_url
  feed_key = feed_rec.key

  ### todo/fix: normalize/unifiy feed_url
  ##  - same in fetcher - use shared utitlity method or similar

  @worker.use_cache = true
  @worker.cache[ feed_url ] = {
    'etag'          => feed_rec.http_etag,
    'last-modified' => feed_rec.http_last_modified
  }

  begin
    response = @worker.get( feed_url )
  rescue SocketError => e
    ## catch socket error for unknown domain names (e.g. pragdave.blogs.pragprog.com)
    ###  will result in SocketError -- getaddrinfo: Name or service not known
    puts "*** error: fetching feed '#{feed_key}' - #{e.to_s}"
    Activity.create!( text: "*** error: fetching feed '#{feed_key}' - #{e.to_s}" )

    ### todo/fix: update feed rec in db
    @worker.use_cache = false   # fix/todo: restore old use_cache setting instead of false
    return nil
  end

  @worker.use_cache = false   # fix/todo: restore old use_cache setting instead of false

  if response.code == '304'  # not modified (conditional GET - e.g. using etag/last-modified)
    puts "OK - fetching feed '#{feed_key}' - HTTP status #{response.code} #{response.message}"
    puts "no change; request returns not modified (304); skipping parsing feed"
    return nil   # no updates available; nothing to do
  end

  feed_fetched = Time.now

  if response.code != '200'   # note Net::HTTP response.code is a string in ruby

    puts "*** error: fetching feed '#{feed_key}' - HTTP status #{response.code} #{response.message}"
    
    feed_attribs = {
      http_code:          response.code.to_i,
      http_server:        response.header[ 'server' ],
      http_etag:          nil,
      http_last_modified: nil,
      body:               nil,
      md5:                nil,
      fetched:            feed_fetched 
    }
    feed_rec.update_attributes!( feed_attribs )
    
    ## add log error activity -- in future add to error log - better - why? why not?
    Activity.create!( text: "*** error: fetching feed '#{feed_key}' - HTTP status #{response.code} #{response.message}" )

    return nil  #  sorry; no feed for parsing available
  end

  puts "OK - fetching feed '#{feed_key}' - HTTP status #{response.code} #{response.message}"

  feed_xml = response.body
  ###
  # NB: Net::HTTP will NOT set encoding UTF-8 etc.
  # will mostly be ASCII
  # - try to change encoding to UTF-8 ourselves
  logger.debug "feed_xml.encoding.name (before): #{feed_xml.encoding.name}"

  #####
  # NB: ASCII-8BIT == BINARY == Encoding Unknown; Raw Bytes Here

  ## NB:
  # for now "hardcoded" to utf8 - what else can we do?
  # - note: force_encoding will NOT change the chars only change the assumed encoding w/o translation
  feed_xml = feed_xml.force_encoding( Encoding::UTF_8 )
  logger.debug "feed_xml.encoding.name (after): #{feed_xml.encoding.name}"

  ## check for md5 hash for response.body

  last_feed_md5 = feed_rec.md5
  feed_md5 = Digest::MD5.hexdigest( feed_xml )
  
  if last_feed_md5 && last_feed_md5 == feed_md5
    # not all servers handle conditional gets, so while not much can be
    # done about the bandwidth, but if the response body is identical
    # the downstream processing (parsing, caching, ...) can be avoided.
    #  - thanks to planet mars -fido.rb for the idea, cheers.
    
    puts "no change; md5 digests match; skipping parsing feed"
    return nil   # no updates available; nothing to do
  end

  feed_attribs = {
    http_code:          response.code.to_i,
    http_server:        response.header[ 'server' ],
    http_etag:          response.header[ 'etag' ],
    http_last_modified: response.header[ 'last-modified' ], ## note: last_modified header gets stored as plain text (not datetime)
    body:               feed_xml,
    md5:                feed_md5,
    fetched:            feed_fetched
  }

  ## if debug?
    puts "http header - server: #{response.header['server']} - #{response.header['server'].class.name}"
    puts "http header - etag: #{response.header['etag']} - #{response.header['etag'].class.name}"
    puts "http header - last-modified: #{response.header['last-modified']} - #{response.header['last-modified'].class.name}"
  ## end

  feed_rec.update_attributes!( feed_attribs )

  logger.debug "feed_xml:"
  logger.debug feed_xml[ 0..300 ] # get first 300 chars
    
  puts "Before parsing feed >#{feed_key}<..."

  ### move to feedutils
  ### logger.debug "using stdlib RSS::VERSION #{RSS::VERSION}"

  ## fix/todo: check for feed.nil?   -> error parsing!!!
  #    or throw exception
  feed = FeedUtils::Parser.parse( feed_xml )
end

#fetch_feed(url) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/pluto/fetcher.rb', line 18

def fetch_feed( url )
  response = @worker.get( url )

  ## if debug?
    puts "http status #{response.code} #{response.message}"

    puts "http header - server: #{response.header['server']} - #{response.header['server'].class.name}"
    puts "http header - etag: #{response.header['etag']} - #{response.header['etag'].class.name}"
    puts "http header - last-modified: #{response.header['last-modified']} - #{response.header['last-modified'].class.name}"
  ## end

  xml = response.body

  ###
  # NB: Net::HTTP will NOT set encoding UTF-8 etc.
  # will mostly be ASCII
  # - try to change encoding to UTF-8 ourselves
  logger.debug "xml.encoding.name (before): #{xml.encoding.name}"

  #####
  # NB: ASCII-8BIT == BINARY == Encoding Unknown; Raw Bytes Here

  ## NB:
  # for now "hardcoded" to utf8 - what else can we do?
  # - note: force_encoding will NOT change the chars only change the assumed encoding w/o translation
  xml = xml.force_encoding( Encoding::UTF_8 )
  logger.debug "xml.encoding.name (after): #{xml.encoding.name}"      

  xml
end

#site_by_rec_if_modified(site_rec) ⇒ Object

try smart http update; will update db records



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/pluto/fetcher.rb', line 200

def site_by_rec_if_modified( site_rec )   # try smart http update; will update db records
  site_url = site_rec.url
  site_key = site_rec.key

  ### todo/fix: normalize/unifiy feed_url
  ##  - same in fetcher - use shared utitlity method or similar

  @worker.use_cache = true
  @worker.cache[ site_url ] = {
    'etag'          => site_rec.http_etag,
    'last-modified' => site_rec.http_last_modified
  }

  response = @worker.get( site_url )
  @worker.use_cache = false   # fix/todo: restore old use_cache setting instead of false

  if response.code == '304'  # not modified (conditional GET - e.g. using etag/last-modified)
    puts "OK - fetching site '#{site_key}' - HTTP status #{response.code} #{response.message}"
    puts "no change; request returns not modified (304); skipping parsing site config"
    return nil   # no updates available; nothing to do
  end

  site_fetched = Time.now

  if response.code != '200'   # note Net::HTTP response.code is a string in ruby

    puts "*** error: fetching site '#{site_key}' - HTTP status #{response.code} #{response.message}"

    site_attribs = {
      http_code:          response.code.to_i,
      http_server:        response.header[ 'server' ],
      http_etag:          nil,
      http_last_modified: nil,
      body:               nil,
      md5:                nil,
      fetched:            feed_fetched 
    }
    site_rec.update_attributes!( site_attribs )
    
    ## add log error activity -- in future add to error log - better - why? why not?
    Activity.create!( text: "*** error: fetching site '#{site_key}' - HTTP status #{response.code} #{response.message}" )

    return nil  #  sorry; no feed for parsing available
  end

  puts "OK - fetching site '#{site_key}' - HTTP status #{response.code} #{response.message}"

  site_text = response.body
  
  ###
  # NB: Net::HTTP will NOT set encoding UTF-8 etc.
  # will mostly be ASCII
  # - try to change encoding to UTF-8 ourselves
  logger.debug "site_text.encoding.name (before): #{site_text.encoding.name}"

  #####
  # NB: ASCII-8BIT == BINARY == Encoding Unknown; Raw Bytes Here

  ## NB:
  # for now "hardcoded" to utf8 - what else can we do?
  # - note: force_encoding will NOT change the chars only change the assumed encoding w/o translation
  site_text = site_text.force_encoding( Encoding::UTF_8 )
  logger.debug "site_text.encoding.name (after): #{site_text.encoding.name}"

  site_attribs = {
    http_code:          response.code.to_i,
    http_server:        response.header[ 'server' ],
    http_etag:          response.header[ 'etag' ],
    http_last_modified: response.header[ 'last-modified' ], ## note: last_modified header gets stored as plain text (not datetime)
    fetched:            site_fetched
  }

  ## if debug?
    puts "http header - server: #{response.header['server']} - #{response.header['server'].class.name}"
    puts "http header - etag: #{response.header['etag']} - #{response.header['etag'].class.name}"
    puts "http header - last-modified: #{response.header['last-modified']} - #{response.header['last-modified'].class.name}"
  ## end

  site_rec.update_attributes!( site_attribs )

  ## logger.debug "site_text:"
  ## logger.debug site_text[ 0..300 ] # get first 300 chars


  puts "Before parsing site config >#{site_key}<..."
  
  # assume ini format for now
  site_config = INI.load( site_text )
end