summaryrefslogtreecommitdiff
path: root/animism-align/frontend/app/views/viewer/player/components.media/video.subtitles.js
blob: dfa7a85bcf8c4cda94da36010d22f61ed70229fb (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
import React, { Component } from 'react'
import { connect } from 'react-redux'

import actions from 'app/actions'
import { timestampToSeconds, floatInRange } from 'app/utils'

const REGEXP_ALL_COMMAS = new RegExp(',', 'g')

export default class VideoSubtitles extends Component {
  state = {
    subtitles: [],
    current: null,
  }
  componentDidMount() {
    this.loadSubtitles()
  }
  componentDidUpdate(prevProps) {
    if (this.props.play_ts !== prevProps.play_ts) {
      this.updateCurrentSubtitle()
    }
  }
  loadSubtitles() {
    if (!this.props.mediaItem || !this.props.mediaItem.settings.subtitles) return;
    const groups = this.props.mediaItem.settings.subtitles.split("\n\n")
    const subtitles = groups.map((group) => {
      if (!group) return
      const lines = group.trim().split("\n")
      if (!lines.length || !parseInt(lines[0])) {
        return null
      }
      let ts_parts = lines[1].replace(REGEXP_ALL_COMMAS, '.').split(" --> ").map(timestampToSeconds)
      return {
        id: parseInt(lines[0]),
        start_ts: ts_parts[0],
        end_ts: ts_parts[1],
        lines: lines.slice(2),
      }
    }).filter(a => !!a)
    this.setState({ subtitles, current: null })
  }
  updateCurrentSubtitle() {
    const { play_ts } = this.props
    const current = this.state.subtitles.filter(({ start_ts, end_ts }) => (
      floatInRange(start_ts, play_ts, end_ts )
    )).slice(-1)
    if (!current.length) {
      this.setState({ current: null })
    } else {
      this.setState({ current: current[0] })
    }
  }
  render() {
    const { current } = this.state
    if (!current) return <div className="video-subtitles hidden" />
    return (
      <div className="video-subtitles">
        {current.lines.map(line => <span key={line}>{line}</span>)}
      </div>
    )
  }
}