Browse Source

Added android implementation close #19

Ben Hsieh 8 years ago
parent
commit
1d3dcfae72

+ 19
- 1
src/android/src/main/java/com/RNFetchBlob/RNFetchBlob.java View File

45
 
45
 
46
     @ReactMethod
46
     @ReactMethod
47
     public void getEnvironmentDirs(Callback callback) {
47
     public void getEnvironmentDirs(Callback callback) {
48
-
49
         ReactApplicationContext ctx = this.getReactApplicationContext();
48
         ReactApplicationContext ctx = this.getReactApplicationContext();
50
         RNFetchBlobFS.getSystemfolders(ctx, callback);
49
         RNFetchBlobFS.getSystemfolders(ctx, callback);
50
+    }
51
 
51
 
52
+    @ReactMethod
53
+    public void createFile(String path, String content, String encode, Callback callback) {
54
+        RNFetchBlobFS.createFile(path, content, encode, callback);
52
     }
55
     }
53
 
56
 
54
     @ReactMethod
57
     @ReactMethod
56
         RNFetchBlobFS.unlink(path, callback);
59
         RNFetchBlobFS.unlink(path, callback);
57
     }
60
     }
58
 
61
 
62
+    @ReactMethod
63
+    public void mkdir(String path, Callback callback) {
64
+        RNFetchBlobFS.mkdir(path, callback);
65
+    }
66
+
59
     @ReactMethod
67
     @ReactMethod
60
     public void exists(String path, Callback callback) {
68
     public void exists(String path, Callback callback) {
61
         RNFetchBlobFS.exists(path, callback);
69
         RNFetchBlobFS.exists(path, callback);
86
         RNFetchBlobFS.writeChunk(streamId, data, callback);
94
         RNFetchBlobFS.writeChunk(streamId, data, callback);
87
     }
95
     }
88
 
96
 
97
+    @ReactMethod
98
+    public void closeStream(String streamId, Callback callback) {
99
+        RNFetchBlobFS.closeStream(streamId, callback);
100
+    }
101
+
102
+    @ReactMethod
103
+    public void removeSession(ReadableArray paths, Callback callback) {
104
+        RNFetchBlobFS.removeSession(paths, callback);
105
+    }
106
+
89
     @ReactMethod
107
     @ReactMethod
