react-native-fs-turbo 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,458 @@
1
+ /*
2
+ The MIT License (MIT)
3
+
4
+ Copyright (c) 2015 Johannes Lumpe
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ Modified by Sergei Kazakov on 31.10.24.
17
+ */
18
+
19
+ package com.cmpayc.rnfsturbo;
20
+
21
+ import android.content.Context;
22
+ import android.content.res.AssetFileDescriptor;
23
+ import android.content.res.AssetManager;
24
+ import android.media.MediaScannerConnection;
25
+ import android.net.Uri;
26
+ import android.os.Environment;
27
+ import android.os.StatFs;
28
+ import android.util.SparseArray;
29
+
30
+ import java.io.File;
31
+ import java.io.FileNotFoundException;
32
+ import java.io.IOException;
33
+ import java.io.InputStream;
34
+ import java.io.OutputStream;
35
+ import java.net.URL;
36
+ import java.util.ArrayList;
37
+ import java.util.HashMap;
38
+ import java.util.Map;
39
+
40
+ public class RNFSTurboPlatformHelper {
41
+
42
+ public static String tag = "RNFSTurboPlatformHelper";
43
+
44
+ public static SparseArray<RNFSTurboDownloader> downloaders = new SparseArray<>();
45
+ public static SparseArray<RNFSTurboUploader> uploaders = new SparseArray<>();
46
+
47
+ public static native void downloadCompleteCallback(int jobId, int statusCode, double bytesWritten);
48
+
49
+ public static native void downloadErrorCallback(int jobId, String error);
50
+
51
+ public static native void downloadBeginCallback(int jobId, int statusCode, double contentLength, HashMap<String, String> headers);
52
+
53
+ public static native void downloadProgressCallback(int jobId, double contentLength, double bytesWritten);
54
+
55
+ public static native void uploadCompleteCallback(int jobId, int statusCode, HashMap<String, String> headers, String body);
56
+
57
+ public static native void uploadErrorCallback(int jobId, String error);
58
+
59
+ public static native void uploadBeginCallback(int jobId);
60
+
61
+ public static native void uploadProgressCallback(int jobId, double totalBytesExpectedToSend, double totalBytesSent);
62
+
63
+ public static native void scanCallback(int jobId, String path);
64
+
65
+ private Context context;
66
+
67
+ public RNFSTurboPlatformHelper(Context ctx) {
68
+ context = ctx;
69
+ }
70
+
71
+ public String[] readDirAssets(String dirPath) {
72
+ ArrayList<String> filesList = new ArrayList<String>();
73
+ try {
74
+ AssetManager assetManager = context.getAssets();
75
+ String[] list = assetManager.list(dirPath);
76
+
77
+ for (String childFile : list) {
78
+ filesList.add(childFile);
79
+ String path = dirPath.isEmpty() ? childFile : String.format("%s/%s", dirPath, childFile); // don't allow / at the start when directory is ""
80
+ filesList.add(path);
81
+ int length = 0;
82
+ boolean isDirectory = true;
83
+ try {
84
+ AssetFileDescriptor assetFileDescriptor = assetManager.openFd(path);
85
+ if (assetFileDescriptor != null) {
86
+ length = (int) assetFileDescriptor.getLength();
87
+ assetFileDescriptor.close();
88
+ isDirectory = false;
89
+ }
90
+ } catch (IOException ex) {
91
+ isDirectory = !ex.getMessage().contains("compressed");
92
+ }
93
+ filesList.add(String.valueOf(length));
94
+ filesList.add(isDirectory ? "1" : "0");
95
+ }
96
+ } catch (IOException e) {
97
+ String[] files = new String[1];
98
+ files[0] = "-1";
99
+ return files;
100
+ }
101
+ return filesList.toArray(new String[0]);
102
+ }
103
+
104
+ public byte[] readFileAssetsOrRes(String filePath, boolean isRes) throws Exception {
105
+ InputStream stream = null;
106
+ try {
107
+ if (isRes) {
108
+ int res = getResIdentifier(filePath);
109
+ stream = context.getResources().openRawResource(res);
110
+ if (stream == null) {
111
+ throw new Exception("Failed to open file");
112
+ }
113
+ } else {
114
+ AssetManager assetManager = context.getAssets();
115
+ stream = assetManager.open(filePath, 0);
116
+ if (stream == null) {
117
+ throw new Exception("Failed to open file");
118
+ }
119
+ }
120
+
121
+ byte[] buffer = new byte[stream.available()];
122
+ stream.read(buffer);
123
+
124
+ return buffer;
125
+ } catch (Exception ex) {
126
+ ex.printStackTrace();
127
+ throw new Exception("Failed to open file");
128
+ } finally {
129
+ if (stream != null) {
130
+ try {
131
+ stream.close();
132
+ } catch (IOException ignored) {
133
+ }
134
+ }
135
+ }
136
+ }
137
+
138
+ public void copyFileAssetsOrRes(String filePath, String destPath, boolean isRes) throws Exception {
139
+ InputStream stream = null;
140
+ try {
141
+ if (isRes) {
142
+ int res = getResIdentifier(filePath);
143
+ stream = context.getResources().openRawResource(res);
144
+ } else {
145
+ AssetManager assetManager = context.getAssets();
146
+ stream = assetManager.open(filePath);
147
+ }
148
+ copyInputStream(stream, filePath, destPath);
149
+ } catch (Exception ex) {
150
+ // Default error message is just asset name, so make a more helpful error here.
151
+ throw new Exception(ex.getLocalizedMessage());
152
+ } finally {
153
+ if (stream != null) {
154
+ try {
155
+ stream.close();
156
+ } catch (IOException ignored) {
157
+ }
158
+ }
159
+ }
160
+ }
161
+
162
+ public boolean existsAssetsOrRes(String filePath, boolean isRes) throws Exception {
163
+ InputStream stream = null;
164
+ try {
165
+ if (isRes) {
166
+ int res = getResIdentifier(filePath);
167
+ if (res > 0) {
168
+ return true;
169
+ } else {
170
+ return false;
171
+ }
172
+ } else {
173
+ AssetManager assetManager = context.getAssets();
174
+ try {
175
+ String[] list = assetManager.list(filePath);
176
+ if (list != null && list.length > 0) {
177
+ return true;
178
+ }
179
+ } catch (Exception ignored) {
180
+ //.. probably not a directory then
181
+ }
182
+ // Attempt to open file (win = exists)
183
+ stream = assetManager.open(filePath);
184
+ return true;
185
+ }
186
+ } catch (Exception ex) {
187
+ return false;
188
+ } finally {
189
+ if (stream != null) {
190
+ try {
191
+ stream.close();
192
+ } catch (IOException ignored) {
193
+ }
194
+ }
195
+ }
196
+ }
197
+
198
+ public void downloadFile(
199
+ int jobId,
200
+ String fromUrl,
201
+ String toFile,
202
+ HashMap<String, String> headers,
203
+ int progressInterval,
204
+ float progressDivider,
205
+ int connectionTimeout,
206
+ int readTimeout,
207
+ boolean hasBeginCallback,
208
+ boolean hasProgressCallback
209
+ ) {
210
+ try {
211
+ File file = new File(toFile);
212
+ URL url = new URL(fromUrl);
213
+
214
+ RNFSTurboDownloadParams params = new RNFSTurboDownloadParams();
215
+
216
+ params.src = url;
217
+ params.dest = file;
218
+ params.headers = headers;
219
+ params.progressInterval = progressInterval;
220
+ params.progressDivider = progressDivider;
221
+ params.readTimeout = readTimeout;
222
+ params.connectionTimeout = connectionTimeout;
223
+
224
+ params.onTaskCompleted = new RNFSTurboDownloadParams.OnTaskCompleted() {
225
+ public void onTaskCompleted(RNFSTurboDownloadResult res) {
226
+ if (res.exception == null) {
227
+ downloadCompleteCallback(jobId, res.statusCode, (double)res.bytesWritten);
228
+ } else {
229
+ downloadErrorCallback(jobId, res.exception.toString());
230
+ }
231
+ downloaders.remove(jobId);
232
+ }
233
+ };
234
+
235
+ if (hasBeginCallback) {
236
+ params.onDownloadBegin = new RNFSTurboDownloadParams.OnDownloadBegin() {
237
+ @Override
238
+ public void onDownloadBegin(int statusCode, long contentLength, Map<String, String> headers) {
239
+ downloadBeginCallback(jobId, statusCode, (double)contentLength, new HashMap<String, String>(headers));
240
+ }
241
+ };
242
+ }
243
+
244
+ if (hasProgressCallback) {
245
+ params.onDownloadProgress = new RNFSTurboDownloadParams.OnDownloadProgress() {
246
+ public void onDownloadProgress(long contentLength, long bytesWritten) {
247
+ downloadProgressCallback(jobId, (double)contentLength, (double)bytesWritten);
248
+ }
249
+ };
250
+ }
251
+
252
+ RNFSTurboDownloader downloader = new RNFSTurboDownloader();
253
+
254
+ downloader.execute(params);
255
+
256
+ downloaders.put(jobId, downloader);
257
+ } catch (Exception ex) {
258
+ ex.printStackTrace();
259
+ downloadErrorCallback(jobId, ex.toString());
260
+ }
261
+ }
262
+
263
+ public void stopDownload(int jobId) {
264
+ RNFSTurboDownloader downloader = downloaders.get(jobId);
265
+
266
+ if (downloader != null) {
267
+ downloader.stop();
268
+ downloaders.remove(jobId);
269
+ }
270
+ }
271
+
272
+ public void uploadFile(
273
+ int jobId,
274
+ String toUrl,
275
+ boolean binaryStreamOnly,
276
+ String[] files,
277
+ int filesNum,
278
+ HashMap<String, String> headers,
279
+ HashMap<String, String> fields,
280
+ String method,
281
+ boolean hasBeginCallback,
282
+ boolean hasProgressCallback
283
+ ) {
284
+ try {
285
+ URL url = new URL(toUrl);
286
+ RNFSTurboUploadParams params = new RNFSTurboUploadParams();
287
+ params.src = url;
288
+ params.files = files;
289
+ params.filesNum = filesNum;
290
+ params.headers = headers;
291
+ params.method = method;
292
+ params.fields = fields;
293
+ params.binaryStreamOnly = binaryStreamOnly;
294
+ params.onUploadComplete = new RNFSTurboUploadParams.onUploadComplete() {
295
+ public void onUploadComplete(RNFSTurboUploadResult res) {
296
+ if (res.exception == null) {
297
+ uploadCompleteCallback(jobId, res.statusCode, new HashMap<String, String>(res.headers), res.body);
298
+ } else {
299
+ uploadErrorCallback(jobId, res.exception.toString());
300
+ }
301
+ uploaders.remove(jobId);
302
+ }
303
+ };
304
+
305
+ if (hasBeginCallback) {
306
+ params.onUploadBegin = new RNFSTurboUploadParams.onUploadBegin() {
307
+ public void onUploadBegin() {
308
+ uploadBeginCallback(jobId);
309
+ }
310
+ };
311
+ }
312
+
313
+ if (hasProgressCallback) {
314
+ params.onUploadProgress = new RNFSTurboUploadParams.onUploadProgress() {
315
+ public void onUploadProgress(double totalBytesExpectedToSend, double totalBytesSent) {
316
+ uploadProgressCallback(jobId, totalBytesExpectedToSend, totalBytesSent);
317
+ }
318
+ };
319
+ }
320
+
321
+ RNFSTurboUploader uploader = new RNFSTurboUploader();
322
+
323
+ uploader.execute(params);
324
+
325
+ uploaders.put(jobId, uploader);
326
+ } catch (Exception ex) {
327
+ ex.printStackTrace();
328
+ uploadErrorCallback(jobId, ex.toString());
329
+ }
330
+ }
331
+
332
+ public void stopUpload(int jobId) {
333
+ RNFSTurboUploader uploader = uploaders.get(jobId);
334
+
335
+ if (uploader != null) {
336
+ uploader.stop();
337
+ uploaders.remove(jobId);
338
+ }
339
+ }
340
+
341
+ public long[] getFSInfo() {
342
+ File path = Environment.getDataDirectory();
343
+ StatFs stat = new StatFs(path.getPath());
344
+ StatFs statEx = new StatFs(Environment.getExternalStorageDirectory().getPath());
345
+ long[] info = new long[4];
346
+ if (android.os.Build.VERSION.SDK_INT >= 18) {
347
+ info[0] = stat.getTotalBytes();
348
+ info[1] = stat.getFreeBytes();
349
+ info[2] = statEx.getTotalBytes();
350
+ info[3] = statEx.getFreeBytes();
351
+ } else {
352
+ long blockSize = stat.getBlockSize();
353
+ info[0] = blockSize * stat.getBlockCount();
354
+ info[1] = blockSize * stat.getAvailableBlocks();
355
+ }
356
+
357
+ return info;
358
+ }
359
+
360
+ public void scanFile(int jobId, String path) {
361
+ MediaScannerConnection.scanFile(context,
362
+ new String[]{path},
363
+ null,
364
+ new MediaScannerConnection.MediaScannerConnectionClient() {
365
+ @Override
366
+ public void onMediaScannerConnected() {}
367
+ @Override
368
+ public void onScanCompleted(String path, Uri uri) {
369
+ scanCallback(jobId, uri != null ? uri.toString() : "");
370
+ }
371
+ }
372
+ );
373
+ }
374
+
375
+ public String[] getAllExternalFilesDirs() {
376
+ File[] allExternalFilesDirs = context.getExternalFilesDirs(null);
377
+ ArrayList<String> filesList = new ArrayList<String>();
378
+ for (File f : allExternalFilesDirs) {
379
+ if (f != null) {
380
+ filesList.add(f.getAbsolutePath());
381
+ }
382
+ }
383
+ return filesList.toArray(new String[0]);
384
+ }
385
+
386
+ private int getResIdentifier(String filename) {
387
+ String suffix = filename.substring(filename.lastIndexOf(".") + 1);
388
+ String name = filename.substring(0, filename.lastIndexOf("."));
389
+ Boolean isImage = suffix.equals("png") || suffix.equals("jpg") || suffix.equals("jpeg") || suffix.equals("bmp") || suffix.equals("gif") || suffix.equals("webp") || suffix.equals("psd") || suffix.equals("svg") || suffix.equals("tiff");
390
+ return context.getResources().getIdentifier(name, isImage ? "drawable" : "raw", context.getPackageName());
391
+ }
392
+
393
+ private Uri getFileUri(String filepath, boolean isDirectoryAllowed) throws RNFSTurboIORejectionException {
394
+ Uri uri = Uri.parse(filepath);
395
+ if (uri.getScheme() == null) {
396
+ // No prefix, assuming that provided path is absolute path to file
397
+ File file = new File(filepath);
398
+ if (!isDirectoryAllowed && file.isDirectory()) {
399
+ throw new RNFSTurboIORejectionException("EISDIR", "EISDIR: illegal operation on a directory, read '" + filepath + "'");
400
+ }
401
+ uri = Uri.parse("file://" + filepath);
402
+ }
403
+ return uri;
404
+ }
405
+
406
+ private String getWriteAccessByAPILevel() {
407
+ return android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.P ? "w" : "rwt";
408
+ }
409
+
410
+ private OutputStream getOutputStream(String filepath, boolean append) throws RNFSTurboIORejectionException {
411
+ Uri uri = getFileUri(filepath, false);
412
+ OutputStream stream;
413
+ try {
414
+ stream = context.getContentResolver().openOutputStream(uri, append ? "wa" : getWriteAccessByAPILevel());
415
+ } catch (FileNotFoundException ex) {
416
+ throw new RNFSTurboIORejectionException("ENOENT", "ENOENT: " + ex.getMessage() + ", open '" + filepath + "'");
417
+ }
418
+ if (stream == null) {
419
+ throw new RNFSTurboIORejectionException("ENOENT", "ENOENT: could not open an output stream for '" + filepath + "'");
420
+ }
421
+ return stream;
422
+ }
423
+
424
+ /**
425
+ * Internal method for copying that works with any InputStream
426
+ *
427
+ * @param in InputStream from assets or file
428
+ * @param source source path (only used for logging errors)
429
+ * @param destination destination path
430
+ */
431
+ private void copyInputStream(InputStream in, String source, String destination) throws Exception {
432
+ OutputStream out = null;
433
+ try {
434
+ out = getOutputStream(destination, false);
435
+
436
+ byte[] buffer = new byte[1024 * 10]; // 10k buffer
437
+ int read;
438
+ while ((read = in.read(buffer)) != -1) {
439
+ out.write(buffer, 0, read);
440
+ }
441
+ } catch (Exception ex) {
442
+ throw new Exception(String.format("Failed to copy '%s' to %s (%s)", source, destination, ex.getLocalizedMessage()));
443
+ } finally {
444
+ if (in != null) {
445
+ try {
446
+ in.close();
447
+ } catch (IOException ignored) {
448
+ }
449
+ }
450
+ if (out != null) {
451
+ try {
452
+ out.close();
453
+ } catch (IOException ignored) {
454
+ }
455
+ }
456
+ }
457
+ }
458
+ }
@@ -0,0 +1,45 @@
1
+ /*
2
+ The MIT License (MIT)
3
+
4
+ Copyright (c) 2015 Johannes Lumpe
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ Modified by Sergei Kazakov on 31.10.24.
17
+ */
18
+
19
+ package com.cmpayc.rnfsturbo;
20
+
21
+ import java.net.URL;
22
+ import java.util.Map;
23
+
24
+ public class RNFSTurboUploadParams {
25
+ public interface onUploadComplete{
26
+ void onUploadComplete(RNFSTurboUploadResult res);
27
+ }
28
+ public interface onUploadProgress{
29
+ void onUploadProgress(double totalBytesExpectedToSend, double totalBytesSent);
30
+ }
31
+ public interface onUploadBegin{
32
+ void onUploadBegin();
33
+ }
34
+ public URL src;
35
+ public String[] files;
36
+ public int filesNum;
37
+ public boolean binaryStreamOnly;
38
+ public String name;
39
+ public Map<String, String> headers;
40
+ public Map<String, String> fields;
41
+ public String method;
42
+ public onUploadComplete onUploadComplete;
43
+ public onUploadProgress onUploadProgress;
44
+ public onUploadBegin onUploadBegin;
45
+ }
@@ -0,0 +1,28 @@
1
+ /*
2
+ The MIT License (MIT)
3
+
4
+ Copyright (c) 2015 Johannes Lumpe
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ Modified by Sergei Kazakov on 31.10.24.
17
+ */
18
+
19
+ package com.cmpayc.rnfsturbo;
20
+
21
+ import java.util.Map;
22
+
23
+ public class RNFSTurboUploadResult {
24
+ public int statusCode;
25
+ public Map<String, String> headers;
26
+ public Exception exception;
27
+ public String body;
28
+ }