import { Dropbox } from "dropbox"; import { StorageType } from "../../types/StorageType"; import { IPayloadReference } from "../../interfaces/core/IPayloadReference"; import { IStorageFetcher } from "../../interfaces/core/IStorageFetcher"; export class DropboxFetcher implements IStorageFetcher { storageType: StorageType = "dropbox"; private readonly MAX_RETRIES = 3; private readonly RETRY_DELAY_BASE = 1000; // 1 second base delay constructor() {} async fetch(reference: IPayloadReference): Promise { const apiToken: string = reference.apiToken!; const dropboxPath: string | undefined = reference.filePath; if (!dropboxPath) throw new Error("Dropbox file path is required"); if (!apiToken) throw new Error("Dropbox API token is required"); const dbx = new Dropbox({ accessToken: apiToken }); let lastError: Error | null = null; // Retry mechanism with exponential backoff for (let attempt = 1; attempt <= this.MAX_RETRIES; attempt++) { try { console.log(`[DropboxFetcher] Downloading file from Dropbox (attempt ${attempt}/${this.MAX_RETRIES}): ${dropboxPath}`); const response = await dbx.filesDownload({ path: dropboxPath }); let data: any = response.result; // Ví dụ data // { // name: 'test.txt', // path_lower: '/snake/test.txt', // path_display: '/snake/test.txt', // id: 'id:kX8FUt-pFHoAAAAAAAAAWQ', // client_modified: '2025-09-20T01:31:28Z', // server_modified: '2025-09-20T01:31:28Z', // rev: '0163f318b9f105500000001f007c770', // size: 11, // is_downloadable: true, // content_hash: 'bc62d4b80d9e36da29c16c5d4d9f11731f36052c72401a76c23c0fb5a9b74423', // fileBinary: // } console.log(`[DropboxFetcher] File downloaded successfully from Dropbox:`, data.name); return { ...reference, data }; } catch (error) { lastError = error as Error; console.error(`[DropboxFetcher] Download attempt ${attempt}/${this.MAX_RETRIES} failed:`, lastError.message); // If this is not the last attempt, wait before retrying if (attempt < this.MAX_RETRIES) { const delayMs = this.RETRY_DELAY_BASE * Math.pow(2, attempt - 1); // Exponential backoff console.log(`[DropboxFetcher] Retrying in ${delayMs}ms...`); await this.delay(delayMs); } } } // All retries exhausted, throw the last error console.error(`[DropboxFetcher] All ${this.MAX_RETRIES} download attempts failed for: ${dropboxPath}`); throw new Error(`Failed to download file from Dropbox after ${this.MAX_RETRIES} attempts: ${lastError?.message || 'Unknown error'}`); } private delay(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } }