Skip to content

Commit

Permalink
Added webvtt escape
Browse files Browse the repository at this point in the history
  • Loading branch information
asticode committed Jul 4, 2023
1 parent 9f9e6a8 commit 1e3a211
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
17 changes: 16 additions & 1 deletion webvtt.go
Expand Up @@ -42,7 +42,8 @@ func parseDurationWebVTT(i string) (time.Duration, error) {

// https://tools.ietf.org/html/rfc8216#section-3.5
// Eg., `X-TIMESTAMP-MAP=LOCAL:00:00:00.000,MPEGTS:900000` => 10s
// `X-TIMESTAMP-MAP=LOCAL:00:00:00.000,MPEGTS:180000` => 2s
//
// `X-TIMESTAMP-MAP=LOCAL:00:00:00.000,MPEGTS:180000` => 2s
func parseTimestampMapWebVTT(line string) (timeOffset time.Duration, err error) {
splits := strings.Split(line, "=")
if len(splits) <= 1 {
Expand Down Expand Up @@ -112,6 +113,9 @@ func ReadFromWebVTT(i io.Reader) (o *Subtitles, err error) {
line = strings.TrimSpace(scanner.Text())
lineNum++

// Unescape line
line = unescapeWebVTT(line)

switch {
// Comment
case strings.HasPrefix(line, "NOTE "):
Expand Down Expand Up @@ -273,6 +277,14 @@ func ReadFromWebVTT(i io.Reader) (o *Subtitles, err error) {
return
}

func escapeWebVTT(i string) string {
return strings.ReplaceAll(i, "&", "&amp;")
}

func unescapeWebVTT(i string) string {
return strings.ReplaceAll(i, "&amp;", "&")
}

// parseTextWebVTT parses the input line to fill the Line
func parseTextWebVTT(i string) (o Line) {
// Create tokenizer
Expand Down Expand Up @@ -475,6 +487,9 @@ func (s Subtitles) WriteToWebVTT(o io.Writer) (err error) {
// Remove last new line
c = c[:len(c)-1]

// Escape content
c = []byte(escapeWebVTT(string(c)))

// Write
if _, err = o.Write(c); err != nil {
err = fmt.Errorf("astisub: writing failed: %w", err)
Expand Down
24 changes: 24 additions & 0 deletions webvtt_test.go
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/asticode/go-astisub"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestWebVTT(t *testing.T) {
Expand Down Expand Up @@ -130,3 +131,26 @@ func TestWebVTTWithTimestampMap(t *testing.T) {
Evening.
`, b.String())
}

func TestWebVTTEscape(t *testing.T) {
testData := `WEBVTT
00:01:00.000 --> 00:02:00.000
Sentence with an &amp; in the middle`

s, err := astisub.ReadFromWebVTT(strings.NewReader(testData))
require.NoError(t, err)

require.Len(t, s.Items, 1)
require.Equal(t, "Sentence with an & in the middle", s.Items[0].String())

b := &bytes.Buffer{}
err = s.WriteToWebVTT(b)
require.NoError(t, err)
require.Equal(t, `WEBVTT
1
00:01:00.000 --> 00:02:00.000
Sentence with an &amp; in the middle
`, b.String())
}

0 comments on commit 1e3a211

Please sign in to comment.