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:) ⇒ 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
# File 'lib/pytty/client/api/attach.rb', line 5

def self.run(id:)
  Async::Task.current.async do |stdin_task|
    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("http://localhost:1234/v1/stdin/#{id}", headers, [stdin_body])

    detach_sequence_started = false
    while c = async_stdin.read(1) do
      case c
      when "\x10"
        detach_sequence_started = true
        next
      when "\x11"
        if detach_sequence_started
          detach_sequence_started = false
          exit 0
        end
      end

      detach_sequence_started = false

      stdin_body = {
        c: c
      }.to_json
      response = internet.post("http://localhost:1234/v1/stdin/#{id}", headers, [stdin_body])
    end
  end

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

    response = internet.post("http://localhost:1234/v1/attach/#{id}", headers, [body])
    response.body.each do |c|
      print c
    end
  rescue Async::Wrapper::Cancelled => ex
  ensure
    internet.close
  end
end