-
Notifications
You must be signed in to change notification settings - Fork 568
/
rest_chunked_upload.js
88 lines (74 loc) · 2.5 KB
/
rest_chunked_upload.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
var assert = require('assert');
var fs = require('fs');
var mime = require('mime');
var path = require('path');
var config = require('../config1');
var Twit = require('../lib/twitter');
describe('twit.postMediaChunked', function () {
it('Posting media via twit.postMediaChunked works with .mp4', function (done) {
var twit = new Twit(config);
var mediaFilePath = path.join(__dirname, './video/station.mp4');
twit.postMediaChunked({ file_path: mediaFilePath }, function (err, bodyObj, resp) {
exports.checkUploadMedia(err, bodyObj, resp)
done()
})
})
it('POST media/upload via manual commands works with .mp4', function (done) {
var mediaFilePath = path.join(__dirname, './video/station.mp4');
var mediaType = mime.lookup(mediaFilePath);
var mediaFileSizeBytes = fs.statSync(mediaFilePath).size;
var twit = new Twit(config);
twit.post('media/upload', {
'command': 'INIT',
'media_type': mediaType,
'total_bytes': mediaFileSizeBytes
}, function (err, bodyObj, resp) {
assert(!err, err);
var mediaIdStr = bodyObj.media_id_string;
var isStreamingFile = true;
var isUploading = false;
var segmentIndex = 0;
var fStream = fs.createReadStream(mediaFilePath, { highWaterMark: 5 * 1024 * 1024 });
var _finalizeMedia = function (mediaIdStr, cb) {
twit.post('media/upload', {
'command': 'FINALIZE',
'media_id': mediaIdStr
}, cb)
}
var _checkFinalizeResp = function (err, bodyObj, resp) {
exports.checkUploadMedia(err, bodyObj, resp)
done();
}
fStream.on('data', function (buff) {
fStream.pause();
isStreamingFile = false;
isUploading = true;
twit.post('media/upload', {
'command': 'APPEND',
'media_id': mediaIdStr,
'segment_index': segmentIndex,
'media': buff.toString('base64'),
}, function (err, bodyObj, resp) {
assert(!err, err);
isUploading = false;
if (!isStreamingFile) {
_finalizeMedia(mediaIdStr, _checkFinalizeResp);
}
});
});
fStream.on('end', function () {
isStreamingFile = false;
if (!isUploading) {
_finalizeMedia(mediaIdStr, _checkFinalizeResp);
}
});
});
})
})
exports.checkUploadMedia = function (err, bodyObj, resp) {
assert(!err, err)
assert(bodyObj)
assert(bodyObj.media_id)
assert(bodyObj.media_id_string)
assert(bodyObj.size)
}