Skip to content

Commit 16cd808

Browse files
authored
Merge pull request #28 from plrthink/add-example
Add example
2 parents 70b0ea9 + ae6366a commit 16cd808

File tree

90 files changed

+5717
-298
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

90 files changed

+5717
-298
lines changed

.npmignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,5 @@ project.xcworkspace
2626
#
2727
node_modules/
2828
npm-debug.log
29+
30+
example/

README.md

Lines changed: 35 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -2,102 +2,64 @@
22

33
Zip archive utility for react-native
44

5+
> ### Important
6+
> If you're using react-native after 0.40.0 on iOS, be sure to use > 0.1.0 of this package.
7+
58
## Installation
69

710
```bash
811
npm install react-native-zip-archive --save
12+
react-native link react-native-zip-archive
913
```
1014

11-
## Getting started - iOS
12-
13-
1. In Xcode, in the project navigator right click `Libraries``Add Files to [your project's name]`
14-
2. Go to `node_modules``react-native-zip-archive` and add `RNZipArchive.xcodeproj`
15-
3. Add `libRNZipArchive.a` (from 'Products' under RNZipArchive.xcodeproj) to your project's `Build Phases``Link Binary With Libraries` phase
16-
4. Add the `libz` library to your target
17-
5. Look for Header Search Paths and make sure it contains both `$(SRCROOT)/../react-native/React` and `$(SRCROOT)/../../React` - mark both as recursive
18-
6. Run your project (`CMD+R`)
19-
20-
Warning: If you're using [rnpm](https://github.com/rnpm/rnpm) to link this module, you also need manually link `libz` library to your target otherwise your project wouldn't compile.
21-
22-
## Getting started - Android
23-
24-
* Edit `android/settings.gradle` to look like this (without the +):
25-
26-
```diff
27-
rootProject.name = 'MyApp'
28-
29-
include ':app'
30-
31-
+ include ':react-native-zip-archive'
32-
+ project(':react-native-zip-archive').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-zip-archive/android')
33-
```
34-
35-
* Edit `android/app/build.gradle` (note: **app** folder) to look like this:
36-
37-
```diff
38-
apply plugin: 'com.android.application'
39-
40-
android {
41-
...
42-
}
43-
44-
dependencies {
45-
compile fileTree(dir: 'libs', include: ['*.jar'])
46-
compile 'com.android.support:appcompat-v7:23.0.0'
47-
compile 'com.facebook.react:react-native:0.16.+'
48-
+ compile project(':react-native-zip-archive')
49-
}
50-
```
51-
52-
* Edit your `MainActivity.java` (deep in `android/app/src/main/java/...`) to look like this (note **two** places to edit):
53-
54-
```diff
55-
package com.myapp;
56-
57-
+ import com.rnziparchive.RNZipArchivePackage;
58-
59-
....
60-
61-
@Override
62-
protected List<ReactPackage> getPackages() {
63-
return Arrays.<ReactPackage>asList(
64-
new MainReactPackage(),
65-
+ new RNZipArchivePackage()
66-
);
67-
}
68-
69-
}
70-
```
71-
7215
## Usage
7316

74-
require it in your file
17+
import it into your code
7518

7619
```js
77-
const ZipArchive = require('react-native-zip-archive')
20+
import { zip, unzip, unzipAssets, subscribe } from 'react-native-zip-archive'
7821
```
7922

