-
Notifications
You must be signed in to change notification settings - Fork 0
/
audio-playback.js
226 lines (208 loc) · 5.81 KB
/
audio-playback.js
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import React from 'react';
import PropTypes from 'prop-types';
import {StyledPlayer} from '@newfrontdoor/audio-player';
import PatchEvent, {set, unset} from 'part:@sanity/form-builder/patch-event';
import Dropzone from 'react-dropzone';
import {ScaleLoader} from 'react-spinners';
import {retry} from '@lifeomic/attempt';
import styles from './plugins/s3-upload-widget/s3upload.css';
const createPatchFrom = value =>
PatchEvent.from(value === '' ? unset() : set(value));
const bucket = '';
const getPresignedPostData = (selectedFile, bucket) => {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
// Set the proper URL here.
const url =
'';
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(
JSON.stringify({
name: selectedFile.name,
type: selectedFile.type,
bucket
})
);
xhr.addEventListener('load', e => {
resolve(JSON.parse(e.target.response));
});
});
};
const uploadFileToS3 = (presignedPostData, file) => {
return new Promise((resolve, reject) => {
const formData = new FormData();
Object.keys(presignedPostData.fields).forEach(key => {
formData.append(key, presignedPostData.fields[key]);
});
// Actual file has to be appended last.
formData.append('file', file);
fetch(presignedPostData.url, {
method: 'post',
body: formData
}).then(response => {
if (response.status === 204) {
resolve();
} else {
reject(response);
}
});
});
};
const baseStyle = {
borderWidth: 2,
borderColor: '#666',
borderStyle: 'dashed',
borderRadius: 5
};
const activeStyle = {
borderStyle: 'solid',
borderColor: '#6c6',
backgroundColor: '#eee'
};
const rejectStyle = {
borderStyle: 'solid',
borderColor: '#c66',
backgroundColor: '#eee'
};
export default class AudioPlayer extends React.Component {
state = {
title: '',
passage: '',
preachedDate: '',
speaker: '',
series: '',
key: null,
fileOnS3: false,
error: false
};
static propTypes = {
type: PropTypes.shape({
title: PropTypes.string
}).isRequired,
value: PropTypes.string
};
onDrop = acceptedFiles => {
this.activateUpload(acceptedFiles[0], bucket);
this.setState({fileName: acceptedFiles[0].name});
};
async activateUpload(selectedFile, bucket) {
await getPresignedPostData(selectedFile, bucket).then(data => {
this.completeUpload(selectedFile, data.data);
});
}
completeUpload(selectedFile, key) {
try {
uploadFileToS3(key, selectedFile)
.then(() => {
this.setState({
fileOnS3: true
});
})
.catch(() => {
console.log('there was a problem with setting fileonS3 to true');
});
console.log(key.fields.key);
this.props.onChange(createPatchFrom(key.fields.key));
console.log('File was successfully uploaded!');
} catch (error) {
console.log('An error occurred!', error.message);
}
}
checkAWS = async () => {
const response = await fetch(
`https://bucket-url/${this.props.value}`,
{
method: 'HEAD',
redirect: 'follow'
}
);
// Abort retrying if the resource doesn't exist
if (response.status !== 200) {
throw new Error(response.statusText);
}
return true;
};
componentDidMount() {
if (this.props.value) {
(async () => {
const result = await retry(this.checkAWS, {
delay: 4000,
factor: 2,
maxAttempts: 4
});
this.setState({
fileOnS3: result
});
})().catch(error => {
console.log(error);
this.setState({
error: true
});
});
}
}
render() {
const {type, value} = this.props;
return (
<div>
<h2>{value ? type.title : 'Upload Audio'}</h2>
{value && this.state.fileOnS3 ? (
<StyledPlayer
hasPlaybackSpeed
hasBorder
isInvert={false}
highlight="#548BF4"
base="#ddd"
audio={`https://s3.us-west-2.amazonaws.com/${bucket}/${value}`}
/>
) : value && this.state.error ? (
<div>
Audio could not load due to an error. Please contact
</div>
) : value ? (
<div>
<ScaleLoader
height={30}
width={10}
radius={2}
margin="2px"
color="#36D7B7"
/>
<p>Loading audio file...</p>
<p>
N.b. It's ok to hit the 'Publish' button below while file is
loading.
</p>
</div>
) : (
<div className={styles.dropArea}>
<Dropzone accept="audio/*" onDrop={this.onDrop}>
{({getRootProps, getInputProps, isDragActive, isDragReject}) => {
let styles = {...baseStyle};
styles = isDragActive ? {...styles, ...activeStyle} : styles;
styles = isDragReject ? {...styles, ...rejectStyle} : styles;
return (
<div {...getRootProps()} style={styles}>
<input {...getInputProps()} />
{this.state.fileName ? (
<p>'{this.state.fileName}' is uploading...</p>
) : isDragReject ? (
<p>Unsupported file type...</p>
) : (
<p>
Try dropping an audio file here, or click to select file
for upload.
</p>
)}
</div>
);
}}
</Dropzone>
</div>
)}
</div>
);
}
}