Nessuna descrizione

FileUtils.java 53KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. /*
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. package org.apache.cordova.file;
  18. import android.Manifest;
  19. import android.app.Activity;
  20. import android.content.Context;
  21. import android.content.pm.PackageManager;
  22. import android.net.Uri;
  23. import android.os.Build;
  24. import android.os.Environment;
  25. import android.util.Base64;
  26. import org.apache.cordova.CallbackContext;
  27. import org.apache.cordova.CordovaInterface;
  28. import org.apache.cordova.CordovaPlugin;
  29. import org.apache.cordova.CordovaWebView;
  30. import org.apache.cordova.LOG;
  31. import org.apache.cordova.PermissionHelper;
  32. import org.apache.cordova.PluginResult;
  33. import org.json.JSONArray;
  34. import org.json.JSONException;
  35. import org.json.JSONObject;
  36. import java.io.ByteArrayOutputStream;
  37. import java.io.File;
  38. import java.io.FileNotFoundException;
  39. import java.io.IOException;
  40. import java.io.InputStream;
  41. import java.net.MalformedURLException;
  42. import java.security.Permission;
  43. import java.util.ArrayList;
  44. import java.util.HashMap;
  45. import java.util.HashSet;
  46. /**
  47. * This class provides file and directory services to JavaScript.
  48. */
  49. public class FileUtils extends CordovaPlugin {
  50. private static final String LOG_TAG = "FileUtils";
  51. public static int NOT_FOUND_ERR = 1;
  52. public static int SECURITY_ERR = 2;
  53. public static int ABORT_ERR = 3;
  54. public static int NOT_READABLE_ERR = 4;
  55. public static int ENCODING_ERR = 5;
  56. public static int NO_MODIFICATION_ALLOWED_ERR = 6;
  57. public static int INVALID_STATE_ERR = 7;
  58. public static int SYNTAX_ERR = 8;
  59. public static int INVALID_MODIFICATION_ERR = 9;
  60. public static int QUOTA_EXCEEDED_ERR = 10;
  61. public static int TYPE_MISMATCH_ERR = 11;
  62. public static int PATH_EXISTS_ERR = 12;
  63. /*
  64. * Permission callback codes
  65. */
  66. public static final int ACTION_GET_FILE = 0;
  67. public static final int ACTION_WRITE = 1;
  68. public static final int ACTION_GET_DIRECTORY = 2;
  69. public static final int WRITE = 3;
  70. public static final int READ = 4;
  71. public static int UNKNOWN_ERR = 1000;
  72. private boolean configured = false;
  73. private PendingRequests pendingRequests;
  74. /*
  75. * We need both read and write when accessing the storage, I think.
  76. */
  77. private String [] permissions = {
  78. Manifest.permission.READ_EXTERNAL_STORAGE,
  79. Manifest.permission.WRITE_EXTERNAL_STORAGE };
  80. // This field exists only to support getEntry, below, which has been deprecated
  81. private static FileUtils filePlugin;
  82. private interface FileOp {
  83. void run(JSONArray args) throws Exception;
  84. }
  85. private ArrayList<Filesystem> filesystems;
  86. public void registerFilesystem(Filesystem fs) {
  87. if (fs != null && filesystemForName(fs.name)== null) {
  88. this.filesystems.add(fs);
  89. }
  90. }
  91. private Filesystem filesystemForName(String name) {
  92. for (Filesystem fs:filesystems) {
  93. if (fs != null && fs.name != null && fs.name.equals(name)) {
  94. return fs;
  95. }
  96. }
  97. return null;
  98. }
  99. protected String[] getExtraFileSystemsPreference(Activity activity) {
  100. String fileSystemsStr = preferences.getString("androidextrafilesystems", "files,files-external,documents,sdcard,cache,cache-external,assets,root");
  101. return fileSystemsStr.split(",");
  102. }
  103. protected void registerExtraFileSystems(String[] filesystems, HashMap<String, String> availableFileSystems) {
  104. HashSet<String> installedFileSystems = new HashSet<String>();
  105. /* Register filesystems in order */
  106. for (String fsName : filesystems) {
  107. if (!installedFileSystems.contains(fsName)) {
  108. String fsRoot = availableFileSystems.get(fsName);
  109. if (fsRoot != null) {
  110. File newRoot = new File(fsRoot);
  111. if (newRoot.mkdirs() || newRoot.isDirectory()) {
  112. registerFilesystem(new LocalFilesystem(fsName, webView.getContext(), webView.getResourceApi(), newRoot));
  113. installedFileSystems.add(fsName);
  114. } else {
  115. LOG.d(LOG_TAG, "Unable to create root dir for filesystem \"" + fsName + "\", skipping");
  116. }
  117. } else {
  118. LOG.d(LOG_TAG, "Unrecognized extra filesystem identifier: " + fsName);
  119. }
  120. }
  121. }
  122. }
  123. protected HashMap<String, String> getAvailableFileSystems(Activity activity) {
  124. Context context = activity.getApplicationContext();
  125. HashMap<String, String> availableFileSystems = new HashMap<String,String>();
  126. availableFileSystems.put("files", context.getFilesDir().getAbsolutePath());
  127. availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath());
  128. availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath());
  129. availableFileSystems.put("root", "/");
  130. if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
  131. try {
  132. availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath());
  133. availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath());
  134. availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath());
  135. }
  136. catch(NullPointerException e) {
  137. LOG.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on");
  138. }
  139. }
  140. return availableFileSystems;
  141. }
  142. @Override
  143. public void initialize(CordovaInterface cordova, CordovaWebView webView) {
  144. super.initialize(cordova, webView);
  145. this.filesystems = new ArrayList<Filesystem>();
  146. this.pendingRequests = new PendingRequests();
  147. String tempRoot = null;
  148. String persistentRoot = null;
  149. Activity activity = cordova.getActivity();
  150. String packageName = activity.getPackageName();
  151. String location = preferences.getString("androidpersistentfilelocation", "internal");
  152. tempRoot = activity.getCacheDir().getAbsolutePath();
  153. if ("internal".equalsIgnoreCase(location)) {
  154. persistentRoot = activity.getFilesDir().getAbsolutePath() + "/files/";
  155. this.configured = true;
  156. } else if ("compatibility".equalsIgnoreCase(location)) {
  157. /*
  158. * Fall-back to compatibility mode -- this is the logic implemented in
  159. * earlier versions of this plugin, and should be maintained here so
  160. * that apps which were originally deployed with older versions of the
  161. * plugin can continue to provide access to files stored under those
  162. * versions.
  163. */
  164. if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
  165. persistentRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
  166. tempRoot = Environment.getExternalStorageDirectory().getAbsolutePath() +
  167. "/Android/data/" + packageName + "/cache/";
  168. } else {
  169. persistentRoot = "/data/data/" + packageName;
  170. }
  171. this.configured = true;
  172. }
  173. if (this.configured) {
  174. // Create the directories if they don't exist.
  175. File tmpRootFile = new File(tempRoot);
  176. File persistentRootFile = new File(persistentRoot);
  177. tmpRootFile.mkdirs();
  178. persistentRootFile.mkdirs();
  179. // Register initial filesystems
  180. // Note: The temporary and persistent filesystems need to be the first two
  181. // registered, so that they will match window.TEMPORARY and window.PERSISTENT,
  182. // per spec.
  183. this.registerFilesystem(new LocalFilesystem("temporary", webView.getContext(), webView.getResourceApi(), tmpRootFile));
  184. this.registerFilesystem(new LocalFilesystem("persistent", webView.getContext(), webView.getResourceApi(), persistentRootFile));
  185. this.registerFilesystem(new ContentFilesystem(webView.getContext(), webView.getResourceApi()));
  186. this.registerFilesystem(new AssetFilesystem(webView.getContext().getAssets(), webView.getResourceApi()));
  187. registerExtraFileSystems(getExtraFileSystemsPreference(activity), getAvailableFileSystems(activity));
  188. // Initialize static plugin reference for deprecated getEntry method
  189. if (filePlugin == null) {
  190. FileUtils.filePlugin = this;
  191. }
  192. } else {
  193. LOG.e(LOG_TAG, "File plugin configuration error: Please set AndroidPersistentFileLocation in config.xml to one of \"internal\" (for new applications) or \"compatibility\" (for compatibility with previous versions)");
  194. activity.finish();
  195. }
  196. }
  197. public static FileUtils getFilePlugin() {
  198. return filePlugin;
  199. }
  200. private Filesystem filesystemForURL(LocalFilesystemURL localURL) {
  201. if (localURL == null) return null;
  202. return filesystemForName(localURL.fsName);
  203. }
  204. @Override
  205. public Uri remapUri(Uri uri) {
  206. // Remap only cdvfile: URLs (not content:).
  207. if (!LocalFilesystemURL.FILESYSTEM_PROTOCOL.equals(uri.getScheme())) {
  208. return null;
  209. }
  210. try {
  211. LocalFilesystemURL inputURL = LocalFilesystemURL.parse(uri);
  212. Filesystem fs = this.filesystemForURL(inputURL);
  213. if (fs == null) {
  214. return null;
  215. }
  216. String path = fs.filesystemPathForURL(inputURL);
  217. if (path != null) {
  218. return Uri.parse("file://" + fs.filesystemPathForURL(inputURL));
  219. }
  220. return null;
  221. } catch (IllegalArgumentException e) {
  222. return null;
  223. }
  224. }
  225. public boolean execute(String action, final String rawArgs, final CallbackContext callbackContext) {
  226. if (!configured) {
  227. callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "File plugin is not configured. Please see the README.md file for details on how to update config.xml"));
  228. return true;
  229. }
  230. if (action.equals("testSaveLocationExists")) {
  231. threadhelper(new FileOp() {
  232. public void run(JSONArray args) {
  233. boolean b = DirectoryManager.testSaveLocationExists();
  234. callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
  235. }
  236. }, rawArgs, callbackContext);
  237. }
  238. else if (action.equals("getFreeDiskSpace")) {
  239. threadhelper( new FileOp( ){
  240. public void run(JSONArray args) {
  241. // The getFreeDiskSpace plugin API is not documented, but some apps call it anyway via exec().
  242. // For compatibility it always returns free space in the primary external storage, and
  243. // does NOT fallback to internal store if external storage is unavailable.
  244. long l = DirectoryManager.getFreeExternalStorageSpace();
  245. callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l));
  246. }
  247. }, rawArgs, callbackContext);
  248. }
  249. else if (action.equals("testFileExists")) {
  250. threadhelper( new FileOp( ){
  251. public void run(JSONArray args) throws JSONException {
  252. String fname=args.getString(0);
  253. boolean b = DirectoryManager.testFileExists(fname);
  254. callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
  255. }
  256. }, rawArgs, callbackContext);
  257. }
  258. else if (action.equals("testDirectoryExists")) {
  259. threadhelper( new FileOp( ){
  260. public void run(JSONArray args) throws JSONException {
  261. String fname=args.getString(0);
  262. boolean b = DirectoryManager.testFileExists(fname);
  263. callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
  264. }
  265. }, rawArgs, callbackContext);
  266. }
  267. else if (action.equals("readAsText")) {
  268. threadhelper( new FileOp( ){
  269. public void run(JSONArray args) throws JSONException, MalformedURLException {
  270. String encoding = args.getString(1);
  271. int start = args.getInt(2);
  272. int end = args.getInt(3);
  273. String fname=args.getString(0);
  274. readFileAs(fname, start, end, callbackContext, encoding, PluginResult.MESSAGE_TYPE_STRING);
  275. }
  276. }, rawArgs, callbackContext);
  277. }
  278. else if (action.equals("readAsDataURL")) {
  279. threadhelper( new FileOp( ){
  280. public void run(JSONArray args) throws JSONException, MalformedURLException {
  281. int start = args.getInt(1);
  282. int end = args.getInt(2);
  283. String fname=args.getString(0);
  284. readFileAs(fname, start, end, callbackContext, null, -1);
  285. }
  286. }, rawArgs, callbackContext);
  287. }
  288. else if (action.equals("readAsArrayBuffer")) {
  289. threadhelper( new FileOp( ){
  290. public void run(JSONArray args) throws JSONException, MalformedURLException {
  291. int start = args.getInt(1);
  292. int end = args.getInt(2);
  293. String fname=args.getString(0);
  294. readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_ARRAYBUFFER);
  295. }
  296. }, rawArgs, callbackContext);
  297. }
  298. else if (action.equals("readAsBinaryString")) {
  299. threadhelper( new FileOp( ){
  300. public void run(JSONArray args) throws JSONException, MalformedURLException {
  301. int start = args.getInt(1);
  302. int end = args.getInt(2);
  303. String fname=args.getString(0);
  304. readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_BINARYSTRING);
  305. }
  306. }, rawArgs, callbackContext);
  307. }
  308. else if (action.equals("write")) {
  309. threadhelper( new FileOp( ){
  310. public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException {
  311. String fname=args.getString(0);
  312. String nativeURL = resolveLocalFileSystemURI(fname).getString("nativeURL");
  313. String data=args.getString(1);
  314. int offset=args.getInt(2);
  315. Boolean isBinary=args.getBoolean(3);
  316. if(needPermission(nativeURL, WRITE)) {
  317. getWritePermission(rawArgs, ACTION_WRITE, callbackContext);
  318. }
  319. else {
  320. long fileSize = write(fname, data, offset, isBinary);
  321. callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
  322. }
  323. }
  324. }, rawArgs, callbackContext);
  325. }
  326. else if (action.equals("truncate")) {
  327. threadhelper( new FileOp( ){
  328. public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException {
  329. String fname=args.getString(0);
  330. int offset=args.getInt(1);
  331. long fileSize = truncateFile(fname, offset);
  332. callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
  333. }
  334. }, rawArgs, callbackContext);
  335. }
  336. else if (action.equals("requestAllFileSystems")) {
  337. threadhelper( new FileOp( ){
  338. public void run(JSONArray args) throws IOException, JSONException {
  339. callbackContext.success(requestAllFileSystems());
  340. }
  341. }, rawArgs, callbackContext);
  342. } else if (action.equals("requestAllPaths")) {
  343. cordova.getThreadPool().execute(
  344. new Runnable() {
  345. public void run() {
  346. try {
  347. callbackContext.success(requestAllPaths());
  348. } catch (JSONException e) {
  349. // TODO Auto-generated catch block
  350. e.printStackTrace();
  351. }
  352. }
  353. }
  354. );
  355. } else if (action.equals("requestFileSystem")) {
  356. threadhelper( new FileOp( ){
  357. public void run(JSONArray args) throws JSONException {
  358. int fstype = args.getInt(0);
  359. long requiredSize = args.optLong(1);
  360. requestFileSystem(fstype, requiredSize, callbackContext);
  361. }
  362. }, rawArgs, callbackContext);
  363. }
  364. else if (action.equals("resolveLocalFileSystemURI")) {
  365. threadhelper( new FileOp( ){
  366. public void run(JSONArray args) throws IOException, JSONException {
  367. String fname=args.getString(0);
  368. JSONObject obj = resolveLocalFileSystemURI(fname);
  369. callbackContext.success(obj);
  370. }
  371. }, rawArgs, callbackContext);
  372. }
  373. else if (action.equals("getFileMetadata")) {
  374. threadhelper( new FileOp( ){
  375. public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
  376. String fname=args.getString(0);
  377. JSONObject obj = getFileMetadata(fname);
  378. callbackContext.success(obj);
  379. }
  380. }, rawArgs, callbackContext);
  381. }
  382. else if (action.equals("getParent")) {
  383. threadhelper( new FileOp( ){
  384. public void run(JSONArray args) throws JSONException, IOException {
  385. String fname=args.getString(0);
  386. JSONObject obj = getParent(fname);
  387. callbackContext.success(obj);
  388. }
  389. }, rawArgs, callbackContext);
  390. }
  391. else if (action.equals("getDirectory")) {
  392. threadhelper( new FileOp( ){
  393. public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
  394. String dirname = args.getString(0);
  395. String path = args.getString(1);
  396. String nativeURL = resolveLocalFileSystemURI(dirname).getString("nativeURL");
  397. boolean containsCreate = (args.isNull(2)) ? false : args.getJSONObject(2).optBoolean("create", false);
  398. if(containsCreate && needPermission(nativeURL, WRITE)) {
  399. getWritePermission(rawArgs, ACTION_GET_DIRECTORY, callbackContext);
  400. }
  401. else if(!containsCreate && needPermission(nativeURL, READ)) {
  402. getReadPermission(rawArgs, ACTION_GET_DIRECTORY, callbackContext);
  403. }
  404. else {
  405. JSONObject obj = getFile(dirname, path, args.optJSONObject(2), true);
  406. callbackContext.success(obj);
  407. }
  408. }
  409. }, rawArgs, callbackContext);
  410. }
  411. else if (action.equals("getFile")) {
  412. threadhelper( new FileOp( ){
  413. public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
  414. String dirname = args.getString(0);
  415. String path = args.getString(1);
  416. String nativeURL = resolveLocalFileSystemURI(dirname).getString("nativeURL");
  417. boolean containsCreate = (args.isNull(2)) ? false : args.getJSONObject(2).optBoolean("create", false);
  418. if(containsCreate && needPermission(nativeURL, WRITE)) {
  419. getWritePermission(rawArgs, ACTION_GET_FILE, callbackContext);
  420. }
  421. else if(!containsCreate && needPermission(nativeURL, READ)) {
  422. getReadPermission(rawArgs, ACTION_GET_FILE, callbackContext);
  423. }
  424. else {
  425. JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false);
  426. callbackContext.success(obj);
  427. }
  428. }
  429. }, rawArgs, callbackContext);
  430. }
  431. else if (action.equals("remove")) {
  432. threadhelper( new FileOp( ){
  433. public void run(JSONArray args) throws JSONException, NoModificationAllowedException, InvalidModificationException, MalformedURLException {
  434. String fname=args.getString(0);
  435. boolean success = remove(fname);
  436. if (success) {
  437. callbackContext.success();
  438. } else {
  439. callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
  440. }
  441. }
  442. }, rawArgs, callbackContext);
  443. }
  444. else if (action.equals("removeRecursively")) {
  445. threadhelper( new FileOp( ){
  446. public void run(JSONArray args) throws JSONException, FileExistsException, MalformedURLException, NoModificationAllowedException {
  447. String fname=args.getString(0);
  448. boolean success = removeRecursively(fname);
  449. if (success) {
  450. callbackContext.success();
  451. } else {
  452. callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
  453. }
  454. }
  455. }, rawArgs, callbackContext);
  456. }
  457. else if (action.equals("moveTo")) {
  458. threadhelper( new FileOp( ){
  459. public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
  460. String fname=args.getString(0);
  461. String newParent=args.getString(1);
  462. String newName=args.getString(2);
  463. JSONObject entry = transferTo(fname, newParent, newName, true);
  464. callbackContext.success(entry);
  465. }
  466. }, rawArgs, callbackContext);
  467. }
  468. else if (action.equals("copyTo")) {
  469. threadhelper( new FileOp( ){
  470. public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
  471. String fname=args.getString(0);
  472. String newParent=args.getString(1);
  473. String newName=args.getString(2);
  474. JSONObject entry = transferTo(fname, newParent, newName, false);
  475. callbackContext.success(entry);
  476. }
  477. }, rawArgs, callbackContext);
  478. }
  479. else if (action.equals("readEntries")) {
  480. threadhelper( new FileOp( ){
  481. public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
  482. String fname=args.getString(0);
  483. JSONArray entries = readEntries(fname);
  484. callbackContext.success(entries);
  485. }
  486. }, rawArgs, callbackContext);
  487. }
  488. else if (action.equals("_getLocalFilesystemPath")) {
  489. // Internal method for testing: Get the on-disk location of a local filesystem url.
  490. // [Currently used for testing file-transfer]
  491. threadhelper( new FileOp( ){
  492. public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
  493. String localURLstr = args.getString(0);
  494. String fname = filesystemPathForURL(localURLstr);
  495. callbackContext.success(fname);
  496. }
  497. }, rawArgs, callbackContext);
  498. }
  499. else {
  500. return false;
  501. }
  502. return true;
  503. }
  504. private void getReadPermission(String rawArgs, int action, CallbackContext callbackContext) {
  505. int requestCode = pendingRequests.createRequest(rawArgs, action, callbackContext);
  506. PermissionHelper.requestPermission(this, requestCode, Manifest.permission.READ_EXTERNAL_STORAGE);
  507. }
  508. private void getWritePermission(String rawArgs, int action, CallbackContext callbackContext) {
  509. int requestCode = pendingRequests.createRequest(rawArgs, action, callbackContext);
  510. PermissionHelper.requestPermission(this, requestCode, Manifest.permission.WRITE_EXTERNAL_STORAGE);
  511. }
  512. private boolean hasReadPermission() {
  513. return PermissionHelper.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
  514. }
  515. private boolean hasWritePermission() {
  516. return PermissionHelper.hasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
  517. }
  518. private boolean needPermission(String nativeURL, int permissionType) throws JSONException {
  519. JSONObject j = requestAllPaths();
  520. ArrayList<String> allowedStorageDirectories = new ArrayList<String>();
  521. allowedStorageDirectories.add(j.getString("applicationDirectory"));
  522. allowedStorageDirectories.add(j.getString("applicationStorageDirectory"));
  523. if(j.has("externalApplicationStorageDirectory")) {
  524. allowedStorageDirectories.add(j.getString("externalApplicationStorageDirectory"));
  525. }
  526. if(permissionType == READ && hasReadPermission()) {
  527. return false;
  528. }
  529. else if(permissionType == WRITE && hasWritePermission()) {
  530. return false;
  531. }
  532. // Permission required if the native url lies outside the allowed storage directories
  533. for(String directory : allowedStorageDirectories) {
  534. if(nativeURL.startsWith(directory)) {
  535. return false;
  536. }
  537. }
  538. return true;
  539. }
  540. public LocalFilesystemURL resolveNativeUri(Uri nativeUri) {
  541. LocalFilesystemURL localURL = null;
  542. // Try all installed filesystems. Return the best matching URL
  543. // (determined by the shortest resulting URL)
  544. for (Filesystem fs : filesystems) {
  545. LocalFilesystemURL url = fs.toLocalUri(nativeUri);
  546. if (url != null) {
  547. // A shorter fullPath implies that the filesystem is a better
  548. // match for the local path than the previous best.
  549. if (localURL == null || (url.uri.toString().length() < localURL.toString().length())) {
  550. localURL = url;
  551. }
  552. }
  553. }
  554. return localURL;
  555. }
  556. /*
  557. * These two native-only methods can be used by other plugins to translate between
  558. * device file system paths and URLs. By design, there is no direct JavaScript
  559. * interface to these methods.
  560. */
  561. public String filesystemPathForURL(String localURLstr) throws MalformedURLException {
  562. try {
  563. LocalFilesystemURL inputURL = LocalFilesystemURL.parse(localURLstr);
  564. Filesystem fs = this.filesystemForURL(inputURL);
  565. if (fs == null) {
  566. throw new MalformedURLException("No installed handlers for this URL");
  567. }
  568. return fs.filesystemPathForURL(inputURL);
  569. } catch (IllegalArgumentException e) {
  570. MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
  571. mue.initCause(e);
  572. throw mue;
  573. }
  574. }
  575. public LocalFilesystemURL filesystemURLforLocalPath(String localPath) {
  576. LocalFilesystemURL localURL = null;
  577. int shortestFullPath = 0;
  578. // Try all installed filesystems. Return the best matching URL
  579. // (determined by the shortest resulting URL)
  580. for (Filesystem fs: filesystems) {
  581. LocalFilesystemURL url = fs.URLforFilesystemPath(localPath);
  582. if (url != null) {
  583. // A shorter fullPath implies that the filesystem is a better
  584. // match for the local path than the previous best.
  585. if (localURL == null || (url.path.length() < shortestFullPath)) {
  586. localURL = url;
  587. shortestFullPath = url.path.length();
  588. }
  589. }
  590. }
  591. return localURL;
  592. }
  593. /* helper to execute functions async and handle the result codes
  594. *
  595. */
  596. private void threadhelper(final FileOp f, final String rawArgs, final CallbackContext callbackContext){
  597. cordova.getThreadPool().execute(new Runnable() {
  598. public void run() {
  599. try {
  600. JSONArray args = new JSONArray(rawArgs);
  601. f.run(args);
  602. } catch ( Exception e) {
  603. if( e instanceof EncodingException){
  604. callbackContext.error(FileUtils.ENCODING_ERR);
  605. } else if(e instanceof FileNotFoundException) {
  606. callbackContext.error(FileUtils.NOT_FOUND_ERR);
  607. } else if(e instanceof FileExistsException) {
  608. callbackContext.error(FileUtils.PATH_EXISTS_ERR);
  609. } else if(e instanceof NoModificationAllowedException ) {
  610. callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
  611. } else if(e instanceof InvalidModificationException ) {
  612. callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
  613. } else if(e instanceof MalformedURLException ) {
  614. callbackContext.error(FileUtils.ENCODING_ERR);
  615. } else if(e instanceof IOException ) {
  616. callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
  617. } else if(e instanceof EncodingException ) {
  618. callbackContext.error(FileUtils.ENCODING_ERR);
  619. } else if(e instanceof TypeMismatchException ) {
  620. callbackContext.error(FileUtils.TYPE_MISMATCH_ERR);
  621. } else if(e instanceof JSONException ) {
  622. callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
  623. } else if (e instanceof SecurityException) {
  624. callbackContext.error(FileUtils.SECURITY_ERR);
  625. } else {
  626. e.printStackTrace();
  627. callbackContext.error(FileUtils.UNKNOWN_ERR);
  628. }
  629. }
  630. }
  631. });
  632. }
  633. /**
  634. * Allows the user to look up the Entry for a file or directory referred to by a local URI.
  635. *
  636. * @param uriString of the file/directory to look up
  637. * @return a JSONObject representing a Entry from the filesystem
  638. * @throws MalformedURLException if the url is not valid
  639. * @throws FileNotFoundException if the file does not exist
  640. * @throws IOException if the user can't read the file
  641. * @throws JSONException
  642. */
  643. private JSONObject resolveLocalFileSystemURI(String uriString) throws IOException, JSONException {
  644. if (uriString == null) {
  645. throw new MalformedURLException("Unrecognized filesystem URL");
  646. }
  647. Uri uri = Uri.parse(uriString);
  648. boolean isNativeUri = false;
  649. LocalFilesystemURL inputURL = LocalFilesystemURL.parse(uri);
  650. if (inputURL == null) {
  651. /* Check for file://, content:// urls */
  652. inputURL = resolveNativeUri(uri);
  653. isNativeUri = true;
  654. }
  655. try {
  656. Filesystem fs = this.filesystemForURL(inputURL);
  657. if (fs == null) {
  658. throw new MalformedURLException("No installed handlers for this URL");
  659. }
  660. if (fs.exists(inputURL)) {
  661. if (!isNativeUri) {
  662. // If not already resolved as native URI, resolve to a native URI and back to
  663. // fix the terminating slash based on whether the entry is a directory or file.
  664. inputURL = fs.toLocalUri(fs.toNativeUri(inputURL));
  665. }
  666. return fs.getEntryForLocalURL(inputURL);
  667. }
  668. } catch (IllegalArgumentException e) {
  669. MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
  670. mue.initCause(e);
  671. throw mue;
  672. }
  673. throw new FileNotFoundException();
  674. }
  675. /**
  676. * Read the list of files from this directory.
  677. *
  678. * @return a JSONArray containing JSONObjects that represent Entry objects.
  679. * @throws FileNotFoundException if the directory is not found.
  680. * @throws JSONException
  681. * @throws MalformedURLException
  682. */
  683. private JSONArray readEntries(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException {
  684. try {
  685. LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
  686. Filesystem fs = this.filesystemForURL(inputURL);
  687. if (fs == null) {
  688. throw new MalformedURLException("No installed handlers for this URL");
  689. }
  690. return fs.readEntriesAtLocalURL(inputURL);
  691. } catch (IllegalArgumentException e) {
  692. MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
  693. mue.initCause(e);
  694. throw mue;
  695. }
  696. }
  697. /**
  698. * A setup method that handles the move/copy of files/directories
  699. *
  700. * @param newName for the file directory to be called, if null use existing file name
  701. * @param move if false do a copy, if true do a move
  702. * @return a Entry object
  703. * @throws NoModificationAllowedException
  704. * @throws IOException
  705. * @throws InvalidModificationException
  706. * @throws EncodingException
  707. * @throws JSONException
  708. * @throws FileExistsException
  709. */
  710. private JSONObject transferTo(String srcURLstr, String destURLstr, String newName, boolean move) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
  711. if (srcURLstr == null || destURLstr == null) {
  712. // either no source or no destination provided
  713. throw new FileNotFoundException();
  714. }
  715. LocalFilesystemURL srcURL = LocalFilesystemURL.parse(srcURLstr);
  716. LocalFilesystemURL destURL = LocalFilesystemURL.parse(destURLstr);
  717. Filesystem srcFs = this.filesystemForURL(srcURL);
  718. Filesystem destFs = this.filesystemForURL(destURL);
  719. // Check for invalid file name
  720. if (newName != null && newName.contains(":")) {
  721. throw new EncodingException("Bad file name");
  722. }
  723. return destFs.copyFileToURL(destURL, newName, srcFs, srcURL, move);
  724. }
  725. /**
  726. * Deletes a directory and all of its contents, if any. In the event of an error
  727. * [e.g. trying to delete a directory that contains a file that cannot be removed],
  728. * some of the contents of the directory may be deleted.
  729. * It is an error to attempt to delete the root directory of a filesystem.
  730. *
  731. * @return a boolean representing success of failure
  732. * @throws FileExistsException
  733. * @throws NoModificationAllowedException
  734. * @throws MalformedURLException
  735. */
  736. private boolean removeRecursively(String baseURLstr) throws FileExistsException, NoModificationAllowedException, MalformedURLException {
  737. try {
  738. LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
  739. // You can't delete the root directory.
  740. if ("".equals(inputURL.path) || "/".equals(inputURL.path)) {
  741. throw new NoModificationAllowedException("You can't delete the root directory");
  742. }
  743. Filesystem fs = this.filesystemForURL(inputURL);
  744. if (fs == null) {
  745. throw new MalformedURLException("No installed handlers for this URL");
  746. }
  747. return fs.recursiveRemoveFileAtLocalURL(inputURL);
  748. } catch (IllegalArgumentException e) {
  749. MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
  750. mue.initCause(e);
  751. throw mue;
  752. }
  753. }
  754. /**
  755. * Deletes a file or directory. It is an error to attempt to delete a directory that is not empty.
  756. * It is an error to attempt to delete the root directory of a filesystem.
  757. *
  758. * @return a boolean representing success of failure
  759. * @throws NoModificationAllowedException
  760. * @throws InvalidModificationException
  761. * @throws MalformedURLException
  762. */
  763. private boolean remove(String baseURLstr) throws NoModificationAllowedException, InvalidModificationException, MalformedURLException {
  764. try {
  765. LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
  766. // You can't delete the root directory.
  767. if ("".equals(inputURL.path) || "/".equals(inputURL.path)) {
  768. throw new NoModificationAllowedException("You can't delete the root directory");
  769. }
  770. Filesystem fs = this.filesystemForURL(inputURL);
  771. if (fs == null) {
  772. throw new MalformedURLException("No installed handlers for this URL");
  773. }
  774. return fs.removeFileAtLocalURL(inputURL);
  775. } catch (IllegalArgumentException e) {
  776. MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
  777. mue.initCause(e);
  778. throw mue;
  779. }
  780. }
  781. /**
  782. * Creates or looks up a file.
  783. *
  784. * @param baseURLstr base directory
  785. * @param path file/directory to lookup or create
  786. * @param options specify whether to create or not
  787. * @param directory if true look up directory, if false look up file
  788. * @return a Entry object
  789. * @throws FileExistsException
  790. * @throws IOException
  791. * @throws TypeMismatchException
  792. * @throws EncodingException
  793. * @throws JSONException
  794. */
  795. private JSONObject getFile(String baseURLstr, String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
  796. try {
  797. LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
  798. Filesystem fs = this.filesystemForURL(inputURL);
  799. if (fs == null) {
  800. throw new MalformedURLException("No installed handlers for this URL");
  801. }
  802. return fs.getFileForLocalURL(inputURL, path, options, directory);
  803. } catch (IllegalArgumentException e) {
  804. MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
  805. mue.initCause(e);
  806. throw mue;
  807. }
  808. }
  809. /**
  810. * Look up the parent DirectoryEntry containing this Entry.
  811. * If this Entry is the root of its filesystem, its parent is itself.
  812. */
  813. private JSONObject getParent(String baseURLstr) throws JSONException, IOException {
  814. try {
  815. LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
  816. Filesystem fs = this.filesystemForURL(inputURL);
  817. if (fs == null) {
  818. throw new MalformedURLException("No installed handlers for this URL");
  819. }
  820. return fs.getParentForLocalURL(inputURL);
  821. } catch (IllegalArgumentException e) {
  822. MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
  823. mue.initCause(e);
  824. throw mue;
  825. }
  826. }
  827. /**
  828. * Returns a File that represents the current state of the file that this FileEntry represents.
  829. *
  830. * @return returns a JSONObject represent a W3C File object
  831. */
  832. private JSONObject getFileMetadata(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException {
  833. try {
  834. LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
  835. Filesystem fs = this.filesystemForURL(inputURL);
  836. if (fs == null) {
  837. throw new MalformedURLException("No installed handlers for this URL");
  838. }
  839. return fs.getFileMetadataForLocalURL(inputURL);
  840. } catch (IllegalArgumentException e) {
  841. MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
  842. mue.initCause(e);
  843. throw mue;
  844. }
  845. }
  846. /**
  847. * Requests a filesystem in which to store application data.
  848. *
  849. * @param type of file system requested
  850. * @param requiredSize required free space in the file system in bytes
  851. * @param callbackContext context for returning the result or error
  852. * @throws JSONException
  853. */
  854. private void requestFileSystem(int type, long requiredSize, final CallbackContext callbackContext) throws JSONException {
  855. Filesystem rootFs = null;
  856. try {
  857. rootFs = this.filesystems.get(type);
  858. } catch (ArrayIndexOutOfBoundsException e) {
  859. // Pass null through
  860. }
  861. if (rootFs == null) {
  862. callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_FOUND_ERR));
  863. } else {
  864. // If a nonzero required size was specified, check that the retrieved filesystem has enough free space.
  865. long availableSize = 0;
  866. if (requiredSize > 0) {
  867. availableSize = rootFs.getFreeSpaceInBytes();
  868. }
  869. if (availableSize < requiredSize) {
  870. callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR));
  871. } else {
  872. JSONObject fs = new JSONObject();
  873. fs.put("name", rootFs.name);
  874. fs.put("root", rootFs.getRootEntry());
  875. callbackContext.success(fs);
  876. }
  877. }
  878. }
  879. /**
  880. * Requests a filesystem in which to store application data.
  881. *
  882. * @return a JSONObject representing the file system
  883. */
  884. private JSONArray requestAllFileSystems() throws IOException, JSONException {
  885. JSONArray ret = new JSONArray();
  886. for (Filesystem fs : filesystems) {
  887. ret.put(fs.getRootEntry());
  888. }
  889. return ret;
  890. }
  891. private static String toDirUrl(File f) {
  892. return Uri.fromFile(f).toString() + '/';
  893. }
  894. private JSONObject requestAllPaths() throws JSONException {
  895. Context context = cordova.getActivity();
  896. JSONObject ret = new JSONObject();
  897. ret.put("applicationDirectory", "file:///android_asset/");
  898. ret.put("applicationStorageDirectory", toDirUrl(context.getFilesDir().getParentFile()));
  899. ret.put("dataDirectory", toDirUrl(context.getFilesDir()));
  900. ret.put("cacheDirectory", toDirUrl(context.getCacheDir()));
  901. if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
  902. try {
  903. ret.put("externalApplicationStorageDirectory", toDirUrl(context.getExternalFilesDir(null).getParentFile()));
  904. ret.put("externalDataDirectory", toDirUrl(context.getExternalFilesDir(null)));
  905. ret.put("externalCacheDirectory", toDirUrl(context.getExternalCacheDir()));
  906. ret.put("externalRootDirectory", toDirUrl(Environment.getExternalStorageDirectory()));
  907. }
  908. catch(NullPointerException e) {
  909. /* If external storage is unavailable, context.getExternal* returns null */
  910. LOG.d(LOG_TAG, "Unable to access these paths, most liklely due to USB storage");
  911. }
  912. }
  913. return ret;
  914. }
  915. /**
  916. * Returns a JSON object representing the given File. Internal APIs should be modified
  917. * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin.
  918. *
  919. * @param file the File to convert
  920. * @return a JSON representation of the given File
  921. * @throws JSONException
  922. */
  923. public JSONObject getEntryForFile(File file) throws JSONException {
  924. JSONObject entry;
  925. for (Filesystem fs : filesystems) {
  926. entry = fs.makeEntryForFile(file);
  927. if (entry != null) {
  928. return entry;
  929. }
  930. }
  931. return null;
  932. }
  933. /**
  934. * Returns a JSON object representing the given File. Deprecated, as this is only used by
  935. * FileTransfer, and because it is a static method that should really be an instance method,
  936. * since it depends on the actual filesystem roots in use. Internal APIs should be modified
  937. * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin.
  938. *
  939. * @param file the File to convert
  940. * @return a JSON representation of the given File
  941. * @throws JSONException
  942. */
  943. @Deprecated
  944. public static JSONObject getEntry(File file) throws JSONException {
  945. if (getFilePlugin() != null) {
  946. return getFilePlugin().getEntryForFile(file);
  947. }
  948. return null;
  949. }
  950. /**
  951. * Read the contents of a file.
  952. * This is done in a background thread; the result is sent to the callback.
  953. *
  954. * @param start Start position in the file.
  955. * @param end End position to stop at (exclusive).
  956. * @param callbackContext The context through which to send the result.
  957. * @param encoding The encoding to return contents as. Typical value is UTF-8. (see http://www.iana.org/assignments/character-sets)
  958. * @param resultType The desired type of data to send to the callback.
  959. * @return Contents of file.
  960. */
  961. public void readFileAs(final String srcURLstr, final int start, final int end, final CallbackContext callbackContext, final String encoding, final int resultType) throws MalformedURLException {
  962. try {
  963. LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
  964. Filesystem fs = this.filesystemForURL(inputURL);
  965. if (fs == null) {
  966. throw new MalformedURLException("No installed handlers for this URL");
  967. }
  968. fs.readFileAtURL(inputURL, start, end, new Filesystem.ReadFileCallback() {
  969. public void handleData(InputStream inputStream, String contentType) {
  970. try {
  971. ByteArrayOutputStream os = new ByteArrayOutputStream();
  972. final int BUFFER_SIZE = 8192;
  973. byte[] buffer = new byte[BUFFER_SIZE];
  974. for (;;) {
  975. int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);
  976. if (bytesRead <= 0) {
  977. break;
  978. }
  979. os.write(buffer, 0, bytesRead);
  980. }
  981. PluginResult result;
  982. switch (resultType) {
  983. case PluginResult.MESSAGE_TYPE_STRING:
  984. result = new PluginResult(PluginResult.Status.OK, os.toString(encoding));
  985. break;
  986. case PluginResult.MESSAGE_TYPE_ARRAYBUFFER:
  987. result = new PluginResult(PluginResult.Status.OK, os.toByteArray());
  988. break;
  989. case PluginResult.MESSAGE_TYPE_BINARYSTRING:
  990. result = new PluginResult(PluginResult.Status.OK, os.toByteArray(), true);
  991. break;
  992. default: // Base64.
  993. byte[] base64 = Base64.encode(os.toByteArray(), Base64.NO_WRAP);
  994. String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII");
  995. result = new PluginResult(PluginResult.Status.OK, s);
  996. }
  997. callbackContext.sendPluginResult(result);
  998. } catch (IOException e) {
  999. LOG.d(LOG_TAG, e.getLocalizedMessage());
  1000. callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
  1001. }
  1002. }
  1003. });
  1004. } catch (IllegalArgumentException e) {
  1005. MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
  1006. mue.initCause(e);
  1007. throw mue;
  1008. } catch (FileNotFoundException e) {
  1009. callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR));
  1010. } catch (IOException e) {
  1011. LOG.d(LOG_TAG, e.getLocalizedMessage());
  1012. callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
  1013. }
  1014. }
  1015. /**
  1016. * Write contents of file.
  1017. *
  1018. * @param data The contents of the file.
  1019. * @param offset The position to begin writing the file.
  1020. * @param isBinary True if the file contents are base64-encoded binary data
  1021. */
  1022. /**/
  1023. public long write(String srcURLstr, String data, int offset, boolean isBinary) throws FileNotFoundException, IOException, NoModificationAllowedException {
  1024. try {
  1025. LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
  1026. Filesystem fs = this.filesystemForURL(inputURL);
  1027. if (fs == null) {
  1028. throw new MalformedURLException("No installed handlers for this URL");
  1029. }
  1030. long x = fs.writeToFileAtURL(inputURL, data, offset, isBinary); LOG.d("TEST",srcURLstr + ": "+x); return x;
  1031. } catch (IllegalArgumentException e) {
  1032. MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
  1033. mue.initCause(e);
  1034. throw mue;
  1035. }
  1036. }
  1037. /**
  1038. * Truncate the file to size
  1039. */
  1040. private long truncateFile(String srcURLstr, long size) throws FileNotFoundException, IOException, NoModificationAllowedException {
  1041. try {
  1042. LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
  1043. Filesystem fs = this.filesystemForURL(inputURL);
  1044. if (fs == null) {
  1045. throw new MalformedURLException("No installed handlers for this URL");
  1046. }
  1047. return fs.truncateFileAtURL(inputURL, size);
  1048. } catch (IllegalArgumentException e) {
  1049. MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL");
  1050. mue.initCause(e);
  1051. throw mue;
  1052. }
  1053. }
  1054. /*
  1055. * Handle the response
  1056. */
  1057. public void onRequestPermissionResult(int requestCode, String[] permissions,
  1058. int[] grantResults) throws JSONException {
  1059. final PendingRequests.Request req = pendingRequests.getAndRemove(requestCode);
  1060. if (req != null) {
  1061. for(int r:grantResults)
  1062. {
  1063. if(r == PackageManager.PERMISSION_DENIED)
  1064. {
  1065. req.getCallbackContext().sendPluginResult(new PluginResult(PluginResult.Status.ERROR, SECURITY_ERR));
  1066. return;
  1067. }
  1068. }
  1069. switch(req.getAction())
  1070. {
  1071. case ACTION_GET_FILE:
  1072. threadhelper( new FileOp( ){
  1073. public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
  1074. String dirname = args.getString(0);
  1075. String path = args.getString(1);
  1076. JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false);
  1077. req.getCallbackContext().success(obj);
  1078. }
  1079. }, req.getRawArgs(), req.getCallbackContext());
  1080. break;
  1081. case ACTION_GET_DIRECTORY:
  1082. threadhelper( new FileOp( ){
  1083. public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
  1084. String dirname = args.getString(0);
  1085. String path = args.getString(1);
  1086. JSONObject obj = getFile(dirname, path, args.optJSONObject(2), true);
  1087. req.getCallbackContext().success(obj);
  1088. }
  1089. }, req.getRawArgs(), req.getCallbackContext());
  1090. break;
  1091. case ACTION_WRITE:
  1092. threadhelper( new FileOp( ){
  1093. public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException {
  1094. String fname=args.getString(0);
  1095. String data=args.getString(1);
  1096. int offset=args.getInt(2);
  1097. Boolean isBinary=args.getBoolean(3);
  1098. long fileSize = write(fname, data, offset, isBinary);
  1099. req.getCallbackContext().sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
  1100. }
  1101. }, req.getRawArgs(), req.getCallbackContext());
  1102. break;
  1103. }
  1104. } else {
  1105. LOG.d(LOG_TAG, "Received permission callback for unknown request code");
  1106. }
  1107. }
  1108. }