Class: Localtunnel::Client

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

Constant Summary collapse

@@pid =
nil
@@url =
nil

Class Method Summary collapse

Class Method Details

.execution_string(log, options) ⇒ Object



43
44
45
46
47
48
49
50
# File 'lib/localtunnel/client.rb', line 43

def self.execution_string(log, options)
  s = "exec lt"
  s << " -p '#{options[:port]}'" if options.key?(:port)
  s << " -s '#{options[:subdomain]}'" if options.key?(:subdomain)
  s << " -h '#{options[:remote_host]}'" if options.key?(:remote_host)
  s << " -l '#{options[:local_host]}'" if options.key?(:local_host)
  s << " > #{log.path} 2>&1"
end

.package_installed?Boolean

Returns:

  • (Boolean)


37
38
39
40
41
# File 'lib/localtunnel/client.rb', line 37

def self.package_installed?
  !`lt --version`.empty?
rescue Errno::ENOENT
  false
end

.parse_url!(log, max_seconds = 10) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/localtunnel/client.rb', line 52

def self.parse_url!(log, max_seconds = 10)
  max_seconds.times do
    sleep 1
    log.rewind
    log_data = log.read

    if match_data = log_data.match(/^your url is: (.*)$/)
      return match_data.captures.first
    elsif log_data.match(/^Error: (.*)$/)
      raise ClientConnectionFailedError
    end
  end

  stop
  raise ClientConnectionFailedError # Timeout.
end

.running?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/localtunnel/client.rb', line 29

def self.running?
  !@@pid.nil?
end

.start(options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/localtunnel/client.rb', line 8

def self.start(options = {})
  return if running?

  raise NpmPackageNotFoundError unless package_installed?

  log = Tempfile.new("localtunnel")
  @@pid = Process.spawn(execution_string(log, options))

  at_exit { stop } # Ensure process is killed if Ruby exits.

  @@url = parse_url!(log)
end

.stopObject



21
22
23
24
25
26
27
# File 'lib/localtunnel/client.rb', line 21

def self.stop
  return unless running?

  `kill -9 #{@@pid} 1>/dev/null 2>&1` # Can't use Process.kill, since JRuby on Raspbian doesn't support it.

  @@pid = nil
end

.urlObject



33
34
35
# File 'lib/localtunnel/client.rb', line 33

def self.url
  @@url if running?
end