aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/client/Network.ts4
-rw-r--r--src/client/util/request-image-size.ts38
-rw-r--r--src/client/views/smartdraw/DrawingFillHandler.tsx8
-rw-r--r--src/server/ApiManagers/FireflyManager.ts164
-rw-r--r--src/server/DashUploadUtils.ts7
5 files changed, 101 insertions, 120 deletions
diff --git a/src/client/Network.ts b/src/client/Network.ts
index a2ecf1bea..b11dcb379 100644
--- a/src/client/Network.ts
+++ b/src/client/Network.ts
@@ -21,10 +21,10 @@ export namespace Networking {
'Content-Type': 'application/json',
},
body: body ? JSON.stringify(body) : undefined,
- }).then(async response => {
+ }).then(response => {
if (response.ok) return response.json() as object;
- return await response.text().then(text => ({ error: '' + response.status + ':' + response.statusText + '-' + text }));
+ return response.text().then(text => ({ error: '' + response.status + ':' + response.statusText + '-' + text }));
});
}
diff --git a/src/client/util/request-image-size.ts b/src/client/util/request-image-size.ts
index 32ab23618..798390c7d 100644
--- a/src/client/util/request-image-size.ts
+++ b/src/client/util/request-image-size.ts
@@ -33,27 +33,25 @@ export function requestImageSize(url: string): Promise<ISizeCalculationResult> {
res.on('data', chunk => {
buffer = Buffer.concat([buffer, chunk]);
- });
-
- res.on('error', reject);
-
- res.on('end', () => {
- try {
- size = imageSize(buffer);
- if (size) {
- resolve(size);
- req.abort();
+ })
+ .on('error', reject)
+ .on('end', () => {
+ try {
+ size = imageSize(buffer);
+ if (size) {
+ resolve(size);
+ req.abort();
+ }
+ } catch (err) {
+ /* empty */
+ console.log('Error: ', err);
+ }
+ if (!size) {
+ reject(new Error('Image has no size'));
+ return;
}
- } catch (err) {
- /* empty */
- console.log('Error: ', err);
- }
- if (!size) {
- reject(new Error('Image has no size'));
- return;
- }
- resolve(size);
- });
+ resolve(size);
+ });
});
req.on('error', reject);
diff --git a/src/client/views/smartdraw/DrawingFillHandler.tsx b/src/client/views/smartdraw/DrawingFillHandler.tsx
index a91ec23b8..b0945fd83 100644
--- a/src/client/views/smartdraw/DrawingFillHandler.tsx
+++ b/src/client/views/smartdraw/DrawingFillHandler.tsx
@@ -26,11 +26,12 @@ export class DrawingFillHandler {
const styleUrl = tags.length
? undefined
: await DocumentView.GetDocImage(styleDocs.filter(doc => doc?.data instanceof ImageField).lastElement())?.then(styleImg => {
- const hrefParts = ImageCast(styleImg).url.href.split('.');
- return `${hrefParts.slice(0, -1).join('.')}_o.${hrefParts.lastElement()}`;
+ const hrefParts = ImageCast(styleImg)?.url.href.split('.');
+ return !hrefParts ? undefined : `${hrefParts.slice(0, -1).join('.')}_o.${hrefParts.lastElement()}`;
});
return DocumentView.GetDocImage(drawing)?.then(imageField => {
- if (imageField) {
+ const href = ImageCast(imageField)?.url.href;
+ if (href) {
const aspectRatio = (drawing.width as number) / (drawing.height as number);
const dims = (() => {
if (aspectRatio > AspectRatioLimits[FireflyImageDimensions.Widescreen]) return FireflyDimensionsMap[FireflyImageDimensions.Widescreen];
@@ -38,7 +39,6 @@ export class DrawingFillHandler {
if (aspectRatio < AspectRatioLimits[FireflyImageDimensions.Portrait]) return FireflyDimensionsMap[FireflyImageDimensions.Portrait];
return FireflyDimensionsMap[FireflyImageDimensions.Square];
})();
- const { href } = ImageCast(imageField).url;
const hrefParts = href.split('.');
const structureUrl = `${hrefParts.slice(0, -1).join('.')}_o.${hrefParts.lastElement()}`;
return gptDescribeImage(user_prompt, structureUrl).then(newPrompt =>
diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts
index 07428798c..d22142d7d 100644
--- a/src/server/ApiManagers/FireflyManager.ts
+++ b/src/server/ApiManagers/FireflyManager.ts
@@ -70,49 +70,42 @@ export default class FireflyManager extends ApiManager {
);
uploadImageToDropbox = (fileUrl: string, user: DashUserModel | undefined, dbx = new Dropbox({ accessToken: user?.dropboxToken || '' })) =>
- new Promise<string | Error>((res, rej) =>
+ new Promise<string>((resolve, reject) => {
fs.readFile(path.join(filesDirectory, `${Directory.images}/${path.basename(fileUrl)}`), undefined, (err, contents) => {
if (err) {
- console.log('Error: ', err);
- rej();
- } else {
- dbx.filesUpload({ path: `/Apps/browndash/${path.basename(fileUrl)}`, contents })
- .then(response => {
- dbx.filesGetTemporaryLink({ path: response.result.path_display ?? '' })
- .then(link => res(link.result.link))
- .catch(e => res(new Error(e.toString())));
- })
- .catch(e => {
- if (user?.dropboxRefresh) {
- console.log('*********** try refresh dropbox for: ' + user.email + ' ***********');
- this.refreshDropboxToken(user).then(token => {
- if (!token) {
- console.log('Dropbox error: cannot refresh token');
- res(new Error(e.toString()));
- } else {
- const dbxNew = new Dropbox({ accessToken: user.dropboxToken || '' });
- dbxNew
- .filesUpload({ path: `/Apps/browndash/${path.basename(fileUrl)}`, contents })
- .then(response => {
- dbxNew
- .filesGetTemporaryLink({ path: response.result.path_display ?? '' })
- .then(link => res(link.result.link))
- .catch(linkErr => res(new Error(linkErr.toString())));
- })
- .catch(uploadErr => {
- console.log('Dropbox error:', uploadErr);
- res(new Error(uploadErr.toString()));
- });
- }
- });
- } else {
- console.log('Dropbox error:', e);
- res(new Error(e.toString()));
- }
- });
+ return reject(new Error('Error reading file:' + err.message));
}
- })
- );
+
+ const uploadToDropbox = (dropboxClient: Dropbox) =>
+ dropboxClient
+ .filesUpload({ path: `/Apps/browndash/${path.basename(fileUrl)}`, contents })
+ .then(response =>
+ dropboxClient
+ .filesGetTemporaryLink({ path: response.result.path_display ?? '' })
+ .then(link => resolve(link.result.link))
+ .catch(linkErr => reject(new Error('Failed to get temporary link: ' + linkErr.message)))
+ )
+ .catch(uploadErr => reject(new Error('Failed to upload file to Dropbox: ' + uploadErr.message)));
+
+ uploadToDropbox(dbx).catch(e => {
+ if (user?.dropboxRefresh) {
+ console.log('Attempting to refresh Dropbox token for user:', user.email);
+ this.refreshDropboxToken(user)
+ .then(token => {
+ if (!token) {
+ return reject(new Error('Failed to refresh Dropbox token.' + user.email));
+ }
+
+ const dbxNew = new Dropbox({ accessToken: token });
+ uploadToDropbox(dbxNew).catch(finalErr => reject(new Error('Failed to refresh Dropbox token:' + finalErr.message)));
+ })
+ .catch(refreshErr => reject(new Error('Failed to refresh Dropbox token: ' + refreshErr.message)));
+ } else {
+ reject(new Error('Dropbox error: ' + e.message));
+ }
+ });
+ });
+ });
generateImage = (prompt: string = 'a realistic illustration of a cat coding', width: number = 2048, height: number = 2048, seed?: number) => {
let body = `{ "prompt": "${prompt}", "size": { "width": ${width}, "height": ${height}} }`;
@@ -289,43 +282,36 @@ export default class FireflyManager extends ApiManager {
register({
method: Method.POST,
subscription: '/queryFireflyImageFromStructure',
- secureHandler: ({ req, res }) =>
- new Promise<void>(resolver => {
- (req.body.styleUrl ? this.uploadImageToDropbox(req.body.styleUrl, req.user as DashUserModel) : Promise.resolve(undefined))
- .then(styleUrl => {
- if (styleUrl instanceof Error) {
- _invalid(res, styleUrl.message);
- throw new Error('Error uploading images to dropbox');
- }
- this.uploadImageToDropbox(req.body.structureUrl, req.user as DashUserModel)
- .then(dropboxStructureUrl => {
- if (dropboxStructureUrl instanceof Error) {
- _invalid(res, dropboxStructureUrl.message);
- throw new Error('Error uploading images to dropbox');
- }
- return { styleUrl, structureUrl: dropboxStructureUrl };
- })
- .then(uploads =>
- this.generateImageFromStructure(req.body.prompt, req.body.width, req.body.height, uploads.structureUrl, req.body.strength, req.body.presets, uploads.styleUrl)
- .then(images => {
- Promise.all((images ?? [new Error('no images were generated')]).map(fire => (fire instanceof Error ? fire : DashUploadUtils.UploadImage(fire.url))))
- .then(dashImages => {
- if (dashImages.every(img => img instanceof Error)) _invalid(res, dashImages[0]!.message);
- else _success(res, JSON.stringify(dashImages.filter(img => !(img instanceof Error))));
- })
- .then(resolver);
- })
- .catch(e => {
- _invalid(res, e.message);
- resolver();
- })
- );
- })
- .catch(() => {
- /* do nothing */
- resolver();
- });
- }),
+ secureHandler: ({ req, res }) =>
+ new Promise<void>(resolver =>
+ (req.body.styleUrl
+ ? this.uploadImageToDropbox(req.body.styleUrl, req.user as DashUserModel)
+ : Promise.resolve(undefined)
+ )
+ .then(styleUrl =>
+ this.uploadImageToDropbox(req.body.structureUrl, req.user as DashUserModel)
+ .then(dropboxStructureUrl =>
+ ({ styleUrl, structureUrl: dropboxStructureUrl })
+ )
+
+ )
+ .then(uploads =>
+ this.generateImageFromStructure(
+ req.body.prompt, req.body.width, req.body.height, uploads.structureUrl, req.body.strength, req.body.presets, uploads.styleUrl
+ ).then(images =>
+ Promise.all((images ?? [new Error('no images were generated')]).map(fire => (fire instanceof Error ? fire : DashUploadUtils.UploadImage(fire.url))))
+ .then(dashImages =>
+ (dashImages.every(img => img instanceof Error))
+ ? _invalid(res, dashImages[0]!.message)
+ : _success(res, JSON.stringify(dashImages.filter(img => !(img instanceof Error))))
+ )
+ )
+ )
+ .catch(e => {
+ _invalid(res, e.message);
+ resolver();
+ })
+ ), // prettier-ignore
});
register({
method: Method.POST,
@@ -357,18 +343,18 @@ export default class FireflyManager extends ApiManager {
method: Method.POST,
subscription: '/expandImage',
secureHandler: ({ req, res }) =>
- this.uploadImageToDropbox(req.body.file, req.user as DashUserModel).then(uploadUrl =>
- uploadUrl instanceof Error
- ? _invalid(res, uploadUrl.message)
- : this.expandImage(uploadUrl, req.body.prompt).then(text => {
- if (text.error_code) _error(res, text.message);
- else
- DashUploadUtils.UploadImage(text.outputs[0].image.url).then(info => {
- if (info instanceof Error) _invalid(res, info.message);
- else _success(res, info);
- });
- })
- ),
+ this.uploadImageToDropbox(req.body.file, req.user as DashUserModel)
+ .then(uploadUrl =>
+ this.expandImage(uploadUrl, req.body.prompt).then(text => {
+ if (text.error_code) _error(res, text.message);
+ else
+ DashUploadUtils.UploadImage(text.outputs[0].image.url).then(info => {
+ if (info instanceof Error) _invalid(res, info.message);
+ else _success(res, info);
+ });
+ })
+ )
+ .catch(e => _invalid(res, e.message)),
});
// construct this url and send user to it. It will allow them to authorize their dropbox account and will send the resulting token to our endpoint /refreshDropbox
diff --git a/src/server/DashUploadUtils.ts b/src/server/DashUploadUtils.ts
index ed109d8f7..f76371b0d 100644
--- a/src/server/DashUploadUtils.ts
+++ b/src/server/DashUploadUtils.ts
@@ -221,9 +221,7 @@ export namespace DashUploadUtils {
const parseExifData = async (source: string) => {
const image = await request.get(source, { encoding: null });
const { /* data, */ error } = await new Promise<{ data: ExifData; error: string | undefined }>(resolve => {
- new ExifImage({ image }, (exifError, data) => {
- resolve({ data, error: exifError?.message });
- });
+ new ExifImage({ image }, (exifError, data) => resolve({ data, error: exifError?.message }));
});
return error ? { data: undefined, error } : { data: await exifr.parse(image), error };
};
@@ -295,7 +293,7 @@ export namespace DashUploadUtils {
try {
// Compute the native width and height ofthe image with an npm module
- const { width: nativeWidth, height: nativeHeight } = await requestImageSize(resolvedUrl);
+ const { width: nativeWidth, height: nativeHeight } = await requestImageSize(resolvedUrl).catch(() => ({ width: 0, height: 0 }));
// Bundle up the information into an object
return {
source,
@@ -307,7 +305,6 @@ export namespace DashUploadUtils {
...results,
};
} catch (e: unknown) {
- console.log(e);
return new Error(e ? e.toString?.() : 'unkown error');
}
};