Class: Proxylinker::ProxyList

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(proxy_file_path, timeout: 5) ⇒ ProxyList

Initialiserer ProxyList med en filsti og timeout-parameter (standard: 5 sek.)



10
11
12
13
14
# File 'lib/proxy_list.rb', line 10

def initialize(proxy_file_path, timeout: 5)
  @proxy_file_path = proxy_file_path
  @timeout = timeout
  @proxies = load_proxies
end

Instance Attribute Details

#proxiesObject (readonly)

Returns the value of attribute proxies.



7
8
9
# File 'lib/proxy_list.rb', line 7

def proxies
  @proxies
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



7
8
9
# File 'lib/proxy_list.rb', line 7

def timeout
  @timeout
end

Instance Method Details

#get_random_proxyObject

Hent en tilfældig fungerende proxy



42
43
44
45
46
47
# File 'lib/proxy_list.rb', line 42

def get_random_proxy
  @proxies.shuffle.each do |proxy|
    return proxy if validate_proxy(proxy)
  end
  nil
end

#load_proxiesObject

Læs proxies fra en fil (forventet format: IP:PORT per linje)



17
18
19
20
21
22
23
24
# File 'lib/proxy_list.rb', line 17

def load_proxies
  proxies = []
  File.readlines(@proxy_file_path).each do |line|
    addr, port = line.strip.split(':')
    proxies << OpenStruct.new(addr: addr, port: port)
  end
  proxies
end

#validate_proxy(proxy) ⇒ Object

Validér en proxy ved at forsøge at oprette forbindelse til en kendt URL



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/proxy_list.rb', line 27

def validate_proxy(proxy)
  uri = URI.parse('https://google.com')
  http = Net::HTTP.new(uri.host, uri.port, proxy.addr, proxy.port)
  http.open_timeout = @timeout
  http.read_timeout = @timeout

  begin
    response = http.get(uri.path)
    return response.is_a?(Net::HTTPSuccess)
  rescue
    false
  end
end