summaryrefslogtreecommitdiff
path: root/vendor/github.com/playwright-community/playwright-go/video.go
blob: a57b61aba57abe29c7b2357ae721b718e3fdb6e6 (plain)
1
2
3
4
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package playwright

import (
	"errors"
	"sync"
)

type videoImpl struct {
	page         *pageImpl
	artifact     *artifactImpl
	artifactChan chan *artifactImpl
	done         chan struct{}
	closeOnce    sync.Once
	isRemote     bool
}

func (v *videoImpl) Path() (string, error) {
	if v.isRemote {
		return "", errors.New("Path is not available when connecting remotely. Use SaveAs() to save a local copy.")
	}
	v.getArtifact()
	if v.artifact == nil {
		return "", errors.New("Page did not produce any video frames")
	}
	return v.artifact.AbsolutePath(), nil
}

func (v *videoImpl) Delete() error {
	v.getArtifact()
	if v.artifact == nil {
		return nil
	}
	return v.artifact.Delete()
}

func (v *videoImpl) SaveAs(path string) error {
	if !v.page.IsClosed() {
		return errors.New("Page is not yet closed. Close the page prior to calling SaveAs")
	}
	v.getArtifact()
	if v.artifact == nil {
		return errors.New("Page did not produce any video frames")
	}
	return v.artifact.SaveAs(path)
}

func (v *videoImpl) artifactReady(artifact *artifactImpl) {
	v.artifactChan <- artifact
}

func (v *videoImpl) pageClosed(p Page) {
	v.closeOnce.Do(func() {
		close(v.done)
	})
}

func (v *videoImpl) getArtifact() {
	// prevent channel block if no video will be produced
	if v.page.browserContext.options == nil {
		v.pageClosed(v.page)
	} else {
		option := v.page.browserContext.options
		if option == nil || option.RecordVideo == nil { // no recordVideo option
			v.pageClosed(v.page)
		}
	}
	select {
	case artifact := <-v.artifactChan:
		if artifact != nil {
			v.artifact = artifact
		}
	case <-v.done: // page closed
		select { // make sure get artifact if it's ready before page closed
		case artifact := <-v.artifactChan:
			if artifact != nil {
				v.artifact = artifact
			}
		default:
		}
	}
}

func newVideo(page *pageImpl) *videoImpl {
	video := &videoImpl{
		page:         page,
		artifactChan: make(chan *artifactImpl, 1),
		done:         make(chan struct{}, 1),
		isRemote:     page.connection.isRemote,
	}

	if page.isClosed {
		video.pageClosed(page)
	} else {
		page.OnClose(video.pageClosed)
	}
	return video
}