From 7c28e5c072ca27e6f2fc4a488c32718514aad924 Mon Sep 17 00:00:00 2001 From: Florrie Date: Tue, 29 May 2018 09:59:01 -0300 Subject: Move cache stuff to downloaders.js --- downloaders.js | 18 +++++++++++++++--- index.js | 32 ++------------------------------ 2 files changed, 17 insertions(+), 33 deletions(-) diff --git a/downloaders.js b/downloaders.js index 0853046..cd78fb0 100644 --- a/downloaders.js +++ b/downloaders.js @@ -27,7 +27,16 @@ class Downloader { const downloaders = { extension: 'mp3', // Generally target file extension + cache: { + http: {}, + youtubedl: {}, + local: {} + }, + http: arg => { + const cached = downloaders.cache.http[arg] + if (cached) return cached + const out = ( tempy.directory() + '/' + sanitize(decodeURIComponent(path.basename(arg)))) @@ -35,10 +44,13 @@ const downloaders = { return fetch(arg) .then(response => response.buffer()) .then(buffer => writeFile(out, buffer)) - .then(() => out) + .then(() => downloaders.cache.http[arg] = out) }, youtubedl: arg => { + const cached = downloaders.cache.youtubedl[arg] + if (cached) return cached + const out = ( tempy.directory() + '/' + sanitize(arg) + '.' + downloaders.extname) @@ -52,7 +64,7 @@ const downloaders = { ] return promisifyProcess(spawn('youtube-dl', opts)) - .then(() => out) + .then(() => downloaders.cache.youtubedl[arg] = out) .catch(err => false) }, @@ -85,7 +97,7 @@ const downloaders = { tempy.directory() + '/' + sanitize(base) + path.extname(arg)) return copyFile(arg, out) - .then(() => out) + .then(() => downloaders.cache.local[arg] = out) }, echo: arg => arg, diff --git a/index.js b/index.js index 6edbd01..a3b4b9f 100644 --- a/index.js +++ b/index.js @@ -5,36 +5,8 @@ const { getDownloaderFor } = require('./downloaders') const EventEmitter = require('events') class InternalApp extends EventEmitter { - constructor() { - super() - - // downloadCache [downloaderFunction] [downloaderArg] - this.downloadCache = new Map() - } - - async download(arg) { - const downloader = getDownloaderFor(arg) - if (this.downloadCache.has(downloader)) { - const category = this.downloadCache.get(downloader) - if (category.hasOwnProperty(arg)) { - return category[arg] - } - } - - const ret = await this.downloadIgnoringCache(arg) - - if (!this.downloadCache.has(downloader)) { - this.downloadCache.set(downloader, {}) - } - - this.downloadCache.get(downloader)[arg] = ret - - return ret - } - - downloadIgnoringCache(arg) { - const downloader = getDownloaderFor(arg) - return downloader(arg) + download(arg) { + return getDownloaderFor(arg)(arg) } } -- cgit 1.3.0-6-gf8a5