Class: IpTracker::SyncDaemon

Inherits:
Object
  • Object
show all
Includes:
Looper
Defined in:
lib/ip_tracker/sync_daemon.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ SyncDaemon

Returns a new instance of SyncDaemon.



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

def initialize(config = {})
  @run = true
  @runs = config[:runs].nil? ? nil : config[:runs]
  @sleep = config[:sleep].nil? ? 60 : config[:sleep]
end

Instance Attribute Details

#last_ipObject

Returns the value of attribute last_ip.



8
9
10
# File 'lib/ip_tracker/sync_daemon.rb', line 8

def last_ip
  @last_ip
end

Instance Method Details

#clientObject



60
61
62
# File 'lib/ip_tracker/sync_daemon.rb', line 60

def client
  @client ||= Client.new
end

#configObject



56
57
58
# File 'lib/ip_tracker/sync_daemon.rb', line 56

def config
  @config ||= Config.new
end

#local_ipObject



40
41
42
43
44
45
46
47
48
49
# File 'lib/ip_tracker/sync_daemon.rb', line 40

def local_ip
  orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily

  UDPSocket.open do |s|
    s.connect '64.233.187.99', 1
    s.addr.last
  end
ensure
  Socket.do_not_reverse_lookup = orig
end

#runObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/ip_tracker/sync_daemon.rb', line 16

def run
  loopme(@sleep) do
    if @runs == 0
      @run = false
    elsif !@runs.nil?
      @runs -= 1
    end

    begin
      new_ip = local_ip

      if @last_ip != new_ip
        puts "#{Time.now}: Updating to #{new_ip}"
        update_ip new_ip

        @last_ip = new_ip
      end
    rescue Client::TargetError
      puts "An error occured trying to communicate with the server, sleeping"
      sleep(6000) unless !@runs.nil?
    end
  end
end

#update_ip(ip) ⇒ Object



51
52
53
54
# File 'lib/ip_tracker/sync_daemon.rb', line 51

def update_ip ip
  client.update(config.host_token, :ip, ip)
  #  CLI.start( ['update', '--ip', ip] )
end