@@ -8,6 +8,10 @@ const fs = require('fs-extra');
8
8
const imgur = require ( 'imgur' ) ;
9
9
const webp = require ( 'webp-converter' ) ;
10
10
const logger = require ( 'winston' ) ;
11
+ const LRU = require ( 'modern-lru' ) ;
12
+ const md5 = require ( 'md5' ) ;
13
+
14
+ const linkCache = new LRU ( 1000 ) ;
11
15
12
16
if ( config . uploadToImgur ) {
13
17
imgur . setClientId ( config . imgurClientId ) ;
@@ -21,22 +25,40 @@ exports.uploadToImgur = function(fileId, config, tg, callback) {
21
25
tg . downloadFile ( fileId , downloadDirPath )
22
26
. then ( function ( filePath ) {
23
27
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
+ } ) ;
34
56
} )
35
- . then ( function ( json ) {
57
+ . then ( function ( link ) {
36
58
37
59
fs . remove ( downloadDirPath )
38
60
. then ( function ( ) {
39
- callback ( json . data . link ) ;
61
+ callback ( link ) ;
40
62
} )
41
63
. catch ( function ( error ) {
42
64
logger . error ( error ) ;
0 commit comments