Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import {
usePhotoCaptureSightTutorial,
useInspectionComplete,
} from './hooks';
// import { SessionTimeTrackerDemo } from '../components/SessionTimeTrackerDemo';
import { useImagesCleanup } from '../hooks/useImagesCleanup';

/**
* Props of the PhotoCapture component.
Expand Down Expand Up @@ -218,12 +218,17 @@ export function PhotoCapture({
closeBadConnectionWarningDialog,
uploadEventHandlers: badConnectionWarningUploadEventHandlers,
} = useBadConnectionWarning({ maxUploadDurationWarning });
const { cleanupEventHandlers } = useImagesCleanup({ inspectionId, apiConfig });
const uploadQueue = useUploadQueue({
inspectionId,
apiConfig,
additionalTasks,
complianceOptions,
eventHandlers: [adaptiveUploadEventHandlers, badConnectionWarningUploadEventHandlers],
eventHandlers: [
adaptiveUploadEventHandlers,
badConnectionWarningUploadEventHandlers,
cleanupEventHandlers,
],
});
const images = usePhotoCaptureImages(inspectionId);
const handlePictureTaken = usePictureTaken({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
} from '@monkvision/types';
import { useCallback, useMemo, useState } from 'react';
import { useObjectMemo } from '@monkvision/common';
import { UploadEventHandlers } from './useUploadQueue';
import { UploadEventHandlers, UploadSuccessPayload } from './useUploadQueue';

const DEFAULT_CAMERA_CONFIG: Required<CameraConfig> = {
quality: 0.6,
Expand Down Expand Up @@ -75,8 +75,8 @@ export function useAdaptiveCameraConfig({
setIsImageUpscalingAllowed(false);
};

const onUploadSuccess = useCallback((durationMs: number) => {
if (durationMs > MAX_UPLOAD_DURATION_MS) {
const onUploadSuccess = useCallback(({ durationMs }: UploadSuccessPayload) => {
if (durationMs && durationMs > MAX_UPLOAD_DURATION_MS) {
lowerMaxImageQuality();
}
}, []);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useCallback, useRef, useState } from 'react';
import { useObjectMemo } from '@monkvision/common';
import { PhotoCaptureAppConfig } from '@monkvision/types';
import { UploadEventHandlers } from './useUploadQueue';
import { UploadEventHandlers, UploadSuccessPayload } from './useUploadQueue';

/**
* Parameters accepted by the useBadConnectionWarning hook.
Expand Down Expand Up @@ -44,8 +44,9 @@ export function useBadConnectionWarning({
);

const onUploadSuccess = useCallback(
(durationMs: number) => {
({ durationMs }: UploadSuccessPayload) => {
if (
durationMs &&
maxUploadDurationWarning >= 0 &&
durationMs > maxUploadDurationWarning &&
!hadDialogBeenDisplayed.current
Expand Down
101 changes: 101 additions & 0 deletions packages/inspection-capture-web/src/hooks/useImagesCleanup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { useMonkState, useObjectMemo } from '@monkvision/common';
import { MonkApiConfig, useMonkApi } from '@monkvision/network';
import { useCallback } from 'react';
import { Image } from '@monkvision/types';
import { UploadEventHandlers, UploadSuccessPayload } from './useUploadQueue';

/**
* Parameters accepted by the useImagesCleanup hook.
*/
export interface ImagesCleanupParams {
/**
* The inspection ID.
*/
inspectionId: string;
/**
* The api config used to communicate with the API.
*/
apiConfig: MonkApiConfig;
}

/**
* Handle used to manage the images cleanup after a new one uploads.
*/
export interface ImagesCleanupHandle {
/**
* A set of event handlers listening to upload events.
*/
cleanupEventHandlers: UploadEventHandlers;
}

function extractOtherImagesToDelete(imagesBySight: Record<string, Image[]>): Image[] {
const imagesToDelete: Image[] = [];

Object.values(imagesBySight)
.filter((images) => images.length > 1)
.forEach((images) => {
const sortedImages = images.sort((a, b) =>
b.createdAt && a.createdAt ? b.createdAt - a.createdAt : 0,
);
imagesToDelete.push(...sortedImages.slice(1));
});

return imagesToDelete;
}

function groupImagesBySightId(images: Image[], sightIdToSkip: string): Record<string, Image[]> {
return images.reduce((acc, image) => {
if (!image.sightId || image.sightId === sightIdToSkip) {
return acc;
}
if (!acc[image.sightId]) {
acc[image.sightId] = [];
}

acc[image.sightId].push(image);
return acc;
}, {} as Record<string, Image[]>);
}

/**
* Custom hook used to cleanup sights' images of the inspection by deleting the old ones
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo: remove apostrophe

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not a typo but how the plural "sights" conjugate.

* when a new image is added.
*/
export function useImagesCleanup(props: ImagesCleanupParams): ImagesCleanupHandle {
const { deleteImage } = useMonkApi(props.apiConfig);
const { state } = useMonkState();

const onUploadSuccess = useCallback(
({ sightId, imageId }: UploadSuccessPayload) => {
if (!sightId) {
return;
}

const otherImagesToDelete = extractOtherImagesToDelete(
groupImagesBySightId(state.images, sightId),
);

const sightImagesToDelete = state.images.filter(
(image) =>
image.inspectionId === props.inspectionId &&
image.sightId === sightId &&
image.id !== imageId,
);

const imagesToDelete = [...otherImagesToDelete, ...sightImagesToDelete];

if (imagesToDelete.length > 0) {
imagesToDelete.forEach((image) =>
deleteImage({ imageId: image.id, id: props.inspectionId }),
);
}
},
[state.images, props.inspectionId],
);

return useObjectMemo({
cleanupEventHandlers: {
onUploadSuccess,
},
});
}
33 changes: 28 additions & 5 deletions packages/inspection-capture-web/src/hooks/useUploadQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,32 @@ import { useRef } from 'react';
import { useMonitoring } from '@monkvision/monitoring';
import { CaptureMode } from '../types';

