Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion packages/zip/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ A plugin to zip and unzip files.
* [Zip a folder](#zip-a-folder)
* [Get zip request progress](#get-zip-request-progress)
* [Get unzip request progress](#get-unzip-request-progress)
* [Platform notes](#platform-notes)
* [API](#api)
* [Zip class](#zip-class)
* [debugEnabled](#debugenabled)
Expand Down Expand Up @@ -113,6 +114,29 @@ function onUnZipProgress(percent: number) {
}
```

## Platform notes

Supported on iOS, macOS, Android, Windows and Linux.

**Windows** uses a built-in C# engine, compiled into the app, that relies on .NET's `DeflateStream` and cryptography APIs. It needs no extra dependencies.

**Linux** uses a bundled, pinned copy of [minizip-ng](https://github.com/zlib-ng/minizip-ng), linked against the system zlib, GLib and OpenSSL (`libcrypto`). These are part of the base system on current desktop distributions, so end users don't need to install anything. Building an app that uses this plugin requires the OpenSSL development headers:

```bash
sudo apt install libssl-dev # Debian / Ubuntu / Pop!_OS
sudo dnf install openssl-devel # Fedora
```

On both platforms:

- **Background work:** zipping and unzipping run on a background thread and stream data, so memory use doesn't depend on archive or file size. Archives over 4 GB (ZIP64) are supported.
- **Passwords:**
- Archives created with a `password` use WinZip AES-256 encryption, the same as iOS and Android.
- When unzipping, both AES and legacy ZipCrypto archives are supported, and AES entries are authenticated.
- **Extraction safety:**
- Entries that would land outside the destination folder are skipped, and so are symbolic links.
- Each file is written to a temporary file first and only moved into place after it has been verified, so a failed extraction never replaces an existing file.

## API

### Zip class
Expand Down Expand Up @@ -163,7 +187,7 @@ Extracts all the files from the zip file specified in the `archive` property of
| `directory` | `string`| _Optional_: The path to extract the files to.
| `archive` | `string` | _Optional_: The path of the zip file.
| `onProgress` | `(progress: number) => void` | _Optional_: Unzip request progress listener.
| `overwrite`| `boolean` | _Optional_: (`iOS-only`)
| `overwrite`| `boolean` | _Optional_: Overwrite existing files (default `true`). Supported on iOS, macOS, Windows and Linux.
| `password`| `string` | _Optional_: The password used to protect the zip file.

## License
Expand Down
File renamed without changes.
68 changes: 68 additions & 0 deletions packages/zip/index.linux.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { Folder, File, path, knownFolders } from '@nativescript/core';
import { UnZipOptions, ZipOptions } from '.';

declare function nszip_zip(directory: string, archive: string, keepParent: number, password: string | null, progress: interop.Pointer, complete: interop.Pointer): void;
declare function nszip_unzip(archive: string, destination: string, overwrite: number, password: string | null, progress: interop.Pointer, complete: interop.Pointer): void;
declare const nativescript: { ref(): void; unref(): void };

function uuid(): string {
return (globalThis as any).crypto?.randomUUID?.() ?? `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`;
}

function run(onProgress: ((percent: number) => void) | undefined, start: (progress: interop.Pointer, complete: interop.Pointer) => void): Promise<void> {
return new Promise((resolve, reject) => {
const native: any = interop;
const progressFn = (percent: number) => {
if (typeof onProgress === 'function') {
onProgress(percent);
}
};
const completeFn = (error: any) => {
const failure = error ? native.stringFromCString(error) : null;
setTimeout(() => {
native.release(progressFn);
native.release(completeFn);
nativescript.unref();
});
if (failure) {
reject(failure);
} else {
resolve();
}
};
const progressPtr = native.callback(progressFn, { returns: native.types.void, args: [native.types.int32] });
const completePtr = native.callback(completeFn, { returns: native.types.void, args: [native.types.pointer] });
nativescript.ref();
start(progressPtr, completePtr);
});
}

export class Zip {
static debugEnabled = false;

private static debug(arg) {
if (this.debugEnabled && console && console.log) {
console.log(arg);
}
}

public static zip(options: ZipOptions): Promise<string> {
if (!options?.directory || !Folder.exists(options.directory)) {
return Promise.reject('Directory does not exist, invalid directory path: ' + options?.directory);
}
const archive = options.archive ?? path.join(knownFolders.temp().path, `${uuid()}_archive.zip`);
const keepParent = (options.keepParent ?? true) ? 1 : 0;
this.debug('Zip.zip - folder=' + options.directory + '\n' + 'Zip.zip - destinationPath=' + archive);
return run(options.onProgress, (progress, complete) => nszip_zip(options.directory, archive, keepParent, options.password || null, progress, complete)).then(() => archive);
}

public static unzip(options: UnZipOptions): Promise<any> {
if (!options?.archive || !File.exists(options.archive)) {
return Promise.reject(`File does not exist, invalid archive path: ${options?.archive}`);
}
const destination = options.directory ?? path.join(knownFolders.temp().path, uuid());
const overwrite = (options.overwrite ?? true) ? 1 : 0;
this.debug(`Zip.unzip - archive=${options.archive}`);
return run(options.onProgress, (progress, complete) => nszip_unzip(options.archive, destination, overwrite, options.password || null, progress, complete)).then(() => destination);
}
}
57 changes: 57 additions & 0 deletions packages/zip/index.windows.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Folder, File, path, knownFolders } from '@nativescript/core';
import { UnZipOptions, ZipOptions } from '.';

declare const NativeScriptZip: any;
declare const NSWinRT: any;

function uuid(): string {
return (globalThis as any).crypto?.randomUUID?.() ?? `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`;
}

function message(e: any): string {
return typeof e === 'string' ? e : (e?.message ?? String(e));
}

function progress(options: { onProgress?: (progress: number) => void }) {
return (percent: number) => {
if (typeof options.onProgress === 'function') {
options.onProgress(percent);
}
};
}

export class Zip {
static debugEnabled = false;

private static debug(arg) {
if (this.debugEnabled && console && console.log) {
console.log(arg);
}
}

public static zip(options: ZipOptions): Promise<string> {
if (!options?.directory || !Folder.exists(options.directory)) {
return Promise.reject('Directory does not exist, invalid directory path: ' + options?.directory);
}
const archive = options.archive ?? path.join(knownFolders.temp().path, `${uuid()}_archive.zip`);
this.debug('Zip.zip - folder=' + options.directory + '\n' + 'Zip.zip - destinationPath=' + archive);
const task = NativeScriptZip.ZipArchiver.ZipAsync(options.directory, archive, options.keepParent ?? true, options.password ?? '', progress(options));
return NSWinRT.dotnet.taskToPromise(task).then(
() => archive,
(e) => Promise.reject(message(e)),
);
}

public static unzip(options: UnZipOptions): Promise<any> {
if (!options?.archive || !File.exists(options.archive)) {
return Promise.reject(`File does not exist, invalid archive path: ${options?.archive}`);
}
const destination = options.directory ?? path.join(knownFolders.temp().path, uuid());
this.debug(`Zip.unzip - archive=${options.archive}`);
const task = NativeScriptZip.ZipArchiver.UnzipAsync(options.archive, destination, options.overwrite ?? true, options.password ?? '', progress(options));
return NSWinRT.dotnet.taskToPromise(task).then(
() => destination,
(e) => Promise.reject(message(e)),
);
}
}
10 changes: 10 additions & 0 deletions packages/zip/nativescript.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,14 @@ export default {
},
],
},
macos: {
SPMPackages: [
{
name: 'ZipArchive',
libs: ['ZipArchive'],
repositoryURL: 'https://github.com/NathanWalker/ZipArchive',
version: '3.0.0',
},
],
},
} as NativeScriptConfig;
12 changes: 9 additions & 3 deletions packages/zip/package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
{
"name": "@nativescript/zip",
"version": "7.0.1",
"version": "7.1.0-alpha.0",
"description": "A simple utility class for zipping and unzipping files in NativeScript",
"main": "index",
"typings": "index.d.ts",
"nativescript": {
"platforms": {
"ios": "6.0.0",
"android": "6.0.0"
"macos": "6.0.0",
"android": "6.0.0",
"windows": "9.1.0",
"linux": "0.1.0-alpha.2"
}
},
"repository": {
Expand All @@ -19,7 +22,10 @@
"JavaScript",
"TypeScript",
"iOS",
"Android"
"macOS",
"Android",
"Windows",
"Linux"
],
"author": {
"name": "NativeScript",
Expand Down
28 changes: 28 additions & 0 deletions packages/zip/platforms/linux/include/nszip.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#ifndef NSZIP_H
#define NSZIP_H

#include <stdint.h>

#if defined(__GNUC__)
#define NSZIP_EXPORT __attribute__((visibility("default")))
#else
#define NSZIP_EXPORT
#endif

#ifdef __cplusplus
extern "C" {
#endif

typedef void (*nszip_progress_callback)(int32_t percent);

typedef void (*nszip_complete_callback)(const char *error);

NSZIP_EXPORT void nszip_zip(const char *directory, const char *archive, int32_t keep_parent, const char *password, nszip_progress_callback progress, nszip_complete_callback complete);

NSZIP_EXPORT void nszip_unzip(const char *archive, const char *destination, int32_t overwrite, const char *password, nszip_progress_callback progress, nszip_complete_callback complete);

#ifdef __cplusplus
}
#endif

#endif
4 changes: 4 additions & 0 deletions packages/zip/platforms/linux/native.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"pkg-config": ["zlib", "glib-2.0", "libcrypto"],
"cflags": ["-O2", "-std=gnu11", "-fvisibility=hidden", "-Wno-deprecated-declarations", "-DHAVE_ZLIB", "-DZLIB_COMPAT", "-DHAVE_PKCRYPT", "-DHAVE_WZAES", "-DHAVE_GETRANDOM", "-D_POSIX_C_SOURCE=200809L", "-D_DEFAULT_SOURCE", "-D_BSD_SOURCE"]
}
17 changes: 17 additions & 0 deletions packages/zip/platforms/linux/src/minizip-ng/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
Condition of use and distribution are the same as zlib:

This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgement in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
7 changes: 7 additions & 0 deletions packages/zip/platforms/linux/src/minizip-ng/VENDORED.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
minizip-ng 4.2.2 (https://github.com/zlib-ng/minizip-ng/releases/tag/4.2.2), zlib license (see LICENSE).

Only the sources for zlib + OpenSSL + PKWARE/WinZip AES encryption are included; `mz_config.h` replaces the CMake-generated header.

Local changes:
- `mz_zip.c`: `mz_zip_entry_read_close` also closes the WinZip AES stream.
- `mz_crypt_openssl.c`: `openssl/engine.h` is only included for OpenSSL < 1.1 (it is absent on systems built without the ENGINE API).
Loading
Loading