π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Inline and reorder
Manav Rathic7e0986b1210
diff --git a/web/apps/photos/src/services/upload/uploadService.ts b/web/apps/photos/src/services/upload/uploadService.tsindex a0deffa59d..fa60476051 100644--- a/web/apps/photos/src/services/upload/uploadService.ts+++ b/web/apps/photos/src/services/upload/uploadService.ts@@ -45,6 +45,7 @@ import {isDataStream,type FileWithCollection2,type LivePhotoAssets2,+ type Metadata,type UploadAsset2,} from "types/upload";import {@@ -52,7 +53,7 @@ import {updateMagicMetadata,} from "utils/magicMetadata";import { readStream } from "utils/native-stream";-import { findMatchingExistingFiles } from "utils/upload";+import { findMatchingExistingFiles, hasFileHash } from "utils/upload";import { getFileStream } from "../readerService";import { getFileType } from "../typeDetectionService";import {@@ -298,6 +299,190 @@ const uploadService = new UploadService();export default uploadService;+interface UploadResponse {+ fileUploadResult: UPLOAD_RESULT;+ uploadedFile?: EnteFile;+}++export async function uploader(+ worker: Remote<DedicatedCryptoWorker>,+ existingFiles: EnteFile[],+ fileWithCollection: FileWithCollection2,+ uploaderName: string,+): Promise<UploadResponse> {+ const { collection, localID, ...uploadAsset2 } = fileWithCollection;+ /* TODO(MR): ElectronFile changes */+ const uploadAsset = uploadAsset2 as UploadAsset;+ const fileNameSize = `${assetName(+ fileWithCollection,+ )}_${convertBytesToHumanReadable(getAssetSize(uploadAsset))}`;++ log.info(`uploader called for ${fileNameSize}`);+ UIService.setFileProgress(localID, 0);+ await wait(0);+ let fileTypeInfo: FileTypeInfo;+ let fileSize: number;+ try {+ const maxFileSize = 4 * 1024 * 1024 * 1024; // 4 GB++ fileSize = getAssetSize(uploadAsset);+ if (fileSize >= maxFileSize) {+ return { fileUploadResult: UPLOAD_RESULT.TOO_LARGE };+ }+ log.info(`getting filetype for ${fileNameSize}`);+ fileTypeInfo = await getAssetFileType(uploadAsset);++ log.info(+ `got filetype for ${fileNameSize} - ${JSON.stringify(fileTypeInfo)}`,+ );++ log.info(`extracting metadata ${fileNameSize}`);+ const { metadata, publicMagicMetadata } =+ await uploadService.extractAssetMetadata(+ worker,+ uploadAsset,+ collection.id,+ fileTypeInfo,+ );++ const matchingExistingFiles = findMatchingExistingFiles(+ existingFiles,+ metadata,+ );+ log.debug(+ () =>+ `matchedFileList: ${matchingExistingFiles+ .map((f) => `${f.id}-${f.metadata.title}`)+ .join(",")}`,+ );+ if (matchingExistingFiles?.length) {+ const matchingExistingFilesCollectionIDs =+ matchingExistingFiles.map((e) => e.collectionID);+ log.debug(+ () =>+ `matched file collectionIDs:${matchingExistingFilesCollectionIDs}+ and collectionID:${collection.id}`,+ );+ if (matchingExistingFilesCollectionIDs.includes(collection.id)) {+ log.info(+ `file already present in the collection , skipped upload for ${fileNameSize}`,+ );+ const sameCollectionMatchingExistingFile =+ matchingExistingFiles.find(+ (f) => f.collectionID === collection.id,+ );+ return {+ fileUploadResult: UPLOAD_RESULT.ALREADY_UPLOADED,+ uploadedFile: sameCollectionMatchingExistingFile,+ };+ } else {+ log.info(+ `same file in ${matchingExistingFilesCollectionIDs.length} collection found for ${fileNameSize} ,adding symlink`,+ );+ // any of the matching file can used to add a symlink+ const resultFile = Object.assign({}, matchingExistingFiles[0]);+ resultFile.collectionID = collection.id;+ await addToCollection(collection, [resultFile]);+ return {+ fileUploadResult: UPLOAD_RESULT.ADDED_SYMLINK,+ uploadedFile: resultFile,+ };+ }+ }+ if (uploadCancelService.isUploadCancelationRequested()) {+ throw Error(CustomError.UPLOAD_CANCELLED);+ }+ log.info(`reading asset ${fileNameSize}`);++ const file = await readAsset(fileTypeInfo, uploadAsset);++ if (file.hasStaticThumbnail) {+ metadata.hasStaticThumbnail = true;+ }++ const pubMagicMetadata = await constructPublicMagicMetadata({+ ...publicMagicMetadata,+ uploaderName,+ });++ const fileWithMetadata: FileWithMetadata = {+ localID,+ filedata: file.filedata,+ thumbnail: file.thumbnail,+ metadata,+ pubMagicMetadata,+ };++ if (uploadCancelService.isUploadCancelationRequested()) {+ throw Error(CustomError.UPLOAD_CANCELLED);+ }+ log.info(`encryptAsset ${fileNameSize}`);+ const encryptedFile = await uploadService.encryptAsset(+ worker,+ fileWithMetadata,+ collection.key,+ );++ if (uploadCancelService.isUploadCancelationRequested()) {+ throw Error(CustomError.UPLOAD_CANCELLED);+ }+ log.info(`uploadToBucket ${fileNameSize}`);+ const logger: Logger = (message: string) => {+ log.info(message, `fileNameSize: ${fileNameSize}`);+ };+ const backupedFile: BackupedFile = await uploadService.uploadToBucket(+ logger,+ encryptedFile.file,+ );++ const uploadFile: UploadFile = uploadService.getUploadFile(+ collection,+ backupedFile,+ encryptedFile.fileKey,+ );+ log.info(`uploading file to server ${fileNameSize}`);++ const uploadedFile = await uploadService.uploadFile(uploadFile);++ log.info(`${fileNameSize} successfully uploaded`);++ return {+ fileUploadResult: metadata.hasStaticThumbnail+ ? UPLOAD_RESULT.UPLOADED_WITH_STATIC_THUMBNAIL+ : UPLOAD_RESULT.UPLOADED,+ uploadedFile: uploadedFile,+ };+ } catch (e) {+ log.info(`upload failed for ${fileNameSize} ,error: ${e.message}`);+ if (+ e.message !== CustomError.UPLOAD_CANCELLED &&+ e.message !== CustomError.UNSUPPORTED_FILE_FORMAT+ ) {+ log.error(+ `file upload failed - ${JSON.stringify({+ fileFormat: fileTypeInfo?.exactType,+ fileSize: convertBytesToHumanReadable(fileSize),+ })}`,+ e,+ );+ }+ const error = handleUploadError(e);+ switch (error.message) {+ case CustomError.ETAG_MISSING:+ return { fileUploadResult: UPLOAD_RESULT.BLOCKED };+ case CustomError.UNSUPPORTED_FILE_FORMAT:+ return { fileUploadResult: UPLOAD_RESULT.UNSUPPORTED };+ case CustomError.FILE_TOO_LARGE:+ return {+ fileUploadResult:+ UPLOAD_RESULT.LARGER_THAN_AVAILABLE_STORAGE,+ };+ default:+ return { fileUploadResult: UPLOAD_RESULT.FAILED };+ }+ }+}+export const getFileName = (file: File | ElectronFile | string) =>typeof file == "string" ? basename(file) : file.name;@@ -712,186 +897,64 @@ async function encryptFileStream(};}-interface UploadResponse {- fileUploadResult: UPLOAD_RESULT;- uploadedFile?: EnteFile;-}--export async function uploader(- worker: Remote<DedicatedCryptoWorker>,+export function findMatchingExistingFiles(existingFiles: EnteFile[],- fileWithCollection: FileWithCollection2,- uploaderName: string,-): Promise<UploadResponse> {- const { collection, localID, ...uploadAsset2 } = fileWithCollection;- /* TODO(MR): ElectronFile changes */- const uploadAsset = uploadAsset2 as UploadAsset;- const fileNameSize = `${assetName(- fileWithCollection,- )}_${convertBytesToHumanReadable(getAssetSize(uploadAsset))}`;-- log.info(`uploader called for ${fileNameSize}`);- UIService.setFileProgress(localID, 0);- await wait(0);- let fileTypeInfo: FileTypeInfo;- let fileSize: number;- try {- const maxFileSize = 4 * 1024 * 1024 * 1024; // 4 GB-- fileSize = getAssetSize(uploadAsset);- if (fileSize >= maxFileSize) {- return { fileUploadResult: UPLOAD_RESULT.TOO_LARGE };+ newFileMetadata: Metadata,+): EnteFile[] {+ const matchingFiles: EnteFile[] = [];+ for (const existingFile of existingFiles) {+ if (areFilesSame(existingFile.metadata, newFileMetadata)) {+ matchingFiles.push(existingFile);}- log.info(`getting filetype for ${fileNameSize}`);- fileTypeInfo = await getAssetFileType(uploadAsset);-- log.info(- `got filetype for ${fileNameSize} - ${JSON.stringify(fileTypeInfo)}`,- );-- log.info(`extracting metadata ${fileNameSize}`);- const { metadata, publicMagicMetadata } =- await uploadService.extractAssetMetadata(- worker,- uploadAsset,- collection.id,- fileTypeInfo,- );-- const matchingExistingFiles = findMatchingExistingFiles(- existingFiles,- metadata,- );- log.debug(- () =>- `matchedFileList: ${matchingExistingFiles- .map((f) => `${f.id}-${f.metadata.title}`)- .join(",")}`,- );- if (matchingExistingFiles?.length) {- const matchingExistingFilesCollectionIDs =- matchingExistingFiles.map((e) => e.collectionID);- log.debug(- () =>- `matched file collectionIDs:${matchingExistingFilesCollectionIDs}- and collectionID:${collection.id}`,- );- if (matchingExistingFilesCollectionIDs.includes(collection.id)) {- log.info(- `file already present in the collection , skipped upload for ${fileNameSize}`,- );- const sameCollectionMatchingExistingFile =- matchingExistingFiles.find(- (f) => f.collectionID === collection.id,- );- return {- fileUploadResult: UPLOAD_RESULT.ALREADY_UPLOADED,- uploadedFile: sameCollectionMatchingExistingFile,- };- } else {- log.info(- `same file in ${matchingExistingFilesCollectionIDs.length} collection found for ${fileNameSize} ,adding symlink`,- );- // any of the matching file can used to add a symlink- const resultFile = Object.assign({}, matchingExistingFiles[0]);- resultFile.collectionID = collection.id;- await addToCollection(collection, [resultFile]);- return {- fileUploadResult: UPLOAD_RESULT.ADDED_SYMLINK,- uploadedFile: resultFile,- };- }- }- if (uploadCancelService.isUploadCancelationRequested()) {- throw Error(CustomError.UPLOAD_CANCELLED);- }- log.info(`reading asset ${fileNameSize}`);-- const file = await readAsset(fileTypeInfo, uploadAsset);-- if (file.hasStaticThumbnail) {- metadata.hasStaticThumbnail = true;- }-- const pubMagicMetadata = await constructPublicMagicMetadata({- ...publicMagicMetadata,- uploaderName,- });-- const fileWithMetadata: FileWithMetadata = {- localID,- filedata: file.filedata,- thumbnail: file.thumbnail,- metadata,- pubMagicMetadata,- };-- if (uploadCancelService.isUploadCancelationRequested()) {- throw Error(CustomError.UPLOAD_CANCELLED);- }- log.info(`encryptAsset ${fileNameSize}`);- const encryptedFile = await uploadService.encryptAsset(- worker,- fileWithMetadata,- collection.key,- );-- if (uploadCancelService.isUploadCancelationRequested()) {- throw Error(CustomError.UPLOAD_CANCELLED);- }- log.info(`uploadToBucket ${fileNameSize}`);- const logger: Logger = (message: string) => {- log.info(message, `fileNameSize: ${fileNameSize}`);- };- const backupedFile: BackupedFile = await uploadService.uploadToBucket(- logger,- encryptedFile.file,- );-- const uploadFile: UploadFile = uploadService.getUploadFile(- collection,- backupedFile,- encryptedFile.fileKey,- );- log.info(`uploading file to server ${fileNameSize}`);-- const uploadedFile = await uploadService.uploadFile(uploadFile);-- log.info(`${fileNameSize} successfully uploaded`);+ }+ return matchingFiles;+}- return {- fileUploadResult: metadata.hasStaticThumbnail- ? UPLOAD_RESULT.UPLOADED_WITH_STATIC_THUMBNAIL- : UPLOAD_RESULT.UPLOADED,- uploadedFile: uploadedFile,- };- } catch (e) {- log.info(`upload failed for ${fileNameSize} ,error: ${e.message}`);+export function areFilesSame(+ existingFile: Metadata,+ newFile: Metadata,+): boolean {+ if (hasFileHash(existingFile) && hasFileHash(newFile)) {+ return areFilesWithFileHashSame(existingFile, newFile);+ } else {+ /*+ * The maximum difference in the creation/modification times of two similar files is set to 1 second.+ * This is because while uploading files in the web - browsers and users could have set reduced+ * precision of file times to prevent timing attacks and fingerprinting.+ * Context: https://developer.mozilla.org/en-US/docs/Web/API/File/lastModified#reduced_time_precision+ */+ const oneSecond = 1e6;if (- e.message !== CustomError.UPLOAD_CANCELLED &&- e.message !== CustomError.UNSUPPORTED_FILE_FORMAT+ existingFile.fileType === newFile.fileType &&+ Math.abs(existingFile.creationTime - newFile.creationTime) <+ oneSecond &&+ Math.abs(existingFile.modificationTime - newFile.modificationTime) <+ oneSecond &&+ existingFile.title === newFile.title) {- log.error(- `file upload failed - ${JSON.stringify({- fileFormat: fileTypeInfo?.exactType,- fileSize: convertBytesToHumanReadable(fileSize),- })}`,- e,- );- }- const error = handleUploadError(e);- switch (error.message) {- case CustomError.ETAG_MISSING:- return { fileUploadResult: UPLOAD_RESULT.BLOCKED };- case CustomError.UNSUPPORTED_FILE_FORMAT:- return { fileUploadResult: UPLOAD_RESULT.UNSUPPORTED };- case CustomError.FILE_TOO_LARGE:- return {- fileUploadResult:- UPLOAD_RESULT.LARGER_THAN_AVAILABLE_STORAGE,- };- default:- return { fileUploadResult: UPLOAD_RESULT.FAILED };+ return true;+ } else {+ return false;}}}++function areFilesWithFileHashSame(+ existingFile: Metadata,+ newFile: Metadata,+): boolean {+ if (+ existingFile.fileType !== newFile.fileType ||+ existingFile.title !== newFile.title+ ) {+ return false;+ }+ if (existingFile.fileType === FILE_TYPE.LIVE_PHOTO) {+ return (+ existingFile.imageHash === newFile.imageHash &&+ existingFile.videoHash === newFile.videoHash+ );+ } else {+ return existingFile.hash === newFile.hash;+ }+}diff --git a/web/apps/photos/src/utils/upload/index.ts b/web/apps/photos/src/utils/upload/index.tsindex 925d19b452..c75cc606bc 100644--- a/web/apps/photos/src/utils/upload/index.ts+++ b/web/apps/photos/src/utils/upload/index.ts@@ -13,72 +13,10 @@ import {const TYPE_JSON = "json";-export function findMatchingExistingFiles(- existingFiles: EnteFile[],- newFileMetadata: Metadata,-): EnteFile[] {- const matchingFiles: EnteFile[] = [];- for (const existingFile of existingFiles) {- if (areFilesSame(existingFile.metadata, newFileMetadata)) {- matchingFiles.push(existingFile);- }- }- return matchingFiles;-}--export function areFilesSame(- existingFile: Metadata,- newFile: Metadata,-): boolean {- if (hasFileHash(existingFile) && hasFileHash(newFile)) {- return areFilesWithFileHashSame(existingFile, newFile);- } else {- /*- * The maximum difference in the creation/modification times of two similar files is set to 1 second.- * This is because while uploading files in the web - browsers and users could have set reduced- * precision of file times to prevent timing attacks and fingerprinting.- * Context: https://developer.mozilla.org/en-US/docs/Web/API/File/lastModified#reduced_time_precision- */- const oneSecond = 1e6;- if (- existingFile.fileType === newFile.fileType &&- Math.abs(existingFile.creationTime - newFile.creationTime) <- oneSecond &&- Math.abs(existingFile.modificationTime - newFile.modificationTime) <- oneSecond &&- existingFile.title === newFile.title- ) {- return true;- } else {- return false;- }- }-}-export function hasFileHash(file: Metadata) {return file.hash || (file.imageHash && file.videoHash);}-export function areFilesWithFileHashSame(- existingFile: Metadata,- newFile: Metadata,-): boolean {- if (- existingFile.fileType !== newFile.fileType ||- existingFile.title !== newFile.title- ) {- return false;- }- if (existingFile.fileType === FILE_TYPE.LIVE_PHOTO) {- return (- existingFile.imageHash === newFile.imageHash &&- existingFile.videoHash === newFile.videoHash- );- } else {- return existingFile.hash === newFile.hash;- }-}-export function segregateMetadataAndMediaFiles(filesWithCollectionToUpload: FileWithCollection[],) {