-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathapp.js
479 lines (438 loc) · 13.5 KB
/
app.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
var fs = require('fs');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var express = require('express')
var https = require('https')
var endMw = require('express-end')
var stream = require('stream');
const getDuration = require('get-video-duration');
var app = express()
// If modifying these scopes, delete your previously saved credentials
var SCOPES = ['https://www.googleapis.com/auth/drive'];
var TOKEN_DIR = __dirname + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'googleDriveAPI.json';
var TEMP_DIR = __dirname + '/.temp/'
var CHUNK_SIZE = 20000000
var PORT = 9001;
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Drive API.
authorize(JSON.parse(content), startLocalServer);
});
function authorize(credentials, callback) {
var clientSecret = credentials.web.client_secret;
var clientId = credentials.web.client_id;
var redirectUrl = credentials.web.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
refreshTokenIfNeed(oauth2Client, callback)
}
});
}
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ');
console.log(authUrl)
callback(oauth2Client)
}
function refreshTokenIfNeed(oauth2Client, callback){
var timeNow = (new Date).getTime()
if(oauth2Client.credentials.expiry_date > timeNow)
callback(oauth2Client)
else
refreshToken(oauth2Client, callback)
}
function refreshToken(oauth2Client, callback) {
oauth2Client.refreshAccessToken(function(err, token) {
if (err) {
console.log('Error while trying to refresh access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client)
})
}
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token), err => {
if(err) throw err
});
}
function startLocalServer(oauth2Client){
app.get(/\/code/, function (req, res){
if(req.query.code){
oauth2Client.getToken(req.query.code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
if(!token.refresh_token){
console.log('No refresh token found.');
return;
}
oauth2Client.credentials = token;
storeToken(token);
});
res.send('Successfully authenticated!');
}
})
app.get(/\/.{15,}/, function(req, res){
refreshTokenIfNeed(oauth2Client, oauth2Client => {
var access_token = oauth2Client.credentials.access_token
var urlSplitted = req.url.match('^[^?]*')[0].split('/')
var fileId = urlSplitted[1]
var action = null
if(urlSplitted[2])
action = urlSplitted[2]
var fileInfo = getInfoFromId(fileId)
if(fileInfo){
performRequest(fileInfo)
}else{
getFileInfo(fileId, access_token, info =>{
addInfo(fileId, info)
var fileInfo = getInfoFromId(fileId)
performRequest(fileInfo)
})
}
function performRequest(fileInfo){
var skipDefault = false
if(action == 'download'){
performRequest_download_start(req, res, access_token, fileInfo)
skipDefault = true
}
if(action == 'download_stop'){
performRequest_download_stop(req, res, access_token, fileInfo)
skipDefault = true
}
if(!skipDefault){
performRequest_default(req, res, access_token, fileInfo)
}
}
})
});
app.listen(PORT)
console.log("Server started at port: " + PORT)
}
function performRequest_default(req, res, access_token, fileInfo){
var fileSize = fileInfo.info.size
var fileMime = fileInfo.info.mimeType
var fileId = fileInfo.id
const range = req.headers.range
if (range) {
const parts = range.replace(/bytes=/, "").split("-")
const start = parseInt(parts[0], 10)
const end = parts[1]
? parseInt(parts[1], 10)
: fileSize-1
const chunksize = (end-start)+1
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
//'Content-Type': 'video/mp4',
'Content-Type': fileMime
}
res.writeHead(206, head);
downloadFile(fileId, access_token, start, end,
res,
() => {res.end()},
(richiesta) => {
res.once('close', function() {
if(typeof richiesta.abort === "function")
richiesta.abort()
if(typeof richiesta.destroy === "function")
richiesta.destroy()
})
}
)
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': fileMime,
}
res.writeHead(200, head)
downloadFile(fileId, access_token, 0, fileSize-1,
res,
() => {res.end()},
(richiesta) => {
res.once('close', function() {
if(typeof richiesta.abort === "function")
richiesta.abort()
if(typeof richiesta.destroy === "function")
richiesta.destroy()
})
}
)
}
}
function performRequest_download_start(req, res, access_token, fileInfo){
var fileSize = fileInfo.info.size
var fileId = fileInfo.id
var status = getDownloadStatus(fileId)
if(!status){
status = addDownloadStatus(fileId)
var lastTime = (new Date).getTime()
var downloadedSize = 0
var downloadSize = 0
var startChunk = 0
if(req.query.p && req.query.p >= 0 && req.query.p <= 100)
startChunk = Math.floor(((fileSize)/CHUNK_SIZE) * req.query.p / 100)
if(req.query.c && req.query.c >= 0 && req.query.c <= Math.floor((fileSize)/CHUNK_SIZE))
startChunk = req.query.c
downloadSize = fileSize - startChunk*CHUNK_SIZE
var videoDuration = null
fileInfo.getVideoLength.then((data) => {
videoDuration = data
})
.catch((error) => {
console.log(error)
})
var echoStream = new stream.Writable()
var chunkSizeSinceLast = 0
echoStream._write = function (chunk, encoding, done) {
chunkSizeSinceLast += chunk.length
var nowTime = (new Date).getTime()
//update status
if(nowTime - lastTime > 2000){
var speedInMBit = ((chunkSizeSinceLast*8 / (nowTime - lastTime)) / 1000)
var speedInByte = (speedInMBit/8) * 1000000
downloadedSize += chunkSizeSinceLast
status.status = (downloadedSize/downloadSize * 100).toFixed(3)
status.speedMbit = speedInMBit.toFixed(3)
status.speedByte = speedInByte
if(videoDuration){
var timeLeftBeforeStreaming = Math.max(Math.round(((downloadSize-downloadedSize) / speedInByte) - (videoDuration*downloadSize/fileSize)) , 0)
status.timeLeftBeforeStreaming = timeLeftBeforeStreaming
}
lastTime = nowTime
chunkSizeSinceLast = 0
}
done();
}
downloadFile(fileId, access_token, startChunk*CHUNK_SIZE, fileSize-1,
echoStream,
() => {
removeDownloadStatus(fileId)
},
(richiesta) => {
status.onClose = () =>{
if(typeof richiesta.abort === "function")
richiesta.abort()
if(typeof richiesta.destroy === "function")
richiesta.destroy()
removeDownloadStatus(fileId)
}
}
)
}
res.writeHead(200)
res.write(JSON.stringify(status))
res.end()
}
function performRequest_download_stop(req, res, access_token, fileInfo){
var fileId = fileInfo.id
var status = getDownloadStatus(fileId)
if(status){
status.onClose()
}
res.writeHead(200)
res.end()
}
function downloadFile(fileId, access_token, start, end, pipe, onEnd, onStart){
var startChunk = Math.floor(start / CHUNK_SIZE)
var chunkName = TEMP_DIR + fileId + '@' + startChunk
if(fs.existsSync(chunkName)){
console.log('req: ' + start + ' / ' + end + ' offline')
var relativeStart = (start > startChunk*CHUNK_SIZE) ? start - (startChunk*CHUNK_SIZE) : 0
var relativeEnd = (end > (startChunk+1)*CHUNK_SIZE ) ? CHUNK_SIZE : end - (startChunk*CHUNK_SIZE)
let readStream = fs.createReadStream(chunkName, {start: relativeStart, end: relativeEnd})
readStream.pipe(pipe, {end:false})
readStream.on('data', chunk => {
//onData(chunk)
})
readStream.on('end', () => {
if (end >= (startChunk+1)*CHUNK_SIZE ){ //Da rivedere
console.log('->')
downloadFile(fileId, access_token, (startChunk+1)*CHUNK_SIZE, end, pipe, onEnd, onStart)
}else{
onEnd()
}
})
readStream.on('close', () => {
})
readStream.on('error', (err) => {
console.log(err)
})
onStart(readStream)
}else{
console.log('req: ' + start + ' / ' + end + ' online')
httpDownloadFile(fileId, access_token, start, end, pipe, onEnd, onStart)
}
}
function httpDownloadFile(fileId, access_token, start, end, pipe, onEnd, onStart){
var options = {
host: 'www.googleapis.com',
path: '/drive/v3/files/'+fileId+'?alt=media',
method: 'GET',
headers: {
'Authorization': 'Bearer ' + access_token,
'Range': 'bytes='+start+'-'+end
}
};
callback = function(response) {
var arrBuffer = []
var arrBufferSize = 0
response.pipe(pipe, {end:false})
response.on('data', function (chunk) {
var buffer = Buffer.from(chunk)
arrBuffer.push(buffer)
arrBufferSize += buffer.length
var nextChunk = Math.floor((start + arrBufferSize) / CHUNK_SIZE)
var chunkName = TEMP_DIR + fileId + '@' + nextChunk
if(fs.existsSync(chunkName) && start + arrBufferSize < end){
req.abort()
downloadFile(fileId, access_token, start + arrBufferSize, end, pipe, onEnd, onStart)
}else{
if(arrBufferSize >= CHUNK_SIZE*2){
arrBuffer = [Buffer.concat(arrBuffer, arrBufferSize)]
arrBuffer = flushBuffers(arrBuffer, fileId, start)
arrBufferSize = arrBuffer[0].length
var offset = (Math.ceil(start / CHUNK_SIZE) * CHUNK_SIZE) - start
start += CHUNK_SIZE + offset
}
}
})
response.on('end', function () {
//Aggiungere il controllo se c'è un errore
if(!req.aborted){
onEnd()
}
})
}
var req = https.request(options, callback)
req.on('error', function(err) {
});
req.end()
onStart(req)
}
function flushBuffers(arrBuffer, fileId, startByte){
var dirtyBuffer = Buffer.alloc(CHUNK_SIZE)
var offset = (Math.ceil(startByte / CHUNK_SIZE) * CHUNK_SIZE) - startByte
arrBuffer[0].copy(dirtyBuffer, 0, offset, offset + CHUNK_SIZE )
var chunkName = TEMP_DIR + fileId + '@' + Math.floor((offset + startByte) / CHUNK_SIZE)
try {
fs.mkdirSync(TEMP_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(chunkName, dirtyBuffer, (err) => {
if (err) throw err;
console.log('The chunk has been saved!');
});
var remainBufferSize = arrBuffer[0].length - CHUNK_SIZE - offset
var remainBuffer = Buffer.alloc(remainBufferSize)
if(remainBuffer.length > 0){
arrBuffer[0].copy(remainBuffer, 0, CHUNK_SIZE + offset, arrBuffer[0].length)
}
return [remainBuffer]
}
function getFileInfo(fileId, access_token, onData){
var options = {
host: 'www.googleapis.com',
path: '/drive/v3/files/'+fileId+'?alt=json&fields=*',
method: 'GET',
headers: {
'Authorization': 'Bearer ' + access_token
}
};
callback = function(response) {
var allData = ''
response.on('data', function (chunk) {
allData += chunk
});
response.on('end', function () {
var info = JSON.parse(allData)
if(!info.error)
onData(info)
else
console.log(info.error)
});
}
https.request(options, callback).end();
}
//File info
var filesInfo = []
function getInfoFromId(fileId){
var result = null
filesInfo.forEach(data =>{
if(data.id == fileId){
result = data
}
})
return result
}
function addInfo(fileId, fileInfo){
var info = {id: fileId, info: fileInfo}
info.getVideoLength = new Promise((resolve, reject) => {
if(!info.videoLength){
getDuration('http://127.0.0.1:' + PORT + '/' + fileId).then((duration) => {
info.videoLength = duration
resolve(duration)
})
.catch((error) => {
console.log(error);
reject(error)
})
}else{
resolve(info.videoLength)
}
})
filesInfo.push(info)
}
//Downloads status
var downloadStatus = []
function getDownloadStatus(fileId){
var result = null
downloadStatus.forEach(data =>{
if(data.id == fileId){
result = data
}
})
return result
}
function addDownloadStatus(fileId){
var status = {id: fileId}
status.onClose = () => {}
downloadStatus.push(status)
return status
}
function removeDownloadStatus(fileId){
for(var i =0; i < downloadStatus.length; i++){
if(downloadStatus[i].id == fileId){
downloadStatus.splice(i, 1)
}
}
}