scraper.rb 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. require 'set'
  2. module Docs
  3. class Scraper < Doc
  4. class << self
  5. attr_accessor :base_url, :root_path, :initial_paths, :options, :html_filters, :text_filters, :stubs
  6. def inherited(subclass)
  7. super
  8. subclass.class_eval do
  9. extend AutoloadHelper
  10. autoload_all "docs/filters/#{to_s.demodulize.underscore}", 'filter'
  11. end
  12. subclass.base_url = base_url
  13. subclass.root_path = root_path
  14. subclass.initial_paths = initial_paths.dup
  15. subclass.options = options.deep_dup
  16. subclass.html_filters = html_filters.inheritable_copy
  17. subclass.text_filters = text_filters.inheritable_copy
  18. subclass.stubs = stubs.dup
  19. end
  20. def filters
  21. html_filters.to_a + text_filters.to_a
  22. end
  23. def stub(path, &block)
  24. @stubs[path] = block
  25. @stubs
  26. end
  27. end
  28. include Instrumentable
  29. self.initial_paths = []
  30. self.options = {}
  31. self.stubs = {}
  32. self.html_filters = FilterStack.new
  33. self.text_filters = FilterStack.new
  34. html_filters.push 'apply_base_url', 'container', 'clean_html', 'normalize_urls', 'internal_urls', 'normalize_paths', 'parse_cf_email'
  35. text_filters.push 'images' # ensure the images filter runs after all html filters
  36. text_filters.push 'inner_html', 'clean_text', 'attribution'
  37. def initialize
  38. super
  39. initialize_stubs
  40. end
  41. def initialize_stubs
  42. self.class.stubs.each do |path, &block|
  43. Typhoeus.stub(url_for(path)).and_return do
  44. Typhoeus::Response.new \
  45. effective_url: url_for(path),
  46. code: 200,
  47. headers: { 'Content-Type' => 'text/html' },
  48. body: self.instance_exec(&block)
  49. end
  50. end
  51. end
  52. def build_page(path)
  53. response = request_one url_for(path)
  54. result = handle_response(response)
  55. yield result if block_given?
  56. result
  57. end
  58. def build_pages
  59. history = Set.new initial_urls.map(&:downcase)
  60. instrument 'running.scraper', urls: initial_urls
  61. request_all initial_urls do |response|
  62. next unless data = handle_response(response)
  63. yield data
  64. next unless data[:internal_urls].present?
  65. next_urls = data[:internal_urls].select { |url| history.add?(url.downcase) }
  66. instrument 'queued.scraper', urls: next_urls
  67. next_urls
  68. end
  69. end
  70. def base_url
  71. @base_url ||= URL.parse self.class.base_url
  72. end
  73. def root_url
  74. @root_url ||= root_path? ? URL.parse(File.join(base_url.to_s, root_path)) : base_url.normalize
  75. end
  76. def root_path
  77. self.class.root_path
  78. end
  79. def root_path?
  80. root_path.present? && root_path != '/'
  81. end
  82. def initial_paths
  83. self.class.initial_paths
  84. end
  85. def initial_urls
  86. @initial_urls ||= [root_url.to_s].concat(initial_paths.map(&method(:url_for))).freeze
  87. end
  88. def pipeline
  89. @pipeline ||= ::HTML::Pipeline.new(self.class.filters).tap do |pipeline|
  90. pipeline.instrumentation_service = Docs
  91. end
  92. end
  93. def options
  94. @options ||= self.class.options.deep_dup.tap do |options|
  95. options.merge! base_url: base_url, root_url: root_url,
  96. root_path: root_path, initial_paths: initial_paths,
  97. version: self.class.version, release: self.class.release
  98. if root_path?
  99. (options[:skip] ||= []).concat ['', '/']
  100. end
  101. if options[:only] || options[:only_patterns]
  102. (options[:only] ||= []).concat initial_paths + (root_path? ? [root_path] : ['', '/'])
  103. end
  104. options.merge!(additional_options)
  105. options.freeze
  106. end
  107. end
  108. private
  109. def request_one(url)
  110. raise NotImplementedError
  111. end
  112. def request_all(url, &block)
  113. raise NotImplementedError
  114. end
  115. def process_response?(response)
  116. raise NotImplementedError
  117. end
  118. def url_for(path)
  119. if path.empty? || path == '/'
  120. root_url.to_s
  121. else
  122. File.join(base_url.to_s, path.to_s)
  123. end
  124. end
  125. def handle_response(response)
  126. if process_response?(response)
  127. instrument 'process_response.scraper', response: response do
  128. process_response(response)
  129. end
  130. else
  131. instrument 'ignore_response.scraper', response: response
  132. end
  133. rescue => e
  134. if Docs.rescue_errors
  135. instrument 'error.doc', exception: e, url: response.url
  136. nil
  137. else
  138. raise e
  139. end
  140. end
  141. def process_response(response)
  142. data = {}
  143. html, title = parse(response)
  144. context = pipeline_context(response)
  145. context[:html_title] = title
  146. pipeline.call(html, context, data)
  147. data
  148. end
  149. def pipeline_context(response)
  150. options.merge url: response.url
  151. end
  152. def parse(response)
  153. parser = Parser.new(response.body)
  154. [parser.html, parser.title]
  155. end
  156. def with_filters(*filters)
  157. stack = FilterStack.new
  158. stack.push(*filters)
  159. pipeline.instance_variable_set :@filters, stack.to_a.freeze
  160. yield
  161. ensure
  162. @pipeline = nil
  163. end
  164. def additional_options
  165. {}
  166. end
  167. module FixInternalUrlsBehavior
  168. def self.included(base)
  169. base.extend ClassMethods
  170. end
  171. def self.prepended(base)
  172. class << base
  173. prepend ClassMethods
  174. end
  175. end
  176. module ClassMethods
  177. def internal_urls
  178. @internal_urls
  179. end
  180. def store_pages(store)
  181. instrument 'info.doc', msg: 'Building internal urls...'
  182. with_internal_urls do
  183. instrument 'info.doc', msg: 'Continuing...'
  184. super
  185. end
  186. end
  187. private
  188. def with_internal_urls
  189. @internal_urls = new.fetch_internal_urls
  190. yield
  191. ensure
  192. @internal_urls = nil
  193. end
  194. end
  195. def fetch_internal_urls
  196. result = []
  197. build_pages do |page|
  198. result << page[:subpath] if page[:entries].present?
  199. end
  200. result
  201. end
  202. def initial_urls
  203. return super unless self.class.internal_urls
  204. @initial_urls ||= self.class.internal_urls.map(&method(:url_for)).freeze
  205. end
  206. private
  207. def additional_options
  208. if self.class.internal_urls
  209. super.merge! \
  210. only: self.class.internal_urls.to_set,
  211. only_patterns: nil,
  212. skip: nil,
  213. skip_patterns: nil,
  214. skip_links: nil,
  215. fixed_internal_urls: true
  216. else
  217. super
  218. end
  219. end
  220. def process_response(response)
  221. super.merge! response_url: response.url
  222. end
  223. end
  224. end
  225. end