diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 7d8c40c0..ce11f1e3 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -46,8 +46,23 @@ jobs: - name: Install Maestro run: | - curl -fsSL "https://get.maestro.mobile.dev" | bash - echo "$HOME/.maestro/bin" >> $GITHUB_PATH + set -euo pipefail + for attempt in 1 2 3; do + echo "Installing Maestro (attempt $attempt)..." + if curl -fsSL "https://get.maestro.mobile.dev" | bash \ + && test -x "$HOME/.maestro/bin/maestro"; then + break + fi + echo "Maestro install failed on attempt $attempt" + rm -rf "$HOME/.maestro" + if [ "$attempt" -eq 3 ]; then + echo "Maestro install failed after 3 attempts" + exit 1 + fi + sleep $((attempt * 5)) + done + echo "$HOME/.maestro/bin" >> "$GITHUB_PATH" + "$HOME/.maestro/bin/maestro" --version - name: Cache node_modules uses: actions/cache@v4 @@ -159,8 +174,23 @@ jobs: - name: Install Maestro run: | - curl -fsSL "https://get.maestro.mobile.dev" | bash - echo "$HOME/.maestro/bin" >> $GITHUB_PATH + set -euo pipefail + for attempt in 1 2 3; do + echo "Installing Maestro (attempt $attempt)..." + if curl -fsSL "https://get.maestro.mobile.dev" | bash \ + && test -x "$HOME/.maestro/bin/maestro"; then + break + fi + echo "Maestro install failed on attempt $attempt" + rm -rf "$HOME/.maestro" + if [ "$attempt" -eq 3 ]; then + echo "Maestro install failed after 3 attempts" + exit 1 + fi + sleep $((attempt * 5)) + done + echo "$HOME/.maestro/bin" >> "$GITHUB_PATH" + "$HOME/.maestro/bin/maestro" --version - name: Cache node_modules uses: actions/cache@v4 diff --git a/.maestro/flows/_home-check.yaml b/.maestro/flows/_home-check.yaml index 45f5f5d7..ed300a52 100644 --- a/.maestro/flows/_home-check.yaml +++ b/.maestro/flows/_home-check.yaml @@ -2,7 +2,16 @@ appId: ${APP_ID} --- - assertVisible: "Zip Operations" - assertVisible: "Unzip Operations" +- assertVisible: "List & Selective Extract" +- scrollUntilVisible: + element: + text: "Password Protection" + direction: DOWN - assertVisible: "Password Protection" +- scrollUntilVisible: + element: + text: "Progress Events" + direction: DOWN - assertVisible: "Progress Events" - scrollUntilVisible: element: diff --git a/.maestro/flows/_list-contents-test.yaml b/.maestro/flows/_list-contents-test.yaml new file mode 100644 index 00000000..3a73348d --- /dev/null +++ b/.maestro/flows/_list-contents-test.yaml @@ -0,0 +1,56 @@ +appId: ${APP_ID} +--- +- runFlow: + when: + notVisible: "List & Selective Extract" + commands: + - tapOn: "Playground" +- scrollUntilVisible: + element: + text: "List & Selective Extract" + direction: DOWN +- tapOn: "List & Selective Extract" +- extendedWaitUntil: + visible: "Create Zip and List Contents" + timeout: 15000 +- tapOn: "Create Zip and List Contents" +- extendedWaitUntil: + visible: "Listed Entries" + timeout: 20000 +- assertVisible: "Listed Entries" +- scrollUntilVisible: + element: + text: "Contains hello.txt" + direction: DOWN + timeout: 10000 +- assertVisible: "Contains hello.txt" +- assertVisible: "Contains readme.md" +- scrollUntilVisible: + element: + text: "Extract Selected Entries" + direction: DOWN +- tapOn: "Extract Selected Entries" +- extendedWaitUntil: + visible: "Selective Extract" + timeout: 20000 +- assertVisible: "Selective Extract" +- scrollUntilVisible: + element: + text: "Extracted docs/guide.md" + direction: DOWN + timeout: 10000 +- assertVisible: "Extracted readme.md" +- assertVisible: "Extracted docs/guide.md" +- assertVisible: "Skipped hello.txt" +- scrollUntilVisible: + element: + text: "Password Selective Extract" + direction: DOWN +- tapOn: "Password Selective Extract" +- extendedWaitUntil: + visible: "Password Selective Extract Done" + timeout: 30000 +- assertVisible: "Password Selective Extract Done" +- assertVisible: "Extracted readme.md" +- assertVisible: "Skipped hello.txt" +- back diff --git a/.maestro/flows/ci-master.yaml b/.maestro/flows/ci-master.yaml index a2e834ff..22ac4b0c 100644 --- a/.maestro/flows/ci-master.yaml +++ b/.maestro/flows/ci-master.yaml @@ -4,6 +4,7 @@ appId: ${APP_ID} - runFlow: _home-check.yaml - runFlow: _zip-test.yaml - runFlow: _unzip-test.yaml +- runFlow: _list-contents-test.yaml - runFlow: _password-test.yaml - runFlow: _progress-test.yaml - runFlow: _assets-test.yaml diff --git a/.maestro/flows/list-contents.yaml b/.maestro/flows/list-contents.yaml new file mode 100644 index 00000000..1da6d211 --- /dev/null +++ b/.maestro/flows/list-contents.yaml @@ -0,0 +1,4 @@ +appId: ${APP_ID} +--- +- runFlow: _setup.yaml +- runFlow: _list-contents-test.yaml diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e4371c7..26d8d8a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## [9.2.0] - 2026-07-25 + +### Added +- `cancel()` — best-effort abort of the in-flight zip/unzip operation; rejects with `ERR_CANCELLED` (#366) +- Stable cross-platform error codes (`ERR_FILE_NOT_FOUND`, `ERR_WRONG_PASSWORD`, `ERR_UNSAFE_PATH`, …) and JS `ErrorCodes` map (#366) + +## [9.1.0] - 2026-07-25 + +### Added +- `listContents(source, charset?)` — inspect archive entries (path, sizes, directory/encrypted flags) without extracting (#365) +- Optional `entries` on `unzip` / `unzipWithPassword` — extract only selected entry paths; directory names include nested children (#365) +- Android unit tests for selective-extract entry matching + ## [9.0.2] - 2026-07-22 ### Fixed diff --git a/README.md b/README.md index 4ee731b7..ee62ea54 100644 --- a/README.md +++ b/README.md @@ -38,10 +38,13 @@ import { zipWithPassword, unzip, unzipWithPassword, + listContents, unzipAssets, + cancel, subscribe, isPasswordProtected, getUncompressedSize, + ErrorCodes, DEFAULT_COMPRESSION, NO_COMPRESSION, BEST_SPEED, @@ -104,9 +107,21 @@ zipWithPassword(sourcePath, targetPath, 'password', 'STANDARD') .catch((error) => console.error(error)) ``` -### `unzip(source: string, target: string, charset?: string): Promise` +### `unzip(source: string, target: string, charset?: string | string[], entries?: string[]): Promise` -Unzip from source to target. +Unzip from source to target. Pass `entries` to extract only those paths; directory names match that entry and all nested children (e.g. `'docs'` extracts `docs/` and `docs/readme.md`). + +You can pass entries as the third argument when using the default charset: + +```js +unzip(sourcePath, targetPath, ['readme.md', 'docs']) +``` + +Or with an explicit charset: + +```js +unzip(sourcePath, targetPath, 'UTF-8', ['readme.md', 'docs']) +``` > The `charset` parameter is only supported on Android (default: `UTF-8`). On iOS it is ignored. @@ -119,14 +134,44 @@ unzip(sourcePath, targetPath, 'UTF-8') .catch((error) => console.error(error)) ``` -### `unzipWithPassword(source: string, target: string, password: string): Promise` +### `unzipWithPassword(source: string, target: string, password: string, entries?: string[]): Promise` -Unzip a password-protected archive. +Unzip a password-protected archive. Pass `entries` to extract only those paths. ```js unzipWithPassword(sourcePath, targetPath, 'password') .then((path) => console.log(`unzip completed at ${path}`)) .catch((error) => console.error(error)) + +unzipWithPassword(sourcePath, targetPath, 'password', ['secret.txt']) + .then((path) => console.log(`selective unzip completed at ${path}`)) + .catch((error) => console.error(error)) +``` + +### `listContents(source: string, charset?: string): Promise` + +List archive entries without extracting. + +```ts +type ZipEntry = { + path: string + size: number // uncompressed size in bytes + compressedSize: number + isDirectory: boolean + isEncrypted: boolean +} +``` + +> The `charset` parameter is only supported on Android (default: `UTF-8`). On iOS it is ignored. + +```js +listContents(sourcePath) + .then((entries) => { + entries.forEach((entry) => { + console.log(entry.path, entry.size, entry.isDirectory) + }) + }) + .catch((error) => console.error(error)) ``` ### `unzipAssets(assetPath: string, target: string): Promise` @@ -153,6 +198,39 @@ getUncompressedSize(sourcePath) .catch((error) => console.error(error)) ``` +### `cancel(): Promise` + +Cancel the in-flight zip/unzip operation (best-effort). The active operation's promise rejects with `ErrorCodes.CANCELLED` (`ERR_CANCELLED`). + +```js +const unzipPromise = unzip(sourcePath, targetPath) +cancel() +unzipPromise.catch((error) => { + if (error.code === ErrorCodes.CANCELLED) { + console.log('unzip cancelled') + } +}) +``` + +### Error codes + +Native rejections use stable `error.code` values on both platforms: + +| Code | When | +|------|------| +| `ERR_FILE_NOT_FOUND` | Source missing | +| `ERR_INVALID_PATH` | Bad / null path | +| `ERR_INVALID_ARGS` | Empty password, empty entries, etc. | +| `ERR_WRONG_PASSWORD` | Password decrypt failed | +| `ERR_NOT_PASSWORD_PROTECTED` | Password API used on a plain archive | +| `ERR_CORRUPT_ARCHIVE` | Not a zip / truncated / unreadable | +| `ERR_UNSAFE_PATH` | Zip Slip / path traversal | +| `ERR_CANCELLED` | `cancel()` interrupted the operation | +| `ERR_ZIP` / `ERR_UNZIP` | Generic zip/unzip failure | +| `ERR_UNSUPPORTED` | API not available on this platform | + +Also exported as the `ErrorCodes` constant map. + ### `subscribe(callback: ({ progress: number, filePath: string }) => void): EmitterSubscription` Subscribe to progress events. Useful for showing a progress bar. @@ -187,9 +265,11 @@ useEffect(() => { | `zip` (files array) | ✅ | ✅ | Compression level ignored on iOS | | `zipWithPassword` (folder) | ✅ | ✅ | AES encryption supported | | `zipWithPassword` (files array) | ⚠️ | ✅ | iOS: only `STANDARD` encryption | -| `unzip` | ✅ | ✅ | Charset ignored on iOS | -| `unzipWithPassword` | ✅ | ✅ | — | +| `unzip` | ✅ | ✅ | Optional `entries` for selective extract; charset ignored on iOS | +| `unzipWithPassword` | ✅ | ✅ | Optional `entries` for selective extract | +| `listContents` | ✅ | ✅ | Charset ignored on iOS | | `unzipAssets` | ❌ | ✅ | Android only | +| `cancel` | ✅ | ✅ | Best-effort mid-operation abort | | `isPasswordProtected` | ✅ | ✅ | — | | `getUncompressedSize` | ✅ | ✅ | Charset ignored on iOS | | Progress Events | ✅ | ✅ | File path empty on iOS for zip | diff --git a/RNZipArchive.podspec b/RNZipArchive.podspec index 78135b42..f2be6c29 100644 --- a/RNZipArchive.podspec +++ b/RNZipArchive.podspec @@ -12,6 +12,9 @@ Pod::Spec.new do |s| s.source = { :git => 'https://github.com/mockingbot/react-native-zip-archive.git', :tag => "#{s.version}"} s.platform = :ios, '15.5' s.preserve_paths = '*.js' + s.pod_target_xcconfig = { + 'HEADER_SEARCH_PATHS' => '$(inherited) "$(PODS_ROOT)/SSZipArchive/SSZipArchive/minizip"' + } if defined?(install_modules_dependencies) != nil install_modules_dependencies(s) diff --git a/__mocks__/react-native.js b/__mocks__/react-native.js index b4076191..22ec107c 100644 --- a/__mocks__/react-native.js +++ b/__mocks__/react-native.js @@ -6,9 +6,21 @@ const mockRNZipArchive = { zipFilesWithPassword: jest.fn(() => Promise.resolve('/mock/path.zip')), unzip: jest.fn(() => Promise.resolve('/mock/dest')), unzipWithPassword: jest.fn(() => Promise.resolve('/mock/dest')), + listContents: jest.fn(() => + Promise.resolve([ + { + path: 'hello.txt', + size: 12, + compressedSize: 10, + isDirectory: false, + isEncrypted: false, + }, + ]) + ), unzipAssets: jest.fn(() => Promise.resolve('/mock/dest')), isPasswordProtected: jest.fn(() => Promise.resolve(true)), getUncompressedSize: jest.fn(() => Promise.resolve(1024)), + cancel: jest.fn(() => Promise.resolve()), addListener: jest.fn(), removeListeners: jest.fn(), }; diff --git a/__tests__/api.test.js b/__tests__/api.test.js index 54559c52..62368f43 100644 --- a/__tests__/api.test.js +++ b/__tests__/api.test.js @@ -3,10 +3,13 @@ const { zipWithPassword, unzip, unzipWithPassword, + listContents, unzipAssets, isPasswordProtected, getUncompressedSize, + cancel, subscribe, + ErrorCodes, DEFAULT_COMPRESSION, NO_COMPRESSION, BEST_SPEED, @@ -25,9 +28,11 @@ describe('react-native-zip-archive API', () => { expect(typeof zipWithPassword).toBe('function'); expect(typeof unzip).toBe('function'); expect(typeof unzipWithPassword).toBe('function'); + expect(typeof listContents).toBe('function'); expect(typeof unzipAssets).toBe('function'); expect(typeof isPasswordProtected).toBe('function'); expect(typeof getUncompressedSize).toBe('function'); + expect(typeof cancel).toBe('function'); expect(typeof subscribe).toBe('function'); }); @@ -38,6 +43,20 @@ describe('react-native-zip-archive API', () => { expect(BEST_COMPRESSION).toBe(9); }); + test('exports stable ErrorCodes', () => { + expect(ErrorCodes.CANCELLED).toBe('ERR_CANCELLED'); + expect(ErrorCodes.WRONG_PASSWORD).toBe('ERR_WRONG_PASSWORD'); + expect(ErrorCodes.UNSAFE_PATH).toBe('ERR_UNSAFE_PATH'); + expect(ErrorCodes.FILE_NOT_FOUND).toBe('ERR_FILE_NOT_FOUND'); + }); + + describe('cancel', () => { + test('cancel calls native module', async () => { + await cancel(); + expect(mockRNZipArchive.cancel).toHaveBeenCalled(); + }); + }); + describe('zip', () => { test('zip resolves with target path', async () => { const result = await zip('/source', '/target.zip'); @@ -81,29 +100,104 @@ describe('react-native-zip-archive API', () => { describe('unzip', () => { test('unzip with default charset', async () => { await unzip('/source.zip', '/dest'); - expect(mockRNZipArchive.unzip).toHaveBeenCalledWith('/source.zip', '/dest', 'UTF-8'); + expect(mockRNZipArchive.unzip).toHaveBeenCalledWith('/source.zip', '/dest', 'UTF-8', null); }); test('unzip with custom charset', async () => { await unzip('/source.zip', '/dest', 'GBK'); - expect(mockRNZipArchive.unzip).toHaveBeenCalledWith('/source.zip', '/dest', 'GBK'); + expect(mockRNZipArchive.unzip).toHaveBeenCalledWith('/source.zip', '/dest', 'GBK', null); }); test('unzip normalizes file:// paths', async () => { await unzip('file:///source.zip', 'file:///dest'); - expect(mockRNZipArchive.unzip).toHaveBeenCalledWith('/source.zip', '/dest', 'UTF-8'); + expect(mockRNZipArchive.unzip).toHaveBeenCalledWith('/source.zip', '/dest', 'UTF-8', null); + }); + + test('unzip with entries array as third arg', async () => { + await unzip('/source.zip', '/dest', ['a.txt', 'b.txt']); + expect(mockRNZipArchive.unzip).toHaveBeenCalledWith( + '/source.zip', + '/dest', + 'UTF-8', + ['a.txt', 'b.txt'] + ); + }); + + test('unzip with charset and entries', async () => { + await unzip('/source.zip', '/dest', 'GBK', ['a.txt']); + expect(mockRNZipArchive.unzip).toHaveBeenCalledWith( + '/source.zip', + '/dest', + 'GBK', + ['a.txt'] + ); + }); + + test('unzip rejects empty entries', async () => { + await expect(unzip('/source.zip', '/dest', [])).rejects.toThrow( + 'unzip: entries must be a non-empty array when provided' + ); }); }); describe('unzipWithPassword', () => { test('unzipWithPassword calls native module', async () => { await unzipWithPassword('/source.zip', '/dest', 'password'); - expect(mockRNZipArchive.unzipWithPassword).toHaveBeenCalledWith('/source.zip', '/dest', 'password'); + expect(mockRNZipArchive.unzipWithPassword).toHaveBeenCalledWith( + '/source.zip', + '/dest', + 'password', + null + ); }); test('unzipWithPassword normalizes file:// paths', async () => { await unzipWithPassword('file:///source.zip', 'file:///dest', 'password'); - expect(mockRNZipArchive.unzipWithPassword).toHaveBeenCalledWith('/source.zip', '/dest', 'password'); + expect(mockRNZipArchive.unzipWithPassword).toHaveBeenCalledWith( + '/source.zip', + '/dest', + 'password', + null + ); + }); + + test('unzipWithPassword with entries', async () => { + await unzipWithPassword('/source.zip', '/dest', 'secret', ['a.txt']); + expect(mockRNZipArchive.unzipWithPassword).toHaveBeenCalledWith( + '/source.zip', + '/dest', + 'secret', + ['a.txt'] + ); + }); + + test('unzipWithPassword rejects empty entries', async () => { + await expect( + unzipWithPassword('/source.zip', '/dest', 'secret', []) + ).rejects.toThrow( + 'unzipWithPassword: entries must be a non-empty array when provided' + ); + }); + }); + + describe('listContents', () => { + test('listContents with default charset', async () => { + const result = await listContents('/source.zip'); + expect(result).toEqual([ + { + path: 'hello.txt', + size: 12, + compressedSize: 10, + isDirectory: false, + isEncrypted: false, + }, + ]); + expect(mockRNZipArchive.listContents).toHaveBeenCalledWith('/source.zip', 'UTF-8'); + }); + + test('listContents normalizes file:// paths', async () => { + await listContents('file:///source.zip', 'GBK'); + expect(mockRNZipArchive.listContents).toHaveBeenCalledWith('/source.zip', 'GBK'); }); }); diff --git a/__tests__/module-integration.test.js b/__tests__/module-integration.test.js index 22cf1b29..71b14381 100644 --- a/__tests__/module-integration.test.js +++ b/__tests__/module-integration.test.js @@ -6,9 +6,11 @@ const mockRNZipArchive = { zipFilesWithPassword: jest.fn(() => Promise.resolve('/mock/path.zip')), unzip: jest.fn(() => Promise.resolve('/mock/dest')), unzipWithPassword: jest.fn(() => Promise.resolve('/mock/dest')), + listContents: jest.fn(() => Promise.resolve([])), unzipAssets: jest.fn(() => Promise.resolve('/mock/dest')), isPasswordProtected: jest.fn(() => Promise.resolve(true)), getUncompressedSize: jest.fn(() => Promise.resolve(1024)), + cancel: jest.fn(() => Promise.resolve()), addListener: jest.fn(), removeListeners: jest.fn(), }; diff --git a/android/src/main/java/com/rnziparchive/RNZipArchiveModule.java b/android/src/main/java/com/rnziparchive/RNZipArchiveModule.java index 104ea7ef..9403f17d 100644 --- a/android/src/main/java/com/rnziparchive/RNZipArchiveModule.java +++ b/android/src/main/java/com/rnziparchive/RNZipArchiveModule.java @@ -12,6 +12,7 @@ import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableType; +import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.DeviceEventManagerModule; @@ -28,6 +29,7 @@ import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -52,6 +54,7 @@ public class RNZipArchiveModule extends NativeZipArchiveSpec { r -> new Thread(r, "RNZipArchiveWorker") ); private final Handler mainHandler = new Handler(Looper.getMainLooper()); + private final AtomicBoolean cancelled = new AtomicBoolean(false); public RNZipArchiveModule(ReactApplicationContext reactContext) { super(reactContext); @@ -74,26 +77,65 @@ public void onCatalystInstanceDestroy() { invalidate(); } + + private void beginOperation() { + cancelled.set(false); + } + + private boolean rejectIfCancelled(Promise promise) { + if (cancelled.get()) { + promise.reject(ZipErrorCodes.CANCELLED, "Operation cancelled"); + return true; + } + return false; + } + + private void rejectMapped(Promise promise, Exception ex, String fallback) { + if (cancelled.get()) { + promise.reject(ZipErrorCodes.CANCELLED, "Operation cancelled"); + return; + } + String message = ex.getMessage() != null ? ex.getMessage() : fallback; + promise.reject(ZipErrorCodes.mapException(ex, fallback), message); + } + + @Override + public void cancel(final Promise promise) { + cancelled.set(true); + promise.resolve(null); + } + @Override public void isPasswordProtected(final String zipFilePath, final Promise promise) { executor.submit(() -> { + beginOperation(); try (net.lingala.zip4j.ZipFile zipFile = new net.lingala.zip4j.ZipFile(zipFilePath)) { promise.resolve(zipFile.isEncrypted()); } catch (Exception ex) { - promise.reject("RNZipArchiveError", String.format("Unable to check for encryption due to: %s", getStackTrace(ex))); + rejectMapped(promise, ex, ZipErrorCodes.UNZIP); } }); } @Override public void unzipWithPassword(final String zipFilePath, final String destDirectory, - final String password, final Promise promise) { + final String password, final ReadableArray entries, + final Promise promise) { + final List entryList = optionalEntriesList(entries, promise); + if (entryList == REJECTED_ENTRIES) { + return; + } + if (entryList != null) { + extractSelectedEntries(zipFilePath, destDirectory, entryList, "UTF-8", password, promise); + return; + } executor.submit(() -> { + beginOperation(); try (net.lingala.zip4j.ZipFile zipFile = new net.lingala.zip4j.ZipFile(zipFilePath)) { if (zipFile.isEncrypted()) { zipFile.setPassword(password.toCharArray()); } else { - promise.reject("RNZipArchiveError", String.format("Zip file: %s is not password protected", zipFilePath)); + promise.reject(ZipErrorCodes.NOT_PASSWORD_PROTECTED, String.format("Zip file: %s is not password protected", zipFilePath)); return; } @@ -103,6 +145,9 @@ public void unzipWithPassword(final String zipFilePath, final String destDirecto updateProgress(0, 1, zipFilePath); // force 0% for (FileHeader fileHeader : fileHeaderList) { + if (rejectIfCancelled(promise)) { + return; + } ZipSecurity.validateExtractPath(destDirectory, fileHeader.getFileName()); if (!fileHeader.isDirectory()) { @@ -115,21 +160,31 @@ public void unzipWithPassword(final String zipFilePath, final String destDirecto promise.resolve(destDirectory); } catch (Exception ex) { updateProgress(0, 1, zipFilePath); // force 0% - promise.reject("RNZipArchiveError", String.format("Failed to unzip file, due to: %s", getStackTrace(ex))); + rejectMapped(promise, ex, ZipErrorCodes.UNZIP); } }); } @Override - public void unzip(final String zipFilePath, final String destDirectory, final String charset, final Promise promise) { + public void unzip(final String zipFilePath, final String destDirectory, final String charset, + final ReadableArray entries, final Promise promise) { + final List entryList = optionalEntriesList(entries, promise); + if (entryList == REJECTED_ENTRIES) { + return; + } + if (entryList != null) { + extractSelectedEntries(zipFilePath, destDirectory, entryList, charset, null, promise); + return; + } executor.submit(() -> { + beginOperation(); if (zipFilePath == null) { - promise.reject("RNZipArchiveError", "Couldn't open file null. "); + promise.reject(ZipErrorCodes.INVALID_PATH, "Couldn't open file null."); return; } File zipFileRef = new File(zipFilePath); if (!zipFileRef.exists()) { - promise.reject("RNZipArchiveError", "Couldn't open file " + zipFilePath + ". "); + promise.reject(ZipErrorCodes.FILE_NOT_FOUND, "Couldn't open file " + zipFilePath + "."); return; } @@ -146,6 +201,9 @@ public void unzip(final String zipFilePath, final String destDirectory, final St updateProgress(0, 1, zipFilePath); // force 0% for (FileHeader fileHeader : fileHeaderList) { + if (rejectIfCancelled(promise)) { + return; + } ZipSecurity.validateExtractPath(destDirectory, fileHeader.getFileName()); if (!fileHeader.isDirectory()) { @@ -159,11 +217,183 @@ public void unzip(final String zipFilePath, final String destDirectory, final St promise.resolve(destDirectory); } catch (Exception ex) { updateProgress(0, 1, zipFilePath); // force 0% - promise.reject("RNZipArchiveError", "Failed to extract file " + ex.getLocalizedMessage()); + rejectMapped(promise, ex, ZipErrorCodes.UNZIP); } }); } + /** + * Sentinel meaning {@link #optionalEntriesList} already rejected the promise. + * Distinct from {@code null} (full extract) and a non-empty list (selective). + */ + private static final List REJECTED_ENTRIES = new ArrayList<>(); + + /** + * @return {@code null} for full extract, a non-empty list for selective extract, + * or {@link #REJECTED_ENTRIES} when the promise was already rejected. + */ + private List optionalEntriesList(ReadableArray entries, Promise promise) { + if (entries == null || entries.size() == 0) { + return null; + } + try { + List entryList = readableArrayToStringList(entries); + if (entryList.isEmpty()) { + promise.reject(ZipErrorCodes.INVALID_ARGS, "entries must be a non-empty array"); + return REJECTED_ENTRIES; + } + return entryList; + } catch (IllegalArgumentException ex) { + promise.reject(ZipErrorCodes.INVALID_ARGS, "Invalid entries array: " + ex.getMessage()); + return REJECTED_ENTRIES; + } + } + + @Override + public void listContents(final String zipFilePath, final String charset, final Promise promise) { + executor.submit(() -> { + beginOperation(); + if (zipFilePath == null) { + promise.reject(ZipErrorCodes.INVALID_PATH, "Couldn't open file null."); + return; + } + File zipFileRef = new File(zipFilePath); + if (!zipFileRef.exists()) { + promise.reject(ZipErrorCodes.FILE_NOT_FOUND, "Couldn't open file " + zipFilePath + "."); + return; + } + + try (net.lingala.zip4j.ZipFile zipFile = openZipFile(zipFilePath, charset)) { + WritableArray entries = Arguments.createArray(); + for (FileHeader fileHeader : zipFile.getFileHeaders()) { + WritableMap entry = Arguments.createMap(); + entry.putString("path", fileHeader.getFileName()); + entry.putDouble("size", Math.max(fileHeader.getUncompressedSize(), 0)); + entry.putDouble("compressedSize", Math.max(fileHeader.getCompressedSize(), 0)); + entry.putBoolean("isDirectory", fileHeader.isDirectory()); + entry.putBoolean("isEncrypted", fileHeader.isEncrypted()); + entries.pushMap(entry); + } + promise.resolve(entries); + } catch (Exception ex) { + rejectMapped(promise, ex, ZipErrorCodes.UNZIP); + } + }); + } + + private void extractSelectedEntries(final String zipFilePath, final String destDirectory, + final List wantedEntries, final String charset, + final String password, final Promise promise) { + executor.submit(() -> { + beginOperation(); + if (zipFilePath == null) { + promise.reject(ZipErrorCodes.INVALID_PATH, "Couldn't open file null."); + return; + } + File zipFileRef = new File(zipFilePath); + if (!zipFileRef.exists()) { + promise.reject(ZipErrorCodes.FILE_NOT_FOUND, "Couldn't open file " + zipFilePath + "."); + return; + } + if (wantedEntries == null || wantedEntries.isEmpty()) { + promise.reject(ZipErrorCodes.INVALID_ARGS, "entries must be a non-empty array"); + return; + } + + try (net.lingala.zip4j.ZipFile zipFile = openZipFile(zipFilePath, charset)) { + if (password != null) { + if (!zipFile.isEncrypted()) { + promise.reject(ZipErrorCodes.NOT_PASSWORD_PROTECTED, + String.format("Zip file: %s is not password protected", zipFilePath)); + return; + } + zipFile.setPassword(password.toCharArray()); + } + + File destDir = new File(destDirectory); + if (!destDir.exists()) { + //noinspection ResultOfMethodCallIgnored + destDir.mkdirs(); + } + + List selected = new ArrayList<>(); + for (FileHeader fileHeader : zipFile.getFileHeaders()) { + if (entryMatchesSelection(fileHeader.getFileName(), wantedEntries)) { + selected.add(fileHeader); + } + } + + if (selected.isEmpty()) { + promise.reject(ZipErrorCodes.INVALID_ARGS, "None of the requested entries were found in the archive"); + return; + } + + long totalBytes = Math.max(totalUncompressedSize(selected), 1); + long extractedBytes = 0; + + updateProgress(0, 1, zipFilePath); + for (FileHeader fileHeader : selected) { + if (rejectIfCancelled(promise)) { + return; + } + ZipSecurity.validateExtractPath(destDirectory, fileHeader.getFileName()); + + if (!fileHeader.isDirectory()) { + zipFile.extractFile(fileHeader, destDirectory, ZipSecurity.createExtractParameters()); + extractedBytes += Math.max(fileHeader.getUncompressedSize(), 0); + } else { + File dir = new File(destDirectory, fileHeader.getFileName()); + //noinspection ResultOfMethodCallIgnored + dir.mkdirs(); + } + updateProgress(extractedBytes, totalBytes, zipFilePath); + } + + updateProgress(1, 1, zipFilePath); + promise.resolve(destDirectory); + } catch (Exception ex) { + updateProgress(0, 1, zipFilePath); + rejectMapped(promise, ex, ZipErrorCodes.UNZIP); + } + }); + } + + /** + * Returns true when {@code entryName} should be extracted for the given selection list. + * Matches exact paths, directory prefixes ({@code foo/} or {@code foo}), and strips a + * trailing slash from either side before comparing. + */ + static boolean entryMatchesSelection(String entryName, List wantedEntries) { + if (entryName == null || wantedEntries == null) { + return false; + } + String normalizedEntry = stripTrailingSlash(entryName.replace('\\', '/')); + for (String wanted : wantedEntries) { + if (wanted == null || wanted.isEmpty()) { + continue; + } + String normalizedWanted = stripTrailingSlash(wanted.replace('\\', '/')); + if (normalizedEntry.equals(normalizedWanted)) { + return true; + } + if (normalizedEntry.startsWith(normalizedWanted + "/")) { + return true; + } + } + return false; + } + + private static String stripTrailingSlash(String path) { + if (path == null || path.isEmpty()) { + return path; + } + int end = path.length(); + while (end > 0 && path.charAt(end - 1) == '/') { + end--; + } + return path.substring(0, end); + } + /** * Extract a zip held in the assets directory. *

