From fa5abf0863b03fcea52c3e60d9c931820d6fc0b7 Mon Sep 17 00:00:00 2001 From: bobzel Date: Sat, 2 Dec 2023 12:24:13 -0500 Subject: replaced sharp with jimp --- src/server/ApiManagers/UploadManager.ts | 88 +++++++++++---------------------- src/server/DashUploadUtils.ts | 67 +++++++++---------------- src/server/downsize.ts | 40 --------------- 3 files changed, 52 insertions(+), 143 deletions(-) delete mode 100644 src/server/downsize.ts (limited to 'src/server') diff --git a/src/server/ApiManagers/UploadManager.ts b/src/server/ApiManagers/UploadManager.ts index ea5d8cb33..478f7da3d 100644 --- a/src/server/ApiManagers/UploadManager.ts +++ b/src/server/ApiManagers/UploadManager.ts @@ -1,7 +1,7 @@ import * as formidable from 'formidable'; import { createReadStream, createWriteStream, unlink, writeFile } from 'fs'; import { basename, dirname, extname, normalize } from 'path'; -import * as sharp from 'sharp'; +import Jimp from 'jimp'; import { filesDirectory, publicDirectory } from '..'; import { retrocycle } from '../../decycler/decycler'; import { DashUploadUtils, InjectSize, SizeSuffix } from '../DashUploadUtils'; @@ -13,6 +13,7 @@ import ApiManager, { Registration } from './ApiManager'; import { SolrManager } from './SearchManager'; import v4 = require('uuid/v4'); import { DashVersion } from '../../fields/DocSymbols'; +import { JPEGStream } from 'canvas'; const AdmZip = require('adm-zip'); const imageDataUri = require('image-data-uri'); const fs = require('fs'); @@ -164,7 +165,7 @@ export default class UploadManager extends ApiManager { if (error) { return res.send(); } - await DashUploadUtils.outputResizedImages(() => createReadStream(resolvedPath), resolvedName, pathToDirectory(Directory.images)); + await DashUploadUtils.outputResizedImages(resolvedPath, resolvedName, pathToDirectory(Directory.images)); res.send({ accessPaths: { agnostic: DashUploadUtils.getAccessPaths(Directory.images, resolvedName), @@ -261,34 +262,18 @@ export default class UploadManager extends ApiManager { try { zip.extractEntryTo(entry.entryName, publicDirectory, true, false); createReadStream(pathname).pipe(createWriteStream(targetname)); - if (extension !== '.pdf') { - const { pngs, jpgs } = AcceptableMedia; - const resizers = [ - { resizer: sharp().resize(100, undefined, { withoutEnlargement: true }), suffix: SizeSuffix.Small }, - { resizer: sharp().resize(400, undefined, { withoutEnlargement: true }), suffix: SizeSuffix.Medium }, - { resizer: sharp().resize(900, undefined, { withoutEnlargement: true }), suffix: SizeSuffix.Large }, - ]; - let isImage = false; - if (pngs.includes(extension)) { - resizers.forEach(element => { - element.resizer = element.resizer.png(); - }); - isImage = true; - } else if (jpgs.includes(extension)) { - resizers.forEach(element => { - element.resizer = element.resizer.jpeg(); - }); - isImage = true; - } - if (isImage) { - resizers.forEach(resizer => { - createReadStream(pathname) - .on('error', e => console.log('Resizing read:' + e)) - .pipe(resizer.resizer) - .on('error', e => console.log('Resizing write: ' + e)) - .pipe(createWriteStream(targetname.replace('_o' + extension, resizer.suffix + extension)).on('error', e => console.log('Resizing write: ' + e))); - }); - } + if (AcceptableMedia.imageFormats.includes(extension)) { + [ + { size: 100, suffix: SizeSuffix.Small }, + { size: 400, suffix: SizeSuffix.Medium }, + { size: 900, suffix: SizeSuffix.Large }, + ].forEach(resizer => + Jimp.read(pathname).then(img => + img + .resize(resizer.size, Jimp.AUTO) // + .write(targetname.replace('_o' + extension, resizer.suffix + extension)) + ) + ); } unlink(pathname, () => {}); } catch (e) { @@ -346,7 +331,7 @@ export default class UploadManager extends ApiManager { method: Method.POST, subscription: '/uploadURI', secureHandler: ({ req, res }) => { - const uri = req.body.uri; + const uri: any = req.body.uri; const filename = req.body.name; const origSuffix = req.body.nosuffix ? SizeSuffix.None : SizeSuffix.Original; const deleteFiles = req.body.replaceRootFilename; @@ -364,33 +349,20 @@ export default class UploadManager extends ApiManager { return imageDataUri.outputFile(uri, serverPathToFile(Directory.images, InjectSize(filename, origSuffix))).then((savedName: string) => { const ext = extname(savedName).toLowerCase(); const { pngs, jpgs } = AcceptableMedia; - const resizers = !origSuffix - ? [{ resizer: sharp().resize(400, undefined, { withoutEnlargement: true }), suffix: SizeSuffix.Medium }] - : [ - { resizer: sharp().resize(100, undefined, { withoutEnlargement: true }), suffix: SizeSuffix.Small }, - { resizer: sharp().resize(400, undefined, { withoutEnlargement: true }), suffix: SizeSuffix.Medium }, - { resizer: sharp().resize(900, undefined, { withoutEnlargement: true }), suffix: SizeSuffix.Large }, - ]; - let isImage = false; - if (pngs.includes(ext)) { - resizers.forEach(element => { - element.resizer = element.resizer.png(); - }); - isImage = true; - } else if (jpgs.includes(ext)) { - resizers.forEach(element => { - element.resizer = element.resizer.jpeg(); - }); - isImage = true; - } - if (isImage) { - resizers.forEach(resizer => { - const path = serverPathToFile(Directory.images, InjectSize(filename, resizer.suffix) + ext); - createReadStream(savedName) - .on('error', e => console.log('Resizing read:' + e)) - .pipe(resizer.resizer) - .on('error', e => console.log('Resizing write: ' + e)) - .pipe(createWriteStream(path).on('error', e => console.log('Resizing write: ' + e))); + if (!pngs.includes(ext) && !jpgs.includes(ext)) { + (!origSuffix + ? [{ size: 400, suffix: SizeSuffix.Medium }] + : [ + { size: 100, suffix: SizeSuffix.Small }, + { size: 400, suffix: SizeSuffix.Medium }, + { size: 900, suffix: SizeSuffix.Large }, + ] + ).forEach(resizer => { + Jimp.read(savedName).then(img => + img + .resize(resizer.size, Jimp.AUTO) // + .write(serverPathToFile(Directory.images, InjectSize(filename, resizer.suffix) + ext)) + ); }); } res.send(clientPathToFile(Directory.images, filename + ext)); diff --git a/src/server/DashUploadUtils.ts b/src/server/DashUploadUtils.ts index 19cb3f240..b2616af1f 100644 --- a/src/server/DashUploadUtils.ts +++ b/src/server/DashUploadUtils.ts @@ -5,8 +5,7 @@ import { File } from 'formidable'; import { createReadStream, createWriteStream, existsSync, readFileSync, rename, unlinkSync, writeFile } from 'fs'; import * as path from 'path'; import { basename } from 'path'; -import * as sharp from 'sharp'; -import { Readable, Stream } from 'stream'; +import Jimp from 'jimp'; import { filesDirectory, publicDirectory } from '.'; import { Opt } from '../fields/Doc'; import { ParsedPDF } from '../server/PdfTypes'; @@ -55,9 +54,9 @@ export namespace DashUploadUtils { } export const Sizes: { [size: string]: Size } = { - SMALL: { width: 100, suffix: SizeSuffix.Small }, - MEDIUM: { width: 400, suffix: SizeSuffix.Medium }, LARGE: { width: 900, suffix: SizeSuffix.Large }, + MEDIUM: { width: 400, suffix: SizeSuffix.Medium }, + SMALL: { width: 100, suffix: SizeSuffix.Small }, }; export function validateExtension(url: string) { @@ -367,7 +366,7 @@ export namespace DashUploadUtils { } export interface ImageResizer { - resizer?: sharp.Sharp; + width?: any; // sharp.Sharp; suffix: SizeSuffix; } @@ -540,7 +539,7 @@ export namespace DashUploadUtils { writtenFiles = {}; } } else { - writtenFiles = await outputResizedImages(() => request(requestable), resolved, pathToDirectory(Directory.images)); + writtenFiles = await outputResizedImages(metadata.source, resolved, pathToDirectory(Directory.images)); } for (const suffix of Object.keys(writtenFiles)) { information.accessPaths[suffix] = getAccessPaths(images, writtenFiles[suffix]); @@ -595,57 +594,35 @@ export namespace DashUploadUtils { * @param outputDirectory the directory to output to, usually Directory.Images * @returns a map with suffixes as keys and resized filenames as values. */ - export async function outputResizedImages(streamProvider: () => Stream | Promise, outputFileName: string, outputDirectory: string) { - const writtenFiles: { [suffix: string]: string } = {}; - for (const { resizer, suffix } of resizers(path.extname(outputFileName))) { - const outputPath = path.resolve(outputDirectory, (writtenFiles[suffix] = InjectSize(outputFileName, suffix))); - await new Promise(async (resolve, reject) => { - const source = streamProvider(); - let readStream = source instanceof Promise ? await source : source; - let error = false; - if (resizer) { - readStream = readStream.pipe(resizer.withMetadata()).on('error', async args => { - error = true; - if (error) { - const source2 = streamProvider(); - let readStream2: Stream | undefined; - readStream2 = source2 instanceof Promise ? await source2 : source2; - readStream2?.pipe(createWriteStream(outputPath)).on('error', resolve).on('close', resolve); - } + export async function outputResizedImages(sourcePath: string, outputFileName: string, outputDirectory: string) { + return await new Promise<{ [suffix: string]: string }>(async resolve => { + Jimp.read(sourcePath).then(async img => { + const writtenFiles: { [suffix: string]: string } = {}; + for (const { width, suffix } of resizers(path.extname(outputFileName))) { + const outputPath = path.resolve(outputDirectory, (writtenFiles[suffix] = InjectSize(outputFileName, suffix))); + await new Promise(async res => { + if (!width) createReadStream(sourcePath).pipe(createWriteStream(outputPath)).on('close', res); + else img = img.resize(width, Jimp.AUTO).write(outputPath); + res(); }); } - !error && readStream?.pipe(createWriteStream(outputPath)).on('error', resolve).on('close', resolve); + resolve(writtenFiles); }); - } - return writtenFiles; + }); } /** * define the resizers to use * @param ext the extension - * @returns an array of resizer functions from sharp + * @returns an array of resize descriptions */ function resizers(ext: string): DashUploadUtils.ImageResizer[] { return [ { suffix: SizeSuffix.Original }, - ...Object.values(DashUploadUtils.Sizes).map(({ suffix, width }) => { - let initial: sharp.Sharp | undefined = sharp({ failOnError: false }).resize(width, undefined, { withoutEnlargement: true }); - if (pngs.includes(ext)) { - initial = initial.png(pngOptions); - } else if (jpgs.includes(ext)) { - initial = initial.jpeg(); - } else if (webps.includes(ext)) { - initial = initial.webp(); - } else if (tiffs.includes(ext)) { - initial = initial.tiff(); - } else if (ext === '.gif') { - initial = undefined; - } - return { - resizer: suffix === '_o' ? undefined : initial, - suffix, - }; - }), + ...[...(AcceptableMedia.imageFormats.includes(ext) ? Object.values(DashUploadUtils.Sizes) : [])].map(({ suffix, width }) => ({ + width, + suffix, + })), ]; } } diff --git a/src/server/downsize.ts b/src/server/downsize.ts deleted file mode 100644 index 382994e2d..000000000 --- a/src/server/downsize.ts +++ /dev/null @@ -1,40 +0,0 @@ -import * as fs from 'fs'; -import * as sharp from 'sharp'; - -const folder = "./src/server/public/files/"; -const pngTypes = ["png", "PNG"]; -const jpgTypes = ["jpg", "JPG", "jpeg", "JPEG"]; -const smallResizer = sharp().resize(100); -fs.readdir(folder, async (err, files) => { - if (err) { - console.log("readdir:" + err); - return; - } - // files.forEach(file => { - // if (file.includes("_s") || file.includes("_m") || file.includes("_l")) { - // fs.unlink(folder + file, () => { }); - // } - // }); - for (const file of files) { - const filesplit = file.split("."); - const resizers = [ - { resizer: sharp().resize(100, undefined, { withoutEnlargement: true }), suffix: "_s" }, - { resizer: sharp().resize(400, undefined, { withoutEnlargement: true }), suffix: "_m" }, - { resizer: sharp().resize(900, undefined, { withoutEnlargement: true }), suffix: "_l" }, - ]; - if (pngTypes.some(type => file.endsWith(type))) { - resizers.forEach(element => { - element.resizer = element.resizer.png(); - }); - } else if (jpgTypes.some(type => file.endsWith(type))) { - resizers.forEach(element => { - element.resizer = element.resizer.jpeg(); - }); - } else { - continue; - } - resizers.forEach(resizer => { - fs.createReadStream(folder + file).pipe(resizer.resizer).pipe(fs.createWriteStream(folder + filesplit[0] + resizer.suffix + "." + filesplit[1])); - }); - } -}); \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 6abda9e76cce35272ff73c3911af5aa8c18ce30b Mon Sep 17 00:00:00 2001 From: bobzel Date: Sat, 2 Dec 2023 14:46:35 -0500 Subject: jimp cleanup --- src/client/views/PreviewCursor.tsx | 2 +- src/server/ApiManagers/UploadManager.ts | 58 +++++++++++++-------------------- src/server/DashUploadUtils.ts | 29 ++++++++--------- 3 files changed, 36 insertions(+), 53 deletions(-) (limited to 'src/server') diff --git a/src/client/views/PreviewCursor.tsx b/src/client/views/PreviewCursor.tsx index e3a43d45f..d1bd0500b 100644 --- a/src/client/views/PreviewCursor.tsx +++ b/src/client/views/PreviewCursor.tsx @@ -50,7 +50,7 @@ export class PreviewCursor extends React.Component<{}> { PreviewCursor._slowLoadDocuments?.(plain.split('v=')[1].split('&')[0], options, generatedDocuments, '', undefined, PreviewCursor._addDocument).then(batch.end); } else if (re.test(plain)) { const url = plain; - if (url.startsWith(window.location.href)) { + if (!url.startsWith(window.location.href)) { undoBatch(() => PreviewCursor._addDocument( Docs.Create.WebDocument(url, { diff --git a/src/server/ApiManagers/UploadManager.ts b/src/server/ApiManagers/UploadManager.ts index 478f7da3d..83644e564 100644 --- a/src/server/ApiManagers/UploadManager.ts +++ b/src/server/ApiManagers/UploadManager.ts @@ -1,6 +1,6 @@ import * as formidable from 'formidable'; import { createReadStream, createWriteStream, unlink, writeFile } from 'fs'; -import { basename, dirname, extname, normalize } from 'path'; +import * as path from 'path'; import Jimp from 'jimp'; import { filesDirectory, publicDirectory } from '..'; import { retrocycle } from '../../decycler/decycler'; @@ -13,7 +13,6 @@ import ApiManager, { Registration } from './ApiManager'; import { SolrManager } from './SearchManager'; import v4 = require('uuid/v4'); import { DashVersion } from '../../fields/DocSymbols'; -import { JPEGStream } from 'canvas'; const AdmZip = require('adm-zip'); const imageDataUri = require('image-data-uri'); const fs = require('fs'); @@ -30,11 +29,11 @@ export enum Directory { } export function serverPathToFile(directory: Directory, filename: string) { - return normalize(`${filesDirectory}/${directory}/${filename}`); + return path.normalize(`${filesDirectory}/${directory}/${filename}`); } export function pathToDirectory(directory: Directory) { - return normalize(`${filesDirectory}/${directory}`); + return path.normalize(`${filesDirectory}/${directory}`); } export function clientPathToFile(directory: Directory, filename: string) { @@ -256,26 +255,20 @@ export default class UploadManager extends ApiManager { if (!entryName.startsWith('files/')) { return; } - const extension = extname(entryName); + const extension = path.extname(entryName); const pathname = publicDirectory + '/' + entry.entryName; const targetname = publicDirectory + '/' + entryName; try { zip.extractEntryTo(entry.entryName, publicDirectory, true, false); createReadStream(pathname).pipe(createWriteStream(targetname)); - if (AcceptableMedia.imageFormats.includes(extension)) { - [ - { size: 100, suffix: SizeSuffix.Small }, - { size: 400, suffix: SizeSuffix.Medium }, - { size: 900, suffix: SizeSuffix.Large }, - ].forEach(resizer => - Jimp.read(pathname).then(img => - img - .resize(resizer.size, Jimp.AUTO) // - .write(targetname.replace('_o' + extension, resizer.suffix + extension)) - ) - ); - } - unlink(pathname, () => {}); + Jimp.read(pathname).then(img => { + DashUploadUtils.imageResampleSizes(extension).forEach(({ width, suffix }) => { + const outputPath = InjectSize(targetname, suffix); + if (!width) createReadStream(pathname).pipe(createWriteStream(outputPath)); + else img = img.resize(width, Jimp.AUTO).write(outputPath); + }); + unlink(pathname, () => {}); + }); } catch (e) { console.log(e); } @@ -347,23 +340,16 @@ export default class UploadManager extends ApiManager { .map((f: any) => fs.unlinkSync(path + f)); } return imageDataUri.outputFile(uri, serverPathToFile(Directory.images, InjectSize(filename, origSuffix))).then((savedName: string) => { - const ext = extname(savedName).toLowerCase(); - const { pngs, jpgs } = AcceptableMedia; - if (!pngs.includes(ext) && !jpgs.includes(ext)) { - (!origSuffix - ? [{ size: 400, suffix: SizeSuffix.Medium }] - : [ - { size: 100, suffix: SizeSuffix.Small }, - { size: 400, suffix: SizeSuffix.Medium }, - { size: 900, suffix: SizeSuffix.Large }, - ] - ).forEach(resizer => { - Jimp.read(savedName).then(img => - img - .resize(resizer.size, Jimp.AUTO) // - .write(serverPathToFile(Directory.images, InjectSize(filename, resizer.suffix) + ext)) - ); - }); + const ext = path.extname(savedName).toLowerCase(); + if (AcceptableMedia.imageFormats.includes(ext)) { + Jimp.read(savedName).then(img => + (!origSuffix ? [{ width: 400, suffix: SizeSuffix.Medium }] : Object.values(DashUploadUtils.Sizes)) // + .forEach(({ width, suffix }) => { + const outputPath = InjectSize(filename, suffix); + if (!width) createReadStream(savedName).pipe(createWriteStream(outputPath)); + else img = img.resize(width, Jimp.AUTO).write(outputPath); + }) + ); } res.send(clientPathToFile(Directory.images, filename + ext)); }); diff --git a/src/server/DashUploadUtils.ts b/src/server/DashUploadUtils.ts index b2616af1f..6cad49033 100644 --- a/src/server/DashUploadUtils.ts +++ b/src/server/DashUploadUtils.ts @@ -54,7 +54,7 @@ export namespace DashUploadUtils { } export const Sizes: { [size: string]: Size } = { - LARGE: { width: 900, suffix: SizeSuffix.Large }, + LARGE: { width: 800, suffix: SizeSuffix.Large }, MEDIUM: { width: 400, suffix: SizeSuffix.Medium }, SMALL: { width: 100, suffix: SizeSuffix.Small }, }; @@ -594,20 +594,17 @@ export namespace DashUploadUtils { * @param outputDirectory the directory to output to, usually Directory.Images * @returns a map with suffixes as keys and resized filenames as values. */ - export async function outputResizedImages(sourcePath: string, outputFileName: string, outputDirectory: string) { - return await new Promise<{ [suffix: string]: string }>(async resolve => { - Jimp.read(sourcePath).then(async img => { - const writtenFiles: { [suffix: string]: string } = {}; - for (const { width, suffix } of resizers(path.extname(outputFileName))) { + export function outputResizedImages(sourcePath: string, outputFileName: string, outputDirectory: string) { + const writtenFiles: { [suffix: string]: string } = {}; + return Jimp.read(sourcePath).then(async img => { + await Promise.all( + imageResampleSizes(path.extname(outputFileName)).map(({ width, suffix }) => { const outputPath = path.resolve(outputDirectory, (writtenFiles[suffix] = InjectSize(outputFileName, suffix))); - await new Promise(async res => { - if (!width) createReadStream(sourcePath).pipe(createWriteStream(outputPath)).on('close', res); - else img = img.resize(width, Jimp.AUTO).write(outputPath); - res(); - }); - } - resolve(writtenFiles); - }); + if (!width) return new Promise(res => createReadStream(sourcePath).pipe(createWriteStream(outputPath)).on('close', res)); + else img = img.resize(width, Jimp.AUTO).write(outputPath); + }) // prettier-ignore + ); + return writtenFiles; }); } @@ -616,10 +613,10 @@ export namespace DashUploadUtils { * @param ext the extension * @returns an array of resize descriptions */ - function resizers(ext: string): DashUploadUtils.ImageResizer[] { + export function imageResampleSizes(ext: string): DashUploadUtils.ImageResizer[] { return [ { suffix: SizeSuffix.Original }, - ...[...(AcceptableMedia.imageFormats.includes(ext) ? Object.values(DashUploadUtils.Sizes) : [])].map(({ suffix, width }) => ({ + ...[...(AcceptableMedia.imageFormats.includes(ext.toLowerCase()) ? Object.values(DashUploadUtils.Sizes) : [])].map(({ suffix, width }) => ({ width, suffix, })), -- cgit v1.2.3-70-g09d2 From 9c7e055a2cf7ca5bc517edd3a9f44e128ec40ff3 Mon Sep 17 00:00:00 2001 From: bobzel Date: Sat, 2 Dec 2023 15:53:28 -0500 Subject: fixed jimp upload to not hang when error occurs. fied imagebox to show original image if resized images fail. --- src/client/views/nodes/ImageBox.tsx | 6 ++++-- src/client/views/nodes/LoadingBox.tsx | 3 ++- src/server/ApiManagers/UploadManager.ts | 1 + src/server/DashUploadUtils.ts | 29 ++++++++++++++++++----------- 4 files changed, 25 insertions(+), 14 deletions(-) (limited to 'src/server') diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index 7e85c33b8..d28d71fe3 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -319,7 +319,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent { @@ -430,6 +430,8 @@ export class ImageBox extends ViewBoxAnnotatableComponent (this._isHovering = true))} onPointerLeave={action(() => (this._isHovering = false))} key={this.layoutDoc[Id]} ref={this.createDropTarget} onPointerDown={this.marqueeDown}>
- + (this._error = e.toString()))} draggable={false} width={nativeWidth} /> {fadepath === srcpath ? null : (
diff --git a/src/client/views/nodes/LoadingBox.tsx b/src/client/views/nodes/LoadingBox.tsx index 01dd830f8..e554cb8ad 100644 --- a/src/client/views/nodes/LoadingBox.tsx +++ b/src/client/views/nodes/LoadingBox.tsx @@ -63,13 +63,14 @@ export class LoadingBox extends ViewBoxAnnotatableComponent() { const updateFunc = async () => { const result = await Networking.QueryYoutubeProgress(StrCast(this.Document[Id])); // We use the guid of the overwriteDoc to track file uploads. runInAction(() => (this.progress = result.progress)); - !this.Document.loadingError && (this._timer = setTimeout(updateFunc, 1000)); + !this.Document.loadingError && this._timer && (this._timer = setTimeout(updateFunc, 1000)); }; this._timer = setTimeout(updateFunc, 1000); } } componentWillUnmount() { clearTimeout(this._timer); + this._timer = undefined; } render() { diff --git a/src/server/ApiManagers/UploadManager.ts b/src/server/ApiManagers/UploadManager.ts index 83644e564..09ba2a57e 100644 --- a/src/server/ApiManagers/UploadManager.ts +++ b/src/server/ApiManagers/UploadManager.ts @@ -79,6 +79,7 @@ export default class UploadManager extends ApiManager { form.uploadDir = pathToDirectory(Directory.parsed_files); return new Promise(resolve => { form.parse(req, async (_err, _fields, files) => { + fileguids.split(';').map(guid => DashUploadUtils.uploadProgress.set(guid, `resampling images`)); const results: Upload.FileResponse[] = []; if (_err?.message) { results.push({ diff --git a/src/server/DashUploadUtils.ts b/src/server/DashUploadUtils.ts index 6cad49033..eb6c080ef 100644 --- a/src/server/DashUploadUtils.ts +++ b/src/server/DashUploadUtils.ts @@ -594,18 +594,25 @@ export namespace DashUploadUtils { * @param outputDirectory the directory to output to, usually Directory.Images * @returns a map with suffixes as keys and resized filenames as values. */ - export function outputResizedImages(sourcePath: string, outputFileName: string, outputDirectory: string) { + export async function outputResizedImages(sourcePath: string, outputFileName: string, outputDirectory: string) { const writtenFiles: { [suffix: string]: string } = {}; - return Jimp.read(sourcePath).then(async img => { - await Promise.all( - imageResampleSizes(path.extname(outputFileName)).map(({ width, suffix }) => { - const outputPath = path.resolve(outputDirectory, (writtenFiles[suffix] = InjectSize(outputFileName, suffix))); - if (!width) return new Promise(res => createReadStream(sourcePath).pipe(createWriteStream(outputPath)).on('close', res)); - else img = img.resize(width, Jimp.AUTO).write(outputPath); - }) // prettier-ignore - ); - return writtenFiles; - }); + const sizes = imageResampleSizes(path.extname(outputFileName)); + const outputPath = (suffix: SizeSuffix) => path.resolve(outputDirectory, (writtenFiles[suffix] = InjectSize(outputFileName, suffix))); + await Promise.all( + sizes.filter(({ width }) => !width).map(({ suffix }) => + new Promise(res => createReadStream(sourcePath).pipe(createWriteStream(outputPath(suffix))).on('close', res)) + )); // prettier-ignore + return Jimp.read(sourcePath) + .then(async img => { + await Promise.all( sizes.filter(({ width }) => width) .map(({ width, suffix }) => + img = img.resize(width, Jimp.AUTO).write(outputPath(suffix)) + )); // prettier-ignore + return writtenFiles; + }) + .catch(e => { + console.log('ERROR' + e); + return writtenFiles; + }); } /** -- cgit v1.2.3-70-g09d2 From 23f789ab0bc9947f1bd23816183df2b5cc89b0e6 Mon Sep 17 00:00:00 2001 From: bobzel Date: Sat, 2 Dec 2023 16:21:07 -0500 Subject: changed uploading messages. --- src/server/ApiManagers/UploadManager.ts | 5 ++++- src/server/DashUploadUtils.ts | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) (limited to 'src/server') diff --git a/src/server/ApiManagers/UploadManager.ts b/src/server/ApiManagers/UploadManager.ts index 09ba2a57e..391f67bbb 100644 --- a/src/server/ApiManagers/UploadManager.ts +++ b/src/server/ApiManagers/UploadManager.ts @@ -74,12 +74,13 @@ export default class UploadManager extends ApiManager { filesize = value; } }); + fileguids.split(';').map(guid => DashUploadUtils.uploadProgress.set(guid, `upload starting`)); + form.on('progress', e => fileguids.split(';').map(guid => DashUploadUtils.uploadProgress.set(guid, `read:(${Math.round((100 * +e) / +filesize)}%) ${e} of ${filesize}`))); form.keepExtensions = true; form.uploadDir = pathToDirectory(Directory.parsed_files); return new Promise(resolve => { form.parse(req, async (_err, _fields, files) => { - fileguids.split(';').map(guid => DashUploadUtils.uploadProgress.set(guid, `resampling images`)); const results: Upload.FileResponse[] = []; if (_err?.message) { results.push({ @@ -93,6 +94,8 @@ export default class UploadManager extends ApiManager { result: { name: 'failed upload', message: `${_err.message}` }, }); } + fileguids.split(';').map(guid => DashUploadUtils.uploadProgress.set(guid, `resampling images`)); + for (const key in files) { const f = files[key]; if (!Array.isArray(f)) { diff --git a/src/server/DashUploadUtils.ts b/src/server/DashUploadUtils.ts index eb6c080ef..2053ae448 100644 --- a/src/server/DashUploadUtils.ts +++ b/src/server/DashUploadUtils.ts @@ -196,7 +196,7 @@ export namespace DashUploadUtils { const isAzureOn = usingAzure(); const { type, path, name } = file; const types = type?.split('/') ?? []; - uploadProgress.set(overwriteGuid ?? name, 'uploading'); // If the client sent a guid it uses to track upload progress, use that guid. Otherwise, use the file's name. + // uploadProgress.set(overwriteGuid ?? name, 'uploading'); // If the client sent a guid it uses to track upload progress, use that guid. Otherwise, use the file's name. const category = types[0]; let format = `.${types[1]}`; -- cgit v1.2.3-70-g09d2