|
| 1 | +import { existsSync, createWriteStream, mkdirSync } from 'graceful-fs' |
| 2 | +import { createHash } from 'crypto' |
| 3 | +import { imagesCachePath } from './constants' |
| 4 | +import { join } from 'path' |
| 5 | +import axios from 'axios' |
| 6 | +import { protocol } from 'electron' |
| 7 | + |
| 8 | +export const initImagesCache = () => { |
| 9 | + // make sure we have a folder to store the cache |
| 10 | + if (!existsSync(imagesCachePath)) { |
| 11 | + mkdirSync(imagesCachePath) |
| 12 | + } |
| 13 | + |
| 14 | + // use a fake protocol for images we want to cache |
| 15 | + protocol.registerFileProtocol('imagecache', (request, callback) => { |
| 16 | + callback({ path: getImageFromCache(request.url) }) |
| 17 | + }) |
| 18 | +} |
| 19 | + |
| 20 | +const getImageFromCache = (url: string) => { |
| 21 | + const realUrl = url.replace('imagecache://', '') |
| 22 | + // digest of the image url for the file name |
| 23 | + const digest = createHash('sha256').update(realUrl).digest('hex') |
| 24 | + const cachePath = join(imagesCachePath, digest) |
| 25 | + |
| 26 | + if (!existsSync(cachePath)) { |
| 27 | + // if not found, download in the background |
| 28 | + axios |
| 29 | + .get(realUrl, { responseType: 'stream' }) |
| 30 | + .then((response) => response.data.pipe(createWriteStream(cachePath))) |
| 31 | + } |
| 32 | + |
| 33 | + return join(cachePath) |
| 34 | +} |
0 commit comments