forked from grayleonard/node-youtube-resumable-upload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
155 lines (136 loc) · 4.76 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
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
var fs = require('fs');
var google = require('googleapis');
var request = require('request');
var EventEmitter = require('events').EventEmitter;
function resumableUpload() {
this.byteCount = 0; //init variables
this.tokens = {};
this.filepath = '';
this.metadata = {};
this.monitor = false;
this.retry = 0;
};
//Init the upload by POSTing google for an upload URL (saved to self.location)
resumableUpload.prototype.eventEmitter = new EventEmitter();
resumableUpload.prototype.initUpload = function(callback, errorback) {
var self = this;
var options = {
url: 'https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status,contentDetails',
headers: {
'Host': 'www.googleapis.com',
'Authorization': 'Bearer ' + this.tokens.access_token,
'Content-Length': JSON.stringify(this.metadata).length,
'Content-Type': 'application/json',
'X-Upload-Content-Length': fs.statSync(this.filepath).size,
'X-Upload-Content-Type': 'video/*'
},
body: JSON.stringify(this.metadata)
};
//Send request and start upload if success
request.post(options, function(error, response, body) {
if(!error) {
if(!response.headers.location && body){
// bad-token, bad-metadata, etc...
body = JSON.parse(body);
if(body.error){
if(errorback)
errorback(new Error(body.error));
return;
}
}
//console.log('Location: ' + response.headers.location + ' ...');
self.location = response.headers.location;
//once we get the location to upload to, we start the upload
//console.log('Starting upload ...');
self.putUpload(callback, errorback);
if(self.monitor){ //start monitoring if the bool 'monitor' is true (defaults to false)
//console.log('Starting monitor ...');
self.startMonitoring();
}
}else{
if(errorback)
errorback(new Error(error));
}
});
}
//Pipes uploadPipe to self.location (Google's Location header)
resumableUpload.prototype.putUpload = function(callback, errorback) {
var self = this;
var options = {
url: self.location, //self.location becomes the Google-provided URL to PUT to
headers: {
'Authorization': 'Bearer ' + self.tokens.access_token,
'Content-Length': fs.statSync(self.filepath).size - self.byteCount,
'Content-Type': 'video/*'
}
};
try {
//creates file stream, pipes it to self.location
var uploadPipe = fs.createReadStream(self.filepath, {start: self.byteCount, end: fs.statSync(self.filepath).size });
uploadPipe.pipe(request.put(options, function(error, response, body) {
if(!error) {
if(callback)
callback(body);
} else {
if(errorback)
errorback(new Error(error));
if(self.retry>0){
self.retry--;
self.getProgress();
self.initUpload();
}
}
}));
} catch(e) {
//console.log(e.printStackTrace());
//Restart upload
if(self.retry>0){
self.retry--;
self.getProgress();
self.initUpload();
}
}
}
//PUT every 5 seconds to get partial # of bytes uploaded
resumableUpload.prototype.startMonitoring = function() {
var self = this;
var options = {
url: self.location,
headers: {
'Authorization': 'Bearer ' + self.tokens.access_token,
'Content-Length': 0,
'Content-Range': 'bytes */' + fs.statSync(this.filepath).size
}
};
var healthCheck = function() { //Get # of bytes uploaded
request.put(options, function(error, response, body) {
if(!error && response.headers.range != undefined) {
self.eventEmitter.emit('progress', response.headers.range.substring(8, response.headers.range.length) + '/' + fs.statSync(self.filepath).size);
if(response.headers.range == fs.statSync(self.filepath).size) {
clearInterval(healthCheckInteral);
}
}
});
};
var healthCheckInterval = setInterval(healthCheck, 5000);
}
//If an upload fails, get partial # of bytes. Called by putUpload()
resumableUpload.prototype.getProgress = function() {
var self = this;
var options = {
url: self.location,
headers: {
'Authorization': 'Bearer ' + self.tokens.access_token,
'Content-Length': 0,
'Content-Range': 'bytes */' + fs.statSync(this.filepath).size
}
};
request.put(options, function(error, response, body) {
try {
self.byteCount = response.headers.range.substring(8, response.headers.range.length); //parse response
} catch(e) {
//console.log('error');
}
});
}
module.exports = resumableUpload;