-
Notifications
You must be signed in to change notification settings - Fork 1
/
thetaVideoManager.js
101 lines (90 loc) · 2.7 KB
/
thetaVideoManager.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
const request = require('request');
const fs = require('fs');
const log = require('./log');
const presignOptions = {
'method': 'POST',
'url': 'https://api.thetavideoapi.com/upload',
'headers': {
'x-tva-sa-id': process.env.THETA_VIDEO_API_KEY,
'x-tva-sa-secret': process.env.THETA_VIDEO_API_SECRET
}
};
const getOptionsToUpload = (presigned_url, file) => {
return {
'method': 'PUT',
'url': presigned_url,
'headers': {
'Content-Type': 'application/octet-stream'
},
body: file
};
};
const getOptionsToTranscode = (id, title) => {
return {
'method': 'POST',
'url': 'https://api.thetavideoapi.com/video',
'headers': {
'x-tva-sa-id': process.env.THETA_VIDEO_API_KEY,
'x-tva-sa-secret': process.env.THETA_VIDEO_API_SECRET,
'Content-Type': 'application/json'
},
body: JSON.stringify({
source_upload_id: id,
playback_policy: 'public',
file_name: title
})
};
};
const uploadVideo = async (file, videoTitle, retries=0) => {
if (!fs.existsSync(file)) {
if (retries>5) throw new Error('file does not exist');
log.info(`[VM] file ${ file } does not exist, wait 1 second, ${retries + 1} retry`);
await new Promise(resolve => setTimeout(resolve, 1000));
return await uploadVideo(file, videoTitle, ++retries);
}
const video = await new Promise((resolve, reject) => {
request(presignOptions, (error, response) => {
if (error) return reject(error);
const res = JSON.parse(response.body);
log.info(res);
resolve(res.body.uploads[0]);
});
});
log.info(video);
const { presigned_url } = video;
log.info(presigned_url);
const uploadOptions = getOptionsToUpload(presigned_url);
await new Promise((resolve, reject) => {
const r = request(uploadOptions);
log.info(r);
var upload = fs.createReadStream(file);
upload.pipe(r);
var upload_progress = 0;
upload.on("data", function (chunk) {
upload_progress += chunk.length
log.info(new Date(), upload_progress);
})
upload.on("end", function (res) {
log.info('Finished');
resolve();
});
});
// transcode video
console.log('transcoding video');
const transcodeOptions = getOptionsToTranscode(video.id, videoTitle);
const processedVideo = await new Promise((resolve, reject) => {
request(transcodeOptions, (error, response) => {
if (error) throw new Error(error);
console.log(response);
const res = JSON.parse(response.body);
console.log('video transcoded');
console.log(res.body);
resolve(res.body.videos[0]);
});
});
console.log('processed video', processedVideo);
return processedVideo;
};
module.exports = {
uploadVideo
};