|
| 1 | +/** |
| 2 | + * Resource Fetcher for Expo applications (legacy `expo-file-system` API). |
| 3 | + * |
| 4 | + * This module provides functions to download and manage files stored in the application's document directory |
| 5 | + * inside the `react-native-executorch/` directory. These utilities help manage storage and clean up downloaded |
| 6 | + * files when they are no longer needed. |
| 7 | + * |
| 8 | + * It is functionally equivalent to the default `ExpoResourceFetcher` export, but uses the legacy |
| 9 | + * `expo-file-system/legacy` APIs under the hood. Prefer this build only if you cannot adopt the new |
| 10 | + * file-system API yet. |
| 11 | + * @category Utilities - General |
| 12 | + * @remarks |
| 13 | + * **Key Functionality:** |
| 14 | + * - **Download Control**: Pause, resume, and cancel operations through: |
| 15 | + * - {@link pauseFetching} - Pause ongoing downloads |
| 16 | + * - {@link resumeFetching} - Resume paused downloads |
| 17 | + * - {@link cancelFetching} - Cancel ongoing or paused downloads |
| 18 | + * - **File Management**: |
| 19 | + * - {@link getFilesTotalSize} - Get total size of resources |
| 20 | + * - {@link listDownloadedFiles} - List all downloaded files |
| 21 | + * - {@link listDownloadedModels} - List downloaded model files (.pte) |
| 22 | + * - {@link deleteResources} - Delete downloaded resources |
| 23 | + * |
| 24 | + * **Important Notes:** |
| 25 | + * - Pause/resume/cancel operations work only for remote resources |
| 26 | + * - Most functions accept multiple `ResourceSource` arguments (string, number, or object) |
| 27 | + * - The {@link fetch} method accepts a progress callback (0-1) and returns file paths or throws if interrupted |
| 28 | + */ |
| 29 | + |
| 30 | +import { |
| 31 | + deleteAsync, |
| 32 | + readDirectoryAsync, |
| 33 | + readAsStringAsync, |
| 34 | + moveAsync, |
| 35 | +} from 'expo-file-system/legacy'; |
| 36 | +import { RNEDirectory } from './constants/directories'; |
| 37 | +import { |
| 38 | + ResourceSource, |
| 39 | + RnExecutorchErrorCode, |
| 40 | + RnExecutorchError, |
| 41 | + BaseResourceFetcherClass, |
| 42 | +} from 'react-native-executorch'; |
| 43 | +import { |
| 44 | + ResourceFetcherUtils, |
| 45 | + HTTP_CODE, |
| 46 | + DownloadStatus, |
| 47 | +} from './ResourceFetcherUtils'; |
| 48 | +import { |
| 49 | + type ActiveDownload, |
| 50 | + handleObject, |
| 51 | + handleLocalFile, |
| 52 | + handleAsset, |
| 53 | + handleRemote, |
| 54 | +} from './handlers'; |
| 55 | + |
| 56 | +class ExpoResourceFetcherClass extends BaseResourceFetcherClass<ActiveDownload> { |
| 57 | + protected downloads = new Map<ResourceSource, ActiveDownload>(); |
| 58 | + |
| 59 | + protected async getFilesSizes(sources: ResourceSource[]) { |
| 60 | + return ResourceFetcherUtils.getFilesSizes(sources); |
| 61 | + } |
| 62 | + |
| 63 | + protected async handleObject(source: object): Promise<string> { |
| 64 | + return handleObject(source); |
| 65 | + } |
| 66 | + |
| 67 | + protected handleLocalFile(source: string): string { |
| 68 | + return handleLocalFile(source); |
| 69 | + } |
| 70 | + |
| 71 | + protected handleAsset( |
| 72 | + source: number, |
| 73 | + progressCallback: (progress: number) => void |
| 74 | + ): Promise<string> { |
| 75 | + return handleAsset(source, progressCallback, this.downloads); |
| 76 | + } |
| 77 | + |
| 78 | + protected handleRemote( |
| 79 | + uri: string, |
| 80 | + source: ResourceSource, |
| 81 | + progressCallback: (progress: number) => void |
| 82 | + ): Promise<{ path: string; wasDownloaded: boolean }> { |
| 83 | + return handleRemote(uri, source, progressCallback, this.downloads); |
| 84 | + } |
| 85 | + |
| 86 | + protected async pause(source: ResourceSource): Promise<void> { |
| 87 | + const downloadHandle = this.downloads.get(source)!; |
| 88 | + if (downloadHandle.status === DownloadStatus.PAUSED) { |
| 89 | + throw new RnExecutorchError( |
| 90 | + RnExecutorchErrorCode.ResourceFetcherAlreadyPaused, |
| 91 | + "The file download is currently paused. Can't pause the download of the same file twice." |
| 92 | + ); |
| 93 | + } |
| 94 | + downloadHandle.status = DownloadStatus.PAUSED; |
| 95 | + await downloadHandle.downloadResumable.pauseAsync(); |
| 96 | + } |
| 97 | + |
| 98 | + protected async resume(source: ResourceSource): Promise<void> { |
| 99 | + const downloadHandle = this.downloads.get(source)!; |
| 100 | + if (downloadHandle.status === DownloadStatus.ONGOING) { |
| 101 | + throw new RnExecutorchError( |
| 102 | + RnExecutorchErrorCode.ResourceFetcherAlreadyOngoing, |
| 103 | + "The file download is currently ongoing. Can't resume the ongoing download." |
| 104 | + ); |
| 105 | + } |
| 106 | + downloadHandle.status = DownloadStatus.ONGOING; |
| 107 | + const result = await downloadHandle.downloadResumable.resumeAsync(); |
| 108 | + const current = this.downloads.get(source); |
| 109 | + // Paused again or canceled during resume — resolve/reject handled elsewhere. |
| 110 | + if (!current || current.status === DownloadStatus.PAUSED) return; |
| 111 | + |
| 112 | + if ( |
| 113 | + !result || |
| 114 | + (result.status !== HTTP_CODE.OK && |
| 115 | + result.status !== HTTP_CODE.PARTIAL_CONTENT) |
| 116 | + ) { |
| 117 | + this.downloads.delete(source); |
| 118 | + downloadHandle.reject( |
| 119 | + new RnExecutorchError( |
| 120 | + RnExecutorchErrorCode.ResourceFetcherDownloadFailed, |
| 121 | + `Failed to resume download from '${downloadHandle.uri}', status: ${result?.status}` |
| 122 | + ) |
| 123 | + ); |
| 124 | + return; |
| 125 | + } |
| 126 | + |
| 127 | + await moveAsync({ |
| 128 | + from: downloadHandle.cacheFileUri, |
| 129 | + to: downloadHandle.fileUri, |
| 130 | + }); |
| 131 | + this.downloads.delete(source); |
| 132 | + downloadHandle.resolve( |
| 133 | + ResourceFetcherUtils.removeFilePrefix(downloadHandle.fileUri) |
| 134 | + ); |
| 135 | + } |
| 136 | + |
| 137 | + protected async cancel(source: ResourceSource): Promise<void> { |
| 138 | + const downloadHandle = this.downloads.get(source)!; |
| 139 | + await downloadHandle.downloadResumable.cancelAsync(); |
| 140 | + this.downloads.delete(source); |
| 141 | + downloadHandle.reject( |
| 142 | + new RnExecutorchError( |
| 143 | + RnExecutorchErrorCode.DownloadInterrupted, |
| 144 | + 'Download was canceled.' |
| 145 | + ) |
| 146 | + ); |
| 147 | + } |
| 148 | + |
| 149 | + /** |
| 150 | + * Reads the contents of a file as a string. |
| 151 | + * @param path - Absolute file path or file URI to read. |
| 152 | + * @returns A promise that resolves to the file contents as a string. |
| 153 | + */ |
| 154 | + async readAsString(path: string): Promise<string> { |
| 155 | + const uri = path.startsWith('file://') ? path : `file://${path}`; |
| 156 | + return readAsStringAsync(uri); |
| 157 | + } |
| 158 | + |
| 159 | + /** |
| 160 | + * Lists all the downloaded files used by React Native ExecuTorch. |
| 161 | + * @returns A promise that resolves to an array of URIs for all the downloaded files. |
| 162 | + */ |
| 163 | + async listDownloadedFiles(): Promise<string[]> { |
| 164 | + const files = await readDirectoryAsync(RNEDirectory); |
| 165 | + return files.map((file: string) => `${RNEDirectory}${file}`); |
| 166 | + } |
| 167 | + |
| 168 | + /** |
| 169 | + * Deletes downloaded resources from the local filesystem. |
| 170 | + * @param sources - The resource identifiers used when calling `fetch`. |
| 171 | + * @returns A promise that resolves once all specified resources have been removed. |
| 172 | + */ |
| 173 | + async deleteResources(...sources: ResourceSource[]): Promise<void> { |
| 174 | + for (const source of sources) { |
| 175 | + const filename = ResourceFetcherUtils.getFilenameFromUri( |
| 176 | + source as string |
| 177 | + ); |
| 178 | + const fileUri = `${RNEDirectory}${filename}`; |
| 179 | + if (await ResourceFetcherUtils.checkFileExists(fileUri)) { |
| 180 | + await deleteAsync(fileUri); |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + /** |
| 186 | + * Fetches the total size of remote files. Works only for remote files. |
| 187 | + * @param sources - The resource identifiers (URLs). |
| 188 | + * @returns A promise that resolves to the combined size of files in bytes. |
| 189 | + */ |
| 190 | + async getFilesTotalSize(...sources: ResourceSource[]): Promise<number> { |
| 191 | + return (await ResourceFetcherUtils.getFilesSizes(sources)).totalLength; |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +export const ExpoResourceFetcher = new ExpoResourceFetcherClass(); |
0 commit comments