/**
* Payload for the onUploadSuccess event handler.
*/
export interface UploadSuccessPayload {
/**
* The total elapsed time in milliseconds between the start of the upload and the end of the upload.
*/
durationMs?: number;
/**
* The sight ID associated with the uploaded picture, if applicable.
*/
sightId?: string;
/**
* The ID of the uploaded image.
*/
imageId?: string;
}

/**
* Type definition for upload event handlers.
*/
export interface UploadEventHandlers {
/**
* Callback called when a picture upload successfully completes.
*
* @param durationMs The total elapsed time in milliseconds between the start of the upload and the end of the upload.
*/
onUploadSuccess?: (durationMs: number) => void;
onUploadSuccess?: (payload: UploadSuccessPayload) => void;
/**
* Callback called when a picture upload fails because of a timeout.
*/
Expand Down Expand Up @@ -193,7 +209,7 @@ export function useUploadQueue({
}
try {
const startTs = Date.now();
await addImage(
const result = await addImage(
createAddImageOptions(
upload,
inspectionId,
Expand All @@ -205,7 +221,14 @@ export function useUploadQueue({
),
);
const uploadDurationMs = Date.now() - startTs;
eventHandlers?.forEach((handlers) => handlers.onUploadSuccess?.(uploadDurationMs));
const sightId = upload.mode === CaptureMode.SIGHT ? upload.sightId : undefined;
eventHandlers?.forEach((handlers) =>
handlers.onUploadSuccess?.({
durationMs: uploadDurationMs,
sightId,
imageId: result?.image?.id,
}),
);
} catch (err) {
if (
err instanceof Error &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ describe('useAdaptiveCameraConfigTest hook', () => {
expect(result.current.adaptiveCameraConfig.resolution).toEqual(
initialProps.initialCameraConfig.resolution,
);
act(() => result.current.uploadEventHandlers.onUploadSuccess?.(15001));
act(() => result.current.uploadEventHandlers.onUploadSuccess?.({ durationMs: 15001 }));
expect(result.current.adaptiveCameraConfig.resolution).toEqual(CameraResolution.QHD_2K);
expect(result.current.adaptiveCameraConfig.quality).toEqual(0.6);
expect(result.current.adaptiveCameraConfig.allowImageUpscaling).toEqual(false);
Expand All @@ -63,7 +63,7 @@ describe('useAdaptiveCameraConfigTest hook', () => {
expect(result.current.adaptiveCameraConfig.resolution).toEqual(
initialProps.initialCameraConfig.resolution,
);
act(() => result.current.uploadEventHandlers.onUploadSuccess?.(200));
act(() => result.current.uploadEventHandlers.onUploadSuccess?.({ durationMs: 200 }));
expect(result.current.adaptiveCameraConfig).toEqual(
expect.objectContaining(initialProps.initialCameraConfig),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ describe('useBadConnectionWarning hook', () => {
});

act(() => {
result.current.uploadEventHandlers.onUploadSuccess?.(maxUploadDurationWarning + 1);
result.current.uploadEventHandlers.onUploadSuccess?.({
durationMs: maxUploadDurationWarning + 1,
});
});
expect(result.current.isBadConnectionWarningDialogDisplayed).toBe(true);

Expand All @@ -40,7 +42,9 @@ describe('useBadConnectionWarning hook', () => {
});

act(() => {
result.current.uploadEventHandlers.onUploadSuccess?.(maxUploadDurationWarning - 1);
result.current.uploadEventHandlers.onUploadSuccess?.({
durationMs: maxUploadDurationWarning - 1,
});
});
expect(result.current.isBadConnectionWarningDialogDisplayed).toBe(false);

Expand Down Expand Up @@ -68,7 +72,7 @@ describe('useBadConnectionWarning hook', () => {
});

act(() => {
result.current.uploadEventHandlers.onUploadSuccess?.(100000);
result.current.uploadEventHandlers.onUploadSuccess?.({ durationMs: 100000 });
result.current.uploadEventHandlers.onUploadTimeout?.();
});
expect(result.current.isBadConnectionWarningDialogDisplayed).toBe(false);
Expand All @@ -87,7 +91,9 @@ describe('useBadConnectionWarning hook', () => {
});
expect(result.current.isBadConnectionWarningDialogDisplayed).toBe(true);
act(() => {
result.current.uploadEventHandlers.onUploadSuccess?.(maxUploadDurationWarning + 1);
result.current.uploadEventHandlers.onUploadSuccess?.({
durationMs: maxUploadDurationWarning + 1,
});
});
expect(result.current.isBadConnectionWarningDialogDisplayed).toBe(true);

Expand Down Expand Up @@ -131,7 +137,9 @@ describe('useBadConnectionWarning hook', () => {
});
expect(result.current.isBadConnectionWarningDialogDisplayed).toBe(false);
act(() => {
result.current.uploadEventHandlers.onUploadSuccess?.(maxUploadDurationWarning + 1);
result.current.uploadEventHandlers.onUploadSuccess?.({
durationMs: maxUploadDurationWarning + 1,
});
});
expect(result.current.isBadConnectionWarningDialogDisplayed).toBe(false);

Expand Down
Loading