@@ -177,6 +407,7 @@ public void unzip(final String zipFilePath, final String destDirectory, final St @Override public void unzipAssets(final String assetsPath, final String destDirectory, final Promise promise) { executor.submit(() -> { + beginOperation(); InputStream assetsInputStream = null; AssetFileDescriptor fileDescriptor = null; long compressedSize; @@ -208,7 +439,7 @@ public void unzipAssets(final String assetsPath, final String destDirectory, fin } if (assetsInputStream == null) { - promise.reject("RNZipArchiveError", String.format("Asset file `%s` could not be opened", assetsPath)); + promise.reject(ZipErrorCodes.FILE_NOT_FOUND, String.format("Asset file `%s` could not be opened", assetsPath)); return; } @@ -226,6 +457,9 @@ public void unzipAssets(final String assetsPath, final String destDirectory, fin updateProgress(extractedBytes, compressedSize, assetsPath); // force 0% while ((entry = zipIn.getNextEntry()) != null) { + if (rejectIfCancelled(promise)) { + return; + } if (entry.isDirectory()) continue; Log.i("rnziparchive", "Extracting: " + entry.getName()); @@ -259,7 +493,7 @@ public void unzipAssets(final String assetsPath, final String destDirectory, fin } catch (Exception ex) { Log.e(TAG, "Failed to extract asset: " + assetsPath, ex); updateProgress(0, 1, assetsPath); // force 0% - promise.reject("RNZipArchiveError", ex.getMessage()); + rejectMapped(promise, ex, ZipErrorCodes.UNZIP); } finally { if (fileDescriptor != null) { try { @@ -283,7 +517,7 @@ public void zipFiles(final ReadableArray files, final String destDirectory, fina try { fileList = readableArrayToStringList(files); } catch (IllegalArgumentException ex) { - promise.reject("RNZipArchiveError", "Invalid files array: " + ex.getMessage()); + promise.reject(ZipErrorCodes.INVALID_ARGS, "Invalid files array: " + ex.getMessage()); return; } zip(fileList, destDirectory, compressionLevel, promise); @@ -303,7 +537,7 @@ public void zipFilesWithPassword(final ReadableArray files, final String destFil try { fileList = readableArrayToStringList(files); } catch (IllegalArgumentException ex) { - promise.reject("RNZipArchiveError", "Invalid files array: " + ex.getMessage()); + promise.reject(ZipErrorCodes.INVALID_ARGS, "Invalid files array: " + ex.getMessage()); return; } zipWithPassword(fileList, destFile, password, encryptionMethod, compressionLevel, promise); @@ -323,7 +557,7 @@ private void zipWithPassword(final List filesOrDirectory, final String d ZipParameters parameters = buildZipParameters(compressionLevel); if (password == null || password.isEmpty()) { - promise.reject("RNZipArchiveError", "Password is empty"); + promise.reject(ZipErrorCodes.INVALID_ARGS, "Password is empty"); return; } @@ -340,7 +574,9 @@ private void zipWithPassword(final List filesOrDirectory, final String d parameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_128); } } else if ("STANDARD".equals(encryptionMethod)) { - parameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD_VARIANT_STRONG); + // ZipCrypto (ZIP_STANDARD). ZIP_STANDARD_VARIANT_STRONG is write-only in zip4j + // and fails extract with "encryption method is not supported". + parameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD); Log.d(TAG, "Standard Encryption"); } else { parameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD); @@ -349,7 +585,7 @@ private void zipWithPassword(final List filesOrDirectory, final String d processZip(filesOrDirectory, destFile, parameters, promise, password.toCharArray()); } catch (Exception ex) { - promise.reject("RNZipArchiveError", ex.getMessage()); + rejectMapped(promise, ex, ZipErrorCodes.ZIP); } } @@ -358,12 +594,13 @@ private void zip(final List filesOrDirectory, final String destFile, fin ZipParameters parameters = buildZipParameters(compressionLevel); processZip(filesOrDirectory, destFile, parameters, promise, null); } catch (Exception ex) { - promise.reject("RNZipArchiveError", ex.getMessage()); + rejectMapped(promise, ex, ZipErrorCodes.ZIP); } } private void processZip(final List entries, final String destFile, final ZipParameters parameters, final Promise promise, final char[] password) { executor.submit(() -> { + beginOperation(); try (net.lingala.zip4j.ZipFile zipFile = password != null ? new net.lingala.zip4j.ZipFile(destFile, password) : new net.lingala.zip4j.ZipFile(destFile)) { @@ -374,6 +611,9 @@ private void processZip(final List entries, final String destFile, final int fileCounter = 0; for (int i = 0; i < entries.size(); i++) { + if (rejectIfCancelled(promise)) { + return; + } File f = new File(entries.get(i)); if (f.exists()) { @@ -383,6 +623,9 @@ private void processZip(final List entries, final String destFile, final totalFiles += files.size(); for (int j = 0; j < files.size(); j++) { + if (rejectIfCancelled(promise)) { + return; + } if (files.get(j).isDirectory()) { zipFile.addFolder(files.get(j), parameters); } else { @@ -399,12 +642,12 @@ private void processZip(final List entries, final String destFile, final updateProgress(fileCounter, totalFiles, destFile); } } else { - promise.reject("RNZipArchiveError", "File or folder does not exist"); + promise.reject(ZipErrorCodes.FILE_NOT_FOUND, "File or folder does not exist"); return; } } } catch (Exception ex) { - promise.reject("RNZipArchiveError", ex.getMessage()); + rejectMapped(promise, ex, ZipErrorCodes.ZIP); return; } updateProgress(1, 1, destFile); // force 100% @@ -415,15 +658,16 @@ private void processZip(final List entries, final String destFile, final @Override public void getUncompressedSize(String zipFilePath, String charset, final Promise promise) { executor.submit(() -> { + beginOperation(); try { long totalSize = getUncompressedSize(zipFilePath, charset); if (totalSize == -1) { - promise.reject("RNZipArchiveError", "Failed to get uncompressed size"); + promise.reject(ZipErrorCodes.CORRUPT_ARCHIVE, "Failed to get uncompressed size"); } else { promise.resolve((double) totalSize); } } catch (Exception e) { - promise.reject("RNZipArchiveError", "Failed to get uncompressed size: " + e.getMessage()); + rejectMapped(promise, e, ZipErrorCodes.UNZIP); } }); } diff --git a/android/src/main/java/com/rnziparchive/ZipErrorCodes.java b/android/src/main/java/com/rnziparchive/ZipErrorCodes.java new file mode 100644 index 00000000..80654eec --- /dev/null +++ b/android/src/main/java/com/rnziparchive/ZipErrorCodes.java @@ -0,0 +1,51 @@ +package com.rnziparchive; + +import net.lingala.zip4j.exception.ZipException; + +/** + * Stable promise rejection codes shared with the JS API and iOS implementation. + */ +public final class ZipErrorCodes { + public static final String FILE_NOT_FOUND = "ERR_FILE_NOT_FOUND"; + public static final String INVALID_PATH = "ERR_INVALID_PATH"; + public static final String INVALID_ARGS = "ERR_INVALID_ARGS"; + public static final String WRONG_PASSWORD = "ERR_WRONG_PASSWORD"; + public static final String NOT_PASSWORD_PROTECTED = "ERR_NOT_PASSWORD_PROTECTED"; + public static final String CORRUPT_ARCHIVE = "ERR_CORRUPT_ARCHIVE"; + public static final String UNSAFE_PATH = "ERR_UNSAFE_PATH"; + public static final String CANCELLED = "ERR_CANCELLED"; + public static final String BUSY = "ERR_BUSY"; + public static final String ZIP = "ERR_ZIP"; + public static final String UNZIP = "ERR_UNZIP"; + public static final String UNSUPPORTED = "ERR_UNSUPPORTED"; + + private ZipErrorCodes() { + } + + public static String mapException(Exception ex, String fallback) { + if (ex instanceof SecurityException) { + return UNSAFE_PATH; + } + if (ex instanceof ZipException) { + ZipException zipException = (ZipException) ex; + if (zipException.getType() == ZipException.Type.WRONG_PASSWORD) { + return WRONG_PASSWORD; + } + String message = zipException.getMessage(); + if (message != null) { + String lower = message.toLowerCase(); + if (lower.contains("not a zip") || lower.contains("corrupt") + || lower.contains("invalid") || lower.contains("malformed")) { + return CORRUPT_ARCHIVE; + } + if (lower.contains("password")) { + return WRONG_PASSWORD; + } + } + } + if (ex instanceof java.io.FileNotFoundException) { + return FILE_NOT_FOUND; + } + return fallback; + } +} diff --git a/android/src/paper/java/com/rnziparchive/NativeZipArchiveSpec.java b/android/src/paper/java/com/rnziparchive/NativeZipArchiveSpec.java index c502d48d..15728212 100644 --- a/android/src/paper/java/com/rnziparchive/NativeZipArchiveSpec.java +++ b/android/src/paper/java/com/rnziparchive/NativeZipArchiveSpec.java @@ -20,6 +20,7 @@ import com.facebook.react.bridge.ReadableArray; import com.facebook.react.turbomodule.core.interfaces.TurboModule; import javax.annotation.Nonnull; +import javax.annotation.Nullable; public abstract class NativeZipArchiveSpec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule { public static final String NAME = "RNZipArchive"; @@ -39,11 +40,15 @@ public NativeZipArchiveSpec(ReactApplicationContext reactContext) { @ReactMethod @DoNotStrip - public abstract void unzip(String from, String destinationPath, String charset, Promise promise); + public abstract void unzip(String from, String destinationPath, String charset, @Nullable ReadableArray entries, Promise promise); @ReactMethod @DoNotStrip - public abstract void unzipWithPassword(String from, String destinationPath, String password, Promise promise); + public abstract void unzipWithPassword(String from, String destinationPath, String password, @Nullable ReadableArray entries, Promise promise); + + @ReactMethod + @DoNotStrip + public abstract void listContents(String source, String charset, Promise promise); @ReactMethod @DoNotStrip @@ -69,6 +74,10 @@ public NativeZipArchiveSpec(ReactApplicationContext reactContext) { @DoNotStrip public abstract void unzipAssets(String source, String target, Promise promise); + @ReactMethod + @DoNotStrip + public abstract void cancel(Promise promise); + @ReactMethod @DoNotStrip public abstract void addListener(String eventName); diff --git a/android/src/test/java/com/rnziparchive/EntryMatchesSelectionTest.java b/android/src/test/java/com/rnziparchive/EntryMatchesSelectionTest.java new file mode 100644 index 00000000..2b0ecf31 --- /dev/null +++ b/android/src/test/java/com/rnziparchive/EntryMatchesSelectionTest.java @@ -0,0 +1,50 @@ +package com.rnziparchive; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Test; + +public class EntryMatchesSelectionTest { + + @Test + public void matchesExactFile() { + assertTrue(RNZipArchiveModule.entryMatchesSelection( + "hello.txt", Collections.singletonList("hello.txt"))); + } + + @Test + public void matchesExactFileIgnoringTrailingSlashOnWanted() { + assertTrue(RNZipArchiveModule.entryMatchesSelection( + "dir", Collections.singletonList("dir/"))); + } + + @Test + public void matchesDirectoryPrefix() { + assertTrue(RNZipArchiveModule.entryMatchesSelection( + "docs/readme.md", Collections.singletonList("docs"))); + assertTrue(RNZipArchiveModule.entryMatchesSelection( + "docs/readme.md", Collections.singletonList("docs/"))); + } + + @Test + public void doesNotMatchUnrelatedPrefix() { + assertFalse(RNZipArchiveModule.entryMatchesSelection( + "documentation/readme.md", Collections.singletonList("docs"))); + } + + @Test + public void matchesAnyOfMultipleWantedEntries() { + assertTrue(RNZipArchiveModule.entryMatchesSelection( + "b.txt", Arrays.asList("a.txt", "b.txt"))); + } + + @Test + public void normalizesBackslashes() { + assertTrue(RNZipArchiveModule.entryMatchesSelection( + "folder\\file.txt", Collections.singletonList("folder/file.txt"))); + } +} diff --git a/android/src/test/java/com/rnziparchive/ZipErrorCodesTest.java b/android/src/test/java/com/rnziparchive/ZipErrorCodesTest.java new file mode 100644 index 00000000..ca201c7a --- /dev/null +++ b/android/src/test/java/com/rnziparchive/ZipErrorCodesTest.java @@ -0,0 +1,30 @@ +package com.rnziparchive; + +import static org.junit.Assert.assertEquals; + +import net.lingala.zip4j.exception.ZipException; + +import org.junit.Test; + +public class ZipErrorCodesTest { + + @Test + public void mapsSecurityExceptionToUnsafePath() { + assertEquals( + ZipErrorCodes.UNSAFE_PATH, + ZipErrorCodes.mapException(new SecurityException("traversal"), ZipErrorCodes.UNZIP)); + } + + @Test + public void mapsWrongPasswordZipException() { + ZipException ex = new ZipException("bad password", ZipException.Type.WRONG_PASSWORD); + assertEquals(ZipErrorCodes.WRONG_PASSWORD, ZipErrorCodes.mapException(ex, ZipErrorCodes.UNZIP)); + } + + @Test + public void mapsUnknownExceptionToFallback() { + assertEquals( + ZipErrorCodes.ZIP, + ZipErrorCodes.mapException(new RuntimeException("boom"), ZipErrorCodes.ZIP)); + } +} diff --git a/e2e/README.md b/e2e/README.md index 4f78ffcc..5bf59888 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -61,8 +61,11 @@ For other platforms, see the [Maestro installation guide](https://maestro.mobile |------|-------------| | `home.yaml` | Verifies the home screen loads with all demo cards | | `zip-and-unzip.yaml` | Tests zipping a sample folder and unzipping it | +| `list-contents.yaml` | Tests `listContents`, selective `unzip(..., entries)`, and selective `unzipWithPassword(..., entries)` | | `password.yaml` | Tests creating a password-protected zip and extracting it | | `progress.yaml` | Tests subscribing to progress events during a large zip operation | +| `assets.yaml` | Tests unzipping a bundled archive via `unzipAssets` | +| `ci-master.yaml` | Full CI suite (home + zip + unzip + list/selective + password + progress + assets) | ## Writing New Flows diff --git a/index.d.ts b/index.d.ts index 73a0b167..85653d56 100644 --- a/index.d.ts +++ b/index.d.ts @@ -7,6 +7,21 @@ declare module "react-native-zip-archive" { AES_256 = "AES-256", } + export const ErrorCodes: { + FILE_NOT_FOUND: "ERR_FILE_NOT_FOUND"; + INVALID_PATH: "ERR_INVALID_PATH"; + INVALID_ARGS: "ERR_INVALID_ARGS"; + WRONG_PASSWORD: "ERR_WRONG_PASSWORD"; + NOT_PASSWORD_PROTECTED: "ERR_NOT_PASSWORD_PROTECTED"; + CORRUPT_ARCHIVE: "ERR_CORRUPT_ARCHIVE"; + UNSAFE_PATH: "ERR_UNSAFE_PATH"; + CANCELLED: "ERR_CANCELLED"; + BUSY: "ERR_BUSY"; + ZIP: "ERR_ZIP"; + UNZIP: "ERR_UNZIP"; + UNSUPPORTED: "ERR_UNSUPPORTED"; + }; + export const DEFAULT_COMPRESSION: number; export const NO_COMPRESSION: number; export const BEST_SPEED: number; @@ -28,13 +43,47 @@ declare module "react-native-zip-archive" { compressionLevel?: number ): Promise; - export function unzip(source: string, target: string, charset?: string): Promise; - export function unzipWithPassword(source: string, target: string, password: string): Promise; + /** + * Unzip an archive. Pass `entries` to extract only those paths + * (directories include nested children). When using `entries`, you may + * omit charset (`unzip(src, dest, ['a.txt'])`) or pass it explicitly + * (`unzip(src, dest, 'GBK', ['a.txt'])`). + */ + export function unzip( + source: string, + target: string, + charset?: string | string[], + entries?: string[] + ): Promise; + + /** + * Unzip a password-protected archive. Pass `entries` to extract only + * those paths (directories include nested children). + */ + export function unzipWithPassword( + source: string, + target: string, + password: string, + entries?: string[] + ): Promise; + export function unzipAssets(assetPath: string, target: string): Promise; + export type ZipEntry = { + path: string; + size: number; + compressedSize: number; + isDirectory: boolean; + isEncrypted: boolean; + }; + + export function listContents(source: string, charset?: string): Promise; + export function subscribe( callback: ({ progress, filePath }: { progress: number; filePath: string }) => void ): NativeEventSubscription; export function getUncompressedSize(source: string, charset?: string): Promise; + + export function cancel(): Promise; } diff --git a/index.js b/index.js index e6488e74..831cab26 100644 --- a/index.js +++ b/index.js @@ -37,16 +37,58 @@ export const EncryptionMethods = { AES_256: "AES-256", }; +export const ErrorCodes = { + FILE_NOT_FOUND: "ERR_FILE_NOT_FOUND", + INVALID_PATH: "ERR_INVALID_PATH", + INVALID_ARGS: "ERR_INVALID_ARGS", + WRONG_PASSWORD: "ERR_WRONG_PASSWORD", + NOT_PASSWORD_PROTECTED: "ERR_NOT_PASSWORD_PROTECTED", + CORRUPT_ARCHIVE: "ERR_CORRUPT_ARCHIVE", + UNSAFE_PATH: "ERR_UNSAFE_PATH", + CANCELLED: "ERR_CANCELLED", + BUSY: "ERR_BUSY", + ZIP: "ERR_ZIP", + UNZIP: "ERR_UNZIP", + UNSUPPORTED: "ERR_UNSUPPORTED", +}; + export const DEFAULT_COMPRESSION = -1; export const NO_COMPRESSION = 0; export const BEST_SPEED = 1; export const BEST_COMPRESSION = 9; -export const unzip = (source, target, charset = "UTF-8") => { +function resolveUnzipArgs(charsetOrEntries, entries) { + let charset = "UTF-8"; + let selected = entries; + if (Array.isArray(charsetOrEntries)) { + selected = charsetOrEntries; + } else if (charsetOrEntries != null && charsetOrEntries !== "") { + charset = charsetOrEntries; + } + if (selected !== undefined && selected !== null) { + if (!Array.isArray(selected) || selected.length === 0) { + return { + error: new Error( + "unzip: entries must be a non-empty array when provided" + ), + }; + } + } else { + selected = null; + } + return { charset, entries: selected }; +} + +export const unzip = (source, target, charsetOrEntries = "UTF-8", entries) => { + const resolved = resolveUnzipArgs(charsetOrEntries, entries); + if (resolved.error) { + return Promise.reject(resolved.error); + } return getRNZipArchive().unzip( normalizeFilePath(source), normalizeFilePath(target), - charset + resolved.charset, + resolved.entries ); }; @@ -56,14 +98,28 @@ export const isPasswordProtected = (source) => { .then((isEncrypted) => !!isEncrypted); }; -export const unzipWithPassword = (source, target, password) => { +export const unzipWithPassword = (source, target, password, entries) => { + if (entries !== undefined && entries !== null) { + if (!Array.isArray(entries) || entries.length === 0) { + return Promise.reject( + new Error( + "unzipWithPassword: entries must be a non-empty array when provided" + ) + ); + } + } return getRNZipArchive().unzipWithPassword( normalizeFilePath(source), normalizeFilePath(target), - password + password, + entries ?? null ); }; +export const listContents = (source, charset = "UTF-8") => { + return getRNZipArchive().listContents(normalizeFilePath(source), charset); +}; + export const zipWithPassword = ( source, target, @@ -127,3 +183,7 @@ export const getUncompressedSize = (source, charset = "UTF-8") => { charset ); }; + +export const cancel = () => { + return getRNZipArchive().cancel(); +}; diff --git a/ios/RNZipArchive.h b/ios/RNZipArchive.h index 96bfa20a..b64f1d28 100644 --- a/ios/RNZipArchive.h +++ b/ios/RNZipArchive.h @@ -20,6 +20,7 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic, copy, nullable) NSString *processedFilePath; @property (nonatomic) float progress; @property (nonatomic, copy, nullable) void (^progressHandler)(NSUInteger entryNumber, NSUInteger total); +@property (nonatomic) BOOL cancelled; @end diff --git a/ios/RNZipArchive.mm b/ios/RNZipArchive.mm index 2ba09151..34de573c 100644 --- a/ios/RNZipArchive.mm +++ b/ios/RNZipArchive.mm @@ -7,6 +7,7 @@ // #import "RNZipArchive.h" +#import "mz_compat.h" #import #if __has_include() @@ -16,6 +17,35 @@ #import "RCTEventDispatcher.h" #endif +static NSString *const kZipErrFileNotFound = @"ERR_FILE_NOT_FOUND"; +static NSString *const kZipErrInvalidPath = @"ERR_INVALID_PATH"; +static NSString *const kZipErrInvalidArgs = @"ERR_INVALID_ARGS"; +static NSString *const kZipErrWrongPassword = @"ERR_WRONG_PASSWORD"; +static NSString *const kZipErrNotPasswordProtected = @"ERR_NOT_PASSWORD_PROTECTED"; +static NSString *const kZipErrCorruptArchive = @"ERR_CORRUPT_ARCHIVE"; +static NSString *const kZipErrUnsafePath = @"ERR_UNSAFE_PATH"; +static NSString *const kZipErrCancelled = @"ERR_CANCELLED"; +static NSString *const kZipErrZip = @"ERR_ZIP"; +static NSString *const kZipErrUnzip = @"ERR_UNZIP"; +static NSString *const kZipErrUnsupported = @"ERR_UNSUPPORTED"; + +@interface RNZipCancelDelegate : NSObject +@property (nonatomic, weak) RNZipArchive *owner; +@end + +@implementation RNZipCancelDelegate +- (BOOL)zipArchiveShouldUnzipFileAtIndex:(NSInteger)fileIndex + totalFiles:(NSInteger)totalFiles + archivePath:(NSString *)archivePath + fileInfo:(unz_file_info)fileInfo { + (void)fileIndex; + (void)totalFiles; + (void)archivePath; + (void)fileInfo; + return self.owner != nil && !self.owner.cancelled; +} +@end + @implementation RNZipArchive { bool hasListeners; @@ -48,9 +78,30 @@ -(void)stopObserving { return @[@"zipArchiveProgressEvent"]; } +- (void)beginOperation { + self.cancelled = NO; +} + +- (BOOL)rejectIfCancelled:(RCTPromiseRejectBlock)reject { + if (self.cancelled) { + reject(kZipErrCancelled, @"Operation cancelled", nil); + return YES; + } + return NO; +} + +- (void)cancel:(RCTPromiseResolveBlock)resolve + reject:(RCTPromiseRejectBlock)reject { + (void)reject; + self.cancelled = YES; + resolve(nil); +} + - (void)isPasswordProtected:(NSString *)file resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject { + (void)reject; + [self beginOperation]; BOOL isPasswordProtected = [SSZipArchive isFilePasswordProtectedAtPath:file]; resolve([NSNumber numberWithBool:isPasswordProtected]); } @@ -58,24 +109,387 @@ - (void)isPasswordProtected:(NSString *)file - (void)unzip:(NSString *)from destinationPath:(NSString *)destinationPath charset:(NSString *)charset + entries:(NSArray *)entries resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject { + (void)charset; + if (entries != nil && entries.count > 0) { + [self unzipSelectedEntries:from + destinationPath:destinationPath + entries:entries + password:nil + resolve:resolve + reject:reject]; + return; + } [self unzipFile:from destinationPath:destinationPath password:nil resolve:resolve reject:reject]; } - (void)unzipWithPassword:(NSString *)from destinationPath:(NSString *)destinationPath password:(NSString *)password + entries:(NSArray *)entries resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject { + if (entries != nil && entries.count > 0) { + [self unzipSelectedEntries:from + destinationPath:destinationPath + entries:entries + password:password + resolve:resolve + reject:reject]; + return; + } [self unzipFile:from destinationPath:destinationPath password:password resolve:resolve reject:reject]; } +- (void)listContents:(NSString *)source + charset:(NSString *)charset + resolve:(RCTPromiseResolveBlock)resolve + reject:(RCTPromiseRejectBlock)reject { + (void)charset; // iOS always reads entry names as UTF-8 / Latin-1 fallback + [self beginOperation]; + + zipFile zip = unzOpen(source.fileSystemRepresentation); + if (zip == NULL) { + reject(kZipErrFileNotFound, @"failed to open zip file", nil); + return; + } + + NSMutableArray *entries = [NSMutableArray array]; + // Empty archives return a non-UNZ_OK code from unzGoToFirstFile; treat as an empty list. + int ret = unzGoToFirstFile(zip); + while (ret == UNZ_OK) { + unz_file_info fileInfo; + memset(&fileInfo, 0, sizeof(unz_file_info)); + ret = unzGetCurrentFileInfo(zip, &fileInfo, NULL, 0, NULL, 0, NULL, 0); + if (ret != UNZ_OK) { + unzClose(zip); + reject(kZipErrCorruptArchive, @"failed to retrieve info for zip entry", nil); + return; + } + + char *filename = (char *)malloc(fileInfo.size_filename + 1); + if (filename == NULL) { + unzClose(zip); + reject(kZipErrUnzip, @"out of memory while listing zip contents", nil); + return; + } + unzGetCurrentFileInfo(zip, &fileInfo, filename, fileInfo.size_filename + 1, NULL, 0, NULL, 0); + filename[fileInfo.size_filename] = '\0'; + + NSString *path = [NSString stringWithUTF8String:filename]; + if (path == nil) { + path = [[NSString alloc] initWithBytes:filename + length:fileInfo.size_filename + encoding:NSISOLatin1StringEncoding]; + } + BOOL isDirectory = NO; + if (fileInfo.size_filename > 0 && + (filename[fileInfo.size_filename - 1] == '/' || filename[fileInfo.size_filename - 1] == '\\')) { + isDirectory = YES; + } + free(filename); + + if (path == nil) { + path = @""; + } + + BOOL isEncrypted = (fileInfo.flag & 1) != 0; + [entries addObject:@{ + @"path": path, + @"size": @((double)fileInfo.uncompressed_size), + @"compressedSize": @((double)fileInfo.compressed_size), + @"isDirectory": @(isDirectory), + @"isEncrypted": @(isEncrypted), + }]; + + ret = unzGoToNextFile(zip); + } + + unzClose(zip); + resolve(entries); +} + +- (NSString *)normalizedZipPath:(NSString *)path { + NSString *normalized = [path stringByReplacingOccurrencesOfString:@"\\" withString:@"/"]; + while ([normalized hasSuffix:@"/"] && normalized.length > 0) { + normalized = [normalized substringToIndex:normalized.length - 1]; + } + return normalized; +} + +- (BOOL)entry:(NSString *)entryName matchesSelection:(NSArray *)wantedEntries { + if (entryName == nil || wantedEntries.count == 0) { + return NO; + } + NSString *normalizedEntry = [self normalizedZipPath:entryName]; + for (NSString *wanted in wantedEntries) { + if (wanted.length == 0) { + continue; + } + NSString *normalizedWanted = [self normalizedZipPath:wanted]; + if ([normalizedEntry isEqualToString:normalizedWanted]) { + return YES; + } + NSString *prefix = [normalizedWanted stringByAppendingString:@"/"]; + if ([normalizedEntry hasPrefix:prefix]) { + return YES; + } + } + return NO; +} + +- (BOOL)isSafeExtractPath:(NSString *)entryName intoDestination:(NSString *)destinationPath { + if (entryName.length == 0) { + return NO; + } + NSString *fullPath = [destinationPath stringByAppendingPathComponent:entryName]; + NSString *standardizedDest = [[destinationPath stringByStandardizingPath] stringByAppendingString:@"/"]; + NSString *standardizedFull = [fullPath stringByStandardizingPath]; + return [standardizedFull hasPrefix:standardizedDest] || + [standardizedFull isEqualToString:[destinationPath stringByStandardizingPath]]; +} + +- (void)unzipSelectedEntries:(NSString *)from + destinationPath:(NSString *)destinationPath + entries:(NSArray *)entries + password:(NSString *)password + resolve:(RCTPromiseResolveBlock)resolve + reject:(RCTPromiseRejectBlock)reject { + [self beginOperation]; + if (entries.count == 0) { + reject(kZipErrInvalidArgs, @"entries must be a non-empty array", nil); + return; + } + + self.progress = 0.0; + self.processedFilePath = @""; + [self zipArchiveProgressEvent:0 total:1]; + + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSError *dirError = nil; + if (![fileManager fileExistsAtPath:destinationPath]) { + [fileManager createDirectoryAtPath:destinationPath + withIntermediateDirectories:YES + attributes:nil + error:&dirError]; + if (dirError != nil) { + reject(kZipErrUnzip, dirError.localizedDescription, dirError); + return; + } + } + + zipFile zip = unzOpen(from.fileSystemRepresentation); + if (zip == NULL) { + reject(kZipErrFileNotFound, @"failed to open zip file", nil); + return; + } + + // First pass: compute total uncompressed size of matching entries for progress. + unsigned long long totalSize = 0; + NSUInteger matchCount = 0; + int ret = unzGoToFirstFile(zip); + while (ret == UNZ_OK) { + unz_file_info fileInfo; + memset(&fileInfo, 0, sizeof(unz_file_info)); + ret = unzGetCurrentFileInfo(zip, &fileInfo, NULL, 0, NULL, 0, NULL, 0); + if (ret != UNZ_OK) { + break; + } + char *filenameBuf = (char *)malloc(fileInfo.size_filename + 1); + if (filenameBuf == NULL) { + break; + } + unzGetCurrentFileInfo(zip, &fileInfo, filenameBuf, fileInfo.size_filename + 1, NULL, 0, NULL, 0); + filenameBuf[fileInfo.size_filename] = '\0'; + NSString *path = [NSString stringWithUTF8String:filenameBuf]; + if (path == nil) { + path = [[NSString alloc] initWithBytes:filenameBuf + length:fileInfo.size_filename + encoding:NSISOLatin1StringEncoding]; + } + free(filenameBuf); + if ([self entry:path matchesSelection:entries]) { + matchCount += 1; + totalSize += fileInfo.uncompressed_size; + } + ret = unzGoToNextFile(zip); + } + + if (matchCount == 0) { + unzClose(zip); + reject(kZipErrInvalidArgs, @"None of the requested entries were found in the archive", nil); + return; + } + + if (totalSize == 0) { + totalSize = 1; + } + + // Second pass: extract matching entries. + unsigned long long extractedBytes = 0; + BOOL success = YES; + NSError *extractError = nil; + ret = unzGoToFirstFile(zip); + while (ret == UNZ_OK) { + unz_file_info fileInfo; + memset(&fileInfo, 0, sizeof(unz_file_info)); + ret = unzGetCurrentFileInfo(zip, &fileInfo, NULL, 0, NULL, 0, NULL, 0); + if (ret != UNZ_OK) { + success = NO; + extractError = [NSError errorWithDomain:@"RNZipArchive" + code:-1 + userInfo:@{NSLocalizedDescriptionKey: @"failed to retrieve info for zip entry"}]; + break; + } + + char *filename = (char *)malloc(fileInfo.size_filename + 1); + if (filename == NULL) { + success = NO; + extractError = [NSError errorWithDomain:@"RNZipArchive" + code:-1 + userInfo:@{NSLocalizedDescriptionKey: @"out of memory while extracting"}]; + break; + } + unzGetCurrentFileInfo(zip, &fileInfo, filename, fileInfo.size_filename + 1, NULL, 0, NULL, 0); + filename[fileInfo.size_filename] = '\0'; + + NSString *strPath = [NSString stringWithUTF8String:filename]; + if (strPath == nil) { + strPath = [[NSString alloc] initWithBytes:filename + length:fileInfo.size_filename + encoding:NSISOLatin1StringEncoding]; + } + BOOL isDirectory = NO; + if (fileInfo.size_filename > 0 && + (filename[fileInfo.size_filename - 1] == '/' || filename[fileInfo.size_filename - 1] == '\\')) { + isDirectory = YES; + } + free(filename); + + if ([self rejectIfCancelled:reject]) { + unzClose(zip); + return; + } + + if (strPath == nil || ![self entry:strPath matchesSelection:entries]) { + ret = unzGoToNextFile(zip); + continue; + } + + if ([strPath hasPrefix:@"__MACOSX/"]) { + ret = unzGoToNextFile(zip); + continue; + } + + if (![self isSafeExtractPath:strPath intoDestination:destinationPath]) { + success = NO; + extractError = [NSError errorWithDomain:@"RNZipArchive" + code:-1 + userInfo:@{NSLocalizedDescriptionKey: + [NSString stringWithFormat:@"Found Zip Path Traversal Vulnerability with %@", strPath]}]; + break; + } + + self.processedFilePath = strPath; + NSString *fullPath = [destinationPath stringByAppendingPathComponent:strPath]; + + if (isDirectory) { + [fileManager createDirectoryAtPath:fullPath + withIntermediateDirectories:YES + attributes:nil + error:nil]; + extractedBytes += fileInfo.uncompressed_size; + [self zipArchiveProgressEvent:extractedBytes total:totalSize]; + ret = unzGoToNextFile(zip); + continue; + } + + NSString *parentDir = [fullPath stringByDeletingLastPathComponent]; + [fileManager createDirectoryAtPath:parentDir + withIntermediateDirectories:YES + attributes:nil + error:nil]; + + if (password.length > 0) { + ret = unzOpenCurrentFilePassword(zip, [password cStringUsingEncoding:NSUTF8StringEncoding]); + } else { + ret = unzOpenCurrentFile(zip); + } + if (ret != UNZ_OK) { + success = NO; + extractError = [NSError errorWithDomain:@"RNZipArchive" + code:-1 + userInfo:@{NSLocalizedDescriptionKey: @"failed to open file in zip archive"}]; + break; + } + + FILE *out = fopen(fullPath.fileSystemRepresentation, "wb"); + if (out == NULL) { + unzCloseCurrentFile(zip); + success = NO; + extractError = [NSError errorWithDomain:@"RNZipArchive" + code:-1 + userInfo:@{NSLocalizedDescriptionKey: @"failed to write extracted file"}]; + break; + } + + unsigned char buffer[4096]; + int readBytes; + do { + readBytes = unzReadCurrentFile(zip, buffer, sizeof(buffer)); + if (readBytes < 0) { + success = NO; + extractError = [NSError errorWithDomain:@"RNZipArchive" + code:-1 + userInfo:@{NSLocalizedDescriptionKey: @"failed to read zip entry"}]; + break; + } + if (readBytes > 0) { + fwrite(buffer, 1, readBytes, out); + } + } while (readBytes > 0); + + fclose(out); + unzCloseCurrentFile(zip); + + if (!success) { + break; + } + + extractedBytes += fileInfo.uncompressed_size; + [self zipArchiveProgressEvent:extractedBytes total:totalSize]; + ret = unzGoToNextFile(zip); + } + + unzClose(zip); + + self.progress = 1.0; + [self zipArchiveProgressEvent:1 total:1]; + + if (success) { + resolve(destinationPath); + } else if (self.cancelled) { + reject(kZipErrCancelled, @"Operation cancelled", nil); + } else { + NSString *message = extractError ? extractError.localizedDescription : @"unable to unzip selected entries"; + NSString *code = kZipErrUnzip; + if ([message containsString:@"Zip Path Traversal"]) { + code = kZipErrUnsafePath; + } else if ([message.lowercaseString containsString:@"password"]) { + code = kZipErrWrongPassword; + } + reject(code, message, extractError); + } +} + - (void)unzipFile:(NSString *)from destinationPath:(NSString *)destinationPath password:(NSString *)password resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject { + [self beginOperation]; self.progress = 0.0; self.processedFilePath = @""; [self zipArchiveProgressEvent:0 total:1]; // force 0% @@ -89,6 +503,8 @@ - (void)unzipFile:(NSString *)from __block unsigned long long extractedBytes = 0; __weak RNZipArchive *weakSelf = self; + RNZipCancelDelegate *cancelDelegate = [RNZipCancelDelegate new]; + cancelDelegate.owner = self; BOOL success = [SSZipArchive unzipFileAtPath:from toDestination:destinationPath @@ -97,7 +513,7 @@ - (void)unzipFile:(NSString *)from nestedZipLevel:0 password:password error:&error - delegate:nil + delegate:cancelDelegate progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) { RNZipArchive *strongSelf = weakSelf; if (strongSelf == nil) { @@ -116,11 +532,20 @@ - (void)unzipFile:(NSString *)from self.progress = 1.0; [self zipArchiveProgressEvent:1 total:1]; // force 100% - if (success) { + if (self.cancelled) { + reject(kZipErrCancelled, @"Operation cancelled", nil); + } else if (success) { resolve(destinationPath); } else { NSString *errorMessage = error ? [error localizedDescription] : @"unable to unzip"; - reject(@"unzip_error", errorMessage, error); + NSString *code = kZipErrUnzip; + NSString *lower = errorMessage.lowercaseString; + if ([lower containsString:@"password"]) { + code = kZipErrWrongPassword; + } else if ([lower containsString:@"failed to open zip"]) { + code = kZipErrFileNotFound; + } + reject(code, errorMessage, error); } } @@ -129,6 +554,7 @@ - (void)zipFolder:(NSString *)from compressionLevel:(double)compressionLevel resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject { + [self beginOperation]; self.progress = 0.0; self.processedFilePath = @""; [self zipArchiveProgressEvent:0 total:1]; // force 0% @@ -147,11 +573,12 @@ - (void)zipFolder:(NSString *)from self.progress = 1.0; [self zipArchiveProgressEvent:1 total:1]; // force 100% - if (success) { + if (self.cancelled) { + reject(kZipErrCancelled, @"Operation cancelled", nil); + } else if (success) { resolve(destinationPath); } else { - NSError *error = nil; - reject(@"zip_error", @"unable to zip", error); + reject(kZipErrZip, @"unable to zip", nil); } } @@ -201,6 +628,10 @@ - (BOOL)writeZipEntriesToPath:(NSString *)destinationPath if (success) { NSUInteger total = entries.count, complete = 0; for (NSArray *entry in entries) { + if (self.cancelled) { + success = NO; + break; + } success &= [zipArchive writeFileAtPath:entry[0] withFileName:entry[1] compressionLevel:compressionLevel password:password AES:aes]; if (self.progressHandler) { complete++; @@ -217,6 +648,7 @@ - (void)zipFiles:(NSArray *)from compressionLevel:(double)compressionLevel resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject { + [self beginOperation]; self.progress = 0.0; self.processedFilePath = @""; [self zipArchiveProgressEvent:0 total:1]; // force 0% @@ -229,11 +661,12 @@ - (void)zipFiles:(NSArray *)from self.progress = 1.0; [self zipArchiveProgressEvent:1 total:1]; // force 100% - if (success) { + if (self.cancelled) { + reject(kZipErrCancelled, @"Operation cancelled", nil); + } else if (success) { resolve(destinationPath); } else { - NSError *error = nil; - reject(@"zip_error", @"unable to zip", error); + reject(kZipErrZip, @"unable to zip", nil); } } @@ -244,6 +677,7 @@ - (void)zipFolderWithPassword:(NSString *)from compressionLevel:(double)compressionLevel resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject { + [self beginOperation]; self.progress = 0.0; self.processedFilePath = @""; [self zipArchiveProgressEvent:0 total:1]; // force 0% @@ -262,11 +696,12 @@ - (void)zipFolderWithPassword:(NSString *)from self.progress = 1.0; [self zipArchiveProgressEvent:1 total:1]; // force 100% - if (success) { + if (self.cancelled) { + reject(kZipErrCancelled, @"Operation cancelled", nil); + } else if (success) { resolve(destinationPath); } else { - NSError *error = nil; - reject(@"zip_error", @"unable to zip", error); + reject(kZipErrZip, @"unable to zip", nil); } } @@ -277,6 +712,7 @@ - (void)zipFilesWithPassword:(NSArray *)from compressionLevel:(double)compressionLevel resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject { + [self beginOperation]; self.progress = 0.0; self.processedFilePath = @""; [self zipArchiveProgressEvent:0 total:1]; // force 0% @@ -290,11 +726,12 @@ - (void)zipFilesWithPassword:(NSArray *)from self.progress = 1.0; [self zipArchiveProgressEvent:1 total:1]; // force 100% - if (success) { + if (self.cancelled) { + reject(kZipErrCancelled, @"Operation cancelled", nil); + } else if (success) { resolve(destinationPath); } else { - NSError *error = nil; - reject(@"zip_error", @"unable to zip", error); + reject(kZipErrZip, @"unable to zip", nil); } } @@ -318,7 +755,7 @@ - (void)unzipAssets:(NSString *)source reject:(RCTPromiseRejectBlock)reject { // iOS doesn't have assets like Android, return error NSError *error = [NSError errorWithDomain:@"RNZipArchive" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"unzipAssets is not supported on iOS"}]; - reject(@"unzip_assets_not_supported", @"unzipAssets is not supported on iOS", error); + reject(kZipErrUnsupported, @"unzipAssets is not supported on iOS", error); } - (void)addListener:(NSString *)eventName { diff --git a/package.json b/package.json index 71a7a799..e918b076 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "react-native-zip-archive", - "version": "9.0.2", + "version": "9.2.0", "description": "A TurboModule wrapper on ZipArchive for React Native's New Architecture", "main": "index.js", "scripts": { diff --git a/playground-expo/app/_layout.tsx b/playground-expo/app/_layout.tsx index 787ba018..5fb87aa7 100644 --- a/playground-expo/app/_layout.tsx +++ b/playground-expo/app/_layout.tsx @@ -10,6 +10,7 @@ export default function RootLayout() { + diff --git a/playground-expo/app/index.tsx b/playground-expo/app/index.tsx index 8fbbb64f..e2aa351e 100644 --- a/playground-expo/app/index.tsx +++ b/playground-expo/app/index.tsx @@ -13,6 +13,7 @@ import { Link } from 'expo-router'; const DEMOS = [ { href: '/zip' as const, title: 'Zip Operations', desc: 'Zip folders & files with compression levels' }, { href: '/unzip' as const, title: 'Unzip Operations', desc: 'Extract archives with charset support' }, + { href: '/list-contents' as const, title: 'List & Selective Extract', desc: 'Inspect entries and extract a subset' }, { href: '/password' as const, title: 'Password Protection', desc: 'AES & standard encryption demos' }, { href: '/progress' as const, title: 'Progress Events', desc: 'Real-time zip/unzip progress' }, { href: '/benchmark' as const, title: 'Benchmarks', desc: 'Compare compression levels & speed' }, diff --git a/playground-expo/app/list-contents.tsx b/playground-expo/app/list-contents.tsx new file mode 100644 index 00000000..9766705d --- /dev/null +++ b/playground-expo/app/list-contents.tsx @@ -0,0 +1,289 @@ +import React, { useState } from 'react'; +import { + Text, + StyleSheet, + ScrollView, + TouchableOpacity, + ActivityIndicator, +} from 'react-native'; +import * as FileSystem from 'expo-file-system/legacy'; +import { ResultCard } from '../components/ResultCard'; +import { CodePreview } from '../components/CodePreview'; +import { ensureDir, listFilesRecursive } from '../utils/fileSystem'; +import { + zip, + zipWithPassword, + listContents, + unzip, + unzipWithPassword, + type ZipEntry, +} from 'react-native-zip-archive'; + +const SOURCE_CODE = `import { listContents, unzip, unzipWithPassword } from 'react-native-zip-archive'; + +const entries = await listContents(sourceZip); +await unzip(sourceZip, outputFolder, ['readme.md', 'docs']); +await unzipWithPassword(sourceZip, outputFolder, 'secret', ['readme.md']); +`; + +export default function ListContentsScreen() { + const [loading, setLoading] = useState(false); + const [entries, setEntries] = useState([]); + const [extractedFiles, setExtractedFiles] = useState([]); + const [resultTitle, setResultTitle] = useState('Result'); + const [result, setResult] = useState(''); + const [notExtracted, setNotExtracted] = useState([]); + const [error, setError] = useState(''); + const [zipPath, setZipPath] = useState(''); + + const createPlainDemoZip = async () => { + const dir = FileSystem.documentDirectory + 'demo-list/'; + await ensureDir(dir); + await ensureDir(dir + 'docs/'); + await FileSystem.writeAsStringAsync(dir + 'hello.txt', 'Hello from zip!'); + await FileSystem.writeAsStringAsync(dir + 'readme.md', '# Demo'); + await FileSystem.writeAsStringAsync(dir + 'docs/guide.md', '# Guide'); + const target = FileSystem.documentDirectory + 'demo-list-sample.zip'; + try { + await FileSystem.deleteAsync(target, { idempotent: true }); + } catch {} + await zip(dir, target, 0); + return target; + }; + + const createPasswordDemoZip = async () => { + const dir = FileSystem.documentDirectory + 'demo-list-pw/'; + await ensureDir(dir); + await ensureDir(dir + 'docs/'); + await FileSystem.writeAsStringAsync(dir + 'hello.txt', 'Hello from zip!'); + await FileSystem.writeAsStringAsync(dir + 'readme.md', '# Demo'); + await FileSystem.writeAsStringAsync(dir + 'docs/guide.md', '# Guide'); + const target = FileSystem.documentDirectory + 'demo-list-password.zip'; + try { + await FileSystem.deleteAsync(target, { idempotent: true }); + } catch {} + await zipWithPassword(dir, target, 'secret', 'STANDARD', 0); + return target; + }; + + const summarizeExtraction = (files: string[]) => { + const normalized = files.map((f) => f.replace(/\\/g, '/')); + const missing = ['hello.txt'].filter( + (name) => !normalized.some((f) => f === name || f.endsWith('/' + name)) + ); + return { files: normalized, missing }; + }; + + const handleList = async () => { + setLoading(true); + setError(''); + setEntries([]); + setExtractedFiles([]); + setNotExtracted([]); + setResult(''); + try { + const path = await createPlainDemoZip(); + setZipPath(path); + const listed = await listContents(path); + setEntries(listed); + setResultTitle('Listed Entries'); + const names = listed.map((e) => e.path.replace(/\\/g, '/')).join(', '); + setResult(`Listed ${listed.length} entries: ${names}`); + } catch (e: any) { + setError(e?.message || String(e)); + } finally { + setLoading(false); + } + }; + + const handleSelective = async () => { + if (!zipPath) return; + setLoading(true); + setError(''); + setExtractedFiles([]); + setNotExtracted([]); + try { + const out = FileSystem.documentDirectory + 'selective/' + Date.now() + '/'; + await ensureDir(out); + const path = await unzip(zipPath, out, ['readme.md', 'docs']); + const { files, missing } = summarizeExtraction(await listFilesRecursive(out)); + setExtractedFiles(files); + setNotExtracted(missing); + setResultTitle('Selective Extract'); + setResult(`Selective extract to ${path}`); + } catch (e: any) { + setError(e?.message || String(e)); + } finally { + setLoading(false); + } + }; + + const handlePasswordSelective = async () => { + setLoading(true); + setError(''); + setEntries([]); + setExtractedFiles([]); + setNotExtracted([]); + setResult(''); + try { + const source = await createPasswordDemoZip(); + const out = FileSystem.documentDirectory + 'selective-pw/' + Date.now() + '/'; + await ensureDir(out); + const path = await unzipWithPassword(source, out, 'secret', ['readme.md']); + const { files, missing } = summarizeExtraction(await listFilesRecursive(out)); + setExtractedFiles(files); + setNotExtracted(missing); + setResultTitle('Password Selective Extract Done'); + setResult(`Password selective extract to ${path}`); + } catch (e: any) { + setError(e?.message || String(e)); + } finally { + setLoading(false); + } + }; + + const entryMarkers = entries.flatMap((entry) => { + const path = entry.path.replace(/\\/g, '/'); + const markers = [`Contains ${path}`]; + const base = path.split('/').pop(); + if (base && base !== path) { + markers.push(`Contains ${base}`); + } + return markers; + }); + + return ( + + Demo: List Contents + + {loading ? ( + + ) : ( + Create Zip and List Contents + )} + + + Demo: Selective Extract + + {loading ? ( + + ) : ( + Extract Selected Entries + )} + + + Demo: Password Selective Extract + + {loading ? ( + + ) : ( + Password Selective Extract + )} + + + {result ? ( + + {result} + {entryMarkers.map((marker) => ( + + {marker} + + ))} + {entries.length > 0 && ( + <> + Entries: + {entries.map((entry) => ( + + • {entry.path} + {entry.isDirectory ? '/' : ''} ({entry.size} B) + + ))} + + )} + {extractedFiles.map((f) => ( + + Extracted {f} + + ))} + {notExtracted.map((f) => ( + + Skipped {f} + + ))} + + ) : null} + + {error ? ( + + {error} + + ) : null} + + + + ); +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: '#fff', + paddingHorizontal: 16, + paddingTop: 16, + }, + section: { + fontSize: 15, + fontWeight: '700', + marginTop: 16, + marginBottom: 8, + }, + actionBtn: { + backgroundColor: '#007AFF', + paddingVertical: 12, + borderRadius: 10, + alignItems: 'center', + }, + disabledBtn: { + backgroundColor: '#A1A1AA', + }, + actionText: { + color: '#fff', + fontWeight: '700', + }, + mono: { + fontFamily: 'Courier', + fontSize: 12, + color: '#1C1C1E', + }, + subHeading: { + marginTop: 8, + fontWeight: '700', + fontSize: 13, + }, + fileItem: { + fontSize: 13, + color: '#3A3A3C', + marginLeft: 4, + }, + marker: { + fontSize: 13, + color: '#1C1C1E', + fontWeight: '600', + marginTop: 4, + }, +}); diff --git a/playground-rn/src/App.tsx b/playground-rn/src/App.tsx index 2c0223b3..a37d29e8 100644 --- a/playground-rn/src/App.tsx +++ b/playground-rn/src/App.tsx @@ -5,6 +5,7 @@ import { SafeAreaProvider } from 'react-native-safe-area-context'; import HomeScreen from './screens/HomeScreen'; import ZipScreen from './screens/ZipScreen'; import UnzipScreen from './screens/UnzipScreen'; +import ListContentsScreen from './screens/ListContentsScreen'; import PasswordScreen from './screens/PasswordScreen'; import ProgressScreen from './screens/ProgressScreen'; import BenchmarkScreen from './screens/BenchmarkScreen'; @@ -14,6 +15,7 @@ export type RootStackParamList = { Home: undefined; Zip: undefined; Unzip: undefined; + ListContents: undefined; Password: undefined; Progress: undefined; Benchmark: undefined; @@ -30,6 +32,7 @@ function App(): React.JSX.Element { + diff --git a/playground-rn/src/screens/HomeScreen.tsx b/playground-rn/src/screens/HomeScreen.tsx index e3f0ab39..df8cebe5 100644 --- a/playground-rn/src/screens/HomeScreen.tsx +++ b/playground-rn/src/screens/HomeScreen.tsx @@ -15,6 +15,7 @@ type RootStackParamList = { Home: undefined; Zip: undefined; Unzip: undefined; + ListContents: undefined; Password: undefined; Progress: undefined; Benchmark: undefined; @@ -26,6 +27,7 @@ type NavigationProp = NativeStackNavigationProp; const DEMOS = [ { screen: 'Zip' as const, title: 'Zip Operations', desc: 'Zip folders & files with compression levels' }, { screen: 'Unzip' as const, title: 'Unzip Operations', desc: 'Extract archives with charset support' }, + { screen: 'ListContents' as const, title: 'List & Selective Extract', desc: 'Inspect entries and extract a subset' }, { screen: 'Password' as const, title: 'Password Protection', desc: 'AES & standard encryption demos' }, { screen: 'Progress' as const, title: 'Progress Events', desc: 'Real-time zip/unzip progress' }, { screen: 'Benchmark' as const, title: 'Benchmarks', desc: 'Compare compression levels & speed' }, diff --git a/playground-rn/src/screens/ListContentsScreen.tsx b/playground-rn/src/screens/ListContentsScreen.tsx new file mode 100644 index 00000000..7e3d3e9c --- /dev/null +++ b/playground-rn/src/screens/ListContentsScreen.tsx @@ -0,0 +1,289 @@ +import React, { useState } from 'react'; +import { + Text, + StyleSheet, + ScrollView, + TouchableOpacity, + ActivityIndicator, +} from 'react-native'; +import RNFS from 'react-native-fs'; +import { ResultCard } from '../components/ResultCard'; +import { CodePreview } from '../components/CodePreview'; +import { ensureDir, listFilesRecursive } from '../utils/fileSystem'; +import { + zip, + zipWithPassword, + listContents, + unzip, + unzipWithPassword, + type ZipEntry, +} from 'react-native-zip-archive'; + +const SOURCE_CODE = `import { listContents, unzip, unzipWithPassword } from 'react-native-zip-archive'; + +const entries = await listContents(sourceZip); +await unzip(sourceZip, outputFolder, ['readme.md', 'docs']); +await unzipWithPassword(sourceZip, outputFolder, 'secret', ['readme.md']); +`; + +export default function ListContentsScreen() { + const [loading, setLoading] = useState(false); + const [entries, setEntries] = useState([]); + const [extractedFiles, setExtractedFiles] = useState([]); + const [resultTitle, setResultTitle] = useState('Result'); + const [result, setResult] = useState(''); + const [notExtracted, setNotExtracted] = useState([]); + const [error, setError] = useState(''); + const [zipPath, setZipPath] = useState(''); + + const createPlainDemoZip = async () => { + const dir = RNFS.DocumentDirectoryPath + '/demo-list/'; + await ensureDir(dir); + await ensureDir(dir + 'docs/'); + await RNFS.writeFile(dir + 'hello.txt', 'Hello from zip!', 'utf8'); + await RNFS.writeFile(dir + 'readme.md', '# Demo', 'utf8'); + await RNFS.writeFile(dir + 'docs/guide.md', '# Guide', 'utf8'); + const target = RNFS.DocumentDirectoryPath + '/demo-list-sample.zip'; + try { + if (await RNFS.exists(target)) await RNFS.unlink(target); + } catch {} + await zip(dir, target, 0); + return target; + }; + + const createPasswordDemoZip = async () => { + const dir = RNFS.DocumentDirectoryPath + '/demo-list-pw/'; + await ensureDir(dir); + await ensureDir(dir + 'docs/'); + await RNFS.writeFile(dir + 'hello.txt', 'Hello from zip!', 'utf8'); + await RNFS.writeFile(dir + 'readme.md', '# Demo', 'utf8'); + await RNFS.writeFile(dir + 'docs/guide.md', '# Guide', 'utf8'); + const target = RNFS.DocumentDirectoryPath + '/demo-list-password.zip'; + try { + if (await RNFS.exists(target)) await RNFS.unlink(target); + } catch {} + await zipWithPassword(dir, target, 'secret', 'STANDARD', 0); + return target; + }; + + const summarizeExtraction = (files: string[]) => { + const normalized = files.map((f) => f.replace(/\\/g, '/')); + const missing = ['hello.txt'].filter( + (name) => !normalized.some((f) => f === name || f.endsWith('/' + name)) + ); + return { files: normalized, missing }; + }; + + const handleList = async () => { + setLoading(true); + setError(''); + setEntries([]); + setExtractedFiles([]); + setNotExtracted([]); + setResult(''); + try { + const path = await createPlainDemoZip(); + setZipPath(path); + const listed = await listContents(path); + setEntries(listed); + setResultTitle('Listed Entries'); + const names = listed.map((e) => e.path.replace(/\\/g, '/')).join(', '); + setResult(`Listed ${listed.length} entries: ${names}`); + } catch (e: any) { + setError(e?.message || String(e)); + } finally { + setLoading(false); + } + }; + + const handleSelective = async () => { + if (!zipPath) return; + setLoading(true); + setError(''); + setExtractedFiles([]); + setNotExtracted([]); + try { + const out = RNFS.DocumentDirectoryPath + '/selective/' + Date.now() + '/'; + await ensureDir(out); + const path = await unzip(zipPath, out, ['readme.md', 'docs']); + const { files, missing } = summarizeExtraction(await listFilesRecursive(out)); + setExtractedFiles(files); + setNotExtracted(missing); + setResultTitle('Selective Extract'); + setResult(`Selective extract to ${path}`); + } catch (e: any) { + setError(e?.message || String(e)); + } finally { + setLoading(false); + } + }; + + const handlePasswordSelective = async () => { + setLoading(true); + setError(''); + setEntries([]); + setExtractedFiles([]); + setNotExtracted([]); + setResult(''); + try { + const source = await createPasswordDemoZip(); + const out = RNFS.DocumentDirectoryPath + '/selective-pw/' + Date.now() + '/'; + await ensureDir(out); + const path = await unzipWithPassword(source, out, 'secret', ['readme.md']); + const { files, missing } = summarizeExtraction(await listFilesRecursive(out)); + setExtractedFiles(files); + setNotExtracted(missing); + setResultTitle('Password Selective Extract Done'); + setResult(`Password selective extract to ${path}`); + } catch (e: any) { + setError(e?.message || String(e)); + } finally { + setLoading(false); + } + }; + + const entryMarkers = entries.flatMap((entry) => { + const path = entry.path.replace(/\\/g, '/'); + const markers = [`Contains ${path}`]; + const base = path.split('/').pop(); + if (base && base !== path) { + markers.push(`Contains ${base}`); + } + return markers; + }); + + return ( + + Demo: List Contents + + {loading ? ( + + ) : ( + Create Zip and List Contents + )} + + + Demo: Selective Extract + + {loading ? ( + + ) : ( + Extract Selected Entries + )} + + + Demo: Password Selective Extract + + {loading ? ( + + ) : ( + Password Selective Extract + )} + + + {result ? ( + + {result} + {entryMarkers.map((marker) => ( + + {marker} + + ))} + {entries.length > 0 && ( + <> + Entries: + {entries.map((entry) => ( + + • {entry.path} + {entry.isDirectory ? '/' : ''} ({entry.size} B) + + ))} + + )} + {extractedFiles.map((f) => ( + + Extracted {f} + + ))} + {notExtracted.map((f) => ( + + Skipped {f} + + ))} + + ) : null} + + {error ? ( + + {error} + + ) : null} + + + + ); +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: '#fff', + paddingHorizontal: 16, + paddingTop: 16, + }, + section: { + fontSize: 15, + fontWeight: '700', + marginTop: 16, + marginBottom: 8, + }, + actionBtn: { + backgroundColor: '#007AFF', + paddingVertical: 12, + borderRadius: 10, + alignItems: 'center', + }, + disabledBtn: { + backgroundColor: '#A1A1AA', + }, + actionText: { + color: '#fff', + fontWeight: '700', + }, + mono: { + fontFamily: 'Courier', + fontSize: 12, + color: '#1C1C1E', + }, + subHeading: { + marginTop: 8, + fontWeight: '700', + fontSize: 13, + }, + fileItem: { + fontSize: 13, + color: '#3A3A3C', + marginLeft: 4, + }, + marker: { + fontSize: 13, + color: '#1C1C1E', + fontWeight: '600', + marginTop: 4, + }, +}); diff --git a/specs/NativeZipArchive.ts b/specs/NativeZipArchive.ts index 5d653722..38c24e3e 100644 --- a/specs/NativeZipArchive.ts +++ b/specs/NativeZipArchive.ts @@ -1,14 +1,29 @@ import type { TurboModule } from 'react-native'; import { TurboModuleRegistry } from 'react-native'; +export type ZipEntry = { + path: string; + size: number; + compressedSize: number; + isDirectory: boolean; + isEncrypted: boolean; +}; + export interface Spec extends TurboModule { isPasswordProtected(file: string): Promise; - unzip(from: string, destinationPath: string, charset: string): Promise; + unzip( + from: string, + destinationPath: string, + charset: string, + entries?: Array | null + ): Promise; unzipWithPassword( from: string, destinationPath: string, - password: string + password: string, + entries?: Array | null ): Promise; + listContents(source: string, charset: string): Promise; zipFolder( from: string, destinationPath: string, @@ -35,6 +50,7 @@ export interface Spec extends TurboModule { ): Promise; getUncompressedSize(path: string, charset: string): Promise; unzipAssets(source: string, target: string): Promise; + cancel(): Promise; addListener(eventName: string): void; removeListeners(count: number): void; }