import { StorageTypes } from '@internxt/sdk/dist/drive'; import { Thumbnail } from '@internxt/sdk/dist/drive/storage/types'; import { thumbnailableConvertibleImageExtension, thumbnailableExtension, thumbnailableImageExtension, thumbnailablePdfExtension, thumbnailableVideoExtension, } from 'app/drive/types/file-types'; import { Downloadable, downloadFile } from 'app/network/download'; import { FileKey, NetworkCredentials } from 'app/network/types/helper-types'; import { uploadFile as uploadToBucket } from 'app/network/upload'; import { binaryStreamToBlob } from 'services/stream.service'; import { AppDispatch } from 'app/store'; import { storageActions } from 'app/store/slices/storage'; import Resizer from 'react-image-file-resizer'; import { pdfjs } from 'react-pdf'; import { SdkFactory } from 'app/core/factory/sdk'; import errorService from 'services/error.service'; import localStorageService from 'services/local-storage.service'; import navigationService from 'services/navigation.service'; import { AppView } from 'app/core/types'; import notificationsService, { ToastType } from 'app/notifications/services/notifications.service'; import { DriveFileData, DriveItemData, ThumbnailConfig } from '../types'; import fetchFileBlob from './download.service/fetchFileBlob'; import { convertImageForPreview } from './image-preview.service'; import { getEnvironmentConfig } from './network.service'; import { FileToUpload } from './file.service/types'; import { ErrorLoadingVideoFileError } from './errors/thumbnail.service.errors'; import encryptedStorageService from 'services/encrypted-storage.service'; import { getDatabaseFilePreviewData, updateDatabaseFilePreviewData } from './database.service'; export interface ThumbnailToUpload { fileId: string; size: number; max_width: number; max_height: number; type: string; content: File; } interface ThumbnailGenerated { file: File | null; max_width: number; max_height: number; type: string; } interface RefreshFileThumbnailPayload { file: DriveFileData; content: Blob; isWorkspace: boolean; dispatch: AppDispatch; } const VIDEO_FRAME_QUALITY = 0.75; export const MAX_CONVERTIBLE_THUMBNAIL_SOURCE_BYTES = 50 * 1024 * 1024; export const isValidImage = (file: File): Promise => { return new Promise((resolve) => { const img = new Image(); img.onload = () => resolve(true); img.onerror = () => resolve(false); img.src = URL.createObjectURL(file); }); }; export const getImageThumbnail = async (file: File): Promise => { const isValid = await isValidImage(file); if (!isValid) { return null; } return new Promise((resolve) => { Resizer.imageFileResizer( file, ThumbnailConfig.MaxWidth, ThumbnailConfig.MaxHeight, ThumbnailConfig.Type, ThumbnailConfig.Quality, 0, (uri) => { if (uri && uri instanceof File) resolve(uri); else resolve(null); }, 'file', ); }); }; const getPDFThumbnail = async (file: File): Promise => { const loadingTask = pdfjs.getDocument(await file.arrayBuffer()); const pdfDocument = await loadingTask.promise; const page = await pdfDocument.getPage(1); const viewport = page.getViewport({ scale: 1.0 }); const canvas = document.createElement('canvas'); canvas.width = viewport.width; canvas.height = viewport.height; const canvasContext = canvas.getContext('2d', { alpha: false }); if (canvasContext) { const renderTask = page.render({ canvasContext, viewport }); await renderTask.promise; await loadingTask.destroy(); return new Promise((resolve) => { // Convert the canvas to an image buffer. canvas.toBlob((blob: Blob | null) => { if (blob) { resolve(new File([blob], '')); } else { resolve(null); } }); }); } return null; }; export const generateThumbnailBlob = (video: HTMLVideoElement, onBlob: (blob: Blob | null) => void) => { const canvas = document.createElement('canvas'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; const ctx = canvas.getContext('2d'); if (!ctx) { onBlob(null); return; } ctx.drawImage(video, 0, 0, canvas.width, canvas.height); canvas.toBlob((blob) => onBlob(blob), 'image/jpeg', VIDEO_FRAME_QUALITY); }; export const getVideoFrame = async (file: File): Promise => { let seekTo = 5; const onSeekEvent = (videoPlayer: HTMLVideoElement, resolve: (file: File | null) => void) => { generateThumbnailBlob(videoPlayer, (blob) => { resolve(blob ? new File([blob], '') : null); }); }; const onLoadMetadata = ( videoPlayer: HTMLVideoElement, resolve: (file: File | null) => void, reject: (error: Error) => void, ) => { if (videoPlayer.duration < seekTo) { seekTo = videoPlayer.duration / 2; } videoPlayer.currentTime = seekTo; videoPlayer.addEventListener('seeked', () => onSeekEvent(videoPlayer, resolve)); }; return new Promise((resolve, reject) => { const videoPlayer = document.createElement('video'); videoPlayer.setAttribute('src', URL.createObjectURL(file)); videoPlayer.load(); videoPlayer.addEventListener('error', () => { reject(new ErrorLoadingVideoFileError()); }); videoPlayer.addEventListener('loadedmetadata', () => onLoadMetadata(videoPlayer, resolve, reject)); }); }; export const uploadThumbnail = async ( thumbnailToUpload: ThumbnailToUpload, isTeam: boolean, updateProgressCallback: (progress: number) => void, abortController?: AbortController, ): Promise => { const { bridgeUser, bridgePass, encryptionKey, bucketId } = await getEnvironmentConfig(isTeam); if (!bucketId) { notificationsService.show({ text: 'Login again to start uploading files', type: ToastType.Warning }); localStorageService.clear(); navigationService.push(AppView.Login); throw new Error('Bucket not found!'); } const bucketFile = await uploadToBucket(bucketId, { creds: { pass: bridgePass, user: bridgeUser, }, filecontent: thumbnailToUpload.content, filesize: thumbnailToUpload.size, mnemonic: encryptionKey, progressCallback: (totalBytes, uploadedBytes) => { updateProgressCallback(uploadedBytes / totalBytes); }, abortController, }); const storageClient = SdkFactory.getNewApiInstance().createNewStorageClient(); const thumbnailEntry: StorageTypes.CreateThumbnailEntryPayload = { bucketFile, bucketId, encryptVersion: StorageTypes.EncryptionVersion.Aes03, fileUuid: thumbnailToUpload.fileId, maxHeight: thumbnailToUpload.max_height, maxWidth: thumbnailToUpload.max_width, size: thumbnailToUpload.size, type: thumbnailToUpload.type, }; return await storageClient.createThumbnailEntryWithUUID(thumbnailEntry); }; const getConvertibleImageThumbnail = async ( fileToUpload: FileToUpload, fileType: string, ): Promise => { const isTooLargeToConvert = fileToUpload.size > MAX_CONVERTIBLE_THUMBNAIL_SOURCE_BYTES; if (isTooLargeToConvert) return null; try { const previewBlob = await convertImageForPreview(fileToUpload.content, fileType); return await getImageThumbnail(new File([previewBlob], fileToUpload.name, { type: previewBlob.type })); } catch { return null; } }; /** * Generates a thumbnail from the given file to upload. * @async * @function * @param {FileToUpload} fileToUpload - The file to generate the thumbnail from. * @returns {Promise} - A promise that returns the generated thumbnail. */ export const getThumbnailFrom = async (fileToUpload: FileToUpload): Promise => { let thumbnailFile: File | null = null; const fileType = fileToUpload.type ? String(fileToUpload.type).toLowerCase() : ''; if (thumbnailableImageExtension.includes(fileType)) { thumbnailFile = await getImageThumbnail(fileToUpload.content); } else if (thumbnailableConvertibleImageExtension.includes(fileType)) { thumbnailFile = await getConvertibleImageThumbnail(fileToUpload, fileType); } else if (thumbnailablePdfExtension.includes(fileType)) { const firstPDFpageImage = await getPDFThumbnail(fileToUpload.content); if (firstPDFpageImage) { thumbnailFile = await getImageThumbnail(firstPDFpageImage); } } else if (thumbnailableVideoExtension.includes(fileType)) { const videoFrame = await getVideoFrame(fileToUpload.content); if (videoFrame) { thumbnailFile = await getImageThumbnail(videoFrame); } } return { file: thumbnailFile, type: String(ThumbnailConfig.Type), max_width: Number(ThumbnailConfig.MaxWidth), max_height: Number(ThumbnailConfig.MaxHeight), }; }; export const generateThumbnailFromFile = async ( fileToUpload: FileToUpload, fileId: string, isTeam: boolean, ): Promise<{ thumbnail: Thumbnail; thumbnailFile: File } | null> => { const fileType = fileToUpload.type ? String(fileToUpload.type).toLowerCase() : ''; if (thumbnailableExtension.includes(fileType)) { try { const thumbnail = await getThumbnailFrom(fileToUpload); if (thumbnail.file) { const thumbnailToUpload: ThumbnailToUpload = { fileId: fileId, size: thumbnail.file.size, max_width: thumbnail.max_width, max_height: thumbnail.max_height, type: thumbnail.type, content: thumbnail.file, }; const updateProgressCallback = () => { return; }; const abortController = new AbortController(); const thumbnailUploaded = await uploadThumbnail( thumbnailToUpload, isTeam, updateProgressCallback, abortController, ); return { thumbnail: thumbnailUploaded, thumbnailFile: thumbnail.file, }; } } catch (error) { errorService.reportError(error); } } return null; }; export const getCachedThumbnail = async ( file: { uuid: string; updatedAt: string }, readCache: (file: { fileUuid: string; }) => Promise<{ preview?: Blob; updatedAt?: string } | undefined> = getDatabaseFilePreviewData, ): Promise => { try { const cachedPreview = await readCache({ fileUuid: file.uuid }); return cachedPreview?.updatedAt === file.updatedAt ? cachedPreview.preview : undefined; } catch (error) { errorService.reportError(error); return undefined; } }; export const downloadThumbnail = async ( thumbnailToDownload: Pick, isWorkspace: boolean, abortController = new AbortController(), ): Promise => { const updateProgressCallback = () => { return; }; let useWorkspaceCredentials = isWorkspace; if (isWorkspace) { const user = await encryptedStorageService.getUser(); if (user) { const isInPersonalBucket = thumbnailToDownload.bucket_id === user.bucket; if (isInPersonalBucket) { useWorkspaceCredentials = false; } } } return await fetchFileBlob( { fileId: thumbnailToDownload.bucket_file, bucketId: thumbnailToDownload.bucket_id } as Downloadable, { isWorkspace: useWorkspaceCredentials, updateProgressCallback, abortController }, ); }; export const downloadPublicThumbnail = async ( thumbnailToDownload: Thumbnail, creds: NetworkCredentials, key: FileKey, abortController?: AbortController, ): Promise => { const thumbnailStream = await downloadFile({ bucketId: thumbnailToDownload.bucket_id, fileId: thumbnailToDownload.bucket_file, creds, key, options: abortController && { notifyProgress: () => undefined, abortController }, }); return binaryStreamToBlob(thumbnailStream); }; export const setCurrentThumbnail = ( thumbnailBlob: Blob, newThumbnail: Thumbnail, item: DriveItemData, dispatch: AppDispatch, ): void => { const currentThumbnail = Object.assign({}, newThumbnail); currentThumbnail.urlObject = URL.createObjectURL(thumbnailBlob); dispatch( storageActions.patchItem({ uuid: item.uuid, folderId: item.isFolder ? item.parentUuid : item.folderUuid, isFolder: item.isFolder, patch: { currentThumbnail: currentThumbnail, }, }), ); }; export const setThumbnails = (thumbnails: Thumbnail[], item: DriveItemData, dispatch: AppDispatch): void => { dispatch( storageActions.patchItem({ uuid: item.uuid, folderId: item.isFolder ? item.parentUuid : item.folderUuid, isFolder: item.isFolder, patch: { thumbnails: thumbnails, }, }), ); }; /** * Compares two thumbnails to determine if they are the same * @function * @param {Thumbnail} thumbnail - Thumbnail to compare. * @param {ThumbnailGenerated} compareTo - Thumbnail being compared to. * @returns {boolean} Returns true if both thumbnails are the same. */ export const compareThumbnail = (thumbnail: Thumbnail, compareTo: ThumbnailGenerated): boolean => { return ( Number(thumbnail.size) === Number(compareTo.file?.size) && String(thumbnail.type) === String(compareTo.type) && Number(thumbnail.max_width) === Number(compareTo.max_width) && Number(thumbnail.max_height) === Number(compareTo.max_height) ); }; const generateThumbnailFromContent = (file: DriveFileData, content: Blob): Promise => { const isImageContent = content.type?.startsWith('image/'); return getThumbnailFrom({ name: file.name, size: file.size, type: isImageContent ? content.type.split('/')[1] : file.type, content: new File([content], file.name, { type: content.type }), parentFolderId: file.folderUuid, }); }; /** * Regenerates the thumbnail of a file from its downloaded content. A thumbnail that differs from * the current one is uploaded and replaces it; an equal one is only stored locally if missing. */ export const refreshFileThumbnailFromContent = async ({ file, content, isWorkspace, dispatch, }: RefreshFileThumbnailPayload): Promise => { const generatedThumbnail = await generateThumbnailFromContent(file, content); const thumbnailFile = generatedThumbnail.file; if (!thumbnailFile) return; const currentThumbnail = file.thumbnails?.[0]; const previewData = { fileUuid: file.uuid, updatedAt: file.updatedAt }; if (currentThumbnail && compareThumbnail(currentThumbnail, generatedThumbnail)) { const isStoredLocally = !!(await getDatabaseFilePreviewData({ fileUuid: file.uuid })); if (!isStoredLocally) { await updateDatabaseFilePreviewData({ ...previewData, previewBlob: new Blob([thumbnailFile], { type: thumbnailFile.type }), }); } return; } const uploadedThumbnail = await uploadThumbnail( { fileId: file.uuid, size: thumbnailFile.size, max_width: generatedThumbnail.max_width, max_height: generatedThumbnail.max_height, type: generatedThumbnail.type, content: thumbnailFile, }, isWorkspace, () => undefined, ); const thumbnails = currentThumbnail ? [uploadedThumbnail, ...file.thumbnails.slice(1)] : [uploadedThumbnail]; setCurrentThumbnail(thumbnailFile, uploadedThumbnail, file as DriveItemData, dispatch); setThumbnails(thumbnails, file as DriveItemData, dispatch); await updateDatabaseFilePreviewData({ ...previewData, previewBlob: thumbnailFile }); };