-
Notifications
You must be signed in to change notification settings - Fork 556
/
FilesystemPlugin.java
509 lines (455 loc) · 18.9 KB
/
FilesystemPlugin.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
package com.capacitorjs.plugins.filesystem;
import android.Manifest;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import com.capacitorjs.plugins.filesystem.exceptions.CopyFailedException;
import com.capacitorjs.plugins.filesystem.exceptions.DirectoryExistsException;
import com.capacitorjs.plugins.filesystem.exceptions.DirectoryNotFoundException;
import com.getcapacitor.JSArray;
import com.getcapacitor.JSObject;
import com.getcapacitor.Logger;
import com.getcapacitor.PermissionState;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.annotation.Permission;
import com.getcapacitor.annotation.PermissionCallback;
import com.getcapacitor.plugin.util.HttpRequestHandler;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import org.json.JSONException;
@CapacitorPlugin(
name = "Filesystem",
permissions = {
@Permission(
strings = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE },
alias = "publicStorage"
)
}
)
public class FilesystemPlugin extends Plugin {
private Filesystem implementation;
@Override
public void load() {
implementation = new Filesystem(getContext());
}
private static final String PERMISSION_DENIED_ERROR = "Unable to do file operation, user denied permission request";
@PluginMethod
public void readFile(PluginCall call) {
String path = call.getString("path");
String directory = getDirectoryParameter(call);
String encoding = call.getString("encoding");
Charset charset = implementation.getEncoding(encoding);
if (encoding != null && charset == null) {
call.reject("Unsupported encoding provided: " + encoding);
return;
}
if (isPublicDirectory(directory) && !isStoragePermissionGranted()) {
requestAllPermissions(call, "permissionCallback");
} else {
try {
String dataStr = implementation.readFile(path, directory, charset);
JSObject ret = new JSObject();
ret.putOpt("data", dataStr);
call.resolve(ret);
} catch (FileNotFoundException ex) {
call.reject("File does not exist", ex);
} catch (IOException ex) {
call.reject("Unable to read file", ex);
} catch (JSONException ex) {
call.reject("Unable to return value for reading file", ex);
}
}
}
@PluginMethod
public void writeFile(PluginCall call) {
String path = call.getString("path");
String data = call.getString("data");
Boolean recursive = call.getBoolean("recursive", false);
if (path == null) {
Logger.error(getLogTag(), "No path or filename retrieved from call", null);
call.reject("NO_PATH");
return;
}
if (data == null) {
Logger.error(getLogTag(), "No data retrieved from call", null);
call.reject("NO_DATA");
return;
}
String directory = getDirectoryParameter(call);
if (directory != null) {
if (isPublicDirectory(directory) && !isStoragePermissionGranted()) {
requestAllPermissions(call, "permissionCallback");
} else {
// create directory because it might not exist
File androidDir = implementation.getDirectory(directory);
if (androidDir != null) {
if (androidDir.exists() || androidDir.mkdirs()) {
// path might include directories as well
File fileObject = new File(androidDir, path);
if (fileObject.getParentFile().exists() || (recursive && fileObject.getParentFile().mkdirs())) {
saveFile(call, fileObject, data);
} else {
call.reject("Parent folder doesn't exist");
}
} else {
Logger.error(getLogTag(), "Not able to create '" + directory + "'!", null);
call.reject("NOT_CREATED_DIR");
}
} else {
Logger.error(getLogTag(), "Directory ID '" + directory + "' is not supported by plugin", null);
call.reject("INVALID_DIR");
}
}
} else {
// check file:// or no scheme uris
Uri u = Uri.parse(path);
if (u.getScheme() == null || u.getScheme().equals("file")) {
File fileObject = new File(u.getPath());
// do not know where the file is being store so checking the permission to be secure
// TODO to prevent permission checking we need a property from the call
if (!isStoragePermissionGranted()) {
requestAllPermissions(call, "permissionCallback");
} else {
if (
fileObject.getParentFile() == null ||
fileObject.getParentFile().exists() ||
(recursive && fileObject.getParentFile().mkdirs())
) {
saveFile(call, fileObject, data);
} else {
call.reject("Parent folder doesn't exist");
}
}
} else {
call.reject(u.getScheme() + " scheme not supported");
}
}
}
private void saveFile(PluginCall call, File file, String data) {
String encoding = call.getString("encoding");
boolean append = call.getBoolean("append", false);
Charset charset = implementation.getEncoding(encoding);
if (encoding != null && charset == null) {
call.reject("Unsupported encoding provided: " + encoding);
return;
}
try {
implementation.saveFile(file, data, charset, append);
// update mediaStore index only if file was written to external storage
if (isPublicDirectory(getDirectoryParameter(call))) {
MediaScannerConnection.scanFile(getContext(), new String[] { file.getAbsolutePath() }, null, null);
}
Logger.debug(getLogTag(), "File '" + file.getAbsolutePath() + "' saved!");
JSObject result = new JSObject();
result.put("uri", Uri.fromFile(file).toString());
call.resolve(result);
} catch (IOException ex) {
Logger.error(
getLogTag(),
"Creating file '" + file.getPath() + "' with charset '" + charset + "' failed. Error: " + ex.getMessage(),
ex
);
call.reject("FILE_NOTCREATED");
} catch (IllegalArgumentException ex) {
call.reject("The supplied data is not valid base64 content.");
}
}
@PluginMethod
public void appendFile(PluginCall call) {
try {
call.getData().putOpt("append", true);
} catch (JSONException ex) {}
this.writeFile(call);
}
@PluginMethod
public void deleteFile(PluginCall call) {
String file = call.getString("path");
String directory = getDirectoryParameter(call);
if (isPublicDirectory(directory) && !isStoragePermissionGranted()) {
requestAllPermissions(call, "permissionCallback");
} else {
try {
boolean deleted = implementation.deleteFile(file, directory);
if (!deleted) {
call.reject("Unable to delete file");
} else {
call.resolve();
}
} catch (FileNotFoundException ex) {
call.reject(ex.getMessage());
}
}
}
@PluginMethod
public void mkdir(PluginCall call) {
String path = call.getString("path");
String directory = getDirectoryParameter(call);
boolean recursive = call.getBoolean("recursive", false).booleanValue();
if (isPublicDirectory(directory) && !isStoragePermissionGranted()) {
requestAllPermissions(call, "permissionCallback");
} else {
try {
boolean created = implementation.mkdir(path, directory, recursive);
if (!created) {
call.reject("Unable to create directory, unknown reason");
} else {
call.resolve();
}
} catch (DirectoryExistsException ex) {
call.reject(ex.getMessage());
}
}
}
@PluginMethod
public void rmdir(PluginCall call) {
String path = call.getString("path");
String directory = getDirectoryParameter(call);
Boolean recursive = call.getBoolean("recursive", false);
File fileObject = implementation.getFileObject(path, directory);
if (isPublicDirectory(directory) && !isStoragePermissionGranted()) {
requestAllPermissions(call, "permissionCallback");
} else {
if (!fileObject.exists()) {
call.reject("Directory does not exist");
return;
}
if (fileObject.isDirectory() && fileObject.listFiles().length != 0 && !recursive) {
call.reject("Directory is not empty");
return;
}
boolean deleted = false;
try {
implementation.deleteRecursively(fileObject);
deleted = true;
} catch (IOException ignored) {}
if (!deleted) {
call.reject("Unable to delete directory, unknown reason");
} else {
call.resolve();
}
}
}
@PluginMethod
public void readdir(PluginCall call) {
String path = call.getString("path");
String directory = getDirectoryParameter(call);
if (isPublicDirectory(directory) && !isStoragePermissionGranted()) {
requestAllPermissions(call, "permissionCallback");
} else {
try {
File[] files = implementation.readdir(path, directory);
JSArray filesArray = new JSArray();
if (files != null) {
for (var i = 0; i < files.length; i++) {
File fileObject = files[i];
JSObject data = new JSObject();
data.put("name", fileObject.getName());
data.put("type", fileObject.isDirectory() ? "directory" : "file");
data.put("size", fileObject.length());
data.put("mtime", fileObject.lastModified());
data.put("uri", Uri.fromFile(fileObject).toString());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
BasicFileAttributes attr = Files.readAttributes(fileObject.toPath(), BasicFileAttributes.class);
// use whichever is the oldest between creationTime and lastAccessTime
if (attr.creationTime().toMillis() < attr.lastAccessTime().toMillis()) {
data.put("ctime", attr.creationTime().toMillis());
} else {
data.put("ctime", attr.lastAccessTime().toMillis());
}
} catch (Exception ex) {}
} else {
data.put("ctime", null);
}
filesArray.put(data);
}
JSObject ret = new JSObject();
ret.put("files", filesArray);
call.resolve(ret);
} else {
call.reject("Unable to read directory");
}
} catch (DirectoryNotFoundException ex) {
call.reject(ex.getMessage());
}
}
}
@PluginMethod
public void getUri(PluginCall call) {
String path = call.getString("path");
String directory = getDirectoryParameter(call);
File fileObject = implementation.getFileObject(path, directory);
if (isPublicDirectory(directory) && !isStoragePermissionGranted()) {
requestAllPermissions(call, "permissionCallback");
} else {
JSObject data = new JSObject();
data.put("uri", Uri.fromFile(fileObject).toString());
call.resolve(data);
}
}
@PluginMethod
public void stat(PluginCall call) {
String path = call.getString("path");
String directory = getDirectoryParameter(call);
File fileObject = implementation.getFileObject(path, directory);
if (isPublicDirectory(directory) && !isStoragePermissionGranted()) {
requestAllPermissions(call, "permissionCallback");
} else {
if (!fileObject.exists()) {
call.reject("File does not exist");
return;
}
JSObject data = new JSObject();
data.put("type", fileObject.isDirectory() ? "directory" : "file");
data.put("size", fileObject.length());
data.put("mtime", fileObject.lastModified());
data.put("uri", Uri.fromFile(fileObject).toString());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
BasicFileAttributes attr = Files.readAttributes(fileObject.toPath(), BasicFileAttributes.class);
// use whichever is the oldest between creationTime and lastAccessTime
if (attr.creationTime().toMillis() < attr.lastAccessTime().toMillis()) {
data.put("ctime", attr.creationTime().toMillis());
} else {
data.put("ctime", attr.lastAccessTime().toMillis());
}
} catch (Exception ex) {}
} else {
data.put("ctime", null);
}
call.resolve(data);
}
}
@PluginMethod
public void rename(PluginCall call) {
this._copy(call, true);
}
@PluginMethod
public void copy(PluginCall call) {
this._copy(call, false);
}
@PluginMethod
public void downloadFile(PluginCall call) {
try {
String directory = call.getString("directory", Environment.DIRECTORY_DOWNLOADS);
if (isPublicDirectory(directory) && !isStoragePermissionGranted()) {
requestAllPermissions(call, "permissionCallback");
} else {
HttpRequestHandler.ProgressEmitter emitter = (bytes, contentLength) -> {
JSObject ret = new JSObject();
ret.put("url", call.getString("url"));
ret.put("bytes", bytes);
ret.put("contentLength", contentLength);
notifyListeners("progress", ret);
};
JSObject response = implementation.downloadFile(call, bridge, emitter);
call.resolve(response);
}
} catch (Exception ex) {
call.reject("Error downloading file: " + ex.getLocalizedMessage(), ex);
}
}
private void _copy(PluginCall call, Boolean doRename) {
String from = call.getString("from");
String to = call.getString("to");
String directory = call.getString("directory");
String toDirectory = call.getString("toDirectory");
if (from == null || from.isEmpty() || to == null || to.isEmpty()) {
call.reject("Both to and from must be provided");
return;
}
if (isPublicDirectory(directory) || isPublicDirectory(toDirectory)) {
if (!isStoragePermissionGranted()) {
requestAllPermissions(call, "permissionCallback");
return;
}
}
try {
File file = implementation.copy(from, directory, to, toDirectory, doRename);
if (!doRename) {
JSObject result = new JSObject();
result.put("uri", Uri.fromFile(file).toString());
call.resolve(result);
} else {
call.resolve();
}
} catch (CopyFailedException ex) {
call.reject(ex.getMessage());
} catch (IOException ex) {
call.reject("Unable to perform action: " + ex.getLocalizedMessage());
}
}
@PermissionCallback
private void permissionCallback(PluginCall call) {
if (!isStoragePermissionGranted()) {
Logger.debug(getLogTag(), "User denied storage permission");
call.reject(PERMISSION_DENIED_ERROR);
return;
}
switch (call.getMethodName()) {
case "appendFile":
case "writeFile":
writeFile(call);
break;
case "deleteFile":
deleteFile(call);
break;
case "mkdir":
mkdir(call);
break;
case "rmdir":
rmdir(call);
break;
case "rename":
rename(call);
break;
case "copy":
copy(call);
break;
case "readFile":
readFile(call);
break;
case "readdir":
readdir(call);
break;
case "getUri":
getUri(call);
break;
case "stat":
stat(call);
break;
case "downloadFile":
downloadFile(call);
break;
}
}
/**
* Checks the the given permission is granted or not
* @return Returns true if the permission is granted and false if it is denied.
*/
private boolean isStoragePermissionGranted() {
return getPermissionState("publicStorage") == PermissionState.GRANTED;
}
/**
* Reads the directory parameter from the plugin call
* @param call the plugin call
*/
private String getDirectoryParameter(PluginCall call) {
return call.getString("directory");
}
/**
* True if the given directory string is a public storage directory, which is accessible by the user or other apps.
* @param directory the directory string.
*/
private boolean isPublicDirectory(String directory) {
return "DOCUMENTS".equals(directory) || "EXTERNAL_STORAGE".equals(directory);
}
}