Няма описание

LocalFilesystem.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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 java.io.ByteArrayInputStream;
  19. import java.io.File;
  20. import java.io.FileInputStream;
  21. import java.io.FileNotFoundException;
  22. import java.io.FileOutputStream;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.io.OutputStream;
  26. import java.io.RandomAccessFile;
  27. import java.nio.channels.FileChannel;
  28. import org.apache.cordova.CordovaResourceApi;
  29. import org.json.JSONException;
  30. import org.json.JSONObject;
  31. import android.os.Build;
  32. import android.os.Environment;
  33. import android.util.Base64;
  34. import android.net.Uri;
  35. import android.content.Context;
  36. import android.content.Intent;
  37. import java.nio.charset.Charset;
  38. public class LocalFilesystem extends Filesystem {
  39. private final Context context;
  40. public LocalFilesystem(String name, Context context, CordovaResourceApi resourceApi, File fsRoot) {
  41. super(Uri.fromFile(fsRoot).buildUpon().appendEncodedPath("").build(), name, resourceApi);
  42. this.context = context;
  43. }
  44. public String filesystemPathForFullPath(String fullPath) {
  45. return new File(rootUri.getPath(), fullPath).toString();
  46. }
  47. @Override
  48. public String filesystemPathForURL(LocalFilesystemURL url) {
  49. return filesystemPathForFullPath(url.path);
  50. }
  51. private String fullPathForFilesystemPath(String absolutePath) {
  52. if (absolutePath != null && absolutePath.startsWith(rootUri.getPath())) {
  53. return absolutePath.substring(rootUri.getPath().length() - 1);
  54. }
  55. return null;
  56. }
  57. @Override
  58. public Uri toNativeUri(LocalFilesystemURL inputURL) {
  59. return nativeUriForFullPath(inputURL.path);
  60. }
  61. @Override
  62. public LocalFilesystemURL toLocalUri(Uri inputURL) {
  63. if (!"file".equals(inputURL.getScheme())) {
  64. return null;
  65. }
  66. File f = new File(inputURL.getPath());
  67. // Removes and duplicate /s (e.g. file:///a//b/c)
  68. Uri resolvedUri = Uri.fromFile(f);
  69. String rootUriNoTrailingSlash = rootUri.getEncodedPath();
  70. rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
  71. if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
  72. return null;
  73. }
  74. String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
  75. // Strip leading slash
  76. if (!subPath.isEmpty()) {
  77. subPath = subPath.substring(1);
  78. }
  79. Uri.Builder b = new Uri.Builder()
  80. .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL)
  81. .authority("localhost")
  82. .path(name);
  83. if (!subPath.isEmpty()) {
  84. b.appendEncodedPath(subPath);
  85. }
  86. if (f.isDirectory()) {
  87. // Add trailing / for directories.
  88. b.appendEncodedPath("");
  89. }
  90. return LocalFilesystemURL.parse(b.build());
  91. }
  92. @Override
  93. public LocalFilesystemURL URLforFilesystemPath(String path) {
  94. return localUrlforFullPath(fullPathForFilesystemPath(path));
  95. }
  96. @Override
  97. public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
  98. String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
  99. boolean create = false;
  100. boolean exclusive = false;
  101. if (options != null) {
  102. create = options.optBoolean("create");
  103. if (create) {
  104. exclusive = options.optBoolean("exclusive");
  105. }
  106. }
  107. // Check for a ":" character in the file to line up with BB and iOS
  108. if (path.contains(":")) {
  109. throw new EncodingException("This path has an invalid \":\" in it.");
  110. }
  111. LocalFilesystemURL requestedURL;
  112. // Check whether the supplied path is absolute or relative
  113. if (directory && !path.endsWith("/")) {
  114. path += "/";
  115. }
  116. if (path.startsWith("/")) {
  117. requestedURL = localUrlforFullPath(normalizePath(path));
  118. } else {
  119. requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
  120. }
  121. File fp = new File(this.filesystemPathForURL(requestedURL));
  122. if (create) {
  123. if (exclusive && fp.exists()) {
  124. throw new FileExistsException("create/exclusive fails");
  125. }
  126. if (directory) {
  127. fp.mkdir();
  128. } else {
  129. fp.createNewFile();
  130. }
  131. if (!fp.exists()) {
  132. throw new FileExistsException("create fails");
  133. }
  134. }
  135. else {
  136. if (!fp.exists()) {
  137. throw new FileNotFoundException("path does not exist");
  138. }
  139. if (directory) {
  140. if (fp.isFile()) {
  141. throw new TypeMismatchException("path doesn't exist or is file");
  142. }
  143. } else {
  144. if (fp.isDirectory()) {
  145. throw new TypeMismatchException("path doesn't exist or is directory");
  146. }
  147. }
  148. }
  149. // Return the directory
  150. return makeEntryForURL(requestedURL);
  151. }
  152. @Override
  153. public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException {
  154. File fp = new File(filesystemPathForURL(inputURL));
  155. // You can't delete a directory that is not empty
  156. if (fp.isDirectory() && fp.list().length > 0) {
  157. throw new InvalidModificationException("You can't delete a directory that is not empty.");
  158. }
  159. return fp.delete();
  160. }
  161. @Override
  162. public boolean exists(LocalFilesystemURL inputURL) {
  163. File fp = new File(filesystemPathForURL(inputURL));
  164. return fp.exists();
  165. }
  166. @Override
  167. public long getFreeSpaceInBytes() {
  168. return DirectoryManager.getFreeSpaceInBytes(rootUri.getPath());
  169. }
  170. @Override
  171. public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException {
  172. File directory = new File(filesystemPathForURL(inputURL));
  173. return removeDirRecursively(directory);
  174. }
  175. protected boolean removeDirRecursively(File directory) throws FileExistsException {
  176. if (directory.isDirectory()) {
  177. for (File file : directory.listFiles()) {
  178. removeDirRecursively(file);
  179. }
  180. }
  181. if (!directory.delete()) {
  182. throw new FileExistsException("could not delete: " + directory.getName());
  183. } else {
  184. return true;
  185. }
  186. }
  187. @Override
  188. public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
  189. File fp = new File(filesystemPathForURL(inputURL));
  190. if (!fp.exists()) {
  191. // The directory we are listing doesn't exist so we should fail.
  192. throw new FileNotFoundException();
  193. }
  194. File[] files = fp.listFiles();
  195. if (files == null) {
  196. // inputURL is a directory
  197. return null;
  198. }
  199. LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length];
  200. for (int i = 0; i < files.length; i++) {
  201. entries[i] = URLforFilesystemPath(files[i].getPath());
  202. }
  203. return entries;
  204. }
  205. @Override
  206. public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
  207. File file = new File(filesystemPathForURL(inputURL));
  208. if (!file.exists()) {
  209. throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
  210. }
  211. JSONObject metadata = new JSONObject();
  212. try {
  213. // Ensure that directories report a size of 0
  214. metadata.put("size", file.isDirectory() ? 0 : file.length());
  215. metadata.put("type", resourceApi.getMimeType(Uri.fromFile(file)));
  216. metadata.put("name", file.getName());
  217. metadata.put("fullPath", inputURL.path);
  218. metadata.put("lastModifiedDate", file.lastModified());
  219. } catch (JSONException e) {
  220. return null;
  221. }
  222. return metadata;
  223. }
  224. private void copyFile(Filesystem srcFs, LocalFilesystemURL srcURL, File destFile, boolean move) throws IOException, InvalidModificationException, NoModificationAllowedException {
  225. if (move) {
  226. String realSrcPath = srcFs.filesystemPathForURL(srcURL);
  227. if (realSrcPath != null) {
  228. File srcFile = new File(realSrcPath);
  229. if (srcFile.renameTo(destFile)) {
  230. return;
  231. }
  232. // Trying to rename the file failed. Possibly because we moved across file system on the device.
  233. }
  234. }
  235. CordovaResourceApi.OpenForReadResult offr = resourceApi.openForRead(srcFs.toNativeUri(srcURL));
  236. copyResource(offr, new FileOutputStream(destFile));
  237. if (move) {
  238. srcFs.removeFileAtLocalURL(srcURL);
  239. }
  240. }
  241. private void copyDirectory(Filesystem srcFs, LocalFilesystemURL srcURL, File dstDir, boolean move) throws IOException, NoModificationAllowedException, InvalidModificationException, FileExistsException {
  242. if (move) {
  243. String realSrcPath = srcFs.filesystemPathForURL(srcURL);
  244. if (realSrcPath != null) {
  245. File srcDir = new File(realSrcPath);
  246. // If the destination directory already exists and is empty then delete it. This is according to spec.
  247. if (dstDir.exists()) {
  248. if (dstDir.list().length > 0) {
  249. throw new InvalidModificationException("directory is not empty");
  250. }
  251. dstDir.delete();
  252. }
  253. // Try to rename the directory
  254. if (srcDir.renameTo(dstDir)) {
  255. return;
  256. }
  257. // Trying to rename the file failed. Possibly because we moved across file system on the device.
  258. }
  259. }
  260. if (dstDir.exists()) {
  261. if (dstDir.list().length > 0) {
  262. throw new InvalidModificationException("directory is not empty");
  263. }
  264. } else {
  265. if (!dstDir.mkdir()) {
  266. // If we can't create the directory then fail
  267. throw new NoModificationAllowedException("Couldn't create the destination directory");
  268. }
  269. }
  270. LocalFilesystemURL[] children = srcFs.listChildren(srcURL);
  271. for (LocalFilesystemURL childLocalUrl : children) {
  272. File target = new File(dstDir, new File(childLocalUrl.path).getName());
  273. if (childLocalUrl.isDirectory) {
  274. copyDirectory(srcFs, childLocalUrl, target, false);
  275. } else {
  276. copyFile(srcFs, childLocalUrl, target, false);
  277. }
  278. }
  279. if (move) {
  280. srcFs.recursiveRemoveFileAtLocalURL(srcURL);
  281. }
  282. }
  283. @Override
  284. public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName,
  285. Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException {
  286. // Check to see if the destination directory exists
  287. String newParent = this.filesystemPathForURL(destURL);
  288. File destinationDir = new File(newParent);
  289. if (!destinationDir.exists()) {
  290. // The destination does not exist so we should fail.
  291. throw new FileNotFoundException("The source does not exist");
  292. }
  293. // Figure out where we should be copying to
  294. final LocalFilesystemURL destinationURL = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory);
  295. Uri dstNativeUri = toNativeUri(destinationURL);
  296. Uri srcNativeUri = srcFs.toNativeUri(srcURL);
  297. // Check to see if source and destination are the same file
  298. if (dstNativeUri.equals(srcNativeUri)) {
  299. throw new InvalidModificationException("Can't copy onto itself");
  300. }
  301. if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) {
  302. throw new InvalidModificationException("Source URL is read-only (cannot move)");
  303. }
  304. File destFile = new File(dstNativeUri.getPath());
  305. if (destFile.exists()) {
  306. if (!srcURL.isDirectory && destFile.isDirectory()) {
  307. throw new InvalidModificationException("Can't copy/move a file to an existing directory");
  308. } else if (srcURL.isDirectory && destFile.isFile()) {
  309. throw new InvalidModificationException("Can't copy/move a directory to an existing file");
  310. }
  311. }
  312. if (srcURL.isDirectory) {
  313. // E.g. Copy /sdcard/myDir to /sdcard/myDir/backup
  314. if (dstNativeUri.toString().startsWith(srcNativeUri.toString() + '/')) {
  315. throw new InvalidModificationException("Can't copy directory into itself");
  316. }
  317. copyDirectory(srcFs, srcURL, destFile, move);
  318. } else {
  319. copyFile(srcFs, srcURL, destFile, move);
  320. }
  321. return makeEntryForURL(destinationURL);
  322. }
  323. @Override
  324. public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
  325. int offset, boolean isBinary) throws IOException, NoModificationAllowedException {
  326. boolean append = false;
  327. if (offset > 0) {
  328. this.truncateFileAtURL(inputURL, offset);
  329. append = true;
  330. }
  331. byte[] rawData;
  332. if (isBinary) {
  333. rawData = Base64.decode(data, Base64.DEFAULT);
  334. } else {
  335. rawData = data.getBytes(Charset.defaultCharset());
  336. }
  337. ByteArrayInputStream in = new ByteArrayInputStream(rawData);
  338. try
  339. {
  340. byte buff[] = new byte[rawData.length];
  341. String absolutePath = filesystemPathForURL(inputURL);
  342. FileOutputStream out = new FileOutputStream(absolutePath, append);
  343. try {
  344. in.read(buff, 0, buff.length);
  345. out.write(buff, 0, rawData.length);
  346. out.flush();
  347. } finally {
  348. // Always close the output
  349. out.close();
  350. }
  351. if (isPublicDirectory(absolutePath)) {
  352. broadcastNewFile(Uri.fromFile(new File(absolutePath)));
  353. }
  354. }
  355. catch (NullPointerException e)
  356. {
  357. // This is a bug in the Android implementation of the Java Stack
  358. NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
  359. realException.initCause(e);
  360. throw realException;
  361. }
  362. return rawData.length;
  363. }
  364. private boolean isPublicDirectory(String absolutePath) {
  365. // TODO: should expose a way to scan app's private files (maybe via a flag).
  366. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  367. // Lollipop has a bug where SD cards are null.
  368. for (File f : context.getExternalMediaDirs()) {
  369. if(f != null && absolutePath.startsWith(f.getAbsolutePath())) {
  370. return true;
  371. }
  372. }
  373. }
  374. String extPath = Environment.getExternalStorageDirectory().getAbsolutePath();
  375. return absolutePath.startsWith(extPath);
  376. }
  377. /**
  378. * Send broadcast of new file so files appear over MTP
  379. */
  380. private void broadcastNewFile(Uri nativeUri) {
  381. Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, nativeUri);
  382. context.sendBroadcast(intent);
  383. }
  384. @Override
  385. public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
  386. File file = new File(filesystemPathForURL(inputURL));
  387. if (!file.exists()) {
  388. throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
  389. }
  390. RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
  391. try {
  392. if (raf.length() >= size) {
  393. FileChannel channel = raf.getChannel();
  394. channel.truncate(size);
  395. return size;
  396. }
  397. return raf.length();
  398. } finally {
  399. raf.close();
  400. }
  401. }
  402. @Override
  403. public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
  404. String path = filesystemPathForURL(inputURL);
  405. File file = new File(path);
  406. return file.exists();
  407. }
  408. // This is a copy & paste from CordovaResource API that is required since CordovaResourceApi
  409. // has a bug pre-4.0.0.
  410. // TODO: Once cordova-android@4.0.0 is released, delete this copy and make the plugin depend on
  411. // 4.0.0 with an engine tag.
  412. private static void copyResource(CordovaResourceApi.OpenForReadResult input, OutputStream outputStream) throws IOException {
  413. try {
  414. InputStream inputStream = input.inputStream;
  415. if (inputStream instanceof FileInputStream && outputStream instanceof FileOutputStream) {
  416. FileChannel inChannel = ((FileInputStream)input.inputStream).getChannel();
  417. FileChannel outChannel = ((FileOutputStream)outputStream).getChannel();
  418. long offset = 0;
  419. long length = input.length;
  420. if (input.assetFd != null) {
  421. offset = input.assetFd.getStartOffset();
  422. }
  423. // transferFrom()'s 2nd arg is a relative position. Need to set the absolute
  424. // position first.
  425. inChannel.position(offset);
  426. outChannel.transferFrom(inChannel, 0, length);
  427. } else {
  428. final int BUFFER_SIZE = 8192;
  429. byte[] buffer = new byte[BUFFER_SIZE];
  430. for (;;) {
  431. int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);
  432. if (bytesRead <= 0) {
  433. break;
  434. }
  435. outputStream.write(buffer, 0, bytesRead);
  436. }
  437. }
  438. } finally {
  439. input.inputStream.close();
  440. if (outputStream != null) {
  441. outputStream.close();
  442. }
  443. }
  444. }
  445. }