90
     /**
108
     /**
91
      * @param path Stream file path
109
      * @param path Stream file path

+ 68
- 30
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobFS.java View File

6
 import com.facebook.react.bridge.Arguments;
6
 import com.facebook.react.bridge.Arguments;
7
 import com.facebook.react.bridge.Callback;
7
 import com.facebook.react.bridge.Callback;
8
 import com.facebook.react.bridge.ReactApplicationContext;
8
 import com.facebook.react.bridge.ReactApplicationContext;
9
+import com.facebook.react.bridge.ReadableArray;
10
+import com.facebook.react.bridge.WritableArray;
9
 import com.facebook.react.bridge.WritableMap;
11
 import com.facebook.react.bridge.WritableMap;
10
 import com.facebook.react.modules.core.DeviceEventManagerModule;
12
 import com.facebook.react.modules.core.DeviceEventManagerModule;
11
 import com.loopj.android.http.Base64;
13
 import com.loopj.android.http.Base64;
34
     DeviceEventManagerModule.RCTDeviceEventEmitter emitter;
36
     DeviceEventManagerModule.RCTDeviceEventEmitter emitter;
35
     String encoding = "base64";
37
     String encoding = "base64";
36
     boolean append = false;
38
     boolean append = false;
37
-    FileOutputStream writeStreamInstance = null;
39
+    OutputStream writeStreamInstance = null;
38
     static HashMap<String, RNFetchBlobFS> fileStreams = new HashMap<>();
40
     static HashMap<String, RNFetchBlobFS> fileStreams = new HashMap<>();
39
 
41
 
40
     RNFetchBlobFS(ReactApplicationContext ctx) {
42
     RNFetchBlobFS(ReactApplicationContext ctx) {
50
     static public void getSystemfolders(ReactApplicationContext ctx, Callback callback) {
52
     static public void getSystemfolders(ReactApplicationContext ctx, Callback callback) {
51
         callback.invoke(
53
         callback.invoke(
52
                 // document folder
54
                 // document folder
53
-                String.valueOf(ctx.getFilesDir()),
55
+                String.valueOf(ctx.getFilesDir().getAbsolutePath()),
54
                 // cache folder
56
                 // cache folder
55
-                String.valueOf(ctx.getCacheDir()),
57
+                String.valueOf(ctx.getCacheDir().getAbsolutePath()),
56
                 // SD card folder
58
                 // SD card folder
57
-                String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)),
59
+                String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()),
58
                 // Download folder
60
                 // Download folder
59
-                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
61
+                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
60
         );
62
         );
61
     }
63
     }
62
 
64
 
106
                         }
108
                         }
107
                     } else if (encoding.equalsIgnoreCase("base64")) {
109
                     } else if (encoding.equalsIgnoreCase("base64")) {
108
                         while ((cursor = fs.read(buffer)) != -1) {
110
                         while ((cursor = fs.read(buffer)) != -1) {
109
-                            emitStreamEvent(eventName, "data", Base64.encodeToString(buffer, Base64.NO_WRAP));
111
+                            if(cursor < chunkSize) {
112
+                                byte [] copy = new byte[cursor];
113
+                                for(int i =0;i<cursor;i++) {
114
+                                    copy[i] = buffer[i];
115
+                                }
116
+                                emitStreamEvent(eventName, "data", Base64.encodeToString(copy, Base64.NO_WRAP));
117
+                            }
118
+                            else
119
+                                emitStreamEvent(eventName, "data", Base64.encodeToString(buffer, Base64.NO_WRAP));
110
                         }
120
                         }
111
                     } else {
121
                     } else {
112
                         String msg = "unrecognized encoding `" + encoding + "`";
122
                         String msg = "unrecognized encoding `" + encoding + "`";
147
             this.append = append;
157
             this.append = append;
148
             String streamId = UUID.randomUUID().toString();
158
             String streamId = UUID.randomUUID().toString();
149
             RNFetchBlobFS.fileStreams.put(streamId, this);
159
             RNFetchBlobFS.fileStreams.put(streamId, this);
160
+            this.writeStreamInstance = fs;
150
             callback.invoke(null, streamId);
161
             callback.invoke(null, streamId);
151
         } catch(Exception err) {
162
         } catch(Exception err) {
152
             callback.invoke("failed to create write stream at path `"+path+"` "+ err.getLocalizedMessage());
163
             callback.invoke("failed to create write stream at path `"+path+"` "+ err.getLocalizedMessage());
163
     static void writeChunk(String streamId, String data, Callback callback) {
174
     static void writeChunk(String streamId, String data, Callback callback) {
164
 
175
 
165
         RNFetchBlobFS fs = fileStreams.get(streamId);
176
         RNFetchBlobFS fs = fileStreams.get(streamId);
166
-        FileOutputStream stream = fs.writeStreamInstance;
177
+        OutputStream stream = fs.writeStreamInstance;
167
         byte [] chunk = RNFetchBlobFS.stringToBytes(data, fs.encoding);
178
         byte [] chunk = RNFetchBlobFS.stringToBytes(data, fs.encoding);
168
 
179
 
169
         try {
180
         try {
170
             stream.write(chunk);
181
             stream.write(chunk);
171
-            callback.invoke(null);
172
-        } catch (IOException e) {
182
+            callback.invoke();
183
+        } catch (Exception e) {
173
             callback.invoke(e.getLocalizedMessage());
184
             callback.invoke(e.getLocalizedMessage());
174
         }
185
         }
175
     }
186
     }
182
     static void closeStream(String streamId, Callback callback) {
193
     static void closeStream(String streamId, Callback callback) {
183
         try {
194
         try {
184
             RNFetchBlobFS fs = fileStreams.get(streamId);
195
             RNFetchBlobFS fs = fileStreams.get(streamId);
185
-            FileOutputStream stream = fs.writeStreamInstance;
186
-            stream.close();
187
-            stream = null;
196
+            OutputStream stream = fs.writeStreamInstance;
188
             fileStreams.remove(streamId);
197
             fileStreams.remove(streamId);
198
+            stream.close();
199
+            callback.invoke();
189
         } catch(Exception err) {
200
         } catch(Exception err) {
190
             callback.invoke(err.getLocalizedMessage());
201
             callback.invoke(err.getLocalizedMessage());
191
         }
202
         }
199
     static void unlink(String path, Callback callback) {
210
     static void unlink(String path, Callback callback) {
200
         try {
211
         try {
201
             boolean success = new File(path).delete();
212
             boolean success = new File(path).delete();
202
-            callback.invoke(success);
213
+            callback.invoke( null, success);
203
         } catch(Exception err) {
214
         } catch(Exception err) {
204
             if(err != null)
215
             if(err != null)
205
             callback.invoke(err.getLocalizedMessage());
216
             callback.invoke(err.getLocalizedMessage());
206
         }
217
         }
207
     }
218
     }
208
-
219
+    /**
220
+     * Make a folder
221
+     * @param path Source path
222
+     * @param callback  JS context callback
223
+     */
224
+    static void mkdir(String path, Callback callback) {
225
+        File dest = new File(path);
226
+        if(dest.exists()) {
227
+            callback.invoke("failed to create folder at `" + path + "` folder already exists");
228
+            return;
229
+        }
230
+        dest.mkdirs();
231
+        callback.invoke();
232
+    }
209
     /**
233
     /**
210
      * Copy file to destination path
234
      * Copy file to destination path
211
      * @param path Source path
235
      * @param path Source path
223
                 callback.invoke("source file at path`" + path + "` not exists");
247
                 callback.invoke("source file at path`" + path + "` not exists");
224
                 return;
248
                 return;
225
             }
249
             }
226
-            if(!new File(destFolder).exists())
227
-                new File(destFolder).mkdir();
250
+
228
             if(!new File(dest).exists())
251
             if(!new File(dest).exists())
229
                 new File(dest).createNewFile();
252
                 new File(dest).createNewFile();
230
 
253
 
236
             while ((len = in.read(buf)) > 0) {
259
             while ((len = in.read(buf)) > 0) {
237
                 out.write(buf, 0, len);
260
                 out.write(buf, 0, len);
238
             }
261
             }
239
-            in.close();
240
-            out.close();
241
-            callback.invoke(null);
262
+
242
         } catch (Exception err) {
263
         } catch (Exception err) {
243
             if(err != null)
264
             if(err != null)
244
                 callback.invoke(err.getLocalizedMessage());
265
                 callback.invoke(err.getLocalizedMessage());
245
         } finally {
266
         } finally {
246
             try {
267
             try {
247
                 in.close();
268
                 in.close();
248
-            } catch (IOException e) {
249
-                callback.invoke(e.getLocalizedMessage());
250
-            }
251
-            try {
252
                 out.close();
269
                 out.close();
270
+                callback.invoke();
253
             } catch (IOException e) {
271
             } catch (IOException e) {
254
                 callback.invoke(e.getLocalizedMessage());
272
                 callback.invoke(e.getLocalizedMessage());
255
             }
273
             }
269
             return;
287
             return;
270
         }
288
         }
271
         src.renameTo(new File(dest));
289
         src.renameTo(new File(dest));
272
-        callback.invoke(null);
290
+        callback.invoke();
273
     }
291
     }
274
 
292
 
275
     /**
293
     /**
279
      */
