π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
update downloadManager to use client to handle publicDownloads too
Abhinav3cb05518b5b2
diff --git a/apps/photos/src/services/downloadManager.ts b/apps/photos/src/services/downloadManager.tsindex fdb4eb3322..d6f5d2724f 100644--- a/apps/photos/src/services/downloadManager.ts+++ b/apps/photos/src/services/downloadManager.ts@@ -1,11 +1,8 @@-import { getToken } from '@ente/shared/storage/localStorage/helpers';-import { getFileURL, getThumbnailURL } from '@ente/shared/network/api';import {generateStreamFromArrayBuffer,getRenderableFileURL,createTypedObjectURL,} from 'utils/file';-import HTTPService from '@ente/shared/network/HTTPService';import { EnteFile } from 'types/file';import { logError } from '@ente/shared/sentry';@@ -17,45 +14,91 @@ import { CACHES } from '@ente/shared/storage/cacheStorage/constants';import { Remote } from 'comlink';import { DedicatedCryptoWorker } from '@ente/shared/crypto/internal/crypto.worker';import { LimitedCache } from '@ente/shared/storage/cacheStorage/types';-import { retryAsyncFunction } from 'utils/network';import { addLogLine } from '@ente/shared/logging';+import { APPS } from '@ente/shared/apps/constants';+import { PhotosDownloadClient } from './downloadManagerClients/photos';+import { PublicAlbumsDownloadClient } from './downloadManagerClients/publicAlbums';++export type SourceURLs = {+ original: string[];+ converted: string[];+};++export type OnDownloadProgress = (event: {+ loaded: number;+ total: number;+}) => void;++export interface DownloadClient {+ updateTokens: (token: string, passwordToken?: string) => void;+ updateTimeout: (timeout: number) => void;+ downloadThumbnail: (+ file: EnteFile,+ timeout?: number+ ) => Promise<Uint8Array>;+ downloadFile: (+ file: EnteFile,+ onDownloadProgress: OnDownloadProgress+ ) => Promise<Uint8Array>;+ downloadFileStream: (file: EnteFile) => Promise<Response>;+}class DownloadManager {- private fileObjectURLPromise = new Map<- string,- Promise<{ original: string[]; converted: string[] }>- >();+ private downloadClient: DownloadClient;+ private thumbnailCache: LimitedCache;+ private cryptoWorker: Remote<DedicatedCryptoWorker>;++ private fileObjectURLPromise = new Map<string, Promise<SourceURLs>>();private thumbnailObjectURLPromise = new Map<number, Promise<string>>();private fileDownloadProgress = new Map<number, number>();private progressUpdater: (value: Map<number, number>) => void = () => {};- private thumbnailCache: LimitedCache;+ async init(+ app: APPS,+ token: string,+ passwordToken?: string,+ timeout?: number+ ) {+ this.downloadClient = createDownloadClient(+ app,+ token,+ passwordToken,+ timeout+ );+ this.thumbnailCache = await openThumbnailCache();+ this.cryptoWorker = await ComlinkCryptoWorker.getInstance();+ }++ updateToken(token: string, passwordToken?: string) {+ this.downloadClient.updateTokens(token, passwordToken);+ }++ updateCryptoWorker(cryptoWorker: Remote<DedicatedCryptoWorker>) {+ this.cryptoWorker = cryptoWorker;+ }++ updateTimeout(timeout: number) {+ this.downloadClient.updateTimeout(timeout);+ }setProgressUpdater(progressUpdater: (value: Map<number, number>) => void) {this.progressUpdater = progressUpdater;}- private async getThumbnailCache() {- try {- if (!this.thumbnailCache) {- this.thumbnailCache = await CacheStorageService.open(- CACHES.THUMBS- );- }- return this.thumbnailCache;- } catch (e) {- return null;- // ignore- }+ public async getInMemoryCachedThumbnailURL(fileID: number) {+ return this.thumbnailObjectURLPromise.get(fileID);+ }++ public async getInMemoryCachedFileURL(fileID: number) {+ return this.fileObjectURLPromise.get(fileID.toString());}- public async getCachedThumbnail(file: EnteFile) {+ public async getCachedThumbnail(fileID: number) {try {- const thumbnailCache = await this.getThumbnailCache();- const cacheResp: Response = await thumbnailCache?.match(- file.id.toString()+ const cacheResp: Response = await this.thumbnailCache?.match(+ fileID.toString());if (cacheResp) {@@ -68,33 +111,18 @@ class DownloadManager {}}- public async getThumbnail(- file: EnteFile,- tokenOverride?: string,- usingWorker?: Remote<DedicatedCryptoWorker>,- timeout?: number- ) {+ public async getThumbnail(file: EnteFile) {try {- const token = tokenOverride || getToken();- if (!token) {- return null;- }if (!this.thumbnailObjectURLPromise.has(file.id)) {const downloadPromise = async () => {- const thumbnailCache = await this.getThumbnailCache();- const cachedThumb = await this.getCachedThumbnail(file);+ const cachedThumb = await this.getCachedThumbnail(file.id);if (cachedThumb) {return cachedThumb;}- const thumb = await this.downloadThumb(- token,- file,- usingWorker,- timeout- );+ const thumb = await this.downloadThumb(file);const thumbBlob = new Blob([thumb]);- thumbnailCache+ this.thumbnailCache?.put(file.id.toString(), new Response(thumbBlob)).catch((e) => {logError(e, 'cache put failed');@@ -113,26 +141,12 @@ class DownloadManager {}}- downloadThumb = async (- token: string,- file: EnteFile,- usingWorker?: Remote<DedicatedCryptoWorker>,- timeout?: number- ) => {- const resp = await HTTPService.get(- getThumbnailURL(file.id),- null,- { 'X-Auth-Token': token },- { responseType: 'arraybuffer', timeout }- );- if (typeof resp.data === 'undefined') {- throw Error(CustomError.REQUEST_FAILED);- }- const cryptoWorker =- usingWorker || (await ComlinkCryptoWorker.getInstance());- const decrypted = await cryptoWorker.decryptThumbnail(- new Uint8Array(resp.data),- await cryptoWorker.fromB64(file.thumbnail.decryptionHeader),+ downloadThumb = async (file: EnteFile) => {+ const encrypted = await this.downloadClient.downloadThumbnail(file);++ const decrypted = await this.cryptoWorker.decryptThumbnail(+ encrypted,+ await this.cryptoWorker.fromB64(file.thumbnail.decryptionHeader),file.key);return decrypted;@@ -166,24 +180,8 @@ class DownloadManager {}};- public async getCachedOriginalFile(file: EnteFile) {- return (await this.fileObjectURLPromise.get(file.id.toString()))- ?.original;- }-- async downloadFile(- file: EnteFile,- tokenOverride?: string,- usingWorker?: Remote<DedicatedCryptoWorker>,- timeout?: number- ) {+ async downloadFile(file: EnteFile) {try {- const cryptoWorker =- usingWorker || (await ComlinkCryptoWorker.getInstance());- const token = tokenOverride || getToken();- if (!token) {- return null;- }const onDownloadProgress = this.trackDownloadProgress(file.id,file.info?.fileSize@@ -192,26 +190,17 @@ class DownloadManager {file.metadata.fileType === FILE_TYPE.IMAGE ||file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {- const resp = await retryAsyncFunction(() =>- HTTPService.get(- getFileURL(file.id),- null,- { 'X-Auth-Token': token },- {- responseType: 'arraybuffer',- timeout,- onDownloadProgress,- }- )+ const encrypted = await this.downloadClient.downloadFile(+ file,+ onDownloadProgress);this.clearDownloadProgress(file.id);- if (typeof resp.data === 'undefined') {- throw Error(CustomError.REQUEST_FAILED);- }try {- const decrypted = await cryptoWorker.decryptFile(- new Uint8Array(resp.data),- await cryptoWorker.fromB64(file.file.decryptionHeader),+ const decrypted = await this.cryptoWorker.decryptFile(+ new Uint8Array(encrypted),+ await this.cryptoWorker.fromB64(+ file.file.decryptionHeader+ ),file.key);return generateStreamFromArrayBuffer(decrypted);@@ -231,27 +220,24 @@ class DownloadManager {throw e;}}- const resp = await retryAsyncFunction(() =>- fetch(getFileURL(file.id), {- headers: {- 'X-Auth-Token': token,- },- })- );+ const resp = await this.downloadClient.downloadFileStream(file);const reader = resp.body.getReader();const contentLength = +resp.headers.get('Content-Length') ?? 0;let downloadedBytes = 0;const stream = new ReadableStream({- async start(controller) {+ start: async (controller) => {try {- const decryptionHeader = await cryptoWorker.fromB64(- file.file.decryptionHeader+ const decryptionHeader =+ await this.cryptoWorker.fromB64(+ file.file.decryptionHeader+ );+ const fileKey = await this.cryptoWorker.fromB64(+ file.key);- const fileKey = await cryptoWorker.fromB64(file.key);const { pullState, decryptionChunkSize } =- await cryptoWorker.initChunkDecryption(+ await this.cryptoWorker.initChunkDecryption(decryptionHeader,fileKey);@@ -285,7 +271,7 @@ class DownloadManager {);try {const { decryptedData } =- await cryptoWorker.decryptFileChunk(+ await this.cryptoWorker.decryptFileChunk(fileData,pullState);@@ -329,7 +315,7 @@ class DownloadManager {if (data) {try {const { decryptedData } =- await cryptoWorker.decryptFileChunk(+ await this.cryptoWorker.decryptFileChunk(data,pullState);@@ -413,3 +399,25 @@ class DownloadManager {}export default new DownloadManager();++async function openThumbnailCache() {+ try {+ return await CacheStorageService.open(CACHES.THUMBS);+ } catch (e) {+ logError(e, 'Failed to open thumbnail cache');+ return null;+ }+}++function createDownloadClient(+ app: APPS,+ token: string,+ passwordToken?: string,+ timeout?: number+): DownloadClient {+ if (app === APPS.ALBUMS) {+ return new PublicAlbumsDownloadClient(token, passwordToken, timeout);+ } else {+ return new PhotosDownloadClient(token, timeout);+ }+}diff --git a/apps/photos/src/services/downloadManagerClients/photos.ts b/apps/photos/src/services/downloadManagerClients/photos.tsnew file mode 100644index 0000000000..38dab41cf4--- /dev/null+++ b/apps/photos/src/services/downloadManagerClients/photos.ts@@ -0,0 +1,65 @@+import HTTPService from '@ente/shared/network/HTTPService';+import { getFileURL, getThumbnailURL } from '@ente/shared/network/api';+import { EnteFile } from 'types/file';+import { DownloadClient } from 'services/downloadManager';+import { CustomError } from '@ente/shared/error';+import { retryAsyncFunction } from 'utils/network';++export class PhotosDownloadClient implements DownloadClient {+ constructor(private token: string, private timeout) {}+ updateTokens(token: string) {+ this.token = token;+ }++ updateTimeout(timeout: number) {+ this.timeout = timeout;+ }++ async downloadThumbnail(file: EnteFile) {+ if (!this.token) {+ return;+ }+ const resp = await HTTPService.get(+ getThumbnailURL(file.id),+ null,+ { 'X-Auth-Token': this.token },+ { responseType: 'arraybuffer', timeout: this.timeout }+ );+ if (typeof resp.data === 'undefined') {+ throw Error(CustomError.REQUEST_FAILED);+ }+ return new Uint8Array(resp.data);+ }++ async downloadFile(+ file: EnteFile,+ onDownloadProgress: (event: { loaded: number; total: number }) => void+ ): Promise<Uint8Array> {+ const resp = await retryAsyncFunction(() =>+ HTTPService.get(+ getFileURL(file.id),+ null,+ { 'X-Auth-Token': this.token },+ {+ responseType: 'arraybuffer',+ timeout: this.timeout,+ onDownloadProgress,+ }+ )+ );+ if (typeof resp.data === 'undefined') {+ throw Error(CustomError.REQUEST_FAILED);+ }+ return new Uint8Array(resp.data);+ }++ async downloadFileStream(file: EnteFile): Promise<Response> {+ return retryAsyncFunction(() =>+ fetch(getFileURL(file.id), {+ headers: {+ 'X-Auth-Token': this.token,+ },+ })+ );+ }+}diff --git a/apps/photos/src/services/downloadManagerClients/publicAlbums.ts b/apps/photos/src/services/downloadManagerClients/publicAlbums.tsnew file mode 100644index 0000000000..7a93e0e2af--- /dev/null+++ b/apps/photos/src/services/downloadManagerClients/publicAlbums.ts@@ -0,0 +1,78 @@+import HTTPService from '@ente/shared/network/HTTPService';+import {+ getPublicCollectionFileURL,+ getPublicCollectionThumbnailURL,+} from '@ente/shared/network/api';+import { EnteFile } from 'types/file';+import { DownloadClient } from 'services/downloadManager';+import { CustomError } from '@ente/shared/error';+import { retryAsyncFunction } from 'utils/network';++export class PublicAlbumsDownloadClient implements DownloadClient {+ constructor(+ private token: string,+ private passwordToken: string,+ private timeout: number+ ) {}++ updateTokens(token: string, passwordToken: string) {+ this.token = token;+ this.passwordToken = passwordToken;+ }++ updateTimeout(timeout: number) {+ this.timeout = timeout;+ }++ downloadThumbnail = async (file: EnteFile) => {+ const resp = await HTTPService.get(+ getPublicCollectionThumbnailURL(file.id),+ null,+ {+ 'X-Auth-Access-Token': this.token,+ ...(this.passwordToken && {+ 'X-Auth-Access-Token-JWT': this.passwordToken,+ }),+ },+ { responseType: 'arraybuffer' }+ );++ if (typeof resp.data === 'undefined') {+ throw Error(CustomError.REQUEST_FAILED);+ }+ return new Uint8Array(resp.data);+ };++ downloadFile = async (+ file: EnteFile,+ onDownloadProgress: (event: { loaded: number; total: number }) => void+ ) => {+ const resp = await retryAsyncFunction(() =>+ HTTPService.get(+ getPublicCollectionFileURL(file.id),+ null,+ { 'X-Auth-Token': this.token },+ {+ responseType: 'arraybuffer',+ timeout: this.timeout,+ onDownloadProgress,+ }+ )+ );++ if (typeof resp.data === 'undefined') {+ throw Error(CustomError.REQUEST_FAILED);+ }+ return new Uint8Array(resp.data);+ };++ async downloadFileStream(file: EnteFile): Promise<Response> {+ return retryAsyncFunction(() =>+ fetch(getPublicCollectionFileURL(file.id), {+ headers: {+ 'X-Auth-Token': this.token,+ },+ })+ );+ }+}diff --git a/apps/photos/src/services/publicCollectionDownloadManager.ts b/apps/photos/src/services/publicCollectionDownloadManager.tsdeleted file mode 100644index d1fb1385b8..0000000000--- a/apps/photos/src/services/publicCollectionDownloadManager.ts+++ /dev/null@@ -1,314 +0,0 @@-import {- getPublicCollectionFileURL,- getPublicCollectionThumbnailURL,-} from '@ente/shared/network/api';-import {- generateStreamFromArrayBuffer,- getRenderableFileURL,- createTypedObjectURL,-} from 'utils/file';-import HTTPService from '@ente/shared/network/HTTPService';-import { EnteFile } from 'types/file';--import { logError } from '@ente/shared/sentry';-import { FILE_TYPE } from 'constants/file';-import { CustomError } from '@ente/shared/error';-import ComlinkCryptoWorker from '@ente/shared/crypto';-import { CACHES } from '@ente/shared/storage/cacheStorage/constants';-import { CacheStorageService } from '@ente/shared/storage/cacheStorage';-import { LimitedCache } from '@ente/shared/storage/cacheStorage/types';--class PublicCollectionDownloadManager {- private fileObjectURLPromise = new Map<- string,- Promise<{ original: string[]; converted: string[] }>- >();- private thumbnailObjectURLPromise = new Map<number, Promise<string>>();-- private fileDownloadProgress = new Map<number, number>();-- private progressUpdater: (value: Map<number, number>) => void;-- setProgressUpdater(progressUpdater: (value: Map<number, number>) => void) {- this.progressUpdater = progressUpdater;- }-- private async getThumbnailCache() {- try {- const thumbnailCache = await CacheStorageService.open(- CACHES.THUMBS- );- return thumbnailCache;- } catch (e) {- return null;- // ignore- }- }-- public async getCachedThumbnail(- file: EnteFile,- thumbnailCache?: LimitedCache- ) {- try {- if (!thumbnailCache) {- thumbnailCache = await this.getThumbnailCache();- }- const cacheResp: Response = await thumbnailCache?.match(- file.id.toString()- );-- if (cacheResp) {- return URL.createObjectURL(await cacheResp.blob());- }- return null;- } catch (e) {- logError(e, 'failed to get cached thumbnail');- throw e;- }- }-- public async getThumbnail(- file: EnteFile,- token: string,- passwordToken: string- ) {- try {- if (!token) {- return null;- }-- if (!this.thumbnailObjectURLPromise.has(file.id)) {- const downloadPromise = async () => {- const thumbnailCache = await this.getThumbnailCache();- const cachedThumb = await this.getCachedThumbnail(- file,- thumbnailCache- );- if (cachedThumb) {- return cachedThumb;- }-- const thumb = await this.downloadThumb(- token,- passwordToken,- file- );- const thumbBlob = new Blob([thumb]);- try {- await thumbnailCache?.put(- file.id.toString(),- new Response(thumbBlob)- );- } catch (e) {- // TODO: handle storage full exception.- }- return URL.createObjectURL(thumbBlob);- };- this.thumbnailObjectURLPromise.set(file.id, downloadPromise());- }-- return await this.thumbnailObjectURLPromise.get(file.id);- } catch (e) {- this.thumbnailObjectURLPromise.delete(file.id);- logError(e, 'get publicDownloadManger preview Failed');- throw e;- }- }-- private downloadThumb = async (- token: string,- passwordToken: string,- file: EnteFile- ) => {- const resp = await HTTPService.get(- getPublicCollectionThumbnailURL(file.id),- null,- {- 'X-Auth-Access-Token': token,- ...(passwordToken && {- 'X-Auth-Access-Token-JWT': passwordToken,- }),- },- { responseType: 'arraybuffer' }- );- if (typeof resp.data === 'undefined') {- throw Error(CustomError.REQUEST_FAILED);- }- const cryptoWorker = await ComlinkCryptoWorker.getInstance();- const decrypted = await cryptoWorker.decryptThumbnail(- new Uint8Array(resp.data),- await cryptoWorker.fromB64(file.thumbnail.decryptionHeader),- file.key- );- return decrypted;- };-- getFile = async (- file: EnteFile,- token: string,- passwordToken: string,- forPreview = false- ) => {- const fileKey = forPreview ? `${file.id}_preview` : `${file.id}`;- try {- const getFilePromise = async () => {- const fileStream = await this.downloadFile(- token,- passwordToken,- file- );- const fileBlob = await new Response(fileStream).blob();- if (forPreview) {- return await getRenderableFileURL(file, fileBlob);- } else {- const fileURL = await createTypedObjectURL(- fileBlob,- file.metadata.title- );- return { converted: [fileURL], original: [fileURL] };- }- };-- if (!this.fileObjectURLPromise.get(fileKey)) {- this.fileObjectURLPromise.set(fileKey, getFilePromise());- }- const fileURLs = await this.fileObjectURLPromise.get(fileKey);- return fileURLs;- } catch (e) {- this.fileObjectURLPromise.delete(fileKey);- logError(e, 'public download manager Failed to get File');- throw e;- }- };-- public async getCachedOriginalFile(file: EnteFile) {- return await this.fileObjectURLPromise.get(file.id.toString());- }-- async downloadFile(token: string, passwordToken: string, file: EnteFile) {- const cryptoWorker = await ComlinkCryptoWorker.getInstance();- if (!token) {- return null;- }- const onDownloadProgress = this.trackDownloadProgress(file.id);-- if (- file.metadata.fileType === FILE_TYPE.IMAGE ||- file.metadata.fileType === FILE_TYPE.LIVE_PHOTO- ) {- const resp = await HTTPService.get(- getPublicCollectionFileURL(file.id),- null,- {- 'X-Auth-Access-Token': token,- ...(passwordToken && {- 'X-Auth-Access-Token-JWT': passwordToken,- onDownloadProgress,- }),- },- { responseType: 'arraybuffer' }- );- if (typeof resp.data === 'undefined') {- throw Error(CustomError.REQUEST_FAILED);- }- const decrypted = await cryptoWorker.decryptFile(- new Uint8Array(resp.data),- await cryptoWorker.fromB64(file.file.decryptionHeader),- file.key- );- return generateStreamFromArrayBuffer(decrypted);- }- const resp = await fetch(getPublicCollectionFileURL(file.id), {- headers: {- 'X-Auth-Access-Token': token,- ...(passwordToken && {- 'X-Auth-Access-Token-JWT': passwordToken,- }),- },- });- const reader = resp.body.getReader();-- const contentLength = +resp.headers.get('Content-Length');- let downloadedBytes = 0;-- const stream = new ReadableStream({- async start(controller) {- const decryptionHeader = await cryptoWorker.fromB64(- file.file.decryptionHeader- );- const fileKey = await cryptoWorker.fromB64(file.key);- const { pullState, decryptionChunkSize } =- await cryptoWorker.initChunkDecryption(- decryptionHeader,- fileKey- );- let data = new Uint8Array();- // The following function handles each data chunk- function push() {- // "done" is a Boolean and value a "Uint8Array"- reader.read().then(async ({ done, value }) => {- // Is there more data to read?- if (!done) {- downloadedBytes += value.byteLength;- onDownloadProgress({- loaded: downloadedBytes,- total: contentLength,- });- const buffer = new Uint8Array(- data.byteLength + value.byteLength- );- buffer.set(new Uint8Array(data), 0);- buffer.set(new Uint8Array(value), data.byteLength);- if (buffer.length > decryptionChunkSize) {- const fileData = buffer.slice(- 0,- decryptionChunkSize- );- const { decryptedData } =- await cryptoWorker.decryptFileChunk(- fileData,- pullState- );- controller.enqueue(decryptedData);- data = buffer.slice(decryptionChunkSize);- } else {- data = buffer;- }- push();- } else {- if (data) {- const { decryptedData } =- await cryptoWorker.decryptFileChunk(- data,- pullState- );- controller.enqueue(decryptedData);- data = null;- }- controller.close();- }- });- }-- push();- },- });- return stream;- }-- trackDownloadProgress = (fileID: number) => {- return (event: { loaded: number; total: number }) => {- if (event.loaded === event.total) {- this.fileDownloadProgress.delete(fileID);- } else {- this.fileDownloadProgress.set(- fileID,- Math.round((event.loaded * 100) / event.total)- );- }- this.progressUpdater(new Map(this.fileDownloadProgress));- };- };-}--export default new PublicCollectionDownloadManager();