Class: TestRecorder::CdpRecorder

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

Instance Method Summary collapse

Constructor Details

#initialize(enabled:) ⇒ CdpRecorder

Returns a new instance of CdpRecorder.



7
8
9
10
11
12
# File 'lib/test_recorder/cdp_recorder.rb', line 7

def initialize(enabled:)
  @enabled = enabled
  @started = nil
  @page = nil
  setup
end

Instance Method Details

#setupObject



14
15
16
17
# File 'lib/test_recorder/cdp_recorder.rb', line 14

def setup
  @video_dir = ::Rails.root.join("tmp", "videos")
  FileUtils.mkdir_p(@video_dir)
end

#start(page:, enabled: nil) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/test_recorder/cdp_recorder.rb', line 19

def start(page:, enabled: nil)
  enabled = @enabled if enabled.nil?
  @started = enabled
  return unless @started

  @tmp_video = Tempfile.open(["testrecorder", ".webm"])
  cmd = "ffmpeg -loglevel quiet -f image2pipe -avioflags direct -fpsprobesize 0 -probesize 32 -analyzeduration 0 -c:v mjpeg -i - -y -an -r 25 -qmin 0 -qmax 50 -crf 8 -deadline realtime -speed 8 -b:v 1M -threads 1 #{@tmp_video.path}"
  @stdin, @wait_thrs = *Open3.pipeline_w(cmd)
  @stdin.set_encoding("ASCII-8BIT")

  @page = page
  @page.driver.browser.devtools.page.enable

  @page.driver.browser.devtools.page.on(:screencast_frame) do |event|
    decoded_data = Base64.decode64(event["data"])
    @stdin.print(decoded_data) rescue nil
    @page.driver.browser.devtools.page.screencast_frame_ack(session_id: event["sessionId"])
  end

  @page.driver.browser.devtools.page.start_screencast(format: "jpeg", quality: 90)
end

#stop_and_discardObject



41
42
43
44
45
46
# File 'lib/test_recorder/cdp_recorder.rb', line 41

def stop_and_discard
  if @started
    @page.driver.browser.devtools.page.stop_screencast
    @stdin.close
  end
end

#stop_and_save(filename) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/test_recorder/cdp_recorder.rb', line 48

def stop_and_save(filename)
  return "" unless @started

  @page.driver.browser.devtools.page.stop_screencast
  @stdin.close
  @wait_thrs.each(&:join)

  video_path = File.join(@video_dir, filename)
  FileUtils.copy(@tmp_video.path, video_path)
  @tmp_video.close(true)

  video_path
end