2023-01-09 17:17:33 +00:00
|
|
|
import * as plugins from './smartjimp.plugins.js';
|
|
|
|
|
|
|
|
export interface IDimensions {
|
|
|
|
width?: number;
|
|
|
|
height?: number;
|
|
|
|
}
|
2020-02-02 20:10:42 +00:00
|
|
|
|
|
|
|
export class SmartJimp {
|
2023-01-09 17:17:33 +00:00
|
|
|
public levelCache = new plugins.levelcache.LevelCache({
|
|
|
|
cacheId: 'mastercache',
|
|
|
|
maxMemoryStorageInMB: 100,
|
|
|
|
maxDiskStorageInMB: 5000,
|
|
|
|
});
|
|
|
|
|
|
|
|
/**
|
|
|
|
* get a key that is unique for a wanted asset variation
|
|
|
|
*/
|
|
|
|
private getCacheKey(
|
2023-11-24 19:08:48 +00:00
|
|
|
sourceTypeArg: 'streamfile' | 'smartfile',
|
2023-01-09 17:17:33 +00:00
|
|
|
sourceIdArg: string,
|
|
|
|
wantedDimensionsArg?: IDimensions
|
|
|
|
) {
|
|
|
|
return `${sourceTypeArg}_${sourceIdArg}_${
|
|
|
|
wantedDimensionsArg
|
|
|
|
? `${wantedDimensionsArg.width || 'auto' }x${wantedDimensionsArg.height || 'auto'}`
|
|
|
|
: 'original'
|
|
|
|
}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
private async computeAssetVariation(assetBuffer: Buffer, wantedDimensions?: IDimensions) {
|
|
|
|
if (!wantedDimensions) {
|
|
|
|
return assetBuffer;
|
|
|
|
}
|
|
|
|
let sharpImage = plugins.sharp(assetBuffer);
|
|
|
|
sharpImage = sharpImage.resize(wantedDimensions.width, wantedDimensions.height);
|
2023-11-24 19:08:48 +00:00
|
|
|
const result = await sharpImage.resize(wantedDimensions.width, wantedDimensions.height).avif().toBuffer();
|
2023-01-09 17:17:33 +00:00
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
public async getFromSmartfile(
|
2023-11-24 19:08:48 +00:00
|
|
|
smartfileArg: plugins.smartfile.SmartFile,
|
2023-01-09 17:17:33 +00:00
|
|
|
wantedDimensionsArg?: IDimensions
|
|
|
|
) {
|
2023-11-24 19:08:48 +00:00
|
|
|
const cacheKey = this.getCacheKey('smartfile', await smartfileArg.getHash(), wantedDimensionsArg);
|
2023-01-09 17:17:33 +00:00
|
|
|
const existingCacheEntry = await this.levelCache.retrieveCacheEntryByKey(cacheKey);
|
|
|
|
if (existingCacheEntry) {
|
|
|
|
return existingCacheEntry.contents;
|
|
|
|
} else {
|
|
|
|
const computedAssetBuffer = await this.computeAssetVariation(smartfileArg.contentBuffer, wantedDimensionsArg);
|
|
|
|
this.levelCache.storeCacheEntryByKey(cacheKey, new plugins.levelcache.CacheEntry({
|
|
|
|
contents: computedAssetBuffer,
|
|
|
|
ttl: 600000
|
|
|
|
}));
|
|
|
|
return computedAssetBuffer;
|
|
|
|
}
|
|
|
|
}
|
2023-11-24 19:08:48 +00:00
|
|
|
|
|
|
|
public async createAvifImageFromBuffer(bufferArg: Buffer) {
|
|
|
|
const sharpImage = plugins.sharp(bufferArg);
|
|
|
|
const result = await sharpImage.avif().toBuffer();
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2020-02-02 20:10:42 +00:00
|
|
|
}
|