File size: 1,957 Bytes
f120063
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const fs = require('fs')
const path = require('path')
const config = require('../config')
const { logger } = require('./logger')

class imgCacheManager {
  constructor() {
    this.cacheMap = new Map()
  }

  getCachePath(signature) {
    return path.join(config.cacheDir, `${signature}.txt`)
  }

  cacheIsExist(signature) {
    try {
      if (config.cacheMode === 'default') {
        return this.cacheMap.has(signature)
      } else {
        const cachePath = this.getCachePath(signature)
        return fs.existsSync(cachePath)
      }
    } catch (e) {
      logger.error('缓存检查失败', 'CACHE', '', e)
      return false
    }
  }

  addCache(signature, url) {
    try {
      const isExist = this.cacheIsExist(signature)

      if (isExist) {
        return false
      } else {

        if (config.cacheMode === 'default') {
          this.cacheMap.set(signature, url)
        } else {
          const cachePath = this.getCachePath(signature)
          fs.mkdirSync(config.cacheDir, { recursive: true })
          fs.writeFileSync(cachePath, url)
        }

        return true

      }
    } catch (e) {
      logger.error('添加缓存失败', 'CACHE', '', e)
      return false
    }
  }

  getCache(signature) {
    try {
      const cachePath = this.getCachePath(signature)
      const isExist = this.cacheIsExist(signature)

      if (isExist) {
        if (config.cacheMode === 'default') {
          return {
            status: 200,
            url: this.cacheMap.get(signature)
          }
        } else {
          const data = fs.readFileSync(cachePath, 'utf-8')
          return {
            status: 200,
            url: data
          }
        }
      } else {
        return {
          status: 404,
          url: null
        }
      }
    } catch (e) {
      logger.error('获取缓存失败', 'CACHE', '', e)
      return {
        status: 500,
        url: null
      }
    }
  }
}

module.exports = imgCacheManager