Class: Browze::Client

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/browze/client.rb

Overview

Desktop and mobile clients inherit from the base client.

Direct Known Subclasses

Desktop, Mobile

Defined Under Namespace

Classes: Desktop, Mobile

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeClient

Initialize the cookie jar and headers.



18
19
20
21
# File 'lib/browze/client.rb', line 18

def initialize
  @cookies = CookieHash.new
  @headers = {}
end

Instance Attribute Details

#cookiesObject (readonly)

Returns the value of attribute cookies.



14
15
16
# File 'lib/browze/client.rb', line 14

def cookies
  @cookies
end

#headersHash

Get the updated headers.

Returns:

  • (Hash)


63
64
65
# File 'lib/browze/client.rb', line 63

def headers
  @headers.merge({ 'User-Agent' => user_agent, 'Cookie' => @cookies.to_cookie_string })
end

Instance Method Details

#download(url, filename: nil) ⇒ Object

Download a file with an optional filename.

Parameters:

  • url (String)
  • filename (String) (defaults to: nil)


48
49
50
51
52
53
54
55
56
57
58
# File 'lib/browze/client.rb', line 48

def download(url, filename: nil)
  bar = TTY::ProgressBar.new('Downloading... [:bar] :percent')
  tempfile = Down.download(
    url,
    content_length_proc: ->(content_length) { bar.update(total: content_length) },
    progress_proc: ->(progress) { bar.current = progress }
  )
  filename ||= tempfile.original_filename
  FileUtils.mv(tempfile, filename)
  puts "Download complete: #{filename} (#{tempfile.size} bytes)"
end

#get(url) ⇒ Browze::Response

Perform a GET request to the given url.

Parameters:

  • url (String)

Returns:



27
28
29
30
31
# File 'lib/browze/client.rb', line 27

def get(url)
  resp = Browze::Response.new(self.class.get(url, headers: headers))
  resp.set_cookie.each { |c| @cookies.add_cookies(c) }
  resp
end

#ipString

Get the current public ip address.

Returns:

  • (String)

    the IP address



77
78
79
# File 'lib/browze/client.rb', line 77

def ip
  @ip ||= get('http://whatismyip.akamai.com').body
end

#locationString

Return the current location based on the public ip address.

Returns:

  • (String)


84
85
86
87
# File 'lib/browze/client.rb', line 84

def location
  l = Geocoder.search(ip).first
  "#{l.city}, #{l.country}"
end

#post(url, body_hash) ⇒ Browze::Response

Perform a POST request to the given url with a request body.

Parameters:

  • url (String)
  • body_hash (Hash)

Returns:



38
39
40
41
42
# File 'lib/browze/client.rb', line 38

def post(url, body_hash)
  resp = Browze::Response.new(self.class.post(url, body: body_hash, headers: headers))
  resp.set_cookie.each { |c| @cookies.add_cookies(c) }
  resp
end

#user_agentString

Pick a random user agent and persist it in the instance.

Returns:

  • (String)


70
71
72
# File 'lib/browze/client.rb', line 70

def user_agent
  @user_agent ||= self.class::USER_AGENTS.sample
end