8023
you may also want to use something like [react-native-fs](https://github.com/johanneslumpe/react-native-fs) to access the file system (check its repo for more information)
8124

8225
```js
83-
const RNFS = require('react-native-fs')
26+
import { MainBundlePath, DocumentDirectoryPath } from 'react-native-fs'
8427
```
8528

8629
## API
8730

31+
**zip(source: string, target: string): Promise**
32+
33+
> zip source to target
34+
35+
Example
36+
37+
```js
38+
const targetPath = `${DocumentDirectoryPath}/myFile.zip`
39+
const sourcePath = DocumentDirectoryPath
40+
41+
zip(sourcePath, targetPath)
42+
.then((path) => {
43+
console.log(`unzip completed at ${path}`)
44+
})
45+
.catch((error) => {
46+
console.log(error)
47+
})
48+
```
49+
8850
**unzip(source: string, target: string): Promise**
8951

9052
> unzip from source to target
9153
9254
Example
9355

9456
```js
95-
let sourcePath = 'path_to_your_zip_file'
96-
let targetPath = RNFS.DocumentDirectoryPath
57+
const sourcePath = `${DocumentDirectoryPath}/myFile.zip`
58+
const targetPath = DocumentDirectoryPath
9759

98-
ZipArchive.unzip(sourcePath, targetPath)
99-
.then(() => {
100-
console.log('unzip completed!')
60+
unzip(sourcePath, targetPath)
61+
.then((path) => {
62+
console.log(`unzip completed at ${path}`)
10163
})
10264
.catch((error) => {
10365
console.log(error)
@@ -113,10 +75,10 @@ ZipArchive.unzip(sourcePath, targetPath)
11375
`assetPath` is the relative path to the file inside the pre-bundled assets folder, e.g. `folder/myFile.zip`. Do not pass an absolute directory.
11476

11577
```js
116-
const assetPath = 'folder/myFile.zip'
117-
const targetPath = RNFS.DocumentDirectoryPath
78+
const assetPath = `${DocumentDirectoryPath}/myFile.zip`
79+
const targetPath = DocumentDirectoryPath
11880

119-
ZipArchive.unzipAssets(assetPath, targetPath)
81+
unzipAssets(assetPath, targetPath)
12082
.then(() => {
12183
console.log('unzip completed!')
12284
})
@@ -137,7 +99,7 @@ Your callback will be passed an object with the following fields:
13799

138100
```js
139101
componentWillMount() {
140-
this.zipProgress = ZipArchive.subscribe((e) => {
102+
this.zipProgress = subscribe((e) => {
141103
this.setState({ zipProgress: e.progress })
142104
})
143105
}

android/build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,5 @@ repositories {
3030
}
3131

3232
dependencies {
33-
compile 'com.facebook.react:react-native:0.12.+'
33+
compile "com.facebook.react:react-native:+"
3434
}

android/src/main/java/com/rnziparchive/RNZipArchiveModule.java

Lines changed: 40 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import android.util.Log;
55

66
import com.facebook.react.bridge.Arguments;
7-
import com.facebook.react.bridge.Callback;
7+
import com.facebook.react.bridge.Promise;
88
import com.facebook.react.bridge.ReactApplicationContext;
99
import com.facebook.react.bridge.ReactContextBaseJavaModule;
1010
import com.facebook.react.bridge.ReactMethod;
@@ -43,21 +43,27 @@ public String getName() {
4343
}
4444

4545
@ReactMethod
46-
public void unzip(String zipFilePath, String destDirectory, Callback callback) {
46+
public void unzip(String zipFilePath, String destDirectory, Promise promise) {
4747
FileInputStream inputStream;
4848
File file;
4949
try {
5050
inputStream = new FileInputStream(zipFilePath);
5151
file = new File(zipFilePath);
5252
} catch (FileNotFoundException | NullPointerException e) {
53-
callback.invoke(makeErrorPayload("Couldn't open file " + zipFilePath + ". ", e));
53+
promise.reject(null, "Couldn't open file " + zipFilePath + ". ");
5454
return;
5555
}
56-
unzipStream(zipFilePath, destDirectory, inputStream, file.length(), callback);
56+
try {
57+
unzipStream(zipFilePath, destDirectory, inputStream, file.length());
58+
} catch (Exception ex) {
59+
promise.reject(null, ex.getMessage());
60+
return;
61+
}
62+
promise.resolve(destDirectory);
5763
}
5864

5965
@ReactMethod
60-
public void unzipAssets(String assetsPath, String destDirectory, Callback completionCallback) {
66+
public void unzipAssets(String assetsPath, String destDirectory, Promise promise) {
6167
InputStream assetsInputStream;
6268
long size;
6369

@@ -66,15 +72,21 @@ public void unzipAssets(String assetsPath, String destDirectory, Callback comple
6672
AssetFileDescriptor fileDescriptor = getReactApplicationContext().getAssets().openFd(assetsPath);
6773
size = fileDescriptor.getLength();
6874
} catch (IOException e) {
69-
completionCallback.invoke(makeErrorPayload(String.format("Asset file `%s` could not be opened", assetsPath), e));
75+
promise.reject(null, String.format("Asset file `%s` could not be opened", assetsPath));
7076
return;
7177
}
7278

73-
unzipStream(assetsPath, destDirectory, assetsInputStream, size, completionCallback);
79+
try {
80+
unzipStream(assetsPath, destDirectory, assetsInputStream, size);
81+
} catch (Exception ex) {
82+
promise.reject(null, ex.getMessage());
83+
return;
84+
}
85+
promise.resolve(destDirectory);
7486
}
7587

7688
@ReactMethod
77-
public void zip(String fileOrDirectory, String destDirectory, Callback callback) {
89+
public void zip(String fileOrDirectory, String destDirectory, Promise promise) {
7890
List<String> filePaths = new ArrayList<>();
7991
File file;
8092
try {
@@ -92,14 +104,21 @@ public void zip(String fileOrDirectory, String destDirectory, Callback callback)
92104
throw new FileNotFoundException(fileOrDirectory);
93105
}
94106
} catch (FileNotFoundException | NullPointerException e) {
95-
callback.invoke(makeErrorPayload("Couldn't open file/directory " + fileOrDirectory + ". ", e));
107+
promise.reject(null, "Couldn't open file/directory " + fileOrDirectory + ".");
96108
return;
97109
}
98110

99-
zipStream(filePaths.toArray(new String[filePaths.size()]), destDirectory, filePaths.size(), callback);
111+
try {
112+
zipStream(filePaths.toArray(new String[filePaths.size()]), destDirectory, filePaths.size());
113+
} catch (Exception ex) {
114+
promise.reject(null, ex.getMessage());
115+
return;
116+
}
117+
118+
promise.resolve(destDirectory);
100119
}
101120

102-
private void zipStream(String[] files, String destFile, long totalSize, Callback completionCallback) {
121+
private void zipStream(String[] files, String destFile, long totalSize) throws Exception {
103122
try {
104123
if (destFile.contains("/")) {
105124
File destDir = new File(destFile.substring(0, destFile.lastIndexOf("/")));
@@ -136,11 +155,10 @@ private void zipStream(String[] files, String destFile, long totalSize, Callback
136155
}
137156
updateProgress(1, 1, destFile); // force 100%
138157
out.close();
139-
completionCallback.invoke(null, null);
140158
} catch (Exception ex) {
141159
ex.printStackTrace();
142160
updateProgress(0, 1, destFile); // force 0%
143-
completionCallback.invoke(makeErrorPayload(String.format("Couldn't zip %s", destFile), ex));
161+
throw new Exception(String.format("Couldn't zip %s", destFile));
144162
}
145163
}
146164

@@ -161,7 +179,7 @@ private List<File> getSubFiles(File baseDir, boolean isContainFolder) {
161179
return fileList;
162180
}
163181

164-
private void unzipStream(String zipFilePath, String destDirectory, InputStream inputStream, long totalSize, Callback completionCallback) {
182+
private void unzipStream(String zipFilePath, String destDirectory, InputStream inputStream, long totalSize) throws Exception {
165183
try {
166184
File destDir = new File(destDirectory);
167185
if (!destDir.exists()) {
@@ -176,17 +194,17 @@ private void unzipStream(String zipFilePath, String destDirectory, InputStream i
176194

177195
updateProgress(0, 1, zipFilePath); // force 0%
178196
File fout=null;
179-
while((entry = zipIn.getNextEntry())!=null){
180-
if(entry.isDirectory()) continue;
197+
while((entry = zipIn.getNextEntry())!=null){
198+
if(entry.isDirectory()) continue;
181199
fout=new File(destDirectory, entry.getName());
182200
if(!fout.exists()){
183-
(new File(fout.getParent())).mkdirs();
184-
}
201+
(new File(fout.getParent())).mkdirs();
202+
}
185203
FileOutputStream out=new FileOutputStream(fout);
186204
BufferedOutputStream Bout=new BufferedOutputStream(out);
187-
int b;
205+
int b;
188206
while((b=bin.read())!=-1){
189-
Bout.write(b);
207+
Bout.write(b);
190208
}
191209
Bout.close();
192210
out.close();
@@ -195,14 +213,13 @@ private void unzipStream(String zipFilePath, String destDirectory, InputStream i
195213
updateProgress(1, 1, zipFilePath); // force 100%
196214
bin.close();
197215
zipIn.close();
198-
completionCallback.invoke(null, null);
199216
} catch (Exception ex) {
200217
ex.printStackTrace();
201218
updateProgress(0, 1, zipFilePath); // force 0%
202-
completionCallback.invoke(makeErrorPayload(String.format("Couldn't extract %s", zipFilePath), ex));
219+
throw new Exception(String.format("Couldn't extract %s", zipFilePath));
203220
}
204221
}
205-
222+
206223
private void updateProgress(long extractedBytes, long totalSize, String zipFilePath) {
207224
double progress = (double) extractedBytes / (double) totalSize;
208225
Log.d(TAG, String.format("updateProgress: %.0f%%", progress * 100));
@@ -235,10 +252,4 @@ private long extractFile(ZipInputStream zipIn, String filePath) throws IOExcepti
235252

236253
return size;
237254
}
238-
239-
private WritableMap makeErrorPayload(String message, Exception ex) {
240-
WritableMap error = Arguments.createMap();
241-
error.putString("message", String.format("%s (%s)", message, ex.getMessage()));
242-
return error;
243-
}
244255
}

example/.babelrc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"presets": ["react-native"]
3+
}

example/.buckconfig

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
2+
[android]
3+
target = Google Inc.:Google APIs:23
4+
5+
[maven_repositories]
6+
central = https://repo1.maven.org/maven2

example/.flowconfig

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
[ignore]
2+
; We fork some components by platform
3+
.*/*[.]android.js
4+
5+
; Ignore "BUCK" generated dirs
6+
<PROJECT_ROOT>/\.buckd/
7+
8+
; Ignore unexpected extra "@providesModule"
9+
.*/node_modules/.*/node_modules/fbjs/.*
10+
11+
; Ignore duplicate module providers
12+
; For RN Apps installed via npm, "Libraries" folder is inside
13+
; "node_modules/react-native" but in the source repo it is in the root
14+
.*/Libraries/react-native/React.js
15+
.*/Libraries/react-native/ReactNative.js
16+
17+
[include]
18+
19+
[libs]
20+
node_modules/react-native/Libraries/react-native/react-native-interface.js
21+
node_modules/react-native/flow
22+
flow/
23+
24+
[options]
25+
module.system=haste
26+
27+
experimental.strict_type_args=true
28+
29+
munge_underscores=true
30+
31+
module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub'
32+
33+
suppress_type=$FlowIssue
34+
suppress_type=$FlowFixMe
35+
suppress_type=$FixMe
36+
37+
suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(3[0-6]\\|[1-2][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)
38+
suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(3[0-6]\\|1[0-9]\\|[1-2][0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+
39+
suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy
40+
41+
unsafe.enable_getters_and_setters=true
42+
43+
[version]
44+
^0.36.0

example/.gitattributes

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
*.pbxproj -text

0 commit comments

Comments
 (0)