@capacitor/filesystem 7.0.0-dev-2269-20241202T174443.0 → 7.0.0-dev-2287-20241220T140459.0

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.
@@ -28,6 +28,10 @@ import java.nio.charset.Charset;
28
28
  import java.nio.charset.StandardCharsets;
29
29
  import java.util.Locale;
30
30
  import org.json.JSONException;
31
+ import java.util.concurrent.ExecutorService;
32
+ import java.util.concurrent.Executors;
33
+ import android.os.Handler;
34
+ import android.os.Looper;
31
35
 
32
36
  public class Filesystem {
33
37
 
@@ -101,7 +105,7 @@ public class Filesystem {
101
105
  }
102
106
 
103
107
  public File copy(String from, String directory, String to, String toDirectory, boolean doRename)
104
- throws IOException, CopyFailedException {
108
+ throws IOException, CopyFailedException {
105
109
  if (toDirectory == null) {
106
110
  toDirectory = directory;
107
111
  }
@@ -303,81 +307,123 @@ public class Filesystem {
303
307
  }
304
308
  }
305
309
 
306
- public JSObject downloadFile(PluginCall call, Bridge bridge, HttpRequestHandler.ProgressEmitter emitter)
307
- throws IOException, URISyntaxException, JSONException {
310
+ public void downloadFile(PluginCall call, Bridge bridge, HttpRequestHandler.ProgressEmitter emitter,
311
+ FilesystemDownloadCallback callback) throws IOException, URISyntaxException, JSONException {
308
312
  String urlString = call.getString("url", "");
309
- JSObject headers = call.getObject("headers", new JSObject());
310
- JSObject params = call.getObject("params", new JSObject());
311
- Integer connectTimeout = call.getInt("connectTimeout");
312
- Integer readTimeout = call.getInt("readTimeout");
313
- Boolean disableRedirects = call.getBoolean("disableRedirects");
314
- Boolean shouldEncode = call.getBoolean("shouldEncodeUrlParams", true);
315
- Boolean progress = call.getBoolean("progress", false);
316
-
317
- String method = call.getString("method", "GET").toUpperCase(Locale.ROOT);
318
- String path = call.getString("path");
319
- String directory = call.getString("directory", Environment.DIRECTORY_DOWNLOADS);
320
-
321
- final URL url = new URL(urlString);
322
- final File file = getFileObject(path, directory);
323
-
324
- HttpRequestHandler.HttpURLConnectionBuilder connectionBuilder = new HttpRequestHandler.HttpURLConnectionBuilder()
325
- .setUrl(url)
326
- .setMethod(method)
327
- .setHeaders(headers)
328
- .setUrlParams(params, shouldEncode)
329
- .setConnectTimeout(connectTimeout)
330
- .setReadTimeout(readTimeout)
331
- .setDisableRedirects(disableRedirects)
332
- .openConnection();
333
-
334
- CapacitorHttpUrlConnection connection = connectionBuilder.build();
335
-
336
- connection.setSSLSocketFactory(bridge);
337
-
338
- InputStream connectionInputStream = connection.getInputStream();
339
- FileOutputStream fileOutputStream = new FileOutputStream(file, false);
340
-
341
- String contentLength = connection.getHeaderField("content-length");
342
- int bytes = 0;
343
- int maxBytes = 0;
313
+ ExecutorService executor = Executors.newSingleThreadExecutor();
314
+ Handler handler = new Handler(Looper.getMainLooper());
315
+
316
+ executor.execute(() -> {
317
+ AsyncTaskResult result = doDownloadInBackground(urlString, call, bridge, emitter);
318
+ handler.post(() -> {
319
+ if (result.error != null) {
320
+ callback.onError(result.error);
321
+ } else {
322
+ callback.onSuccess(result.result);
323
+ }
324
+ });
325
+ executor.shutdown();
326
+ });
327
+ }
344
328
 
329
+ private AsyncTaskResult doDownloadInBackground(String urlString, PluginCall call, Bridge bridge,
330
+ HttpRequestHandler.ProgressEmitter emitter) {
345
331
  try {
346
- maxBytes = contentLength != null ? Integer.parseInt(contentLength) : 0;
347
- } catch (NumberFormatException ignored) {}
332
+ JSObject headers = call.getObject("headers", new JSObject());
333
+ JSObject params = call.getObject("params", new JSObject());
334
+ Integer connectTimeout = call.getInt("connectTimeout");
335
+ Integer readTimeout = call.getInt("readTimeout");
336
+ Boolean disableRedirects = call.getBoolean("disableRedirects");
337
+ Boolean shouldEncode = call.getBoolean("shouldEncodeUrlParams", true);
338
+ Boolean progress = call.getBoolean("progress", false);
339
+
340
+ String method = call.getString("method", "GET").toUpperCase(Locale.ROOT);
341
+ String path = call.getString("path");
342
+ String directory = call.getString("directory", Environment.DIRECTORY_DOWNLOADS);
343
+
344
+ final URL url = new URL(urlString);
345
+ final File file = getFileObject(path, directory);
346
+
347
+ HttpRequestHandler.HttpURLConnectionBuilder connectionBuilder = new HttpRequestHandler.HttpURLConnectionBuilder()
348
+ .setUrl(url)
349
+ .setMethod(method)
350
+ .setHeaders(headers)
351
+ .setUrlParams(params, shouldEncode)
352
+ .setConnectTimeout(connectTimeout)
353
+ .setReadTimeout(readTimeout)
354
+ .setDisableRedirects(disableRedirects)
355
+ .openConnection();
356
+
357
+ CapacitorHttpUrlConnection connection = connectionBuilder.build();
358
+
359
+ connection.setSSLSocketFactory(bridge);
360
+
361
+ InputStream connectionInputStream = connection.getInputStream();
362
+ FileOutputStream fileOutputStream = new FileOutputStream(file, false);
363
+
364
+ String contentLength = connection.getHeaderField("content-length");
365
+ int bytes = 0;
366
+ int maxBytes = 0;
367
+
368
+ try {
369
+ maxBytes = contentLength != null ? Integer.parseInt(contentLength) : 0;
370
+ } catch (NumberFormatException ignored) {
371
+ }
348
372
 
349
- byte[] buffer = new byte[1024];
350
- int len;
373
+ byte[] buffer = new byte[1024];
374
+ int len;
351
375
 
352
- // Throttle emitter to 100ms so it doesn't slow down app
353
- long lastEmitTime = System.currentTimeMillis();
354
- long minEmitIntervalMillis = 100;
376
+ // Throttle emitter to 100ms so it doesn't slow down app
377
+ long lastEmitTime = System.currentTimeMillis();
378
+ long minEmitIntervalMillis = 100;
355
379
 
356
- while ((len = connectionInputStream.read(buffer)) > 0) {
357
- fileOutputStream.write(buffer, 0, len);
380
+ while ((len = connectionInputStream.read(buffer)) > 0) {
381
+ fileOutputStream.write(buffer, 0, len);
358
382
 
359
- bytes += len;
383
+ bytes += len;
360
384
 
361
- if (progress && null != emitter) {
362
- long currentTime = System.currentTimeMillis();
363
- if (currentTime - lastEmitTime > minEmitIntervalMillis) {
364
- emitter.emit(bytes, maxBytes);
365
- lastEmitTime = currentTime;
385
+ if (progress && null != emitter) {
386
+ long currentTime = System.currentTimeMillis();
387
+ if (currentTime - lastEmitTime > minEmitIntervalMillis) {
388
+ emitter.emit(bytes, maxBytes);
389
+ lastEmitTime = currentTime;
390
+ }
366
391
  }
367
392
  }
393
+
394
+ if (progress && null != emitter) {
395
+ emitter.emit(bytes, maxBytes);
396
+ }
397
+
398
+ connectionInputStream.close();
399
+ fileOutputStream.close();
400
+
401
+ JSObject ret = new JSObject();
402
+ ret.put("path", file.getAbsolutePath());
403
+ return new AsyncTaskResult(ret);
404
+ } catch (Exception e) {
405
+ return new AsyncTaskResult(e);
406
+ }
407
+ }
408
+
409
+ private static class AsyncTaskResult {
410
+ final JSObject result;
411
+ final Exception error;
412
+
413
+ AsyncTaskResult(JSObject result) {
414
+ this.result = result;
415
+ this.error = null;
368
416
  }
369
417
 
370
- if (progress && null != emitter) {
371
- emitter.emit(bytes, maxBytes);
418
+ AsyncTaskResult(Exception error) {
419
+ this.result = null;
420
+ this.error = error;
372
421
  }
422
+ }
373
423
 
374
- connectionInputStream.close();
375
- fileOutputStream.close();
424
+ public interface FilesystemDownloadCallback {
425
+ void onSuccess(JSObject result);
376
426
 
377
- return new JSObject() {
378
- {
379
- put("path", file.getAbsolutePath());
380
- }
381
- };
427
+ void onError(Exception error);
382
428
  }
383
429
  }
@@ -133,7 +133,7 @@ public class FilesystemPlugin extends Plugin {
133
133
  } else {
134
134
  if (
135
135
  fileObject.getParentFile() == null ||
136
- fileObject.getParentFile().exists() ||
136
+ fileObject.getParentFile().exists() ||
137
137
  (recursive && fileObject.getParentFile().mkdirs())
138
138
  ) {
139
139
  saveFile(call, fileObject, data);
@@ -169,7 +169,7 @@ public class FilesystemPlugin extends Plugin {
169
169
  call.resolve(result);
170
170
  } catch (IOException ex) {
171
171
  Logger.error(
172
- getLogTag(),
172
+ getLogTag(),
173
173
  "Creating file '" + file.getPath() + "' with charset '" + charset + "' failed. Error: " + ex.getMessage(),
174
174
  ex
175
175
  );
@@ -388,23 +388,37 @@ public class FilesystemPlugin extends Plugin {
388
388
 
389
389
  if (isPublicDirectory(directory) && !isStoragePermissionGranted()) {
390
390
  requestAllPermissions(call, "permissionCallback");
391
- } else {
392
- HttpRequestHandler.ProgressEmitter emitter = (bytes, contentLength) -> {
393
- JSObject ret = new JSObject();
394
- ret.put("url", call.getString("url"));
395
- ret.put("bytes", bytes);
396
- ret.put("contentLength", contentLength);
391
+ return;
392
+ }
397
393
 
398
- notifyListeners("progress", ret);
399
- };
394
+ HttpRequestHandler.ProgressEmitter emitter = (bytes, contentLength) -> {
395
+ JSObject ret = new JSObject();
396
+ ret.put("url", call.getString("url"));
397
+ ret.put("bytes", bytes);
398
+ ret.put("contentLength", contentLength);
399
+ notifyListeners("progress", ret);
400
+ };
401
+
402
+ implementation.downloadFile(
403
+ call,
404
+ bridge,
405
+ emitter,
406
+ new Filesystem.FilesystemDownloadCallback() {
407
+ @Override
408
+ public void onSuccess(JSObject response) {
409
+ // update mediaStore index only if file was written to external storage
410
+ if (isPublicDirectory(directory)) {
411
+ MediaScannerConnection.scanFile(getContext(), new String[] { response.getString("path") }, null, null);
412
+ }
413
+ call.resolve(response);
414
+ }
400
415
 
401
- JSObject response = implementation.downloadFile(call, bridge, emitter);
402
- // update mediaStore index only if file was written to external storage
403
- if (isPublicDirectory(directory)) {
404
- MediaScannerConnection.scanFile(getContext(), new String[] { response.getString("path") }, null, null);
416
+ @Override
417
+ public void onError(Exception error) {
418
+ call.reject("Error downloading file: " + error.getLocalizedMessage(), error);
419
+ }
405
420
  }
406
- call.resolve(response);
407
- }
421
+ );
408
422
  } catch (Exception ex) {
409
423
  call.reject("Error downloading file: " + ex.getLocalizedMessage(), ex);
410
424
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capacitor/filesystem",
3
- "version": "7.0.0-dev-2269-20241202T174443.0",
3
+ "version": "7.0.0-dev-2287-20241220T140459.0",
4
4
  "description": "The Filesystem API provides a NodeJS-like API for working with files on the device.",
5
5
  "main": "dist/plugin.cjs.js",
6
6
  "module": "dist/esm/index.js",