forked from beatfreaker/subdownloader
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
96 lines (90 loc) · 2.56 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
'use strict';
var Promise = require('pinkie-promise');
var crypto = require('crypto');
var fs = require('fs');
var path = require('path');
var http = require('http');
var obj = {fileName: '', hash: ''};
var returnObj = {success: [], failed: []};
var EventEmitter = require('events').EventEmitter;
var exp = new EventEmitter();
var getHash = function (obj) {
return new Promise(function (resolve, reject) {
var shasum = crypto.createHash('md5');
var s = fs.createReadStream(obj.fileName, {start: 0, end: (64 * 1024) - 1});
s.on('data', function (d) {
shasum.update(d);
});
s.on('end', function () {
var stats = fs.statSync(obj.fileName);
var sNew = fs.createReadStream(obj.fileName, {start: stats.size - (64 * 1024), end: stats.size - 1});
sNew.on('data', function (d) {
shasum.update(d);
});
sNew.on('end', function () {
var d = shasum.digest('hex');
obj.hash = d;
resolve(obj);
});
});
});
};
var downloadSubtitle = function (obj) {
return new Promise(function (resolve, reject) {
var srtFileName = path.basename(obj.fileName, path.extname(obj.fileName)) + '.srt';
var srtFilePathName = path.dirname(obj.fileName) + '/' + srtFileName;
var finalData = '';
var green = '\u001b[42m \u001b[0m';
exp.emit('processing', obj);
var options = {
hostname: 'api.thesubdb.com',
path: '/?action=download&hash=' + obj.hash + '&language=en',
method: 'GET',
headers: {'user-agent': 'SubDB/1.0'}
};
http.get(options, function (res) {
exp.emit('response', obj, res);
res.statusCode = '' + (res.statusCode).toString();
res.setEncoding('utf8');
res.on('data', function (chunk) {
finalData += chunk;
exp.emit('data', obj, chunk);
});
res.on('end', function () {
exp.emit('end', obj, res);
if (res.statusCode === '200') {
fs.writeFile(srtFilePathName, finalData, function (err) {
if (err) {
console.log(err);
}
returnObj.success.push(obj.fileName);
resolve(obj);
});
} else {
returnObj.failed.push(obj.fileName);
resolve('error');
}
});
});
});
};
var processFiles = function (arr) {
return arr.reduce(function (promise, file) {
return promise.then(function () {
obj.fileName = file;
exp.emit('processing', obj);
return getHash(obj).then(function (obj) {
return downloadSubtitle(obj);
});
});
}, Promise.resolve());
};
exp.subdownload = function (fileList, opt) {
opt = opt || {};
return new Promise(function (resolve, reject) {
processFiles(fileList).then(function () {
resolve(returnObj);
});
});
};
module.exports = exp;