297
      */
280
     static void exists(String path, Callback callback) {
298
     static void exists(String path, Callback callback) {
281
         boolean exist = new File(path).exists();
299
         boolean exist = new File(path).exists();
282
-        boolean isDir = false;
283
-        if(exist)
284
-         isDir = new File(path).isDirectory();
300
+        boolean isDir = new File(path).isDirectory();;
285
         callback.invoke(exist, isDir);
301
         callback.invoke(exist, isDir);
286
     }
302
     }
287
 
303
 
292
      */
308
      */
293
     static void ls(String path, Callback callback) {
309
     static void ls(String path, Callback callback) {
294
         File src = new File(path);
310
         File src = new File(path);
295
-        if(!src.exists() || !src.isDirectory())
296
-            callback.invoke("failed to list path `"+path+"` for it is not exist or it is not a folder");
311
+        if(!src.exists() || !src.isDirectory()) {
312
+            callback.invoke("failed to list path `" + path + "` for it is not exist or it is not a folder");
313
+            return;
314
+        }
297
         String [] files = new File(path).list();
315
         String [] files = new File(path).list();
298
-        callback.invoke(null, files);
316
+        WritableArray arg = Arguments.createArray();
317
+        for(String i : files) {
318
+            arg.pushString(i);
319
+        }
320
+        callback.invoke(null, arg);
299
     }
321
     }
300
 
322
 
301
     /**
323
     /**
321
         }
343
         }
322
     }
344
     }
323
 
345
 
346
+    static void removeSession(ReadableArray paths, Callback callback) {
347
+
348
+        AsyncTask<ReadableArray, Integer, Integer> task = new AsyncTask<ReadableArray, Integer, Integer>() {
349
+            @Override
350
+            protected Integer doInBackground(ReadableArray ...paths) {
351
+                for(int i =0; i< paths[0].size(); i++) {
352
+                    File f = new File(paths[0].getString(i));
353
+                    if(f.exists())
354
+                        f.delete();
355
+                }
356
+                return paths[0].size();
357
+            }
358
+        };
359
+        task.execute(paths);
360
+    }
361
+
324
     /**
362
     /**
325
      * String to byte converter method
363
      * String to byte converter method
326
      * @param data  Raw data in string format
364
      * @param data  Raw data in string format