Skip to content

Commit

Permalink
Merge pull request #2 from beatfreaker/gh-cli-api
Browse files Browse the repository at this point in the history
add cli api
  • Loading branch information
beatfreaker committed Sep 30, 2015
2 parents 7e4ac6d + 4dc718f commit ea76c75
Show file tree
Hide file tree
Showing 6 changed files with 214 additions and 184 deletions.
29 changes: 21 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,39 @@ npm install -g subdownloader

## How to use

- After installation navigate to the folder `cd subdownloader`
- Execute `npm link`
- Now navigate to any folder where movies or TV series files are present through command prompt and execute `subdownload` command and let all the magic happens.
- Navigate to the folder in which you have the file for which you want to download subtitles through command prompt.
- Execute `subdownload` command and let all the magic happens.
- `sd` is a shorthand command. You can use `sd` instead of `subdownload`

## Options

- To download subtitles for all the movies in a folder execute.

`subdownload`
`> subdownload`
- To download subtitles for single movie execute.

`subdownload "Movie Name"`
`> subdownload "Movie Name"`
- To download subtitles for more then one movie but not all movies in a folder execute.

`subdownload "Movie 1" "Movie 2" .... "Movie n"`
`> subdownload "Movie 1" "Movie 2" .... "Movie n"`
- To enable deep download means to download subtitles for files in a folder as well as subfolders.

`subdownload --deep`
- Use `subdownload --help` for listing all the options available.
`> subdownload --deep`
- Use `> subdownload --help` for listing all the options available.

##API

```js
var subd = require('subdownloader');

//filesArray - is the array of path to the files for which
//you want to download the subtitles
//obj - in return you will return an object having success and failed files array
subd.subdownload(filesArray).then(function(obj){
console.log(obj);
//=> { success: [successfile1,successfile2], failed: [failedfile1]}
});
```

## Demo

Expand Down
84 changes: 84 additions & 0 deletions cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#! /usr/bin/env node
'use strict';
var subd = require('./');
var fs = require('fs');
var path = require('path');
var Q = require('q');
var isVideo = require('is-video');
var meow = require('meow');
var p = process.cwd();
var filesArray = [];

var cli = meow({
help: [
'Help\n',
' > subdownload\n',
' To download subtitles for all the files present in current folder\n',
' > subdownload --deep\n',
' To download subtitles for all the files present in current folder as well as in subfolder\n',
' > subdownload "File Name.mkv"\n',
' To download subtitles for specific file\n',
' > subdownload "File1.mkv" "File2.avi" .... "Filen"\n',
' To download subtitles for more then one file\n'
]
});

var filterFiles = function (files) {
try {
return files.filter(function (file) {
return fs.statSync(file).isFile() && isVideo(file);
});
} catch (err) {
console.log('Please check if all the file name given exists or not.');
}
};

var getFileList = function () {
var fileList;
var counter = 1;
var defered = Q.defer();
fs.readdir(p, function (err, files) {
if (err) {
throw err;
}
if (cli.input.length === 0) {
fileList = filterFiles(files);
} else {
fileList = filterFiles(cli.input);
}
if (fileList) {
fileList.forEach(function (file) {
filesArray.push(file);
counter++;
if (counter > fileList.length) {
defered.resolve(filesArray);
}
});
}
});
return defered.promise;
};

var getDeepFiles = function (currentDir) {
fs.readdirSync(currentDir).forEach(function (name) {
var filePath = path.join(currentDir, name);
var stat = fs.statSync(filePath);
if (stat.isFile() && isVideo(filePath)) {
filesArray.push(filePath);
} else if (stat.isDirectory()) {
getDeepFiles(filePath);
}
});
};

var getPara = function () {
if (cli.flags.deep) {
getDeepFiles(p);
subd.subdownload(filesArray);
} else {
getFileList().then(function (data) {
subd.subdownload(data);
});
}
};
getPara();
100 changes: 100 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
'use strict';
var Promise = require('pinkie-promise');
var crypto = require('crypto');
var fs = require('fs');
var path = require('path');
var http = require('http');
var ProgressBar = require('progress');
var chalk = require('chalk');
var obj = {fileName: '', hash: ''};
var returnObj = {success: [], failed: []};
var exp = module.exports;

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 progressBarMessage = 'Downloading ' + chalk.bgBlue.bold(srtFileName) + ' [:bar] :percent :etas | :current of :total bytes';
var finalData = '';
var green = '\u001b[42m \u001b[0m';
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) {
var len = parseInt(res.headers['content-length'], 10);
var bar = new ProgressBar(progressBarMessage, {
complete: green,
incomplete: '-',
width: 10,
total: len
});
res.statusCode = '' + (res.statusCode).toString();
res.setEncoding('utf8');
res.on('data', function (chunk) {
bar.tick(chunk.length);
finalData += chunk;
});
res.on('end', function () {
if (res.statusCode === '200') {
fs.writeFile(srtFilePathName, finalData, function (err) {
if (err) {
console.log(err);
}
returnObj.success.push(obj.fileName);
resolve(obj);
});
} else {
console.log('Sorry no subitles were found for ====> ' + chalk.bgRed.bold(obj.fileName));
returnObj.failed.push(obj.fileName);
resolve('error');
}
console.log('\n');
});
});
});
};

var processFiles = function (arr) {
return arr.reduce(function (promise, file) {
return promise.then(function () {
obj.fileName = file;
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);
});
});
};
11 changes: 8 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
{
"name": "subdownloader",
"description": "Painless subtitles downloader",
"version": "1.1.0",
"version": "2.0.0",
"author": {
"name": "Chintan Radia",
"email": "[email protected]",
"url": "http://beatfreaker.github.io/"
},
"bin": {
"subdownload": "subdownloader.js",
"sd": "subdownloader.js"
"subdownload": "cli.js",
"sd": "cli.js"
},
"bugs": {
"url": "https://github.com/beatfreaker/subdownloader/issues"
Expand All @@ -22,12 +22,17 @@
"is-video": "^1.0.1",
"meow": "^3.3.0",
"path": "^0.11.14",
"pinkie-promise": "^1.0.0",
"progress": "^1.1.8",
"q": "^1.4.1"
},
"devDependencies": {
"tape": "^4.2.0"
},
"files": [
"cli.js",
"index.js"
],
"homepage": "https://github.com/beatfreaker/subdownloader",
"keywords": [
"cli",
Expand Down
Loading

0 comments on commit ea76c75

Please sign in to comment.