Class: Pytty::Client::Api::Attach

Inherits:
Object
  • Object
show all
Defined in:
lib/pytty/client/api/attach.rb

Class Method Summary collapse

Class Method Details

.run(id:, interactive:) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
# File 'lib/pytty/client/api/attach.rb', line 5

def self.run(id:, interactive:)
  stdin_task = Async::Task.current.async do
    internet = Async::HTTP::Internet.new
    headers = [['accept', 'application/json']]
    body = {}.to_json

    $stdin.raw!
    $stdin.echo = false
    async_stdin = Async::IO::Stream.new(
      Async::IO::Generic.new($stdin)
    )

    stdin_body = {
      c: "\f"
    }.to_json
    response = internet.post("#{Pytty::Client.host_url}/v1/stdin/#{id}", headers, [stdin_body])

    detach_sequence_started = false
    while c = async_stdin.read(1) do
      detach = false
      case c
      when "\x10"
        detach_sequence_started = true
        next
      when "\x11"
        detach = true if detach_sequence_started
      when "\x03"
        detach = true unless interactive
      end

      if detach
        puts ""
        puts "detached.\r"
        exit 0
      end

      detach_sequence_started = false

      if interactive
        stdin_body = {
          c: c
        }.to_json
        response = internet.post("#{Pytty::Client.host_url}/v1/stdin/#{id}", headers, [stdin_body])
      end
    end
  end

  begin
    internet = Async::HTTP::Internet.new
    headers = [['accept', 'application/json']]
    body = {}.to_json

    response = internet.post("#{Pytty::Client.host_url}/v1/attach/#{id}", headers, [body])
    response.body.each do |c|
      print c
    end
  rescue Async::Wrapper::Cancelled => ex
    p ["rescued", ex]
  ensure
    stdin_task.stop

    internet.close
  end
end