From b182988c7a53307cfe793c8fb0d3c4f11e4d49b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80=20?= =?UTF-8?q?=D0=9F=D0=BE=D1=80=D1=8F=D0=B4=D0=B8=D0=BD?= Date: Sun, 17 May 2026 13:19:23 +0300 Subject: [PATCH] fix: harden photo upload flow --- docs/PHOTO-UPLOAD-SMOKE-CHECKLIST.md | 38 +++ package.json | 1 + pnpm-lock.yaml | 12 + .../profile/hooks/photoUploadHooks.test.tsx | 209 ++++++++++++++++ src/features/profile/hooks/useTutorPhotos.ts | 54 ++-- src/features/profile/hooks/useUserAvatar.ts | 37 +-- .../hooks/useTutorServicePhotos.test.tsx | 171 +++++++++++++ .../services/hooks/useTutorServicePhotos.ts | 43 ++-- .../services/screens/ServiceWizardScreen.tsx | 33 +++ src/shared/config/i18n.ts | 16 +- src/shared/utils/media.test.ts | 113 ++++++++- src/shared/utils/media.ts | 234 ++++++++++++++---- vitest.setup.ts | 32 +++ 13 files changed, 902 insertions(+), 91 deletions(-) create mode 100644 docs/PHOTO-UPLOAD-SMOKE-CHECKLIST.md create mode 100644 src/features/profile/hooks/photoUploadHooks.test.tsx create mode 100644 src/features/services/hooks/useTutorServicePhotos.test.tsx diff --git a/docs/PHOTO-UPLOAD-SMOKE-CHECKLIST.md b/docs/PHOTO-UPLOAD-SMOKE-CHECKLIST.md new file mode 100644 index 0000000..d4af053 --- /dev/null +++ b/docs/PHOTO-UPLOAD-SMOKE-CHECKLIST.md @@ -0,0 +1,38 @@ +# Photo Upload — Beta Smoke Checklist + +Run on real device (iOS + Android) before beta launch. + +## User avatar + +- [ ] Open Profile -> tap avatar -> ImagePicker permission requested first time +- [ ] Pick photo from library -> upload starts, progress visible +- [ ] After upload -> avatar refreshes without app restart +- [ ] Restart app -> avatar still loads from S3, not blank +- [ ] Tap avatar again -> replace with new photo -> old object is removed from S3 if backend access is available + +## Tutor profile photos + +- [ ] In Profile -> tutor section -> upload 4 photos in one session +- [ ] Progress is visible while each photo uploads +- [ ] All 4 appear in profile gallery +- [ ] Reorder and delete one -> UI updates immediately +- [ ] Restart app -> gallery order and contents are unchanged + +## Service photos + +- [ ] In ServiceWizardScreen, edit existing service -> add photo to service +- [ ] Save -> photo visible in service detail +- [ ] Other user in student role sees photo while browsing service + +## Edge cases + +- [ ] Slow network simulation on iOS or Android -> upload completes or shows a clear retryable error +- [ ] Kill app mid-upload -> reopen -> no orphan placeholder, upload can be retried +- [ ] Upload 15 MB photo -> app compresses it automatically or rejects it with a friendly message +- [ ] Upload non-image file renamed to `.jpg` -> backend rejects or app shows a clear upload error +- [ ] Two devices on the same user upload simultaneously -> both successful photos are visible after refresh + +## Cross-channel + +- [ ] After tutor uploads a new photo -> student opens tutor profile -> updated photo is visible +- [ ] Presigned GET/proxy URL remains valid long enough for normal profile browsing diff --git a/package.json b/package.json index b09ab50..718982c 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "expo-constants": "~18.0.13", "expo-dev-client": "~6.0.20", "expo-image": "^3.0.11", + "expo-image-manipulator": "~14.0.8", "expo-image-picker": "~17.0.10", "expo-linear-gradient": "^15.0.8", "expo-localization": "~17.0.8", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 62cbf37..5e840b0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -47,6 +47,9 @@ dependencies: expo-image: specifier: ^3.0.11 version: 3.0.11(expo@54.0.32)(react-native-web@0.21.2)(react-native@0.81.5)(react@19.1.0) + expo-image-manipulator: + specifier: ~14.0.8 + version: 14.0.8(expo@54.0.32) expo-image-picker: specifier: ~17.0.10 version: 17.0.10(expo@54.0.32) @@ -5367,6 +5370,15 @@ packages: expo: 54.0.32(@babel/core@7.28.6)(@expo/dom-webview@55.0.6)(@expo/metro-runtime@55.0.11)(react-native@0.81.5)(react@19.1.0) dev: false + /expo-image-manipulator@14.0.8(expo@54.0.32): + resolution: {integrity: sha512-sXsXjm7rIxLWZe0j2A41J/Ph53PpFJRdyzJ3EQ/qetxLUvS2m3K1sP5xy37px43qCf0l79N/i6XgFgenFV36/Q==} + peerDependencies: + expo: '*' + dependencies: + expo: 54.0.32(@babel/core@7.28.6)(@expo/dom-webview@55.0.6)(@expo/metro-runtime@55.0.11)(react-native@0.81.5)(react@19.1.0) + expo-image-loader: 6.0.0(expo@54.0.32) + dev: false + /expo-image-picker@17.0.10(expo@54.0.32): resolution: {integrity: sha512-a2xrowp2trmvXyUWgX3O6Q2rZaa2C59AqivKI7+bm+wLvMfTEbZgldLX4rEJJhM8xtmEDTNU+lzjtObwzBRGaw==} peerDependencies: diff --git a/src/features/profile/hooks/photoUploadHooks.test.tsx b/src/features/profile/hooks/photoUploadHooks.test.tsx new file mode 100644 index 0000000..e5cfcce --- /dev/null +++ b/src/features/profile/hooks/photoUploadHooks.test.tsx @@ -0,0 +1,209 @@ +import React from 'react'; +import TestRenderer, { act } from 'react-test-renderer'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { useTutorPhotos } from './useTutorPhotos'; +import { useUserAvatar } from './useUserAvatar'; + +const apiMocks = vi.hoisted(() => ({ + getUserAvatar: vi.fn(), + requestUserAvatarUploadUrl: vi.fn(), + upsertUserAvatar: vi.fn(), + getTutorPhotos: vi.fn(), + requestTutorPhotoUploadUrl: vi.fn(), + confirmTutorPhotoUpload: vi.fn(), + deleteTutorPhoto: vi.fn(), +})); + +const imagePickerMocks = vi.hoisted(() => ({ + requestMediaLibraryPermissionsAsync: vi.fn(), + launchImageLibraryAsync: vi.fn(), +})); + +const mediaMocks = vi.hoisted(() => ({ + prepareImageForUpload: vi.fn(), + uploadBinaryToStorage: vi.fn(), +})); + +const alertMocks = vi.hoisted(() => ({ + showAlert: vi.fn(), +})); + +const i18nMocks = vi.hoisted(() => ({ + t: (key: string) => key, +})); + +vi.mock('../../../shared/api/client', () => ({ + api: apiMocks, +})); + +vi.mock('expo-image-picker', () => imagePickerMocks); + +vi.mock('../../../shared/utils/media', () => { + const sortByPosition = (items: T[]) => + [...items].sort((left, right) => (left.position ?? 0) - (right.position ?? 0)); + return { + prepareImageForUpload: mediaMocks.prepareImageForUpload, + uploadBinaryToStorage: mediaMocks.uploadBinaryToStorage, + resolveMediaUrl: (media?: { proxy_url?: string | null; url?: string | null } | null) => + media?.proxy_url ?? media?.url ?? null, + sortByPosition, + }; +}); + +vi.mock('../../../shared/utils/alert', () => ({ + showAlert: alertMocks.showAlert, +})); + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: i18nMocks.t, + }), +})); + +const pickedAsset = { + uri: 'file:///picked.jpg', + fileName: 'picked.jpg', + mimeType: 'image/jpeg', + fileSize: 1024, + width: 1000, + height: 800, +}; + +const preparedAsset = { + uri: 'file:///prepared.jpg', + fileName: 'avatar-1.jpg', + contentType: 'image/jpeg', + sizeBytes: 512, + width: 1000, + height: 800, +}; + +const renderHook = (hook: () => T) => { + const result = { current: undefined as T | undefined }; + const TestComponent = () => { + result.current = hook(); + return null; + }; + let renderer: TestRenderer.ReactTestRenderer; + act(() => { + renderer = TestRenderer.create(); + }); + return { + result: result as { current: T }, + unmount: () => renderer.unmount(), + }; +}; + +const pickImage = () => { + imagePickerMocks.requestMediaLibraryPermissionsAsync.mockResolvedValue({ granted: true }); + imagePickerMocks.launchImageLibraryAsync.mockResolvedValue({ + canceled: false, + assets: [pickedAsset], + }); +}; + +beforeEach(() => { + vi.clearAllMocks(); + pickImage(); + mediaMocks.prepareImageForUpload.mockResolvedValue(preparedAsset); + mediaMocks.uploadBinaryToStorage.mockResolvedValue({ sizeBytes: preparedAsset.sizeBytes }); +}); + +describe('photo upload hooks', () => { + it('runs user avatar presign -> upload -> confirm -> refetch', async () => { + apiMocks.getUserAvatar.mockResolvedValue(null); + apiMocks.requestUserAvatarUploadUrl.mockResolvedValue({ + upload_url: 'mock-upload://avatar', + storage_key: 'users/1/avatar/photo.jpg', + }); + apiMocks.upsertUserAvatar.mockResolvedValue({ id: 10, user_id: 1 }); + + const { result } = renderHook(() => useUserAvatar(1, true)); + + await result.current.pickAndUpload(); + await act(async () => undefined); + + expect(apiMocks.requestUserAvatarUploadUrl).toHaveBeenCalledWith(1, { + contentType: 'image/jpeg', + filename: 'avatar-1.jpg', + }); + expect(mediaMocks.uploadBinaryToStorage).toHaveBeenCalledWith( + expect.objectContaining({ + uploadUrl: 'mock-upload://avatar', + fileUri: 'file:///prepared.jpg', + contentType: 'image/jpeg', + }), + ); + expect(apiMocks.upsertUserAvatar).toHaveBeenCalledWith( + 1, + expect.objectContaining({ + storage_key: 'users/1/avatar/photo.jpg', + content_type: 'image/jpeg', + size_bytes: 512, + }), + ); + expect(apiMocks.getUserAvatar).toHaveBeenCalled(); + }); + + it('shows a friendly avatar error when compression leaves the file too large', async () => { + mediaMocks.prepareImageForUpload.mockRejectedValue(new Error('photo_too_large')); + const { result } = renderHook(() => useUserAvatar(1, false)); + + await result.current.pickAndUpload(); + await act(async () => undefined); + + expect(apiMocks.requestUserAvatarUploadUrl).not.toHaveBeenCalled(); + expect(alertMocks.showAlert).toHaveBeenCalledWith('errorTitle', 'photoUploadTooLarge'); + }); + + it('runs tutor photo upload and refetches the list', async () => { + apiMocks.getTutorPhotos.mockResolvedValue([]); + apiMocks.requestTutorPhotoUploadUrl.mockResolvedValue({ + upload_url: 'mock-upload://tutor', + storage_key: 'tutors/7/photo.jpg', + }); + apiMocks.confirmTutorPhotoUpload.mockResolvedValue({ + id: 2, + storage_key: 'tutors/7/photo.jpg', + }); + + const { result } = renderHook(() => useTutorPhotos(7, true)); + + await result.current.pickAndUpload(); + await act(async () => undefined); + + expect(apiMocks.requestTutorPhotoUploadUrl).toHaveBeenCalledWith(7, { + contentType: 'image/jpeg', + filename: 'avatar-1.jpg', + }); + expect(apiMocks.confirmTutorPhotoUpload).toHaveBeenCalledWith( + 7, + expect.objectContaining({ + storage_key: 'tutors/7/photo.jpg', + content_type: 'image/jpeg', + size_bytes: 512, + }), + ); + expect(apiMocks.getTutorPhotos).toHaveBeenCalled(); + }); + + it('optimistically removes tutor photos and rolls back on failure', async () => { + apiMocks.getTutorPhotos.mockResolvedValue([{ id: 1, storage_key: 'tutors/7/one.jpg' }]); + apiMocks.deleteTutorPhoto.mockRejectedValue(new Error('network')); + const { result } = renderHook(() => useTutorPhotos(7, true)); + + await act(async () => undefined); + act(() => { + void result.current.remove(1); + }); + const buttons = alertMocks.showAlert.mock.calls.at(-1)?.[2] as + | Array<{ onPress?: () => Promise }> + | undefined; + + await buttons?.[1]?.onPress?.(); + await act(async () => undefined); + + expect(apiMocks.deleteTutorPhoto).toHaveBeenCalledWith(7, 1); + expect(result.current.items).toEqual([{ id: 1, storage_key: 'tutors/7/one.jpg' }]); + }); +}); diff --git a/src/features/profile/hooks/useTutorPhotos.ts b/src/features/profile/hooks/useTutorPhotos.ts index e3a88be..a87f0f5 100644 --- a/src/features/profile/hooks/useTutorPhotos.ts +++ b/src/features/profile/hooks/useTutorPhotos.ts @@ -6,8 +6,7 @@ import type { TutorPhoto } from '../../../shared/api/types'; import { isConflictError } from '../../../shared/utils/apiError'; import { showAlert } from '../../../shared/utils/alert'; import { - buildImageFileName, - resolveImageContentType, + prepareImageForUpload, sortByPosition, uploadBinaryToStorage, } from '../../../shared/utils/media'; @@ -27,6 +26,8 @@ const useTutorPhotos = (tutorId?: number, enabled = false) => { const { t } = useTranslation(); const [items, setItems] = useState([]); const [isLoading, setIsLoading] = useState(false); + const [isUploading, setIsUploading] = useState(false); + const [uploadProgress, setUploadProgress] = useState(0); const [error, setError] = useState(null); const load = useCallback(async () => { @@ -78,23 +79,23 @@ const useTutorPhotos = (tutorId?: number, enabled = false) => { if (!tutorId) { return null; } - const contentType = resolveImageContentType(payload); - const filename = payload.fileName ?? buildImageFileName('tutor-photo', contentType); + const prepared = await prepareImageForUpload(payload, { filePrefix: 'tutor-photo' }); const uploadData = await api.requestTutorPhotoUploadUrl(tutorId, { - contentType, - filename, + contentType: prepared.contentType, + filename: prepared.fileName, }); const uploadMeta = await uploadBinaryToStorage({ uploadUrl: uploadData.upload_url, - fileUri: payload.uri, - contentType, + fileUri: prepared.uri, + contentType: prepared.contentType, + onProgress: setUploadProgress, }); return api.confirmTutorPhotoUpload(tutorId, { storage_key: uploadData.storage_key, - content_type: contentType, - size_bytes: payload.fileSize ?? uploadMeta.sizeBytes, - width: payload.width ?? undefined, - height: payload.height ?? undefined, + content_type: prepared.contentType, + size_bytes: prepared.sizeBytes || uploadMeta.sizeBytes, + width: prepared.width, + height: prepared.height, position, }); }, @@ -115,6 +116,8 @@ const useTutorPhotos = (tutorId?: number, enabled = false) => { } try { setIsLoading(true); + setIsUploading(true); + setUploadProgress(0); await uploadPayload(payload); await load(); } catch (error) { @@ -125,10 +128,17 @@ const useTutorPhotos = (tutorId?: number, enabled = false) => { const message = error instanceof Error ? error.message : ''; showAlert( t('errorTitle'), - message === 'upload_timeout' ? t('photoUploadTimeoutHint') : t('photoUploadFailed'), + message === 'upload_timeout' + ? t('photoUploadTimeoutHint') + : message === 'photo_type_unsupported' + ? t('photoUploadUnsupportedType') + : message === 'photo_too_large' + ? t('photoUploadTooLarge') + : t('photoUploadFailed'), ); } finally { setIsLoading(false); + setIsUploading(false); } }, [items.length, load, pickImagePayload, t, tutorId, uploadPayload]); @@ -142,6 +152,8 @@ const useTutorPhotos = (tutorId?: number, enabled = false) => { } try { setIsLoading(true); + setIsUploading(true); + setUploadProgress(0); const currentPrimary = items[0]; const uploaded = await uploadPayload(payload, 1); if (uploaded?.id) { @@ -159,10 +171,17 @@ const useTutorPhotos = (tutorId?: number, enabled = false) => { const message = error instanceof Error ? error.message : ''; showAlert( t('errorTitle'), - message === 'upload_timeout' ? t('photoUploadTimeoutHint') : t('photoUploadFailed'), + message === 'upload_timeout' + ? t('photoUploadTimeoutHint') + : message === 'photo_type_unsupported' + ? t('photoUploadUnsupportedType') + : message === 'photo_too_large' + ? t('photoUploadTooLarge') + : t('photoUploadFailed'), ); } finally { setIsLoading(false); + setIsUploading(false); } }, [items, load, pickImagePayload, t, tutorId, uploadPayload]); @@ -192,11 +211,14 @@ const useTutorPhotos = (tutorId?: number, enabled = false) => { text: t('deleteAction'), style: 'destructive', onPress: async () => { + const previousItems = items; try { setIsLoading(true); + setItems((current) => current.filter((item) => item.id !== photoId)); await api.deleteTutorPhoto(tutorId, photoId); await load(); } catch { + setItems(previousItems); showAlert(t('errorTitle'), t('errorGeneric')); } finally { setIsLoading(false); @@ -205,7 +227,7 @@ const useTutorPhotos = (tutorId?: number, enabled = false) => { }, ]); }, - [load, t, tutorId], + [items, load, t, tutorId], ); const move = useCallback( @@ -229,6 +251,8 @@ const useTutorPhotos = (tutorId?: number, enabled = false) => { return { items, isLoading, + isUploading, + uploadProgress, error, load, pickAndUpload, diff --git a/src/features/profile/hooks/useUserAvatar.ts b/src/features/profile/hooks/useUserAvatar.ts index bc80e23..61139d6 100644 --- a/src/features/profile/hooks/useUserAvatar.ts +++ b/src/features/profile/hooks/useUserAvatar.ts @@ -5,8 +5,7 @@ import { api } from '../../../shared/api/client'; import type { UserAvatar } from '../../../shared/api/types'; import { showAlert } from '../../../shared/utils/alert'; import { - buildImageFileName, - resolveImageContentType, + prepareImageForUpload, resolveMediaUrl, uploadBinaryToStorage, } from '../../../shared/utils/media'; @@ -45,6 +44,7 @@ const useUserAvatar = (userId?: number, enabled = true) => { const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const [uploadStep, setUploadStep] = useState('idle'); + const [binaryUploadProgress, setBinaryUploadProgress] = useState(0); const [cacheBustVersion, setCacheBustVersion] = useState(null); const load = useCallback(async () => { @@ -79,7 +79,10 @@ const useUserAvatar = (userId?: number, enabled = true) => { const separator = baseUrl.includes('?') ? '&' : '?'; return `${baseUrl}${separator}v=${cacheBustVersion}`; }, [avatar, cacheBustVersion]); - const uploadProgress = uploadStepProgress[uploadStep]; + const uploadProgress = + uploadStep === 'uploading_binary' + ? Math.max(uploadStepProgress.requesting_upload_url, Math.min(binaryUploadProgress, 1) * 0.65) + : uploadStepProgress[uploadStep]; const isUploading = uploadStep !== 'idle' && uploadStep !== 'done' && uploadStep !== 'failed'; const pickImagePayload = useCallback(async (): Promise => { @@ -111,26 +114,27 @@ const useUserAvatar = (userId?: number, enabled = true) => { if (!userId) { return; } - const contentType = resolveImageContentType(payload); - const filename = payload.fileName ?? buildImageFileName('avatar', contentType); + const prepared = await prepareImageForUpload(payload, { filePrefix: 'avatar' }); setUploadStep('requesting_upload_url'); const uploadData = await api.requestUserAvatarUploadUrl(userId, { - contentType, - filename, + contentType: prepared.contentType, + filename: prepared.fileName, }); setUploadStep('uploading_binary'); + setBinaryUploadProgress(0); const uploadMeta = await uploadBinaryToStorage({ uploadUrl: uploadData.upload_url, - fileUri: payload.uri, - contentType, + fileUri: prepared.uri, + contentType: prepared.contentType, + onProgress: setBinaryUploadProgress, }); setUploadStep('finalizing'); await api.upsertUserAvatar(userId, { storage_key: uploadData.storage_key, - content_type: contentType, - size_bytes: payload.fileSize ?? uploadMeta.sizeBytes, - width: payload.width ?? undefined, - height: payload.height ?? undefined, + content_type: prepared.contentType, + size_bytes: prepared.sizeBytes || uploadMeta.sizeBytes, + width: prepared.width, + height: prepared.height, }); setUploadStep('syncing'); await load(); @@ -151,6 +155,7 @@ const useUserAvatar = (userId?: number, enabled = true) => { try { setIsLoading(true); setUploadStep('requesting_upload_url'); + setBinaryUploadProgress(0); await uploadSelectedImage(payload); } catch (error) { setUploadStep('failed'); @@ -159,7 +164,11 @@ const useUserAvatar = (userId?: number, enabled = true) => { const friendlyMessage = message === 'upload_timeout' ? t('photoUploadTimeoutHint') - : `${t('photoUploadFailed')} (${message})`; + : message === 'photo_type_unsupported' + ? t('photoUploadUnsupportedType') + : message === 'photo_too_large' + ? t('photoUploadTooLarge') + : `${t('photoUploadFailed')} (${message})`; showAlert(t('errorTitle'), friendlyMessage); } finally { setIsLoading(false); diff --git a/src/features/services/hooks/useTutorServicePhotos.test.tsx b/src/features/services/hooks/useTutorServicePhotos.test.tsx new file mode 100644 index 0000000..e0088c5 --- /dev/null +++ b/src/features/services/hooks/useTutorServicePhotos.test.tsx @@ -0,0 +1,171 @@ +import React from 'react'; +import TestRenderer, { act } from 'react-test-renderer'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { useTutorServicePhotos } from './useTutorServicePhotos'; + +const apiMocks = vi.hoisted(() => ({ + getTutorServicePhotos: vi.fn(), + requestTutorServicePhotoUploadUrl: vi.fn(), + confirmTutorServicePhotoUpload: vi.fn(), + deleteTutorServicePhoto: vi.fn(), +})); + +const imagePickerMocks = vi.hoisted(() => ({ + requestMediaLibraryPermissionsAsync: vi.fn(), + launchImageLibraryAsync: vi.fn(), +})); + +const mediaMocks = vi.hoisted(() => ({ + prepareImageForUpload: vi.fn(), + uploadBinaryToStorage: vi.fn(), +})); + +const alertMocks = vi.hoisted(() => ({ + showAlert: vi.fn(), +})); + +const i18nMocks = vi.hoisted(() => ({ + t: (key: string) => key, +})); + +vi.mock('../../../shared/api/client', () => ({ + api: apiMocks, +})); + +vi.mock('expo-image-picker', () => imagePickerMocks); + +vi.mock('../../../shared/utils/media', () => { + const sortByPosition = (items: T[]) => + [...items].sort((left, right) => (left.position ?? 0) - (right.position ?? 0)); + return { + prepareImageForUpload: mediaMocks.prepareImageForUpload, + uploadBinaryToStorage: mediaMocks.uploadBinaryToStorage, + sortByPosition, + }; +}); + +vi.mock('../../../shared/utils/alert', () => ({ + showAlert: alertMocks.showAlert, +})); + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: i18nMocks.t, + }), +})); + +const preparedAsset = { + uri: 'file:///service.jpg', + fileName: 'service-10.jpg', + contentType: 'image/jpeg', + sizeBytes: 512, + width: 1000, + height: 800, +}; + +const renderHook = (hook: () => T) => { + const result = { current: undefined as T | undefined }; + const TestComponent = () => { + result.current = hook(); + return null; + }; + let renderer: TestRenderer.ReactTestRenderer; + act(() => { + renderer = TestRenderer.create(); + }); + return { + result: result as { current: T }, + unmount: () => renderer.unmount(), + }; +}; + +beforeEach(() => { + vi.clearAllMocks(); + imagePickerMocks.requestMediaLibraryPermissionsAsync.mockResolvedValue({ granted: true }); + imagePickerMocks.launchImageLibraryAsync.mockResolvedValue({ + canceled: false, + assets: [ + { + uri: 'file:///picked.jpg', + fileName: 'picked.jpg', + mimeType: 'image/jpeg', + }, + ], + }); + mediaMocks.prepareImageForUpload.mockResolvedValue(preparedAsset); + mediaMocks.uploadBinaryToStorage.mockResolvedValue({ sizeBytes: preparedAsset.sizeBytes }); +}); + +describe('useTutorServicePhotos', () => { + it('runs service photo upload and refetches the list', async () => { + apiMocks.getTutorServicePhotos.mockResolvedValue([]); + apiMocks.requestTutorServicePhotoUploadUrl.mockResolvedValue({ + upload_url: 'mock-upload://service', + storage_key: 'tutors/7/services/10/photo.jpg', + }); + apiMocks.confirmTutorServicePhotoUpload.mockResolvedValue({ + id: 3, + storage_key: 'tutors/7/services/10/photo.jpg', + }); + const { result } = renderHook(() => + useTutorServicePhotos({ tutorId: 7, serviceId: 10, enabled: true }), + ); + + await result.current.addFromLibrary(); + await act(async () => undefined); + + expect(apiMocks.requestTutorServicePhotoUploadUrl).toHaveBeenCalledWith(7, 10, { + contentType: 'image/jpeg', + filename: 'service-10.jpg', + }); + expect(apiMocks.confirmTutorServicePhotoUpload).toHaveBeenCalledWith( + 7, + 10, + expect.objectContaining({ + storage_key: 'tutors/7/services/10/photo.jpg', + content_type: 'image/jpeg', + size_bytes: 512, + }), + ); + expect(apiMocks.getTutorServicePhotos).toHaveBeenCalled(); + }); + + it('surfaces upload validation errors before requesting a presign URL', async () => { + mediaMocks.prepareImageForUpload.mockRejectedValue(new Error('photo_type_unsupported')); + const { result } = renderHook(() => + useTutorServicePhotos({ tutorId: 7, serviceId: 10, enabled: false }), + ); + + await result.current.addFromLibrary(); + await act(async () => undefined); + + expect(apiMocks.requestTutorServicePhotoUploadUrl).not.toHaveBeenCalled(); + expect(alertMocks.showAlert).toHaveBeenCalledWith('errorTitle', 'photoUploadUnsupportedType'); + }); + + it('optimistically removes service photos and rolls back on failure', async () => { + apiMocks.getTutorServicePhotos.mockResolvedValue([ + { id: 3, storage_key: 'tutors/7/services/10/photo.jpg' }, + ]); + apiMocks.deleteTutorServicePhoto.mockRejectedValue(new Error('network')); + const { result } = renderHook(() => + useTutorServicePhotos({ tutorId: 7, serviceId: 10, enabled: true }), + ); + + await act(async () => undefined); + act(() => { + void result.current.remove(3); + }); + const buttons = alertMocks.showAlert.mock.calls.at(-1)?.[2] as + | Array<{ onPress?: () => Promise }> + | undefined; + + await buttons?.[1]?.onPress?.(); + await act(async () => undefined); + + expect(apiMocks.deleteTutorServicePhoto).toHaveBeenCalledWith(7, 10, 3); + expect(result.current.items).toEqual([ + { id: 3, storage_key: 'tutors/7/services/10/photo.jpg' }, + ]); + }); +}); diff --git a/src/features/services/hooks/useTutorServicePhotos.ts b/src/features/services/hooks/useTutorServicePhotos.ts index 73112a2..58aa16b 100644 --- a/src/features/services/hooks/useTutorServicePhotos.ts +++ b/src/features/services/hooks/useTutorServicePhotos.ts @@ -6,8 +6,7 @@ import type { TutorServicePhoto } from '../../../shared/api/types'; import { isConflictError } from '../../../shared/utils/apiError'; import { showAlert } from '../../../shared/utils/alert'; import { - buildImageFileName, - resolveImageContentType, + prepareImageForUpload, sortByPosition, uploadBinaryToStorage, } from '../../../shared/utils/media'; @@ -35,6 +34,8 @@ const useTutorServicePhotos = ({ const { t } = useTranslation(); const [items, setItems] = useState([]); const [isLoading, setIsLoading] = useState(false); + const [isUploading, setIsUploading] = useState(false); + const [uploadProgress, setUploadProgress] = useState(0); const [error, setError] = useState(null); const load = useCallback(async () => { @@ -96,23 +97,25 @@ const useTutorServicePhotos = ({ } try { setIsLoading(true); - const contentType = resolveImageContentType(payload); - const filename = payload.fileName ?? buildImageFileName(`service-${serviceId}`, contentType); + setIsUploading(true); + setUploadProgress(0); + const prepared = await prepareImageForUpload(payload, { filePrefix: `service-${serviceId}` }); const uploadData = await api.requestTutorServicePhotoUploadUrl(tutorId, serviceId, { - contentType, - filename, + contentType: prepared.contentType, + filename: prepared.fileName, }); const uploadMeta = await uploadBinaryToStorage({ uploadUrl: uploadData.upload_url, - fileUri: payload.uri, - contentType, + fileUri: prepared.uri, + contentType: prepared.contentType, + onProgress: setUploadProgress, }); await api.confirmTutorServicePhotoUpload(tutorId, serviceId, { storage_key: uploadData.storage_key, - content_type: contentType, - size_bytes: payload.fileSize ?? uploadMeta.sizeBytes, - width: payload.width ?? undefined, - height: payload.height ?? undefined, + content_type: prepared.contentType, + size_bytes: prepared.sizeBytes || uploadMeta.sizeBytes, + width: prepared.width, + height: prepared.height, }); await load(); } catch (error) { @@ -123,10 +126,17 @@ const useTutorServicePhotos = ({ const message = error instanceof Error ? error.message : ''; showAlert( t('errorTitle'), - message === 'upload_timeout' ? t('photoUploadTimeoutHint') : t('photoUploadFailed'), + message === 'upload_timeout' + ? t('photoUploadTimeoutHint') + : message === 'photo_type_unsupported' + ? t('photoUploadUnsupportedType') + : message === 'photo_too_large' + ? t('photoUploadTooLarge') + : t('photoUploadFailed'), ); } finally { setIsLoading(false); + setIsUploading(false); } }, [items.length, load, pickImagePayload, serviceId, t, tutorId]); @@ -141,11 +151,14 @@ const useTutorServicePhotos = ({ text: t('deleteAction'), style: 'destructive', onPress: async () => { + const previousItems = items; try { setIsLoading(true); + setItems((current) => current.filter((item) => item.id !== photoId)); await api.deleteTutorServicePhoto(tutorId, serviceId, photoId); await load(); } catch { + setItems(previousItems); showAlert(t('errorTitle'), t('errorGeneric')); } finally { setIsLoading(false); @@ -154,7 +167,7 @@ const useTutorServicePhotos = ({ }, ]); }, - [load, serviceId, t, tutorId], + [items, load, serviceId, t, tutorId], ); const move = useCallback( @@ -178,6 +191,8 @@ const useTutorServicePhotos = ({ return { items, isLoading, + isUploading, + uploadProgress, error, load, addFromLibrary, diff --git a/src/features/services/screens/ServiceWizardScreen.tsx b/src/features/services/screens/ServiceWizardScreen.tsx index b4383e4..ab71f16 100644 --- a/src/features/services/screens/ServiceWizardScreen.tsx +++ b/src/features/services/screens/ServiceWizardScreen.tsx @@ -78,6 +78,8 @@ const ServiceWizardScreen = ({ navigation, route }: Props) => { const { items: photos, isLoading: isPhotosLoading, + isUploading: isPhotoUploading, + uploadProgress: photoUploadProgress, error: photosError, addFromLibrary: addPhoto, remove: removePhoto, @@ -486,6 +488,23 @@ const ServiceWizardScreen = ({ navigation, route }: Props) => { {t('serviceWizardPhotosHint', { limit: TUTOR_SERVICE_PHOTOS_LIMIT })} + {isPhotoUploading ? ( + + + {t('photoUploadProgress', { + percent: Math.round(Math.max(photoUploadProgress, 0.06) * 100), + })} + + + + + + ) : null} {photosError ? {photosError} : null} @@ -885,6 +904,20 @@ const createStyles = (theme: ReturnType) => photosHint: { color: theme.textSecondary, }, + photoUploadStatus: { + gap: spacing.xs, + }, + photoUploadTrack: { + height: 6, + borderRadius: radius.full, + backgroundColor: theme.surface, + overflow: 'hidden', + }, + photoUploadFill: { + height: '100%', + borderRadius: radius.full, + backgroundColor: theme.primary, + }, pressablePressed: { opacity: 0.72, }, diff --git a/src/shared/config/i18n.ts b/src/shared/config/i18n.ts index 896b93a..67fca55 100644 --- a/src/shared/config/i18n.ts +++ b/src/shared/config/i18n.ts @@ -11,7 +11,8 @@ const resources = { tutorsTitle: 'Tutors', tutorProfileTitle: 'Tutor profile', tutorProfileUnavailable: 'Profile is unavailable', - tutorProfileUnavailableSubtitle: 'The tutor may have deleted their account or hidden the profile.', + tutorProfileUnavailableSubtitle: + 'The tutor may have deleted their account or hidden the profile.', onboardingTitle: 'Choose your role', onboardingStudent: 'Student', onboardingTutor: 'Tutor', @@ -321,6 +322,9 @@ const resources = { photoUnavailable: 'No preview', photosPermissionDenied: 'Allow access to photos to upload.', photoUploadFailed: 'Failed to upload photo.', + photoUploadTooLarge: 'Photo is still too large after compression. Choose a smaller image.', + photoUploadUnsupportedType: 'Only JPG, PNG, and HEIC photos are supported.', + photoUploadProgress: 'Uploading {{percent}}%', photoUploadTimeoutHint: 'Upload timed out. Check device type and S3_PRESIGN_PUBLIC_ENDPOINT.', avatarUploadTitle: 'Uploading photo', uploadingPhoto: 'Uploading photo...', @@ -797,8 +801,7 @@ const resources = { changePasswordCurrentInvalid: 'Неверный текущий пароль', deleteAccountTitle: 'Удаление аккаунта', deleteAccountWarning: 'Профиль и личные данные будут удалены безвозвратно.', - deleteAccountConsequences: - 'Чаты обезличиваются, история уроков сохраняется в учётных целях.', + deleteAccountConsequences: 'Чаты обезличиваются, история уроков сохраняется в учётных целях.', deleteAccountAction: 'Удалить аккаунт', deleteAccountHoldHint: 'Удерживайте кнопку, чтобы подтвердить удаление.', deleteAccountHoldAction: 'Удерживать для удаления', @@ -814,7 +817,8 @@ const resources = { notificationsUnreadCount: 'Непрочитанные: {{count}}', notificationMessageFallback: 'Открыть детали', notificationsTestPushAction: 'Отправить тестовое push', - notificationsTestPushQueued: 'Тестовое уведомление в очереди — должно прийти в течение минуты', + notificationsTestPushQueued: + 'Тестовое уведомление в очереди — должно прийти в течение минуты', openNotificationSettingsAction: 'Открыть настройки уведомлений', retryIntervalLabel: 'Напоминать каждые … минут', maxAttemptsLabel: 'Количество напоминаний', @@ -852,6 +856,10 @@ const resources = { photoUnavailable: 'Нет превью', photosPermissionDenied: 'Разрешите доступ к фото для загрузки.', photoUploadFailed: 'Не удалось загрузить фото.', + photoUploadTooLarge: + 'Фото всё ещё слишком большое после сжатия. Выберите изображение меньше.', + photoUploadUnsupportedType: 'Поддерживаются только JPG, PNG и HEIC.', + photoUploadProgress: 'Загрузка {{percent}}%', photoUploadTimeoutHint: 'Таймаут загрузки. Проверьте тип устройства и S3_PRESIGN_PUBLIC_ENDPOINT.', avatarUploadTitle: 'Загрузка фото', diff --git a/src/shared/utils/media.test.ts b/src/shared/utils/media.test.ts index 1eca4ef..5344166 100644 --- a/src/shared/utils/media.test.ts +++ b/src/shared/utils/media.test.ts @@ -1,12 +1,50 @@ -import { describe, expect, it } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const fileSystemMocks = vi.hoisted(() => ({ + getInfoAsync: vi.fn(), + createUploadTask: vi.fn(), +})); + +const imageManipulatorMocks = vi.hoisted(() => ({ + manipulateAsync: vi.fn(), +})); + +vi.mock('expo-file-system/legacy', () => ({ + getInfoAsync: fileSystemMocks.getInfoAsync, + createUploadTask: fileSystemMocks.createUploadTask, + FileSystemUploadType: { + BINARY_CONTENT: 'BINARY_CONTENT', + }, +})); + +vi.mock('expo-image-manipulator', () => ({ + manipulateAsync: imageManipulatorMocks.manipulateAsync, + SaveFormat: { + JPEG: 'jpeg', + }, +})); + import { buildImageFileName, + prepareImageForUpload, resolveImageContentType, resolveMediaUrl, sortByPosition, + uploadBinaryToStorage, + validateSourceImageContentType, } from './media'; describe('media utils', () => { + beforeEach(() => { + fileSystemMocks.getInfoAsync.mockResolvedValue({ exists: true, size: 4096 }); + fileSystemMocks.createUploadTask.mockReset(); + imageManipulatorMocks.manipulateAsync.mockResolvedValue({ + uri: 'file:///compressed.jpg', + width: 1920, + height: 1280, + }); + }); + it('resolves supported image content type', () => { expect(resolveImageContentType({ mimeType: 'image/webp' })).toBe('image/webp'); expect(resolveImageContentType({ mimeType: 'image/jpg' })).toBe('image/jpeg'); @@ -14,6 +52,75 @@ describe('media utils', () => { expect(resolveImageContentType({ mimeType: 'application/json' })).toBe('image/jpeg'); }); + it('validates source image types before compression', () => { + expect(validateSourceImageContentType({ mimeType: 'image/heic' })).toBe('image/heic'); + expect(() => validateSourceImageContentType({ mimeType: 'application/pdf' })).toThrow( + 'photo_type_unsupported', + ); + }); + + it('compresses images to jpeg before upload and rejects oversized output', async () => { + const prepared = await prepareImageForUpload( + { + uri: 'file:///original.heic', + fileName: 'original.heic', + mimeType: 'image/heic', + fileSize: 15 * 1024 * 1024, + }, + { filePrefix: 'avatar' }, + ); + expect(imageManipulatorMocks.manipulateAsync).toHaveBeenCalledWith( + 'file:///original.heic', + [{ resize: { width: 1920 } }], + { compress: 0.8, format: 'jpeg' }, + ); + expect(prepared).toMatchObject({ + uri: 'file:///compressed.jpg', + contentType: 'image/jpeg', + sizeBytes: 4096, + width: 1920, + height: 1280, + }); + + fileSystemMocks.getInfoAsync.mockResolvedValueOnce({ + exists: true, + size: 9 * 1024 * 1024, + }); + await expect( + prepareImageForUpload( + { uri: 'file:///large.jpg', fileName: 'large.jpg', mimeType: 'image/jpeg' }, + { filePrefix: 'large' }, + ), + ).rejects.toThrow('photo_too_large'); + }); + + it('uploads binary content with progress and retries transient failures', async () => { + fileSystemMocks.getInfoAsync.mockResolvedValue({ exists: true, size: 1024 }); + fileSystemMocks.createUploadTask + .mockReturnValueOnce({ + uploadAsync: vi.fn(async () => ({ status: 503 })), + cancelAsync: vi.fn(async () => undefined), + }) + .mockReturnValueOnce({ + uploadAsync: vi.fn(async () => ({ status: 200 })), + cancelAsync: vi.fn(async () => undefined), + }); + const onProgress = vi.fn(); + + await expect( + uploadBinaryToStorage({ + uploadUrl: 'https://s3.example.test/key', + fileUri: 'file:///compressed.jpg', + contentType: 'image/jpeg', + retryDelaysMs: [0], + onProgress, + }), + ).resolves.toEqual({ sizeBytes: 1024 }); + + expect(fileSystemMocks.createUploadTask).toHaveBeenCalledTimes(2); + expect(onProgress).toHaveBeenCalledWith(1); + }); + it('builds fallback filename by content type', () => { expect(buildImageFileName('avatar', 'image/png')).toMatch(/^avatar-\d+\.png$/); }); @@ -22,7 +129,9 @@ describe('media utils', () => { expect(resolveMediaUrl({ proxy_url: 'https://cdn.example.com/pic.jpg', url: 'url' })).toBe( 'https://cdn.example.com/pic.jpg', ); - expect(resolveMediaUrl({ proxy_url: '/api/media/users/1/avatar' })).toContain('/api/media/users/1/avatar'); + expect(resolveMediaUrl({ proxy_url: '/api/media/users/1/avatar' })).toContain( + '/api/media/users/1/avatar', + ); expect(resolveMediaUrl(null)).toBeNull(); }); diff --git a/src/shared/utils/media.ts b/src/shared/utils/media.ts index 109e8bd..2768e0b 100644 --- a/src/shared/utils/media.ts +++ b/src/shared/utils/media.ts @@ -1,8 +1,17 @@ +import * as FileSystem from 'expo-file-system/legacy'; +import * as ImageManipulator from 'expo-image-manipulator'; import { API_BASE_URL } from '../constants/config'; -const ALLOWED_IMAGE_CONTENT_TYPES = ['image/jpeg', 'image/png', 'image/webp'] as const; +const ALLOWED_SOURCE_IMAGE_CONTENT_TYPES = ['image/jpeg', 'image/png', 'image/heic'] as const; +const ALLOWED_UPLOAD_IMAGE_CONTENT_TYPES = ['image/jpeg', 'image/png', 'image/webp'] as const; +const ALLOWED_IMAGE_CONTENT_TYPES = ALLOWED_UPLOAD_IMAGE_CONTENT_TYPES; +const MAX_PHOTO_BYTES = 8 * 1024 * 1024; +const PHOTO_RESIZE_WIDTH = 1920; +const PHOTO_COMPRESS_QUALITY = 0.8; +const UPLOAD_RETRY_DELAYS_MS = [1000, 2000, 4000] as const; -type AllowedImageContentType = (typeof ALLOWED_IMAGE_CONTENT_TYPES)[number]; +type AllowedImageContentType = (typeof ALLOWED_UPLOAD_IMAGE_CONTENT_TYPES)[number]; +type AllowedSourceImageContentType = (typeof ALLOWED_SOURCE_IMAGE_CONTENT_TYPES)[number]; type LocalImageAsset = { uri: string; @@ -13,14 +22,42 @@ type LocalImageAsset = { height?: number | null; }; +type PreparedImageAsset = { + uri: string; + fileName: string; + contentType: AllowedImageContentType; + sizeBytes: number; + width?: number; + height?: number; +}; + type MediaWithUrl = { proxy_url?: string | null; url?: string | null; }; -const allowedImageTypeSet = new Set(ALLOWED_IMAGE_CONTENT_TYPES); +type UploadProgressHandler = (progress: number) => void; + +type UploadTaskResult = { + status: number; + body?: string; + headers?: Record; +}; + +type UploadTask = { + uploadAsync(): Promise; + cancelAsync(): Promise; +}; + +type FileInfoWithSize = { + exists: boolean; + size?: number; +}; + +const allowedUploadImageTypeSet = new Set(ALLOWED_UPLOAD_IMAGE_CONTENT_TYPES); +const allowedSourceImageTypeSet = new Set(ALLOWED_SOURCE_IMAGE_CONTENT_TYPES); -const normalizeImageContentType = (value?: string | null): AllowedImageContentType | null => { +const normalizeImageContentType = (value?: string | null): string | null => { if (!value) { return null; } @@ -28,10 +65,10 @@ const normalizeImageContentType = (value?: string | null): AllowedImageContentTy if (normalized === 'image/jpg') { return 'image/jpeg'; } - return allowedImageTypeSet.has(normalized) ? (normalized as AllowedImageContentType) : null; + return normalized; }; -const inferContentTypeFromFilename = (fileName?: string | null): AllowedImageContentType | null => { +const inferContentTypeFromFilename = (fileName?: string | null): string | null => { if (!fileName) { return null; } @@ -45,18 +82,38 @@ const inferContentTypeFromFilename = (fileName?: string | null): AllowedImageCon if (lower.endsWith('.jpg') || lower.endsWith('.jpeg')) { return 'image/jpeg'; } + if (lower.endsWith('.heic')) { + return 'image/heic'; + } return null; }; +const isAllowedSourceImageContentType = ( + value: string | null, +): value is AllowedSourceImageContentType => value !== null && allowedSourceImageTypeSet.has(value); + const resolveImageContentType = (asset: { mimeType?: string | null; fileName?: string | null; }): AllowedImageContentType => { - return ( - normalizeImageContentType(asset.mimeType) ?? - inferContentTypeFromFilename(asset.fileName) ?? - 'image/jpeg' - ); + const candidate = + normalizeImageContentType(asset.mimeType) ?? inferContentTypeFromFilename(asset.fileName); + if (candidate && allowedUploadImageTypeSet.has(candidate)) { + return candidate as AllowedImageContentType; + } + return 'image/jpeg'; +}; + +const validateSourceImageContentType = (asset: { + mimeType?: string | null; + fileName?: string | null; +}): AllowedSourceImageContentType => { + const candidate = + normalizeImageContentType(asset.mimeType) ?? inferContentTypeFromFilename(asset.fileName); + if (isAllowedSourceImageContentType(candidate)) { + return candidate; + } + throw new Error('photo_type_unsupported'); }; const extensionByContentType: Record = { @@ -70,51 +127,133 @@ const buildImageFileName = (prefix: string, contentType: AllowedImageContentType return `${prefix}-${Date.now()}.${extension}`; }; -const fetchWithTimeout = async (input: string, init: RequestInit, timeoutMs: number) => { - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), timeoutMs); - try { - return await fetch(input, { - ...init, - signal: controller.signal, - }); - } catch (error) { - if (error instanceof Error && error.name === 'AbortError') { - throw new Error('upload_timeout'); - } - throw error; - } finally { - clearTimeout(timeoutId); +const getLocalFileSize = async (uri: string): Promise => { + const info = (await FileSystem.getInfoAsync(uri)) as FileInfoWithSize; + if (!info.exists || typeof info.size !== 'number') { + return null; } + return info.size; }; -const uploadBinaryToStorage = async (params: { +const prepareImageForUpload = async ( + asset: LocalImageAsset, + options: { filePrefix: string; maxBytes?: number } = { filePrefix: 'photo' }, +): Promise => { + validateSourceImageContentType(asset); + const manipulated = await ImageManipulator.manipulateAsync( + asset.uri, + [{ resize: { width: PHOTO_RESIZE_WIDTH } }], + { + compress: PHOTO_COMPRESS_QUALITY, + format: ImageManipulator.SaveFormat.JPEG, + }, + ); + const sizeBytes = (await getLocalFileSize(manipulated.uri)) ?? asset.fileSize ?? 0; + if (sizeBytes > (options.maxBytes ?? MAX_PHOTO_BYTES)) { + throw new Error('photo_too_large'); + } + return { + uri: manipulated.uri, + fileName: buildImageFileName(options.filePrefix, 'image/jpeg'), + contentType: 'image/jpeg', + sizeBytes, + width: manipulated.width, + height: manipulated.height, + }; +}; + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +const shouldRetryUpload = (error: unknown) => { + if (!(error instanceof Error)) { + return true; + } + return ( + error.message === 'upload_timeout' || + error.message === 'upload_failed' || + error.message === 'network' + ); +}; + +const uploadFileWithProgress = async (params: { uploadUrl: string; fileUri: string; contentType: AllowedImageContentType; - timeoutMs?: number; -}): Promise<{ sizeBytes: number }> => { - const timeoutMs = params.timeoutMs ?? 45000; - const fileResponse = await fetchWithTimeout(params.fileUri, {}, timeoutMs); - const blob = await fileResponse.blob(); + timeoutMs: number; + onProgress?: UploadProgressHandler; +}): Promise => { if (params.uploadUrl.startsWith('mock-upload://')) { - return { sizeBytes: blob.size }; + params.onProgress?.(1); + return; } - const uploadResponse = await fetchWithTimeout( + const uploadTask = FileSystem.createUploadTask( params.uploadUrl, + params.fileUri, { - method: 'PUT', + httpMethod: 'PUT', + uploadType: FileSystem.FileSystemUploadType.BINARY_CONTENT, headers: { 'Content-Type': params.contentType, }, - body: blob, }, - timeoutMs, - ); - if (uploadResponse.status < 200 || uploadResponse.status >= 300) { - throw new Error('upload_failed'); + ({ totalBytesExpectedToSend, totalBytesSent }) => { + if (totalBytesExpectedToSend > 0) { + params.onProgress?.(Math.min(totalBytesSent / totalBytesExpectedToSend, 1)); + } + }, + ) as UploadTask; + + let timeoutId: ReturnType | null = null; + try { + const timeoutPromise = new Promise((_resolve, reject) => { + timeoutId = setTimeout(() => { + void uploadTask.cancelAsync(); + reject(new Error('upload_timeout')); + }, params.timeoutMs); + }); + const result = await Promise.race([uploadTask.uploadAsync(), timeoutPromise]); + if (result.status < 200 || result.status >= 300) { + throw new Error('upload_failed'); + } + params.onProgress?.(1); + } finally { + if (timeoutId) { + clearTimeout(timeoutId); + } } - return { sizeBytes: blob.size }; +}; + +const uploadBinaryToStorage = async (params: { + uploadUrl: string; + fileUri: string; + contentType: AllowedImageContentType; + timeoutMs?: number; + retryDelaysMs?: readonly number[]; + onProgress?: UploadProgressHandler; +}): Promise<{ sizeBytes: number }> => { + const timeoutMs = params.timeoutMs ?? 45000; + const retryDelaysMs = params.retryDelaysMs ?? UPLOAD_RETRY_DELAYS_MS; + const sizeBytes = (await getLocalFileSize(params.fileUri)) ?? 0; + let lastError: unknown = null; + for (let attempt = 0; attempt <= retryDelaysMs.length; attempt += 1) { + try { + await uploadFileWithProgress({ + uploadUrl: params.uploadUrl, + fileUri: params.fileUri, + contentType: params.contentType, + timeoutMs, + onProgress: params.onProgress, + }); + return { sizeBytes }; + } catch (error) { + lastError = error; + if (!shouldRetryUpload(error) || attempt === retryDelaysMs.length) { + break; + } + await sleep(retryDelaysMs[attempt]); + } + } + throw lastError instanceof Error ? lastError : new Error('upload_failed'); }; const toAbsoluteMediaUrl = (value: string) => { @@ -149,11 +288,22 @@ const sortByPosition = (items: T[]): T[] export { ALLOWED_IMAGE_CONTENT_TYPES, + ALLOWED_SOURCE_IMAGE_CONTENT_TYPES, + MAX_PHOTO_BYTES, resolveImageContentType, + validateSourceImageContentType, + prepareImageForUpload, buildImageFileName, uploadBinaryToStorage, resolveMediaUrl, sortByPosition, }; -export type { AllowedImageContentType, LocalImageAsset, MediaWithUrl }; +export type { + AllowedImageContentType, + AllowedSourceImageContentType, + LocalImageAsset, + PreparedImageAsset, + MediaWithUrl, + UploadProgressHandler, +}; diff --git a/vitest.setup.ts b/vitest.setup.ts index dee4b37..9ae66f9 100644 --- a/vitest.setup.ts +++ b/vitest.setup.ts @@ -189,6 +189,38 @@ vi.mock('expo-image', () => ({ } & Record) => React.createElement('ExpoImage', props, children), })); +vi.mock('expo-file-system/legacy', () => ({ + getInfoAsync: vi.fn(async () => ({ exists: true, size: 1024 })), + createUploadTask: vi.fn( + ( + _url: string, + _fileUri: string, + _options: unknown, + callback?: (progress: { totalBytesExpectedToSend: number; totalBytesSent: number }) => void, + ) => ({ + uploadAsync: vi.fn(async () => { + callback?.({ totalBytesExpectedToSend: 1, totalBytesSent: 1 }); + return { status: 200 }; + }), + cancelAsync: vi.fn(async () => undefined), + }), + ), + FileSystemUploadType: { + BINARY_CONTENT: 'BINARY_CONTENT', + }, +})); + +vi.mock('expo-image-manipulator', () => ({ + manipulateAsync: vi.fn(async (uri: string) => ({ + uri, + width: 1920, + height: 1080, + })), + SaveFormat: { + JPEG: 'jpeg', + }, +})); + vi.mock('react-native-svg', () => { const createSvgHost = (name: string) =>