summaryrefslogtreecommitdiff
path: root/animism-align/frontend/app/views/editor/align/components/sidebar/waveUpload.component.js
blob: 27047efcf0ea499f778d50c6fb3d2ed50fd45467 (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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import React, { Component } from 'react'
import { connect } from 'react-redux'
import extractPeaks from 'webaudio-peaks'

import actions from 'app/actions'
import { formatSize, timestampHMS } from 'app/utils'
import { Loader } from 'app/common'

class WaveUpload extends Component {
  state = {
    working: false,
    status: "",
    filename: "",
    duration: 0,
  }

  upload(e) {
    e.preventDefault()
    document.body.className = ''
    const files = e.dataTransfer ? e.dataTransfer.files : e.target.files
    let i
    let file
    for (i = 0; i < files.length; i++) {
      file = files[i]
      if (file && file.type.match('image.*')) break
    }
    if (!file) {
      console.log('No file specified')
      return
    }
    this.setState({ working: true, status: "Loading MP3...", filename: file.name, size: file.size, duration: 0 })
    const fileReader = new FileReader()
    fileReader.onload = event => {
      fileReader.onload = null
      this.processAudioFile(file, event.target.result)
    }
    fileReader.readAsArrayBuffer(file)
  }

  processAudioFile(audioFile, arrayBuffer) {
    this.setState({ working: true, status: "Extracting peaks..." })
    var audioContext = new (window.AudioContext || window.webkitAudioContext)();
    audioContext.decodeAudioData(arrayBuffer, (audioBuffer) => {
      // buffer, samplesPerPixel, isMono, startOffset, endOffset, bitResolution
      this.setState({ duration: audioBuffer.duration })
      var peaks = extractPeaks(audioBuffer, 441, true);
      console.log(peaks)
      const array = Array.from(peaks.data[0])
      const peaksBlob = new Blob([ JSON.stringify(array) ], {type: "application/json"});
      this.uploadAudioAndPeaks(audioFile, peaksBlob)
    })
  }

  uploadAudioAndPeaks(audioFile, peaksBlob) {
    const { episode } = this.props
    const updatedEpisode = { ...episode }
    this.setState({ status: "Removing old files..." })
    this.destroyTaggedFile('peaks')
    this.destroyTaggedFile('audio')
    .then(() => {
      return this.uploadTaggedFile(peaksBlob, 'peaks', 'episode-' + this.props.episode.id + '-peaks.json')
    })
    .then(peaksResult => {
      updatedEpisode.settings.peaks = peaksResult
      return this.uploadTaggedFile(audioFile, 'audio', this.state.filename)
    })
    .then(audioResult => {
      updatedEpisode.settings.audio = audioResult
      return actions.episode.update(updatedEpisode)
    })
    .then(res => {
      this.setState({ status: "Upload complete", working: false })
    })
  }

  uploadTaggedFile(file, tag, fn) {
    return new Promise((resolve, reject) => {
      this.setState({ status: "Uploading " + tag + "..." })
      const uploadData = {
        tag,
        file,
        __file_filename: fn,
        username: this.props.currentUser.username,
      }
      console.log(uploadData)
      return actions.upload.upload(uploadData).then(data => {
        console.log(data)
        resolve(data.res)
      })
    })
  }

  destroyTaggedFile(tag) {
    return new Promise((resolve, reject) => {
      if (!this.props.episode.settings[tag]) {
        return resolve();
      }
      actions.upload.destroy(this.props.episode.settings[tag])
      .then(() => {
        console.log('Destroy successful')
        resolve()
      })
      .catch(() => {
        console.log('Error deleting the image')
        reject()
      })
    })
  }

  render() {
    const { episode, peaks } = this.props
    return (
      <div className="sidebar-content wave-upload">
        {peaks.length && (
          <div>
            Peaks: {peaks.length}
          </div>
        )}
        <div className="uploadButton">
          <button>
            <span>
              {episode.settings.audio
                ? "Upload a new audio file"
                : "Upload an audio file"
              }
            </span>
          </button>
          <input
            type="file"
            accept="audio/mp3"
            onChange={this.upload.bind(this)}
            required={this.props.required}
          />
        </div>
        <small>Upload an MP3, encoded 192kbit constant bitrate, 44.1kHz stereo</small>
        {this.state.status && (
          <div className='status'>
            {this.state.working && <Loader />}
            <div className='status-message'>{this.state.status}</div>
            {this.state.filename && <small>{this.state.filename}</small>}
            {this.state.size && <small>{'Size: '}{formatSize(this.state.size)}</small>}
            {!!this.state.duration && <small>{'Duration: '}{timestampHMS(this.state.duration)}</small>}
          </div>
        )}
      </div>
    )
  }
}

const mapStateToProps = state => ({
  peaks: state.align.peaks,
  currentUser: state.auth.user,
  project: state.site.project,
  episode: state.site.episode,
})

export default connect(mapStateToProps)(WaveUpload)