Skip to content

Commit 0af4b2d

Browse files
Tuupertunutcaasi
authored andcommitted
Added cache for Imgur links.
1 parent 717fdac commit 0af4b2d

File tree

2 files changed

+36
-12
lines changed

2 files changed

+36
-12
lines changed

package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,10 @@
2828
"irc-colors": "^1.2.1",
2929
"irc-framework": "^2.8.1",
3030
"lodash": "^4.12.0",
31+
"md5": "2.2.1",
3132
"mime": "^2.2.0",
3233
"mkdirp": "^0.5.1",
34+
"modern-lru": "1.3.0",
3335
"node-static": "^0.7.7",
3436
"os-homedir": "^1.0.1",
3537
"qs": "^6.5.2",

src/tg/imgur-utils.js

Lines changed: 34 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ const fs = require('fs-extra');
88
const imgur = require('imgur');
99
const webp = require('webp-converter');
1010
const logger = require('winston');
11+
const LRU = require('modern-lru');
12+
const md5 = require('md5');
13+
14+
const linkCache = new LRU(1000);
1115

1216
if (config.uploadToImgur) {
1317
imgur.setClientId(config.imgurClientId);
@@ -21,22 +25,40 @@ exports.uploadToImgur = function(fileId, config, tg, callback) {
2125
tg.downloadFile(fileId, downloadDirPath)
2226
.then(function(filePath) {
2327

24-
/* Imgur doesn't allow webp, so convert them to png. */
25-
if (path.extname(filePath) === '.webp') {
26-
let convertedFilePath = filePath + '.png';
27-
return convertWebpToPng(filePath, convertedFilePath);
28-
} else {
29-
return Promise.resolve(filePath);
30-
}
31-
})
32-
.then(function(filePath) {
33-
return imgur.uploadFile(filePath);
28+
return fs.readFile(filePath)
29+
.then(function(fileContentBuffer) {
30+
const md5Hash = md5(fileContentBuffer);
31+
const imgurLink = linkCache.get(md5Hash);
32+
if (imgurLink === undefined) {
33+
34+
/* Imgur doesn't allow webp, so convert them to png. */
35+
let conversionPromise;
36+
if (path.extname(filePath) === '.webp') {
37+
const convertedFilePath = filePath + '.png';
38+
conversionPromise = convertWebpToPng(filePath, convertedFilePath);
39+
} else {
40+
conversionPromise = Promise.resolve(filePath);
41+
}
42+
43+
return conversionPromise
44+
.then(function(newFilePath) {
45+
return imgur.uploadFile(newFilePath);
46+
})
47+
.then(function(json) {
48+
const link = json.data.link;
49+
linkCache.set(md5Hash, link);
50+
return link;
51+
});
52+
} else {
53+
return Promise.resolve(imgurLink);
54+
}
55+
});
3456
})
35-
.then(function(json) {
57+
.then(function(link) {
3658

3759
fs.remove(downloadDirPath)
3860
.then(function() {
39-
callback(json.data.link);
61+
callback(link);
4062
})
4163
.catch(function(error) {
4264
logger.error(error);

0 commit comments

Comments
 (0)