Re-process thumbnails on migration

This commit is contained in:
Pitu 2020-07-18 05:50:59 +09:00
parent d644b21d43
commit 898a2dde78
1 changed files with 52 additions and 0 deletions

View File

@ -1,5 +1,9 @@
const nodePath = require('path');
const moment = require('moment');
const jetpack = require('fs-jetpack');
const { path } = require('fs-jetpack');
const sharp = require('sharp');
const ffmpeg = require('fluent-ffmpeg');
const oldDb = require('knex')({
client: 'sqlite3',
@ -42,6 +46,10 @@ const start = async () => {
console.log('Starting migration, this may take a few minutes...'); // Because I half assed it
console.log('Please do NOT kill the process. Wait for it to finish.');
await jetpack.removeAsync(nodePath.join(__dirname, '..', '..', 'uploads', 'thumbs'));
await jetpack.dirAsync(nodePath.join(__dirname, '..', '..', 'uploads', 'thumbs', 'square'));
console.log('Finished deleting old thumbnails to create new ones');
const users = await oldDb.table('users').where('username', '<>', 'root');
for (const user of users) {
const now = moment.utc().toDate();
@ -113,6 +121,7 @@ const start = async () => {
albumId: file.albumid,
fileId: file.id
});
generateThumbnails(file.name);
}
await newDb.batchInsert('files', filesToInsert, 20);
await newDb.batchInsert('albumsFiles', albumsFilesToInsert, 20);
@ -122,4 +131,47 @@ const start = async () => {
process.exit(0);
};
const imageExtensions = ['.jpg', '.jpeg', '.bmp', '.gif', '.png', '.webp'];
const videoExtensions = ['.webm', '.mp4', '.wmv', '.avi', '.mov'];
const generateThumbnails = filename => {
if (!jetpack.exists(nodePath.join(__dirname, '..', '..', 'uploads', filename))) return;
const ext = nodePath.extname(filename).toLowerCase();
const output = `${filename.slice(0, -ext.length)}.webp`;
if (imageExtensions.includes(ext)) return generateThumbnailForImage(filename, output);
if (videoExtensions.includes(ext)) return generateThumbnailForVideo(filename);
};
const generateThumbnailForImage = async (filename, output) => {
const file = await jetpack.readAsync(nodePath.join(__dirname, '..', '..', 'uploads', filename), 'buffer');
await sharp(file)
.resize(64, 64)
.toFormat('webp')
.toFile(nodePath.join(__dirname, '..', '..', 'uploads', 'thumbs', 'square', output));
await sharp(file)
.resize(225, null)
.toFormat('webp')
.toFile(nodePath.join(__dirname, '..', '..', 'uploads', 'thumbs', output));
};
const generateThumbnailForVideo = filename => {
ffmpeg(nodePath.join(__dirname, '..', '..', 'uploads', filename))
.thumbnail({
timestamps: [0],
filename: '%b.png',
folder: nodePath.join(__dirname, '..', '..', 'uploads', 'thumbs', 'square'),
size: '64x64'
})
.on('error', error => console.error(error.message));
ffmpeg(nodePath.join(__dirname, '..', '..', 'uploads', filename))
.thumbnail({
timestamps: [0],
filename: '%b.png',
folder: nodePath.join(__dirname, '..', '..', 'uploads', 'thumbs'),
size: '150x?'
})
.on('error', error => console.error(error.message));
};
start();