-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathindex.js
93 lines (80 loc) · 2.13 KB
/
index.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
const streamToPromise = require('stream-to-promise')
const rp = require('request-promise')
const url = 'https://graph-video.facebook.com'
const version = 'v3.2'
const retryMax = 10
let retry = 0
function apiInit(args, videoSize) {
const options = {
method: 'POST',
uri: `${url}/${version}/${args.id}/videos?access_token=${args.token}`,
json: true,
form: {
upload_phase: 'start',
file_size: videoSize
}
}
return rp(options).then(res => res)
}
function apiFinish(args, upload_session_id, video_id) {
const {token, id, stream, ...extraParams} = args
const options = {
method: 'POST',
json: true,
uri: `${url}/${version}/${args.id}/videos`,
formData: {
...extraParams,
upload_session_id,
access_token: args.token,
upload_phase: 'finish',
}
}
return rp(options)
.then(res => ({...res, video_id}))
}
function uploadChunk(args, id, start, chunk) {
const formData = {
access_token: args.token,
upload_phase: 'transfer',
start_offset: start,
upload_session_id: id,
video_file_chunk: {
value: chunk,
options: {
filename: 'chunk'
}
}
}
const options = {
method: 'POST',
uri: `${url}/${version}/${args.id}/videos`,
formData: formData,
json: true
}
return rp(options)
.then(res => {
retry = 0
return res
})
.catch(err => {
if (retry++ >= retryMax) {
return err
}
return uploadChunk(args, id, start, chunk)
})
}
function uploadChain(buffer, args, res, ids) {
if (res.start_offset === res.end_offset) {
return ids
}
var chunk = buffer.slice(res.start_offset, res.end_offset)
return uploadChunk(args, ids[0], res.start_offset, chunk)
.then(res => uploadChain(buffer, args, res, ids))
}
function facebookApiVideoUpload(args) {
return streamToPromise(args.stream)
.then(buffer => Promise.all([buffer, apiInit(args, buffer.length)]))
.then(([buffer, res]) => uploadChain(buffer, args, res, [res.upload_session_id, res.video_id]))
.then(([id, video_id]) => apiFinish(args, id, video_id))
}
module.exports = facebookApiVideoUpload