-
Notifications
You must be signed in to change notification settings - Fork 23
/
movie.js
80 lines (70 loc) · 2.58 KB
/
movie.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
'use strict';
const config = require('../config');
const path = require('path');
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const md5 = require('md5');
const crypto = require('crypto');
const logger = require('intel').getLogger('movie');
const VideoLib = require('node-video-lib');
const Indexer = require('./indexer');
function openMovie(req, res, next) {
let startTime = Date.now();
return Promise.resolve().then(() => {
req.file = null;
req.index = null;
req.fragmentList = null;
let name = req.params[0];
let fileName = path.join(config.mediaPath, name);
let indexName = Indexer.getIndexName(name);
return Promise.all([
fs.openAsync(fileName, 'r').then((fd) => {
req.file = fd;
}),
fs.openAsync(indexName, 'r').then((fd) => {
req.index = fd;
req.fragmentList = VideoLib.FragmentListIndexer.read(req.index);
}).catch((err) => {
let promise = Promise.resolve();
if (err.code !== 'ENOENT') {
promise = fs.unlinkAsync(indexName).catch(() => {
logger.warn('Cannot remove invalid index file:', indexName);
});
}
return promise.then(() => {
process.send({action: 'index', data: {name: name}});
});
}),
]).then(() => {
if (req.fragmentList === null) {
let movie = VideoLib.MovieParser.parse(req.file);
req.fragmentList = VideoLib.FragmentListBuilder.build(movie, config.fragmentDuration);
}
next();
}).finally(() => {
return Promise.all([req.file, req.index].map((file) => {
if (file !== null) {
return fs.closeAsync(file);
}
}));
}).then(() => {
logger.debug('Elapsed time:', (Date.now() - startTime) + 'ms', 'URL:', path.join(req.baseUrl, req.url).replace(/\\/g, '/'));
});
}).catch(next);
}
function movieKey(name) {
return Buffer.from(md5(`${name}.${config.drmSeed}.key`), 'hex');
}
function movieIv(name) {
return Buffer.from(md5(`${name}.${config.drmSeed}.iv`), 'hex');
}
function encryptChunk(name, buffer) {
let cipher = crypto.createCipheriv('aes-128-cbc', movieKey(name), movieIv(name));
return Buffer.concat([cipher.update(buffer), cipher.final()]);
}
module.exports = {
openMovie,
movieKey,
movieIv,
encryptChunk,
};