Class: Brrowser::Fetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/brrowser/fetcher.rb

Constant Summary collapse

MAX_REDIRECTS =
10
TIMEOUT =
15
USER_AGENT =
"brrowser/0.1 (terminal browser)"
File.join(Dir.home, ".brrowser", "cookies.yml")
MAX_CACHE =
20

Instance Method Summary collapse

Constructor Details

#initializeFetcher

Returns a new instance of Fetcher.



15
16
17
18
19
# File 'lib/brrowser/fetcher.rb', line 15

def initialize
  @cookies = load_cookies
  @page_cache = {}
  @page_cache_order = []
end

Instance Method Details

#fetch(url, method: :get, params: nil) ⇒ Object



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
48
49
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/brrowser/fetcher.rb', line 21

def fetch(url, method: :get, params: nil)
  # Return cached response for GET requests
  if method == :get && !params && @page_cache[url]
    return @page_cache[url]
  end
  # Handle local files
  if url.match?(%r{^file://})
    path = url.sub(%r{^file://}, "")
    body = File.exist?(path) ? File.read(path) : "File not found: #{path}"
    ct = path.match?(/\.html?$/i) ? "text/html" : "text/plain"
    return { body: body, url: url, content_type: ct, status: 200 }
  end
  url = "https://#{url}" unless url.match?(%r{^https?://})
  uri = URI.parse(url)
  redirects = 0

  loop do
    raise "Too many redirects" if redirects >= MAX_REDIRECTS

    http = Net::HTTP.new(uri.host, uri.port)
    http.open_timeout = TIMEOUT
    http.read_timeout = TIMEOUT
    if uri.scheme == "https"
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_PEER
    end

    path = uri.request_uri.empty? ? "/" : uri.request_uri
    if method == :post && params
      req = Net::HTTP::Post.new(path)
      req.set_form_data(params)
    else
      req = Net::HTTP::Get.new(path)
    end
    req["User-Agent"]      = USER_AGENT
    req["Accept"]          = "text/html,application/xhtml+xml,*/*"
    req["Accept-Language"]  = "en-US,en;q=0.9"
    req["Accept-Encoding"] = "identity"
    cookie_str = cookies_for(uri)
    req["Cookie"] = cookie_str unless cookie_str.empty?

    response = http.request(req)
    store_cookies(uri, response)

    case response
    when Net::HTTPRedirection
      location = response["location"]
      uri = location.start_with?("http") ? URI.parse(location) : URI.join(uri, location)
      redirects += 1
    when Net::HTTPSuccess
      ct = response["content-type"] || ""
      body = response.body
      body = body.force_encoding("UTF-8") if ct.match?(/text|html|json|xml/)
      result = {
        body:         body,
        url:          uri.to_s,
        content_type: ct,
        status:       response.code.to_i
      }
      cache_response(url, result) if method == :get
      return result
    else
      return {
        body:         "Error #{response.code}: #{response.message}",
        url:          uri.to_s,
        content_type: "text/plain",
        status:       response.code.to_i
      }
    end
  end
rescue => e
  {
    body:         "Error: #{e.message}",
    url:          url,
    content_type: "text/plain",
    status:       0
  }
end

#invalidate_cache(url = nil) ⇒ Object



104
105
106
107
108
109
110
111
112
# File 'lib/brrowser/fetcher.rb', line 104

def invalidate_cache(url = nil)
  if url
    @page_cache.delete(url)
    @page_cache_order.delete(url)
  else
    @page_cache.clear
    @page_cache_order.clear
  end
end