From 2247d248c8a14aebfabf27c71bc3229d545f41d7 Mon Sep 17 00:00:00 2001 From: Yago Date: Sat, 26 Sep 2015 20:28:04 +0200 Subject: [PATCH] Chain promise on getFileLink and return a new one. Call reject on error --- src/telegram.js | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/src/telegram.js b/src/telegram.js index a6832ec..1202429 100644 --- a/src/telegram.js +++ b/src/telegram.js @@ -449,23 +449,20 @@ TelegramBot.prototype.getFileLink = function(fileId) { */ TelegramBot.prototype.downloadFile = function(fileId, downloadDir) { - var bot = this; + return this.getFileLink(fileId).then(function (fileURI) { + var fileName = fileURI.slice(fileURI.lastIndexOf('/') + 1); + // TODO: Ensure fileName doesn't contains slashes + var filePath = downloadDir + '/' + fileName; + return new Promise(function (resolve, reject) { + request({uri: fileURI}) + .pipe(fs.createWriteStream(filePath)) + .on('error', reject) + .on('close', function() { + resolve(filePath); + }); + }); + }); - return new Promise(function(resolve, reject) { - - bot.getFileLink(fileId).then(function(fileURI) { - // Apparently, this is not the safest method to get the file name, - // but I am pretty sure that Telegram will not include slashes when generating names - var fileName = fileURI.slice(fileURI.lastIndexOf('/') + 1); - var filePath = downloadDir + '/' + fileName; - - request({uri: fileURI}) - .pipe(fs.createWriteStream(filePath)) - .on('close', function() { - resolve(filePath); - }); - }); - }); } module.exports = TelegramBot;